quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! Core Graphics / ImageIO rasteriser for [`crate::primitives::image::Image`].
//!
//! Decodes `image.source`'s encoded bytes through `CGImageSource` (ImageIO),
//! then paints the decoded bitmap into `image.layout(rect)`'s resolved target
//! rect. Same collapse-to-`Unsupported` posture on any decode failure (missing
//! file, corrupt bytes, unrecognised format): `CGImageSourceCreateImageAtIndex`
//! reports all of these the same way, as a null return.
//!
//! Painting is always clipped to the caller's `rect` — the only
//! [`crate::primitives::image::ImageFit`] variants that can extend past
//! it are `Cover` and `None`, and neither should bleed into whatever the
//! host paints next to it. Reuses [`super::backend::ns_push_clip`]/
//! [`super::backend::ns_pop_clip`] — the same save/clip/restore pair
//! every other clipping rasteriser in `macos::` uses — rather than
//! hand-rolling a third clip helper.
//!
//! # Decode cache
//!
//! [`draw_image`] is `pub` inside a `pub mod` — reachable externally as
//! `quadraui::macos::image::draw_image` — so it cannot change its
//! signature without risking a break for external code already calling it
//! directly. `draw_image` itself therefore stays exactly as it always has —
//! uncached, one decode per call — and the caching lives in a sibling,
//! crate-internal [`draw_image_cached`] that [`MacBackend::draw_image`]
//! (the `Backend` trait method) calls instead. Both share the same
//! post-decode clip/counter-flip/draw tail, [`paint_cg_image`].
//!
//! Unlike GTK's `gdk_pixbuf::Pixbuf::scale_simple` (which produces an
//! already-scaled bitmap sized for one particular target rect),
//! `CGContextDrawImage` stretches a `CGImage` into whatever destination
//! rect it's given at draw time — so the decoded `CGImage` here is
//! genuinely reusable across every target size a source is ever painted
//! at, not just repeats of the same size. [`draw_image_cached`] caches
//! the raw decode keyed on source only (width/height pinned to `0` in the
//! [`crate::image_cache::ImageCache`] key — see the call site). See
//! [`paint_cg_image`]'s doc for the counter-flip both entry points share.
//!
//! # Why raw FFI for `CGImageSource`
//!
//! Unlike `CGImage`/`CGDataProvider` (both wrapped by the `core-graphics`
//! crate already in this crate's dependency graph), ImageIO's
//! `CGImageSourceRef` has no representation there — `core-graphics`
//! stops at CoreGraphics proper and never links ImageIO. This module
//! owns the minimal FFI surface itself (an opaque `CGImageSource` type
//! plus the two creation functions it needs), the same shape
//! `macos::text` uses for `CTFontManagerRegisterGraphicsFont` (a gap in
//! `core-text`) and `macos::headless` uses for `CGBitmapContextCreate` (a
//! gap in `core-graphics`'s safe surface). `CGImage` itself is
//! constructed via [`core_graphics::image::CGImage`]'s
//! [`foreign_types::ForeignType::from_ptr`] once ImageIO hands back a
//! raw `CGImageRef`, so its `Drop` impl (`CGImageRelease`) still owns
//! release — only the `CGImageSourceRef` needs a manual `CFRelease`.

use std::sync::Arc;

use core_foundation::base::{CFRelease, CFTypeRef};
use core_foundation::dictionary::CFDictionaryRef;
use core_graphics::base::CGFloat;
use core_graphics::data_provider::CGDataProvider;
use core_graphics::geometry::{CGPoint, CGRect, CGSize};
use core_graphics::image::CGImage;
use core_graphics::sys::{CGContextRef, CGDataProviderRef, CGImageRef};
use foreign_types::ForeignType;

use super::backend::{ns_pop_clip, ns_push_clip};
use crate::backend::ImagePaintResult;
use crate::event::Rect;
use crate::image_cache::ImageCache;
use crate::primitives::image::{Image, ImageSource};

/// Opaque ImageIO type — see the module doc's "Why raw FFI" section.
enum CGImageSource {}
type CGImageSourceRef = *mut CGImageSource;

/// Decode `source`'s encoded bytes into a [`CGImage`], or `None` on any
/// failure. See the module docs for why every failure mode collapses to
/// the same `None` rather than a typed error.
fn decode_image(source: &ImageSource) -> Option<CGImage> {
    let bytes: Vec<u8> = match source {
        ImageSource::Path(path) => std::fs::read(path).ok()?,
        ImageSource::Bytes(bytes) => bytes.clone(),
    };
    if bytes.is_empty() {
        return None;
    }

    let provider = CGDataProvider::from_buffer(Arc::new(bytes));
    // SAFETY: `provider.as_ptr()` is a valid, live `CGDataProviderRef`
    // for the duration of this call — `provider` outlives it.
    let source_ref =
        unsafe { CGImageSourceCreateWithDataProvider(provider.as_ptr(), std::ptr::null()) };
    if source_ref.is_null() {
        return None;
    }
    // SAFETY: `source_ref` was just checked non-null. Released
    // immediately below regardless of whether decoding an image out of
    // it succeeds — `CGImageSourceCreateImageAtIndex` doesn't need the
    // source to outlive the image it decodes.
    let image_ref = unsafe { CGImageSourceCreateImageAtIndex(source_ref, 0, std::ptr::null()) };
    unsafe { CFRelease(source_ref as CFTypeRef) };
    if image_ref.is_null() {
        return None;
    }
    // SAFETY: `image_ref` is a live, `+1`-retained `CGImageRef` handed
    // to us by ImageIO. `CGImage`'s `foreign_type!`-generated `Drop`
    // impl calls `CGImageRelease`, so ownership transfers cleanly here.
    Some(unsafe { CGImage::from_ptr(image_ref) })
}

/// Shared clip/counter-flip/draw tail for [`draw_image`] and
/// [`draw_image_cached`] — both decode `image.source` their own way
/// (fresh vs. cached) and then hand the resulting `cg_image` here to
/// actually paint it. Counter-flips the CTM locally around
/// `CGContextDrawImage`, for the same reason
/// [`super::text::draw_text_impl`] counter-flips the text matrix before
/// `CTLineDraw`: this whole backend paints through a permanently
/// flipped, top-left-origin, y-down context (`QuadraView`'s translate +
/// `CGContextScaleCTM(1, -1)`, documented on
/// `headless::BitmapSurface::new`), and `CGContextDrawImage` has no
/// matrix-setter equivalent to compensate for that the way text does —
/// the caller has to re-flip the CTM locally around the draw itself.
/// Reuses [`super::backend::ns_push_clip`]/[`super::backend::ns_pop_clip`]
/// — the same save/clip/restore pair every other clipping rasteriser in
/// `macos::` uses — rather than hand-rolling a third clip helper.
///
/// # Safety
/// `ctx` must be a valid, live `CGContextRef` for the duration of the
/// call.
unsafe fn paint_cg_image(
    ctx: CGContextRef,
    rect: Rect,
    image: &Image,
    cg_image: &CGImage,
) -> ImagePaintResult {
    debug_assert!(
        !ctx.is_null(),
        "macos::image: about to paint a decoded image with a null CGContextRef",
    );

    let dest = image.layout(rect).bounds;

    // SAFETY: `ctx` is valid per this function's own contract; `cg_image`
    // is a live, owned `CGImage` for the duration of this call.
    ns_push_clip(ctx, rect);

    // Undo the permanent y-flip locally: move the origin to the bottom
    // of `dest` (in the current, already-once-flipped space) and scale y
    // by -1, then draw into a zero-origin rect of the same size —
    // `ns_pop_clip`'s `CGContextRestoreGState` below restores the CTM
    // along with the clip, so this doesn't need its own save/restore
    // pair. See this function's doc for why the flip is needed at all.
    CGContextTranslateCTM(ctx, dest.x as f64, (dest.y + dest.height) as f64);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    let local_rect = CGRect::new(
        &CGPoint::new(0.0, 0.0),
        &CGSize::new(dest.width as f64, dest.height as f64),
    );
    CGContextDrawImage(ctx, local_rect, cg_image.as_ptr());

    ns_pop_clip(ctx);

    ImagePaintResult::Painted
}

/// Paint `image` within `rect` (points, target-relative), decoding
/// `image.source` fresh on every call — see the module docs' "Decode
/// cache" section for why this public entry point deliberately does
/// *not* cache, and [`draw_image_cached`] for the crate-internal one
/// that does.
///
/// Decoding happens before `ctx` is ever touched, so a decode failure or
/// a zero-size `rect` returns [`ImagePaintResult::Unsupported`] without
/// requiring a live context — `ctx` only needs to be valid when this
/// function is actually about to paint (checked with a `debug_assert!`
/// inside [`paint_cg_image`], right before the CoreGraphics calls that
/// dereference it), unlike [`super::minimap::draw_minimap`], which
/// touches `ctx` unconditionally and so asserts on it up front.
///
/// # Safety
/// If a decodable `image.source` and non-zero `rect` cause this function
/// to actually paint, `ctx` must be a valid, live `CGContextRef` for the
/// duration of the call.
pub unsafe fn draw_image(ctx: CGContextRef, rect: Rect, image: &Image) -> ImagePaintResult {
    if rect.width <= 0.0 || rect.height <= 0.0 {
        return ImagePaintResult::Unsupported;
    }
    let Some(cg_image) = decode_image(&image.source) else {
        return ImagePaintResult::Unsupported;
    };
    paint_cg_image(ctx, rect, image, &cg_image)
}

/// Paint `image` within `rect` (points, target-relative), decoding
/// through `cache` — see the module docs. `scale` is folded into
/// the cache key alongside the (pinned-to-`0`) size for consistency with
/// every other backend's [`ImageCache`] key, even though this backend's
/// decode doesn't actually depend on either. Crate-internal:
/// [`MacBackend::draw_image`] is the only caller, so this can take
/// whatever shape is convenient without worrying about breaking an
/// external caller the way changing [`draw_image`]'s signature would.
///
/// # Safety
/// Same contract as [`draw_image`].
pub(crate) unsafe fn draw_image_cached(
    ctx: CGContextRef,
    rect: Rect,
    image: &Image,
    cache: &mut ImageCache<CGImage>,
    scale: f32,
) -> ImagePaintResult {
    if rect.width <= 0.0 || rect.height <= 0.0 {
        return ImagePaintResult::Unsupported;
    }
    let source = &image.source;
    // Width/height pinned to `0`, not the target rect's real size: this
    // decode is reused verbatim at every paint size (see the module
    // docs' "Decode cache" section) — the [`ImageCache`] key still needs
    // *some* size to stay shape-compatible with every other backend's
    // call, so a constant stands in for "doesn't vary."
    let Some(cg_image) = cache.get_or_decode(source, 0, 0, scale, || decode_image(source)) else {
        return ImagePaintResult::Unsupported;
    };
    paint_cg_image(ctx, rect, image, cg_image)
}

// ImageIO has no binding in the `core-graphics`/`core-foundation` crates
// this crate already depends on — see the module doc's "Why raw FFI"
// section. `options` is always passed as `NULL` here (no thumbnail /
// orientation hints needed for this rasteriser's decode-then-paint use),
// so it's typed as the real `CFDictionaryRef` for signature accuracy
// without this module ever constructing one.
#[link(name = "ImageIO", kind = "framework")]
extern "C" {
    fn CGImageSourceCreateWithDataProvider(
        provider: CGDataProviderRef,
        options: CFDictionaryRef,
    ) -> CGImageSourceRef;
    fn CGImageSourceCreateImageAtIndex(
        isrc: CGImageSourceRef,
        index: usize,
        options: CFDictionaryRef,
    ) -> CGImageRef;
}

// Linked transitively via `core-graphics` — same pattern every other
// `macos::*` rasteriser's raw CG FFI block uses (see e.g.
// `macos::minimap`'s own `extern "C"` block). `CGContextTranslateCTM`/
// `CGContextScaleCTM` implement the counter-flip documented on
// `draw_image` above — the same pair `headless::BitmapSurface::new` and
// `macos::text::draw_text_impl`'s callers use for their own CTM/text-
// matrix flips.
extern "C" {
    fn CGContextDrawImage(c: CGContextRef, rect: CGRect, image: CGImageRef);
    fn CGContextTranslateCTM(c: CGContextRef, tx: CGFloat, ty: CGFloat);
    fn CGContextScaleCTM(c: CGContextRef, sx: CGFloat, sy: CGFloat);
}

#[cfg(test)]
mod tests {
    use super::super::headless::BitmapSurface;
    use super::*;
    use crate::primitives::image::ImageFit;
    use crate::types::WidgetId;

    const W: u32 = 200;
    const H: u32 = 200;

    /// A tiny solid-colour PNG, generated at test time rather than
    /// checked in as a binary fixture — same approach
    /// `win::image::tests::tiny_png_bytes` takes (itself mirroring
    /// `gtk::image::tests::tiny_png_bytes`), just re-derived here so this
    /// module has no cross-backend test dependency.
    fn tiny_png_bytes() -> Vec<u8> {
        // Hand-rolled minimal 4x4 opaque-red PNG: a real decoder
        // (ImageIO) must parse this from scratch, so this is not a
        // stand-in for a "loads bytes" no-op — it exercises the actual
        // decode path.
        //
        // `clippy::same_item_push` misreads the filter-byte push as a
        // "replace this loop with vec![0; N]" candidate — the loop body
        // also appends the row's actual pixel bytes right after it, so
        // that rewrite doesn't apply.
        #[allow(clippy::same_item_push)]
        let raw = {
            let mut raw = Vec::new();
            for _ in 0..4 {
                raw.push(0u8);
                for _ in 0..4 {
                    raw.extend_from_slice(&[0xff, 0x00, 0x00]);
                }
            }
            raw
        };
        png_from_rows(&raw)
    }

    /// A 4x4 PNG that is deliberately *not* symmetric top-to-bottom: rows
    /// 0-1 (the top of the raster, in file order) are opaque red, rows
    /// 2-3 (the bottom) are opaque blue. `tiny_png_bytes`'s uniform
    /// solid colour can't distinguish right-side-up from upside-down —
    /// swapping the two halves would still pass every assertion built on
    /// it. This fixture exists so
    /// [`draw_image_orientation_matches_raster_row_order`] actually fails
    /// if `draw_image`'s counter-flip (see the module docs) is missing
    /// or backwards.
    fn two_tone_png_bytes() -> Vec<u8> {
        let mut raw = Vec::new();
        for row in 0..4u32 {
            raw.push(0u8); // filter byte: None
            let colour: [u8; 3] = if row < 2 {
                [0xff, 0x00, 0x00] // top half: red
            } else {
                [0x00, 0x00, 0xff] // bottom half: blue
            };
            for _ in 0..4 {
                raw.extend_from_slice(&colour);
            }
        }
        png_from_rows(&raw)
    }

    /// Wrap `raw` (already-filtered 4x4 RGB scanline bytes, 8-bit,
    /// no interlace) in a minimal PNG container — the shared plumbing
    /// behind [`tiny_png_bytes`] and [`two_tone_png_bytes`].
    fn png_from_rows(raw: &[u8]) -> Vec<u8> {
        let mut png = Vec::new();
        png.extend_from_slice(b"\x89PNG\r\n\x1a\n");

        fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
            out.extend_from_slice(&(data.len() as u32).to_be_bytes());
            let mut body = Vec::with_capacity(4 + data.len());
            body.extend_from_slice(kind);
            body.extend_from_slice(data);
            out.extend_from_slice(&body);
            out.extend_from_slice(&crc32(&body).to_be_bytes());
        }

        // IHDR: 4x4, 8-bit depth, colour type 2 (RGB), no interlace.
        let mut ihdr = Vec::new();
        ihdr.extend_from_slice(&4u32.to_be_bytes());
        ihdr.extend_from_slice(&4u32.to_be_bytes());
        ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
        chunk(&mut png, b"IHDR", &ihdr);

        // IDAT: `raw`'s scanlines, zlib-wrapped with a stored
        // (uncompressed) block.
        let idat = zlib_store(raw);
        chunk(&mut png, b"IDAT", &idat);

        chunk(&mut png, b"IEND", &[]);
        png
    }

    /// Zlib container with a single stored (uncompressed) deflate block —
    /// enough for ImageIO's PNG decoder to accept, no compression needed
    /// for a 4x4 fixture.
    fn zlib_store(data: &[u8]) -> Vec<u8> {
        let mut out = vec![0x78, 0x01]; // zlib header (no compression)
        let len = data.len() as u16;
        out.push(1); // BFINAL=1, BTYPE=00 (stored)
        out.extend_from_slice(&len.to_le_bytes());
        out.extend_from_slice(&(!len).to_le_bytes());
        out.extend_from_slice(data);
        out.extend_from_slice(&adler32(data).to_be_bytes());
        out
    }

    fn adler32(data: &[u8]) -> u32 {
        let mut a: u32 = 1;
        let mut b: u32 = 0;
        for &byte in data {
            a = (a + byte as u32) % 65521;
            b = (b + a) % 65521;
        }
        (b << 16) | a
    }

    fn crc32(data: &[u8]) -> u32 {
        let mut crc: u32 = 0xFFFF_FFFF;
        for &byte in data {
            crc ^= byte as u32;
            for _ in 0..8 {
                let mask = (crc & 1).wrapping_neg();
                crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
            }
        }
        !crc
    }

    fn image(source: ImageSource, fit: ImageFit) -> Image {
        Image {
            id: WidgetId::new("logo"),
            source,
            intrinsic_size: Some((4, 4)),
            fit,
            fallback_text: "[LOGO]".into(),
        }
    }

    fn cache() -> ImageCache<CGImage> {
        ImageCache::with_capacity(4)
    }

    /// A decodable source must paint pixels and report `Painted`.
    #[test]
    fn draw_image_from_bytes_paints_real_pixels() {
        let surface = BitmapSurface::new(W, H);
        surface.fill(1.0, 1.0, 1.0, 1.0);

        let img = image(ImageSource::Bytes(tiny_png_bytes()), ImageFit::Fill);
        let rect = Rect::new(20.0, 20.0, 60.0, 60.0);

        // SAFETY: `surface.context_ptr()` is valid for the surface's
        // lifetime, which outlives this call.
        let result = unsafe { draw_image(surface.context_ptr(), rect, &img) };

        assert_eq!(result, ImagePaintResult::Painted);
        let (r, g, b, _) = surface.pixel(50, 50);
        assert_eq!((r, g, b), (255, 0, 0), "decoded PNG should be red");

        // Outside the target rect: untouched.
        let (r, g, b, _) = surface.pixel(5, 5);
        assert_eq!(
            (r, g, b),
            (255, 255, 255),
            "painting must not bleed outside the target rect"
        );
    }

    /// Corrupt or missing sources must degrade to `Unsupported`
    /// rather than panicking.
    #[test]
    fn draw_image_from_missing_path_reports_unsupported() {
        let surface = BitmapSurface::new(W, H);
        let img = image(
            ImageSource::Path("/nonexistent/does-not-exist.png".into()),
            ImageFit::Contain,
        );
        // SAFETY: surface context valid for this call.
        let result =
            unsafe { draw_image(surface.context_ptr(), Rect::new(0.0, 0.0, 40.0, 40.0), &img) };
        assert_eq!(result, ImagePaintResult::Unsupported);
    }

    #[test]
    fn draw_image_from_corrupt_bytes_reports_unsupported() {
        let surface = BitmapSurface::new(W, H);
        let img = image(ImageSource::Bytes(vec![0, 1, 2, 3]), ImageFit::Contain);
        // SAFETY: surface context valid for this call.
        let result =
            unsafe { draw_image(surface.context_ptr(), Rect::new(0.0, 0.0, 40.0, 40.0), &img) };
        assert_eq!(result, ImagePaintResult::Unsupported);
    }

    #[test]
    fn zero_size_rect_reports_unsupported_without_decoding() {
        let surface = BitmapSurface::new(W, H);
        let img = image(ImageSource::Bytes(tiny_png_bytes()), ImageFit::Contain);
        // SAFETY: surface context valid for this call.
        let result =
            unsafe { draw_image(surface.context_ptr(), Rect::new(0.0, 0.0, 0.0, 0.0), &img) };
        assert_eq!(result, ImagePaintResult::Unsupported);
    }

    #[test]
    fn draw_image_cached_from_bytes_paints_real_pixels() {
        let surface = BitmapSurface::new(W, H);
        surface.fill(1.0, 1.0, 1.0, 1.0);

        let img = image(ImageSource::Bytes(tiny_png_bytes()), ImageFit::Fill);
        let rect = Rect::new(20.0, 20.0, 60.0, 60.0);

        // SAFETY: `surface.context_ptr()` is valid for the surface's
        // lifetime, which outlives this call.
        let result =
            unsafe { draw_image_cached(surface.context_ptr(), rect, &img, &mut cache(), 1.0) };

        assert_eq!(result, ImagePaintResult::Painted);
        let (r, g, b, _) = surface.pixel(50, 50);
        assert_eq!((r, g, b), (255, 0, 0), "decoded PNG should be red");
    }

    #[test]
    fn draw_image_cached_from_missing_path_reports_unsupported() {
        let surface = BitmapSurface::new(W, H);
        let img = image(
            ImageSource::Path("/nonexistent/does-not-exist.png".into()),
            ImageFit::Contain,
        );
        // SAFETY: surface context valid for this call.
        let result = unsafe {
            draw_image_cached(
                surface.context_ptr(),
                Rect::new(0.0, 0.0, 40.0, 40.0),
                &img,
                &mut cache(),
                1.0,
            )
        };
        assert_eq!(result, ImagePaintResult::Unsupported);
    }

    #[test]
    fn draw_image_cached_zero_size_rect_reports_unsupported_without_decoding() {
        let surface = BitmapSurface::new(W, H);
        let img = image(ImageSource::Bytes(tiny_png_bytes()), ImageFit::Contain);
        // SAFETY: surface context valid for this call.
        let result = unsafe {
            draw_image_cached(
                surface.context_ptr(),
                Rect::new(0.0, 0.0, 0.0, 0.0),
                &img,
                &mut cache(),
                1.0,
            )
        };
        assert_eq!(result, ImagePaintResult::Unsupported);
    }

    /// A cache hit must skip re-decoding entirely — this
    /// backend keys on source alone (see the module docs' "Decode cache"
    /// section), so painting the *same* source at two different target
    /// sizes should still hit the cache the second time. Proven the same
    /// way `gtk::image`'s equivalent test is: corrupt the on-disk source
    /// between calls and confirm the second paint still succeeds.
    #[test]
    fn cached_decode_survives_source_becoming_unreadable_on_disk() {
        let path = std::env::temp_dir().join(format!(
            "quadraui_macos_image_cache_test_{}_{}.png",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system clock")
                .as_nanos()
        ));
        std::fs::write(&path, tiny_png_bytes()).expect("write tiny png fixture");

        let surface = BitmapSurface::new(W, H);
        let mut shared_cache = cache();
        let img = image(ImageSource::Path(path.clone()), ImageFit::Contain);

        // SAFETY: surface context valid for this call.
        let first = unsafe {
            draw_image_cached(
                surface.context_ptr(),
                Rect::new(0.0, 0.0, 40.0, 40.0),
                &img,
                &mut shared_cache,
                1.0,
            )
        };
        assert_eq!(
            first,
            ImagePaintResult::Painted,
            "first decode should succeed"
        );

        // Corrupt the file in place — a fresh decode from this point on
        // would fail.
        std::fs::write(&path, b"not a png").expect("corrupt fixture on disk");

        // Different target size too — this backend's cache key ignores
        // size (see the module docs), so this must still hit the cache.
        // SAFETY: surface context valid for this call.
        let second = unsafe {
            draw_image_cached(
                surface.context_ptr(),
                Rect::new(0.0, 0.0, 80.0, 80.0),
                &img,
                &mut shared_cache,
                1.0,
            )
        };
        assert_eq!(
            second,
            ImagePaintResult::Painted,
            "second draw must hit the cache rather than re-decoding the now-corrupt file"
        );

        let _ = std::fs::remove_file(&path);
    }

    /// `ImageFit::Cover` can extend past `rect` on one axis — painting
    /// must still stay clipped to it, mirroring `win::image`'s and
    /// `gtk::image`'s own clip contract.
    #[test]
    fn cover_fit_is_clipped_to_rect() {
        let surface = BitmapSurface::new(W, H);
        surface.fill(1.0, 1.0, 1.0, 1.0);

        // Square 4x4 source over a tall, narrow (10x30) rect: `Cover`
        // scales up until the rect's *taller* axis (height) is filled —
        // 7.5x — which drives the resulting square target well past the
        // rect's narrow width on both sides.
        let img = image(ImageSource::Bytes(tiny_png_bytes()), ImageFit::Cover);
        let rect = Rect::new(90.0, 50.0, 10.0, 30.0);

        // SAFETY: surface context valid for this call.
        let result = unsafe { draw_image(surface.context_ptr(), rect, &img) };
        assert_eq!(result, ImagePaintResult::Painted);

        // `Cover` scales the 4x4 source by 7.5x (30 / 4, the taller axis)
        // to a 30x30 target centered on the rect: x in [80, 110], vs. the
        // clip rect's x in [90, 100]. (85, 65) and (105, 65) sit inside
        // the *unclipped* target but outside the clip rect, so a missing
        // or broken clip would paint red there instead of background.
        for (x, y) in [(85u32, 65u32), (105, 65)] {
            let (r, g, b, _) = surface.pixel(x, y);
            assert_eq!(
                (r, g, b),
                (255, 255, 255),
                "Cover fit must not bleed past the clip rect at ({x}, {y})"
            );
        }

        // Inside the clip rect: the image did paint.
        let (r, g, b, _) = surface.pixel(95, 65);
        assert_eq!(
            (r, g, b),
            (255, 0, 0),
            "expected the image inside the clip rect"
        );
    }

    /// Without the counter-flip documented on `draw_image` (mirroring
    /// `macos::text::draw_text_impl`'s text-matrix flip),
    /// `CGContextDrawImage` paints upside down inside this backend's
    /// permanently-flipped, top-left-origin context. `tiny_png_bytes`'s
    /// uniform fill cannot detect orientation — a mirrored image is
    /// pixel-for-pixel identical to the original along any horizontal
    /// scanline. `two_tone_png_bytes` (red top half, blue bottom half in
    /// raster row order) fails this assertion if the flip is missing or
    /// backwards.
    #[test]
    fn draw_image_orientation_matches_raster_row_order() {
        let surface = BitmapSurface::new(W, H);
        surface.fill(1.0, 1.0, 1.0, 1.0);

        let img = image(ImageSource::Bytes(two_tone_png_bytes()), ImageFit::Fill);
        let rect = Rect::new(20.0, 20.0, 60.0, 60.0);

        // SAFETY: surface context valid for this call.
        let result = unsafe { draw_image(surface.context_ptr(), rect, &img) };
        assert_eq!(result, ImagePaintResult::Painted);

        // Near the top of the target rect: the raster's top half (red).
        let (r, g, b, _) = surface.pixel(50, 25);
        assert_eq!(
            (r, g, b),
            (255, 0, 0),
            "top of the painted rect should show the raster's top-half colour (red) — \
             a mirrored/upside-down paint would show blue here instead"
        );

        // Near the bottom of the target rect: the raster's bottom half
        // (blue).
        let (r, g, b, _) = surface.pixel(50, 75);
        assert_eq!(
            (r, g, b),
            (0, 0, 255),
            "bottom of the painted rect should show the raster's bottom-half colour (blue) — \
             a mirrored/upside-down paint would show red here instead"
        );
    }
}