skia-canvas 0.1.0

GPU-accelerated, multi-threaded HTML Canvas-compatible 2D rendering for Rust and Node, powered by Skia.
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
#![allow(unexpected_cfgs)]
use metal::{
    CommandQueue, Device, MTLDeviceLocation, MTLPixelFormat, MetalLayer,
    foreign_types::{ForeignType, ForeignTypeRef},
};
use objc::rc::autoreleasepool;
use serde_json::{Value, json};
use skia_safe::{
    ColorType, Image, ImageInfo, Size, Surface,
    gpu::{
        Budgeted, DirectContext, SurfaceOrigin, backend_render_targets, direct_contexts, mtl,
        surfaces,
    },
    scalar,
};
use std::{
    cell::RefCell,
    sync::{Arc, OnceLock},
    time::{Duration, Instant},
};

use crate::context::page::ExportOptions;

thread_local!(
    static MTL_CONTEXT: RefCell<Option<MetalContext>> = const { RefCell::new(None) };
);
static MTL_CONTEXT_LIFESPAN: Duration = Duration::from_secs(5);
static MTL_STATUS: OnceLock<Value> = OnceLock::new();

//
// Offscreen rendering
//
pub struct MetalEngine {}

impl MetalEngine {
    pub fn api() -> Option<String> {
        Some("Metal".to_string())
    }

    pub fn supported() -> bool {
        Self::status()["renderer"] == "GPU"
    }

    pub fn status() -> Value {
        MTL_STATUS
            .get_or_init(|| {
                // test whether a context can be created and do some one-time
                // init if so
                match MetalContext::new() {
                    Some(context) => {
                        Self::spawn_idle_watcher(); // watch for inactive contexts and deallocate them

                        let device_name = format!(
                            "{} ({})",
                            match context.device.location() {
                                MTLDeviceLocation::BuiltIn => "Integrated GPU",
                                MTLDeviceLocation::Slot => "Discrete GPU",
                                MTLDeviceLocation::External => "External GPU",
                                _ => "Other GPU",
                            },
                            context.device.name()
                        );

                        json!({
                            "renderer": "GPU",
                            "api": "Metal",
                            "device": device_name,
                            "threads": rayon::current_num_threads(),
                        })
                    }
                    None => json!({
                        "renderer": "CPU",
                        "api": "Metal",
                        "device": "CPU-based renderer (Fallback)",
                        "threads": rayon::current_num_threads(),
                        "error": "GPU initialization failed",
                    }),
                }
            })
            .clone()
    }

    fn spawn_idle_watcher() {
        // use a non-rayon thread so as not to compete with the worker threads
        std::thread::spawn(move || {
            loop {
                // run forever, watching the other threads in the pool
                std::thread::sleep(Duration::from_secs(1));
                rayon::spawn_broadcast(|_| {
                    // drop contexts that haven't been used in a while to free
                    // resources
                    MTL_CONTEXT.with_borrow_mut(|cell| {
                        cell.take_if(|engine| {
                            engine.cleanup(); // it's unclear how effective this is...
                            engine.last_use.elapsed() > MTL_CONTEXT_LIFESPAN
                        });
                    });
                });
            }
        });
    }

    pub fn with_context<T, F>(f: F) -> Result<T, String>
    where
        F: FnOnce(&mut MetalContext) -> Result<T, String>,
    {
        match MetalEngine::supported() {
            false => Err("Metal API not supported".to_string()),
            true => MTL_CONTEXT.with_borrow_mut(|local_ctx| {
                autoreleasepool(||
                    // lazily initialize this thread's context...
                    local_ctx
                        .take()
                        .or_else(|| MetalContext::new() )
                        .ok_or("Metal initialization failed".to_string())
                        .and_then(|ctx|{
                            f(local_ctx.insert(ctx))
                        }))
            }),
        }
    }

    pub fn with_direct_context<F>(f: F)
    where
        F: FnOnce(Option<&mut DirectContext>),
    {
        Self::with_context(|ctx| Ok(f(Some(&mut ctx.context)))).ok();
    }

    pub fn make_surface(image_info: &ImageInfo, opts: &ExportOptions) -> Result<Surface, String> {
        Self::with_context(|ctx| ctx.surface(image_info, opts))
    }
}

pub struct MetalContext {
    device: Device,
    context: DirectContext,
    msaa: Vec<usize>,
    last_use: Instant,
}

impl MetalContext {
    fn new() -> Option<Self> {
        autoreleasepool(|| {
            Device::system_default().and_then(|device| {
                let queue = device.new_command_queue();
                let backend = unsafe {
                    mtl::BackendContext::new(
                        device.as_ptr() as mtl::Handle,
                        queue.as_ptr() as mtl::Handle,
                    )
                };
                let last_use = Instant::now() + MTL_CONTEXT_LIFESPAN;
                let msaa: Vec<usize> = [0, 2, 4, 8, 16, 32]
                    .into_iter()
                    .filter(|s| *s == 0 || device.supports_texture_sample_count(*s as _))
                    .collect();
                direct_contexts::make_metal(&backend, None).map(|context| MetalContext {
                    device,
                    context,
                    msaa,
                    last_use,
                })
            })
        })
    }

    fn surface(&mut self, image_info: &ImageInfo, opts: &ExportOptions) -> Result<Surface, String> {
        self.last_use = self.last_use.max(Instant::now());
        surfaces::render_target(
            &mut self.context,
            Budgeted::Yes,
            image_info,
            Some(opts.msaa_from(&self.msaa)?),
            SurfaceOrigin::BottomLeft,
            Some(&opts.surface_props()),
            false,
            None,
        )
        .ok_or(format!(
            "Could not allocate new {}Ă—{} bitmap (color type: {:?})",
            image_info.width(),
            image_info.height(),
            image_info.color_type()
        ))
    }

    fn cleanup(&mut self) {
        self.context.free_gpu_resources();
        self.context
            .perform_deferred_cleanup(Duration::from_secs(1), None);
    }
}

//
// Windowed rendering
//

#[cfg(feature = "window")]
use {
    super::{RenderCache, RenderState::Resizing},
    crate::context::page::Page,
    core_graphics_types::geometry::CGSize,
    objc::{
        msg_send,
        runtime::{self, Object},
        sel, sel_impl,
    },
    raw_window_metal::Layer,
    skia_safe::{Color, Matrix, Paint, SurfaceProps, canvas::SrcRectConstraint},
    winit::{
        dpi::PhysicalSize,
        event_loop::ActiveEventLoop,
        raw_window_handle::{HasWindowHandle, RawWindowHandle},
        window::Window,
    },
};

#[allow(non_upper_case_globals)]
#[link(name = "QuartzCore", kind = "framework")]
unsafe extern "C" {
    static kCAGravityTopLeft: *mut Object;
    static kCAGravityBottomLeft: *mut Object;
}

#[cfg(feature = "window")]
pub struct MetalRenderer {
    window: Arc<Window>,
    backend: MetalBackend,
    layer: MetalLayer,
    cache: RenderCache,
}

#[cfg(feature = "window")]
impl MetalRenderer {
    pub fn for_window(_event_loop: &ActiveEventLoop, window: Arc<Window>) -> Self {
        // SAFETY: Metal is always available on supported macOS hardware.
        let device = Device::system_default().expect("Metal device not found");

        let raw_window = window
            .window_handle()
            // SAFETY: Window handle is always available for active windows.
            .expect("Failed to retrieve a window handle")
            .as_raw();

        let raw_layer = match raw_window {
            RawWindowHandle::AppKit(handle) => unsafe { Layer::from_ns_view(handle.ns_view) },
            RawWindowHandle::UiKit(handle) => unsafe { Layer::from_ui_view(handle.ui_view) },
            _ => panic!("Unsupported window handle type"),
        };

        let layer = unsafe {
            let mtl_layer = MetalLayer::from_ptr(raw_layer.into_raw().as_ptr().cast());
            let gravity = match msg_send![mtl_layer.as_ptr(), contentsAreFlipped] {
                runtime::YES => kCAGravityBottomLeft,
                _ => kCAGravityTopLeft,
            };
            let _: () = msg_send![mtl_layer.as_ptr(), setContentsGravity: gravity];
            mtl_layer
        };
        layer.set_device(&device);
        layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
        layer.set_presents_with_transaction(false);
        layer.set_display_sync_enabled(true);
        layer.set_opaque(false);
        layer.set_framebuffer_only(false); // to enable blend modes

        let draw_size = window.inner_size();
        layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64));

        let backend = MetalBackend::for_layer(&layer);
        let cache = RenderCache::default();

        Self {
            window,
            layer,
            backend,
            cache,
        }
    }

    pub fn resize(&mut self, size: PhysicalSize<u32>) {
        let cg_size = CGSize::new(size.width as f64, size.height as f64);
        self.layer.set_drawable_size(cg_size);
        self.cache.state = Resizing;
    }

    pub fn draw(&mut self, page: Page, matrix: Matrix, props: SurfaceProps, matte: Color) {
        let (clip, _) = matrix.map_rect(page.bounds);
        let dpr = self.window.scale_factor() as f32;
        let sync = self.cache.state == Resizing;

        let frame =
            self.backend
                .render_to_layer(&self.layer, &self.window, sync, &props, |canvas| {
                    // draw background (either use raster cache or set to
                    // window’s background color)
                    canvas.clear(Color::TRANSPARENT);
                    if let Some((image, src, dst)) = self.cache.validate(&page, matte, dpr, clip) {
                        canvas.draw_image_rect(
                            image,
                            Some((src, SrcRectConstraint::Strict)),
                            dst,
                            &Paint::default(),
                        );
                    } else {
                        canvas.clear(matte);
                    }

                    // draw newly added vector layers
                    canvas.scale((dpr, dpr)).clip_rect(clip, None, Some(true));
                    for pict in page.layers.iter().skip(self.cache.depth()) {
                        canvas.draw_picture(pict, Some(&matrix), None);
                    }
                });

        match frame {
            Ok(frame) => self.cache.update(frame, &page, matte, dpr, clip),
            Err(e) => eprintln!("MetalRenderer: draw failed: {}", e),
        }
    }
}

pub struct MetalBackend {
    skia_ctx: DirectContext,
    queue: CommandQueue,
}

impl Drop for MetalBackend {
    fn drop(&mut self) {
        self.skia_ctx.abandon();
    }
}

impl MetalBackend {
    pub fn for_layer(layer: &MetalLayer) -> Self {
        let queue = layer.device().new_command_queue();
        let backend_ctx = unsafe {
            mtl::BackendContext::new(
                layer.device().as_ptr() as mtl::Handle,
                queue.as_ptr() as mtl::Handle,
            )
        };
        let skia_ctx = direct_contexts::make_metal(&backend_ctx, None)
            // SAFETY: Metal context creation only fails on unsupported hardware.
            .expect("Failed to create Metal Skia context");
        Self { skia_ctx, queue }
    }

    fn render_to_layer<F>(
        &mut self,
        layer: &MetalLayer,
        window: &Window,
        sync: bool,
        props: &SurfaceProps,
        f: F,
    ) -> Result<Image, String>
    where
        F: FnOnce(&skia_safe::Canvas),
    {
        let drawable = layer
            .next_drawable()
            .ok_or("MetalBackend: could not allocate framebuffer".to_string())?;

        let drawable_size = {
            let size = layer.drawable_size();
            Size::new(size.width as scalar, size.height as scalar)
        };

        let backend_render_target = unsafe {
            let texture_info = mtl::TextureInfo::new(drawable.texture().as_ptr() as mtl::Handle);
            backend_render_targets::make_mtl(
                (drawable_size.width as i32, drawable_size.height as i32),
                &texture_info,
            )
        };

        let mut surface = surfaces::wrap_backend_render_target(
            &mut self.skia_ctx,
            &backend_render_target,
            SurfaceOrigin::TopLeft,
            ColorType::BGRA8888,
            None,
            Some(props),
        )
        .ok_or("MetalBackend: could not create render target")?;

        // pass the suface's canvas to the user-provided callback
        f(surface.canvas());

        self.skia_ctx.flush_and_submit();
        self.skia_ctx.free_gpu_resources();

        window.pre_present_notify();
        let command_buffer = self.queue.new_command_buffer();
        command_buffer.present_drawable(drawable);
        command_buffer.commit();

        // during resizes, ensure drawing is complete before returning
        if sync {
            command_buffer.wait_until_completed();
        }

        Ok(surface.image_snapshot())
    }
}