apple-cf 0.11.6

Safe Rust bindings for Apple's shared Core* frameworks (CoreFoundation, CoreMedia, CoreVideo, CoreGraphics, IOSurface, Dispatch).
Documentation
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! `CGContext` — offscreen bitmap drawing with Core Graphics.

use core::ffi::c_void;
use core::ptr;

use crate::NullPointerError;

use super::{CGAffineTransform, CGRect};
use super::drawing::{CGColorSpace, CGImage};
use super::ffi;

const BITS_PER_COMPONENT_8: usize = 8;
const CG_IMAGE_ALPHA_NONE: u32 = 0;
const CG_IMAGE_ALPHA_ONLY: u32 = 7;
const CG_IMAGE_ALPHA_PREMULTIPLIED_LAST: u32 = 1;
const CG_BITMAP_BYTE_ORDER_32_BIG: u32 = 16_384;
const RGBA8_BITMAP_INFO: u32 = CG_IMAGE_ALPHA_PREMULTIPLIED_LAST | CG_BITMAP_BYTE_ORDER_32_BIG;
const GRAYSCALE8_BITMAP_INFO: u32 = CG_IMAGE_ALPHA_NONE;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum LineCap {
    Butt = 0,
    Round = 1,
    Square = 2,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum LineJoin {
    Miter = 0,
    Round = 1,
    Bevel = 2,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum PathDrawingMode {
    Fill = 0,
    EvenOddFill = 1,
    Stroke = 2,
    FillStroke = 3,
    EvenOddFillStroke = 4,
}

/// Reference-counted `CGContextRef` backed by a bitmap.
///
/// Clones retain the same mutable native context; they are not independent
/// drawing surfaces.
#[derive(Debug)]
pub struct CGContext {
    ptr: *mut c_void,
}

crate::utils::retained::cf_retained!(
    CGContext,
    field = ptr,
    retain = ffi::CGContextRetain,
    release = ffi::CGContextRelease,
    drop = null_out,
);

impl CGContext {
    /// Wrap a raw `CGContextRef` pointer — takes ownership without retaining.
    ///
    /// # Safety
    ///
    /// `ptr` must be a non-null `CGContextRef` whose ownership the caller is
    /// transferring to the returned [`CGContext`].
    #[must_use]
    pub const unsafe fn from_raw(ptr: *mut c_void) -> Self {
        Self { ptr }
    }

    fn new_bitmap(
        width: usize,
        height: usize,
        bytes_per_row: usize,
        color_space: &CGColorSpace,
        bitmap_info: u32,
    ) -> Result<Self, NullPointerError> {
        let context = unsafe {
            if bytes_per_row == 0 {
                ffi::CGBitmapContextCreate(
                    ptr::null_mut(),
                    width,
                    height,
                    BITS_PER_COMPONENT_8,
                    0,
                    color_space.as_ptr(),
                    bitmap_info,
                )
            } else {
                crate::ffi::acf_cg_context_create_bitmap(
                    width,
                    height,
                    bytes_per_row,
                    color_space.as_ptr(),
                    bitmap_info,
                )
            }
        };

        if context.is_null() {
            Err(NullPointerError::new("CGBitmapContextCreate"))
        } else {
            let context = Self { ptr: context };
            let data = context.data();
            let len = context.buffer_len();
            if !data.is_null() && len != 0 {
                unsafe { data.write_bytes(0, len) };
            }
            Ok(context)
        }
    }

    /// Create a premultiplied-last RGBA8 bitmap context.
    ///
    /// # Errors
    ///
    /// Returns [`NullPointerError`] if Core Graphics fails to create the bitmap context.
    pub fn new_rgba8(width: usize, height: usize) -> Result<Self, NullPointerError> {
        let color_space = CGColorSpace::device_rgb();
        Self::new_bitmap(width, height, 0, &color_space, RGBA8_BITMAP_INFO)
    }

    #[allow(clippy::missing_errors_doc)]
    pub fn new_srgb_rgba8(width: usize, height: usize) -> Result<Self, NullPointerError> {
        let bytes_per_row = width
            .checked_mul(4)
            .ok_or_else(|| NullPointerError::new("CGBitmapContextCreate"))?;
        let color_space = CGColorSpace::srgb();
        Self::new_bitmap(width, height, bytes_per_row, &color_space, RGBA8_BITMAP_INFO)
    }

    #[must_use]
    #[allow(clippy::missing_safety_doc)]
    pub unsafe fn copy_bytes(&self) -> Vec<u8> {
        unsafe { self.as_bytes() }.to_vec()
    }

    /// Create an 8-bit grayscale bitmap context.
    ///
    /// # Errors
    ///
    /// Returns [`NullPointerError`] if Core Graphics fails to create the bitmap context.
    pub fn new_grayscale(width: usize, height: usize) -> Result<Self, NullPointerError> {
        let color_space = CGColorSpace::device_gray();
        Self::new_bitmap(width, height, 0, &color_space, GRAYSCALE8_BITMAP_INFO)
    }

    #[allow(clippy::missing_errors_doc)]
    pub fn new_alpha_only(width: usize, height: usize) -> Result<Self, NullPointerError> {
        let color_space = CGColorSpace::device_gray();
        Self::new_bitmap(width, height, width, &color_space, CG_IMAGE_ALPHA_ONLY)
    }

    #[allow(clippy::missing_errors_doc)]
    pub fn new_premultiplied_last(width: usize, height: usize) -> Result<Self, NullPointerError> {
        let bytes_per_row = width
            .checked_mul(4)
            .ok_or_else(|| NullPointerError::new("CGBitmapContextCreate"))?;
        let color_space = CGColorSpace::device_rgb();
        Self::new_bitmap(
            width,
            height,
            bytes_per_row,
            &color_space,
            CG_IMAGE_ALPHA_PREMULTIPLIED_LAST,
        )
    }

    fn buffer_len(&self) -> usize {
        self.height().checked_mul(self.bytes_per_row()).unwrap_or(0)
    }

    /// Width in pixels.
    #[must_use]
    pub fn width(&self) -> usize {
        unsafe { ffi::CGBitmapContextGetWidth(self.ptr) }
    }

    /// Height in pixels.
    #[must_use]
    pub fn height(&self) -> usize {
        unsafe { ffi::CGBitmapContextGetHeight(self.ptr) }
    }

    /// Bytes per row.
    #[must_use]
    pub fn bytes_per_row(&self) -> usize {
        unsafe { ffi::CGBitmapContextGetBytesPerRow(self.ptr) }
    }

    /// Bits per component.
    #[must_use]
    pub fn bits_per_component(&self) -> usize {
        unsafe { ffi::CGBitmapContextGetBitsPerComponent(self.ptr) }
    }

    /// Bits per pixel.
    #[must_use]
    pub fn bits_per_pixel(&self) -> usize {
        unsafe { ffi::CGBitmapContextGetBitsPerPixel(self.ptr) }
    }

    /// Raw bitmap data pointer.
    ///
    /// Dereferencing the pointer is unsafe because retained aliases and native
    /// drawing operations can mutate the same storage.
    #[must_use]
    pub fn data(&self) -> *mut u8 {
        unsafe { ffi::CGBitmapContextGetData(self.ptr).cast::<u8>() }
    }

    /// The context color space, if one is set.
    #[must_use]
    pub fn color_space(&self) -> Option<CGColorSpace> {
        unsafe {
            let color_space = ffi::CGBitmapContextGetColorSpace(self.ptr);
            if color_space.is_null() {
                None
            } else {
                Some(CGColorSpace::from_raw(ffi::CGColorSpaceRetain(color_space)))
            }
        }
    }

    /// The raw `CGImageAlphaInfo` value for the bitmap context.
    #[must_use]
    pub fn alpha_info(&self) -> u32 {
        unsafe { ffi::CGBitmapContextGetAlphaInfo(self.ptr) }
    }

    /// The bitmap storage as immutable bytes.
    ///
    /// # Safety
    ///
    /// Every byte in the range must already be initialized. For the returned
    /// reference's lifetime, the bitmap allocation must remain live and
    /// immovable, and no retained alias or native call may draw into, clear,
    /// replace, or otherwise mutate the context storage.
    #[must_use]
    pub unsafe fn as_bytes(&self) -> &[u8] {
        let data = self.data();
        let len = self.buffer_len();
        if data.is_null() || len == 0 || isize::try_from(len).is_err() {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(data.cast_const(), len) }
        }
    }

    /// The bitmap storage as mutable bytes.
    ///
    /// # Safety
    ///
    /// Every byte in the range must already be initialized. For the returned
    /// reference's lifetime, the caller must have unique access to the bitmap
    /// storage across every retained wrapper and native alias, and no drawing
    /// or snapshot operation may access the context.
    #[must_use]
    pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        let data = self.data();
        let len = self.buffer_len();
        if data.is_null() || len == 0 || isize::try_from(len).is_err() {
            &mut []
        } else {
            unsafe { std::slice::from_raw_parts_mut(data, len) }
        }
    }

    /// Set the current fill color in `DeviceRGB`.
    pub fn set_rgb_fill_color(&self, r: f64, g: f64, b: f64, a: f64) {
        unsafe { ffi::CGContextSetRGBFillColor(self.ptr, r, g, b, a) };
    }

    pub fn set_gray_fill_color(&self, gray: f64, alpha: f64) {
        unsafe { crate::ffi::acf_cg_context_set_gray_fill_color(self.ptr, gray, alpha) };
    }

    pub fn set_text_fill_mode(&self) {
        unsafe { crate::ffi::acf_cg_context_set_text_fill_mode(self.ptr) };
    }

    pub fn set_allows_antialiasing(&self, allowed: bool) {
        unsafe { crate::ffi::acf_cg_context_set_allows_antialiasing(self.ptr, allowed) };
    }

    pub fn set_should_antialias(&self, enabled: bool) {
        unsafe { crate::ffi::acf_cg_context_set_should_antialias(self.ptr, enabled) };
    }

    pub fn set_allows_font_subpixel_positioning(&self, allowed: bool) {
        unsafe {
            crate::ffi::acf_cg_context_set_allows_font_subpixel_positioning(self.ptr, allowed);
        };
    }

    pub fn set_should_subpixel_position_fonts(&self, enabled: bool) {
        unsafe { crate::ffi::acf_cg_context_set_should_subpixel_position_fonts(self.ptr, enabled) };
    }

    pub fn set_allows_font_subpixel_quantization(&self, allowed: bool) {
        unsafe {
            crate::ffi::acf_cg_context_set_allows_font_subpixel_quantization(self.ptr, allowed);
        };
    }

    pub fn set_should_subpixel_quantize_fonts(&self, enabled: bool) {
        unsafe { crate::ffi::acf_cg_context_set_should_subpixel_quantize_fonts(self.ptr, enabled) };
    }

    pub fn set_should_smooth_fonts(&self, enabled: bool) {
        unsafe { crate::ffi::acf_cg_context_set_should_smooth_fonts(self.ptr, enabled) };
    }

    /// Set the current stroke color in `DeviceRGB`.
    pub fn set_rgb_stroke_color(&self, r: f64, g: f64, b: f64, a: f64) {
        unsafe { ffi::CGContextSetRGBStrokeColor(self.ptr, r, g, b, a) };
    }

    /// Set the stroke line width.
    pub fn set_line_width(&self, w: f64) {
        unsafe { ffi::CGContextSetLineWidth(self.ptr, w) };
    }

    /// Clear a rectangle to transparent black.
    pub fn clear_rect(&self, x: f64, y: f64, w: f64, h: f64) {
        unsafe { ffi::CGContextClearRect(self.ptr, CGRect::new(x, y, w, h)) };
    }

    /// Fill a rectangle.
    pub fn fill_rect(&self, x: f64, y: f64, w: f64, h: f64) {
        unsafe { ffi::CGContextFillRect(self.ptr, CGRect::new(x, y, w, h)) };
    }

    /// Stroke a rectangle.
    pub fn stroke_rect(&self, x: f64, y: f64, w: f64, h: f64) {
        unsafe { ffi::CGContextStrokeRect(self.ptr, CGRect::new(x, y, w, h)) };
    }

    /// Begin a new path.
    pub fn begin_path(&self) {
        unsafe { ffi::CGContextBeginPath(self.ptr) };
    }

    /// Close the current path.
    pub fn close_path(&self) {
        unsafe { ffi::CGContextClosePath(self.ptr) };
    }

    /// Move the current point.
    pub fn move_to(&self, x: f64, y: f64) {
        unsafe { ffi::CGContextMoveToPoint(self.ptr, x, y) };
    }

    /// Add a line segment to the current path.
    pub fn add_line_to(&self, x: f64, y: f64) {
        unsafe { ffi::CGContextAddLineToPoint(self.ptr, x, y) };
    }

    pub fn add_quad_curve_to(&self, cx: f64, cy: f64, x: f64, y: f64) {
        unsafe { ffi::CGContextAddQuadCurveToPoint(self.ptr, cx, cy, x, y) };
    }

    pub fn add_curve_to(&self, c1x: f64, c1y: f64, c2x: f64, c2y: f64, x: f64, y: f64) {
        unsafe { ffi::CGContextAddCurveToPoint(self.ptr, c1x, c1y, c2x, c2y, x, y) };
    }

    pub fn set_line_cap(&self, cap: LineCap) {
        unsafe { ffi::CGContextSetLineCap(self.ptr, cap as u32) };
    }

    pub fn set_line_join(&self, join: LineJoin) {
        unsafe { ffi::CGContextSetLineJoin(self.ptr, join as u32) };
    }

    pub fn set_miter_limit(&self, limit: f64) {
        unsafe { ffi::CGContextSetMiterLimit(self.ptr, limit) };
    }

    pub fn draw_path(&self, mode: PathDrawingMode) {
        unsafe { ffi::CGContextDrawPath(self.ptr, mode as u32) };
    }

    pub fn clip(&self, even_odd: bool) {
        unsafe {
            if even_odd {
                ffi::CGContextEOClip(self.ptr);
            } else {
                ffi::CGContextClip(self.ptr);
            }
        }
    }

    pub fn concat_transform(&self, transform: CGAffineTransform) {
        unsafe { ffi::CGContextConcatCTM(self.ptr, transform) };
    }

    /// Add a rectangle to the current path.
    pub fn add_rect(&self, x: f64, y: f64, w: f64, h: f64) {
        unsafe { ffi::CGContextAddRect(self.ptr, CGRect::new(x, y, w, h)) };
    }

    /// Add an ellipse inscribed in the rectangle.
    pub fn add_ellipse_in_rect(&self, x: f64, y: f64, w: f64, h: f64) {
        unsafe { ffi::CGContextAddEllipseInRect(self.ptr, CGRect::new(x, y, w, h)) };
    }

    /// Fill the current path.
    pub fn fill_path(&self) {
        unsafe { ffi::CGContextFillPath(self.ptr) };
    }

    /// Stroke the current path.
    pub fn stroke_path(&self) {
        unsafe { ffi::CGContextStrokePath(self.ptr) };
    }

    /// Draw an image into the target rectangle.
    pub fn draw_image(&self, x: f64, y: f64, w: f64, h: f64, image: &CGImage) {
        unsafe { ffi::CGContextDrawImage(self.ptr, CGRect::new(x, y, w, h), image.as_ptr()) };
    }

    /// Translate the current transformation matrix.
    pub fn translate(&self, tx: f64, ty: f64) {
        unsafe { ffi::CGContextTranslateCTM(self.ptr, tx, ty) };
    }

    /// Scale the current transformation matrix.
    pub fn scale(&self, sx: f64, sy: f64) {
        unsafe { ffi::CGContextScaleCTM(self.ptr, sx, sy) };
    }

    /// Rotate the current transformation matrix.
    pub fn rotate(&self, radians: f64) {
        unsafe { ffi::CGContextRotateCTM(self.ptr, radians) };
    }

    /// Save the current graphics state.
    pub fn save_g_state(&self) {
        unsafe { ffi::CGContextSaveGState(self.ptr) };
    }

    /// Restore the most recently saved graphics state.
    pub fn restore_g_state(&self) {
        unsafe { ffi::CGContextRestoreGState(self.ptr) };
    }

    /// Snapshot the current bitmap contents to a `CGImage`.
    #[must_use]
    pub fn snapshot_to_image(&self) -> Option<CGImage> {
        let image = unsafe { ffi::CGBitmapContextCreateImage(self.ptr) };
        if image.is_null() {
            None
        } else {
            Some(unsafe { CGImage::from_raw(image) })
        }
    }

    /// Raw `CGContextRef` pointer.
    #[must_use]
    pub const fn as_ptr(&self) -> *mut c_void {
        self.ptr
    }
}