Skip to main content

ferroui_quartz/
lib.rs

1//! Apple system text/drawing backend for macOS 13+ and iOS 16+, with direct Metal GPU rendering.
2#![cfg(any(target_os = "macos", target_os = "ios"))]
3mod bitmap;
4#[cfg(feature = "runtime-shaders")]
5mod custom_shaders;
6#[cfg(feature = "metal")]
7mod external_objects;
8mod writeable_bitmap;
9#[cfg(feature = "metal")]
10pub use external_objects::SharedMetalImage;
11#[cfg(feature = "metal")]
12mod metal;
13#[cfg(feature = "metal")]
14pub use metal::statistics as metal_statistics;
15#[cfg(feature = "metal")]
16pub use metal::submission_count as metal_submission_count;
17mod drawing;
18mod ffi;
19mod fonts;
20pub use fonts::{FontManager as QuartzFontManager, TextShaper as QuartzTextShaper};
21mod geometry;
22mod path_measure;
23mod png_compression;
24mod region;
25use bitmap::Bitmap;
26use drawing::GlyphRun;
27use ferroui_base::{
28    media::{
29        imaging::BitmapInterpolationMode, text_formatting::GlyphInfo, FillRule,
30        GeometryCombineMode, GlyphRun as MediaGlyphRun, GlyphTypeface,
31    },
32    platform::*,
33    FerroLocator, PixelSize, Point, Rect, Vector,
34};
35use ferroui_controls::AppBuilder;
36use geometry::{Builder, Geometry};
37use kurbo::BezPath;
38use std::{
39    io::{self, Read},
40    rc::Rc,
41    sync::Arc,
42};
43
44#[cfg(not(feature = "metal"))]
45use ferroui_base::platform::surfaces::*;
46#[cfg(not(feature = "metal"))]
47use std::any::{Any, TypeId};
48
49/// Whether the OS provides the public path APIs used by Quartz.
50pub fn is_quartz_supported() -> bool {
51    unsafe { ffi::q_supported() != 0 }
52}
53
54pub trait QuartzApplicationExtensions {
55    fn use_quartz(&self) -> AppBuilder;
56}
57impl QuartzApplicationExtensions for AppBuilder {
58    fn use_quartz(&self) -> AppBuilder {
59        if !is_quartz_supported() {
60            eprintln!("Quartz requires macOS 13+ or iOS 16+");
61            return self.clone();
62        }
63        self.use_rendering_subsystem(
64            || {
65                FerroLocator::current_mutable()
66                    .bind::<dyn IPlatformRenderInterface>()
67                    .to_constant(Rc::new(QuartzRenderInterface) as Rc<dyn IPlatformRenderInterface>)
68                    .bind::<dyn IFontManagerImpl>()
69                    .to_constant(Rc::new(fonts::FontManager::default()) as Rc<dyn IFontManagerImpl>);
70            },
71            if cfg!(feature = "metal") { "QuartzMetal" } else { "Quartz" },
72        )
73        .use_text_shaping_subsystem(
74            || {
75                FerroLocator::current_mutable()
76                    .bind::<dyn ITextShaperImpl>()
77                    .to_constant(Rc::new(fonts::TextShaper) as Rc<dyn ITextShaperImpl>);
78            },
79            "CoreText",
80        )
81    }
82}
83pub struct QuartzRenderInterface;
84fn resized(
85    stream: &mut dyn Read,
86    dimension: i32,
87    width: bool,
88    mode: BitmapInterpolationMode,
89) -> io::Result<Bitmap> {
90    if dimension <= 0 {
91        return Err(io::Error::new(
92            io::ErrorKind::InvalidInput,
93            "Decode dimension must be positive",
94        ));
95    }
96    let bitmap = Bitmap::decode(stream)?;
97    let s = bitmap.pixel_size();
98    let size = if width {
99        PixelSize::new(
100            dimension,
101            (s.height as f64 * dimension as f64 / s.width as f64)
102                .floor()
103                .max(1.) as i32,
104        )
105    } else {
106        PixelSize::new(
107            (s.width as f64 * dimension as f64 / s.height as f64)
108                .floor()
109                .max(1.) as i32,
110            dimension,
111        )
112    };
113    Ok(Bitmap::resized(&bitmap, size, mode))
114}
115impl IPlatformRenderInterface for QuartzRenderInterface {
116    fn create_ellipse_geometry(&self, r: Rect) -> Arc<dyn IGeometryImpl> {
117        Geometry::ellipse(r)
118    }
119    fn create_line_geometry(&self, a: Point, b: Point) -> Arc<dyn IGeometryImpl> {
120        let mut p = BezPath::new();
121        p.move_to((a.x, a.y));
122        p.line_to((b.x, b.y));
123        Geometry::paths(p, None, FillRule::NonZero)
124    }
125    fn create_rectangle_geometry(&self, r: Rect) -> Arc<dyn IGeometryImpl> {
126        Geometry::rectangle(r)
127    }
128    fn create_stream_geometry_builder(
129        &self,
130        s: Option<&dyn IGeometryImpl>,
131    ) -> Box<dyn IStreamGeometryBuilder> {
132        Box::new(Builder::new(s))
133    }
134    fn create_geometry_group(
135        &self,
136        rule: FillRule,
137        children: &[Arc<dyn IGeometryImpl>],
138    ) -> Arc<dyn IGeometryImpl> {
139        let mut stroke = BezPath::new();
140        let mut fill = BezPath::new();
141        for child in children {
142            let g = child
143                .as_any()
144                .downcast_ref::<Geometry>()
145                .expect("Quartz geometry group requires Quartz children");
146            stroke.extend(g.stroke.elements().iter().copied());
147            if let Some(p) = &g.fill {
148                fill.extend(p.elements().iter().copied())
149            }
150        }
151        Geometry::paths(stroke, Some(fill), rule)
152    }
153    fn create_combined_geometry(
154        &self,
155        m: GeometryCombineMode,
156        a: Arc<dyn IGeometryImpl>,
157        b: Arc<dyn IGeometryImpl>,
158    ) -> Arc<dyn IGeometryImpl> {
159        Geometry::combine(&*a, &*b, m)
160    }
161    fn build_glyph_run_geometry(&self, g: &MediaGlyphRun) -> Arc<dyn IGeometryImpl> {
162        let run = g.platform_impl();
163        let run = run
164            .as_any()
165            .downcast_ref::<GlyphRun>()
166            .expect("Quartz glyph run");
167        Geometry::new(run.outlines().clone(), FillRule::NonZero)
168    }
169    fn create_glyph_run(
170        &self,
171        f: &Rc<GlyphTypeface>,
172        s: f64,
173        g: &[GlyphInfo],
174        p: Point,
175    ) -> Arc<dyn IGlyphRunImpl> {
176        Arc::new(GlyphRun::new(f, s, g, p))
177    }
178    fn create_render_target_bitmap(
179        &self,
180        s: PixelSize,
181        d: Vector,
182    ) -> Arc<dyn IRenderTargetBitmapImpl> {
183        Arc::new(Bitmap::new(s, d))
184    }
185    fn create_writeable_bitmap(
186        &self,
187        s: PixelSize,
188        d: Vector,
189        f: PixelFormat,
190        a: AlphaFormat,
191    ) -> Arc<dyn IWriteableBitmapImpl> {
192        Arc::new(writeable_bitmap::WriteableBitmap::new(s, d, f, a))
193    }
194    fn load_bitmap_from_file(&self, p: &str) -> io::Result<Arc<SharedBitmapImpl>> {
195        self.load_bitmap(&mut std::fs::File::open(p)?)
196    }
197    fn load_bitmap(&self, s: &mut dyn Read) -> io::Result<Arc<SharedBitmapImpl>> {
198        Ok(Arc::new(Bitmap::decode(s)?))
199    }
200    fn load_writeable_bitmap_to_width(
201        &self,
202        s: &mut dyn Read,
203        w: i32,
204        mode: BitmapInterpolationMode,
205    ) -> io::Result<Arc<dyn IWriteableBitmapImpl>> {
206        Ok(Arc::new(resized(s, w, true, mode)?))
207    }
208    fn load_writeable_bitmap_to_height(
209        &self,
210        s: &mut dyn Read,
211        h: i32,
212        mode: BitmapInterpolationMode,
213    ) -> io::Result<Arc<dyn IWriteableBitmapImpl>> {
214        Ok(Arc::new(resized(s, h, false, mode)?))
215    }
216    fn load_writeable_bitmap_from_file(
217        &self,
218        p: &str,
219    ) -> io::Result<Arc<dyn IWriteableBitmapImpl>> {
220        self.load_writeable_bitmap(&mut std::fs::File::open(p)?)
221    }
222    fn load_writeable_bitmap(&self, s: &mut dyn Read) -> io::Result<Arc<dyn IWriteableBitmapImpl>> {
223        Ok(Arc::new(Bitmap::decode(s)?))
224    }
225    fn load_bitmap_to_width(
226        &self,
227        s: &mut dyn Read,
228        w: i32,
229        mode: BitmapInterpolationMode,
230    ) -> io::Result<Arc<SharedBitmapImpl>> {
231        Ok(Arc::new(resized(s, w, true, mode)?))
232    }
233    fn load_bitmap_to_height(
234        &self,
235        s: &mut dyn Read,
236        h: i32,
237        mode: BitmapInterpolationMode,
238    ) -> io::Result<Arc<SharedBitmapImpl>> {
239        Ok(Arc::new(resized(s, h, false, mode)?))
240    }
241    fn resize_bitmap(
242        &self,
243        b: &dyn IBitmapImpl,
244        s: PixelSize,
245        mode: BitmapInterpolationMode,
246    ) -> Arc<SharedBitmapImpl> {
247        Arc::new(Bitmap::resized(b, s, mode))
248    }
249    fn load_bitmap_from_pixels(
250        &self,
251        f: PixelFormat,
252        a: AlphaFormat,
253        data: &[u8],
254        s: PixelSize,
255        d: Vector,
256        stride: i32,
257    ) -> Arc<SharedBitmapImpl> {
258        Arc::new(Bitmap::from_pixels(f, a, data, s, d, stride))
259    }
260    fn create_backend_context(
261        &self,
262        graphics: Option<Rc<dyn IPlatformGraphicsContext>>,
263    ) -> Rc<dyn IPlatformRenderInterfaceContext> {
264        #[cfg(feature = "metal")]
265        {
266            match metal::MetalContext::new(graphics) {
267                Ok(context) => Rc::new(context),
268                Err(error) => {
269                    eprintln!("Quartz Metal unavailable: {error}");
270                    Rc::new(UnavailableContext)
271                }
272            }
273        }
274        #[cfg(not(feature = "metal"))]
275        {
276            let _ = graphics;
277            Rc::new(QuartzContext)
278        }
279    }
280    fn supports_individual_round_rects(&self) -> bool {
281        true
282    }
283    fn supports_compositing_layers(&self) -> bool {
284        true
285    }
286    fn default_alpha_format(&self) -> AlphaFormat {
287        AlphaFormat::Premul
288    }
289    fn default_pixel_format(&self) -> PixelFormat {
290        PixelFormat::BGRA8888
291    }
292    fn is_supported_bitmap_pixel_format(&self, f: PixelFormat) -> bool {
293        matches!(
294            f,
295            PixelFormat::BGRA8888 | PixelFormat::RGBA8888 | PixelFormat::RGB565
296        )
297    }
298    fn supports_regions(&self) -> bool {
299        true
300    }
301    fn create_region(&self) -> Rc<dyn IPlatformRenderInterfaceRegion> {
302        Rc::new(region::QuartzRegionImpl::new())
303    }
304}
305#[cfg(not(feature = "metal"))]
306struct QuartzContext;
307#[cfg(not(feature = "metal"))]
308impl IOptionalFeatureProvider for QuartzContext {
309    fn try_get_feature(&self, _: TypeId) -> Option<Rc<dyn Any>> {
310        None
311    }
312}
313#[cfg(not(feature = "metal"))]
314impl IPlatformRenderInterfaceContext for QuartzContext {
315    fn is_ready_to_create_render_target(
316        &self,
317        surfaces: &[Arc<dyn IPlatformRenderSurface>],
318    ) -> bool {
319        surfaces
320            .iter()
321            .any(|surface| surface.as_framebuffer_surface().is_some() && surface.is_ready())
322    }
323    fn create_render_target(
324        &self,
325        surfaces: &[Arc<dyn IPlatformRenderSurface>],
326    ) -> Rc<dyn IRenderTarget> {
327        for s in surfaces {
328            if let Some(f) = s.as_framebuffer_surface() {
329                return Rc::new(Target(f.create_framebuffer_render_target()));
330            }
331        }
332        Rc::new(UnavailableTarget)
333    }
334    fn create_offscreen_render_target(
335        &self,
336        s: PixelSize,
337        scaling: Vector,
338        _: bool,
339    ) -> Rc<dyn IDrawingContextLayerImpl> {
340        Rc::new(Bitmap::new(s, scaling * 96.0))
341    }
342    fn is_lost(&self) -> bool {
343        false
344    }
345    fn max_offscreen_render_target_pixel_size(&self) -> Option<PixelSize> {
346        Some(PixelSize::new(16384, 16384))
347    }
348    fn dispose(&self) {}
349}
350#[cfg(not(feature = "metal"))]
351struct Target(Rc<dyn IFramebufferRenderTarget>);
352#[cfg(not(feature = "metal"))]
353impl IRenderTarget for Target {
354    fn properties(&self) -> RenderTargetProperties {
355        RenderTargetProperties {
356            retains_previous_frame_contents: self.0.retains_frame_contents(),
357            is_suitable_for_direct_rendering: true,
358        }
359    }
360    fn create_drawing_context(
361        &self,
362        scene: &RenderTargetSceneInfo,
363    ) -> (
364        Box<dyn IDrawingContextImpl>,
365        RenderTargetDrawingContextProperties,
366    ) {
367        let (frame, props) = self.0.lock(scene);
368        let bitmap = Bitmap::new(frame.size(), frame.dpi());
369        frame.with_data(&mut |data| {
370            bitmap.write(&bitmap::convert(
371                data,
372                frame.row_bytes() as usize,
373                frame.size(),
374                frame.format(),
375                frame.alpha_format(),
376            ))
377        });
378        let output = bitmap.clone();
379        let done = Box::new(move || {
380            let mut bytes = output.pixels();
381            if frame.format() == PixelFormat::RGBA8888 {
382                for p in bytes.chunks_exact_mut(4) {
383                    p.swap(0, 2)
384                }
385            }
386            let row = output.pixel_size().width as usize * 4;
387            frame.with_data(&mut |data| {
388                let stride = frame.row_bytes() as usize;
389                for (y, source) in bytes.chunks_exact(row).enumerate() {
390                    data[y * stride..y * stride + row].copy_from_slice(source)
391                }
392            });
393            frame.dispose();
394        });
395        (
396            Box::new(bitmap.drawing(false, Some(done))),
397            RenderTargetDrawingContextProperties {
398                previous_frame_is_retained: props.previous_frame_is_retained,
399            },
400        )
401    }
402    fn platform_render_target_state(&self) -> PlatformRenderTargetState {
403        self.0.state()
404    }
405    fn dispose(&self) {
406        self.0.dispose()
407    }
408}
409/// GPU-only builds report unavailable surfaces instead of silently switching to CPU rendering.
410#[cfg(feature = "metal")]
411struct UnavailableContext;
412#[cfg(feature = "metal")]
413impl IOptionalFeatureProvider for UnavailableContext {
414    fn try_get_feature(&self, _: std::any::TypeId) -> Option<Rc<dyn std::any::Any>> {
415        None
416    }
417}
418#[cfg(feature = "metal")]
419impl IPlatformRenderInterfaceContext for UnavailableContext {
420    fn is_ready_to_create_render_target(
421        &self,
422        _: &[Arc<dyn ferroui_base::platform::surfaces::IPlatformRenderSurface>],
423    ) -> bool {
424        false
425    }
426    fn create_render_target(
427        &self,
428        _: &[Arc<dyn ferroui_base::platform::surfaces::IPlatformRenderSurface>],
429    ) -> Rc<dyn IRenderTarget> {
430        Rc::new(UnavailableTarget)
431    }
432    fn create_offscreen_render_target(
433        &self,
434        size: PixelSize,
435        scaling: Vector,
436        _: bool,
437    ) -> Rc<dyn IDrawingContextLayerImpl> {
438        Rc::new(Bitmap::new(size, scaling * 96.))
439    }
440    fn is_lost(&self) -> bool {
441        false
442    }
443    fn max_offscreen_render_target_pixel_size(&self) -> Option<PixelSize> {
444        Some(PixelSize::new(16384, 16384))
445    }
446    fn dispose(&self) {}
447}
448struct UnavailableTarget;
449impl IRenderTarget for UnavailableTarget {
450    fn properties(&self) -> RenderTargetProperties {
451        RenderTargetProperties::default()
452    }
453    fn create_drawing_context(
454        &self,
455        _: &RenderTargetSceneInfo,
456    ) -> (
457        Box<dyn IDrawingContextImpl>,
458        RenderTargetDrawingContextProperties,
459    ) {
460        (
461            Box::new(Bitmap::new(PixelSize::new(1, 1), Vector::new(96., 96.)).drawing(false, None)),
462            RenderTargetDrawingContextProperties::default(),
463        )
464    }
465    fn try_create_drawing_context(
466        &self,
467        _: &RenderTargetSceneInfo,
468    ) -> Result<
469        (
470            Box<dyn IDrawingContextImpl>,
471            RenderTargetDrawingContextProperties,
472        ),
473        RenderTargetError,
474    > {
475        Err(RenderTargetError::NotReady(
476            ferroui_base::RenderTargetNotReadyError::new_with_message(
477                "Quartz has no usable render surface",
478            ),
479        ))
480    }
481    fn platform_render_target_state(&self) -> PlatformRenderTargetState {
482        PlatformRenderTargetState::NOT_READY_TRY_LATER
483    }
484    fn dispose(&self) {}
485}
486#[cfg(test)]
487mod parity_tests;
488#[cfg(test)]
489mod tests;
490
491/// Creates an immutable IOSurface-backed synthetic camera frame, filled by Metal.
492/// Development-only: requires the explicit `media-test-fixtures` feature.
493#[cfg(feature = "media-test-fixtures")]
494pub fn create_media_test_buffer(sequence: u64) -> Option<ferroui_media_apple::PixelBuffer> {
495    extern "C" {
496        fn qm_fixture_buffer(sequence: u64) -> ffi::Ptr;
497    }
498    // SAFETY: the fixture returns an immutable +1 CVPixelBuffer after its GPU
499    // producer finishes. PixelBuffer owns that reference for its entire lease.
500    unsafe { ferroui_media_apple::PixelBuffer::from_owned(qm_fixture_buffer(sequence)) }
501}
502
503#[cfg(all(test, feature = "metal"))]
504mod effects_tests;