1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use ffi::{self, cairo_status_t};
use {Status, Surface, UserDataKey};
use libc::{c_double, c_uchar, c_uint, c_void};
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::io;
use std::panic::AssertUnwindSafe;
use std::rc::Rc;
macro_rules! for_stream_constructors {
($constructor_ffi: ident) => {
pub fn for_stream<W: io::Write + 'static>(
width: f64,
height: f64,
stream: W,
) -> Result<Self, crate::enums::Status> {
Ok(Self(Surface::_for_stream(
ffi::$constructor_ffi,
width,
height,
stream,
)?))
}
pub unsafe fn for_raw_stream<W: io::Write + 'static>(
width: f64,
height: f64,
stream: *mut W,
) -> Result<Self, crate::enums::Status> {
Ok(Self(Surface::_for_raw_stream(
ffi::$constructor_ffi,
width,
height,
stream,
)?))
}
};
}
impl Surface {
pub(crate) fn _for_stream<W: io::Write + 'static>(
constructor: Constructor,
width: f64,
height: f64,
stream: W,
) -> Result<Self, Status> {
let env_rc = Rc::new(CallbackEnvironment {
mutable: RefCell::new(MutableCallbackEnvironment {
stream: Some((Box::new(stream), None)),
unwind_payload: None,
}),
saw_already_borrowed: Cell::new(false),
});
let env: *const CallbackEnvironment = &*env_rc;
unsafe {
let ptr = constructor(Some(write_callback::<W>), env as *mut c_void, width, height);
let surface = Surface::from_raw_full(ptr)?;
surface.set_user_data(&STREAM_CALLBACK_ENVIRONMENT, env_rc);
Ok(surface)
}
}
pub(crate) unsafe fn _for_raw_stream<W: io::Write + 'static>(
constructor: Constructor,
width: f64,
height: f64,
stream: *mut W,
) -> Result<Self, Status> {
Self::_for_stream(constructor, width, height, RawStream(stream))
}
pub fn finish_output_stream(&self) -> Result<Box<dyn Any>, StreamWithError> {
self.finish();
let env = self
.get_user_data_ptr(&STREAM_CALLBACK_ENVIRONMENT)
.expect("surface without an output stream");
let env = unsafe { &*env.as_ptr() };
if env.saw_already_borrowed.get() {
panic!("The output stream’s RefCell was already borrowed when cairo attempted a write")
}
let mut mutable = env.mutable.borrow_mut();
if let Some(payload) = mutable.unwind_payload.take() {
std::panic::resume_unwind(payload)
}
let (stream, io_error) = mutable
.stream
.take()
.expect("output stream was already taken");
if let Some(error) = io_error {
Err(StreamWithError { stream, error })
} else {
Ok(stream)
}
}
}
pub struct StreamWithError {
pub stream: Box<dyn Any>,
pub error: io::Error,
}
impl std::fmt::Debug for StreamWithError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.error.fmt(f)
}
}
impl std::fmt::Display for StreamWithError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
self.error.fmt(f)
}
}
impl From<StreamWithError> for io::Error {
fn from(e: StreamWithError) -> Self {
e.error
}
}
pub(crate) type Constructor = unsafe extern "C" fn(
ffi::cairo_write_func_t,
*mut c_void,
c_double,
c_double,
) -> *mut ffi::cairo_surface_t;
static STREAM_CALLBACK_ENVIRONMENT: UserDataKey<CallbackEnvironment> = UserDataKey::new();
struct CallbackEnvironment {
mutable: RefCell<MutableCallbackEnvironment>,
saw_already_borrowed: Cell<bool>,
}
struct MutableCallbackEnvironment {
stream: Option<(Box<dyn Any>, Option<io::Error>)>,
unwind_payload: Option<Box<dyn Any + Send + 'static>>,
}
extern "C" fn write_callback<W: io::Write + 'static>(
env: *mut c_void,
data: *mut c_uchar,
length: c_uint,
) -> cairo_status_t {
let env: *const CallbackEnvironment = env as _;
let env: &CallbackEnvironment = unsafe { &*env };
if let Ok(mut mutable) = env.mutable.try_borrow_mut() {
if let MutableCallbackEnvironment {
stream:
Some((
stream,
io_error @ None,
)),
unwind_payload: unwind_payload @ None,
} = &mut *mutable
{
let stream = unsafe { stream.downcast_mut_unchecked::<W>() };
let data = unsafe { std::slice::from_raw_parts(data, length as usize) };
let result = std::panic::catch_unwind(AssertUnwindSafe(|| stream.write_all(data)));
match result {
Ok(Ok(())) => return Status::Success.into(),
Ok(Err(error)) => {
*io_error = Some(error);
}
Err(payload) => {
*unwind_payload = Some(payload);
}
}
}
} else {
env.saw_already_borrowed.set(true)
}
Status::WriteError.into()
}
struct RawStream<W>(*mut W);
impl<W: io::Write> io::Write for RawStream<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
unsafe { (*self.0).write(buf) }
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
unsafe { (*self.0).write_all(buf) }
}
fn flush(&mut self) -> io::Result<()> {
unsafe { (*self.0).flush() }
}
}
trait AnyExt {
unsafe fn downcast_mut_unchecked<T>(&mut self) -> &mut T {
let ptr = self as *mut Self as *mut T;
&mut *ptr
}
}
impl AnyExt for dyn Any {}