uzor-render-hub 1.2.1

uzor-render-hub: unified rendering backend hub — auto-detects GPU, instantiates the right backend (vello-gpu / vello-hybrid / wgpu-instanced / vello-cpu / tiny-skia), submits frames, collects metrics.
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Concrete [`RenderSurfaceFactory`] implementations for each backend.
//!
//! These factories live here (in the hub) rather than in the individual
//! backend crates to avoid circular dependencies: each backend crate is a
//! dependency of `uzor-render-hub`, so the backends cannot also depend on
//! `uzor-render-hub`.
//!
//! # Available factories
//!
//! | Factory | Backend | Status |
//! |---------|---------|--------|
//! | [`VelloGpuSurfaceFactory`] | `VelloGpu` | Functional |
//! | [`TinySkiaSurfaceFactory`] | `TinySkia` | Functional |
//! | [`VelloCpuSurfaceFactory`] | `VelloCpu` | Functional — pure CPU, no wgpu |
//! | [`VelloHybridSurfaceFactory`] | `VelloHybrid` | Functional — GPU init deferred to first submit |
//! | [`WgpuInstancedSurfaceFactory`] | `InstancedWgpu` | Functional — GPU init deferred to first submit |
//! | [`Canvas2dSurfaceFactory`] | web canvas | wasm32 full impl, native stub |

use uzor::layout::window::RawHandle;

use crate::{RenderBackend, RenderSurfaceFactory, SurfaceError, SurfaceSize, WindowRenderState};

#[cfg(not(target_arch = "wasm32"))]
use std::sync::Mutex;
#[cfg(not(target_arch = "wasm32"))]
use vello::{AaSupport, Renderer, RendererOptions};
#[cfg(not(target_arch = "wasm32"))]
use crate::factory::GpuDevicePool;
#[cfg(not(target_arch = "wasm32"))]
use vello::wgpu::PresentMode;
#[cfg(not(target_arch = "wasm32"))]
use winit::raw_window_handle::{RawWindowHandle, RawDisplayHandle};
#[cfg(not(target_arch = "wasm32"))]
use uzor::layout::window::SoftwarePresenter;
#[cfg(not(target_arch = "wasm32"))]
use uzor_window_desktop::SendSyncHandlePair;

// ─── Internal surface target helper (desktop only) ───────────────────────────

#[cfg(not(target_arch = "wasm32"))]
/// Minimal `HasWindowHandle + HasDisplayHandle` wrapper around raw handles.
///
/// Allows calling `GpuDevicePool::create_surface` from a copied
/// `(RawWindowHandle, RawDisplayHandle)` pair without holding a live
/// `Arc<Window>`.
///
/// # Safety
///
/// The caller must guarantee that the underlying OS window outlives every
/// `wgpu::Surface` created from this target.
struct WinitSurfaceTarget {
    window: RawWindowHandle,
    display: RawDisplayHandle,
}

// SAFETY: raw handles are plain integer/pointer values.  The underlying OS
// window and display are guaranteed to outlive the factory call (the
// `Arc<Window>` in `WinitWindowProvider` keeps them alive for the entire
// runtime duration).  No thread-local state is accessed during wgpu surface
// creation on desktop platforms (Win32, X11, Wayland).
#[cfg(not(target_arch = "wasm32"))]
unsafe impl Send for WinitSurfaceTarget {}
#[cfg(not(target_arch = "wasm32"))]
unsafe impl Sync for WinitSurfaceTarget {}

#[cfg(not(target_arch = "wasm32"))]
impl winit::raw_window_handle::HasWindowHandle for WinitSurfaceTarget {
    fn window_handle(
        &self,
    ) -> Result<winit::raw_window_handle::WindowHandle<'_>, winit::raw_window_handle::HandleError>
    {
        // SAFETY: caller guarantees the underlying window is still alive.
        Ok(unsafe { winit::raw_window_handle::WindowHandle::borrow_raw(self.window) })
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl winit::raw_window_handle::HasDisplayHandle for WinitSurfaceTarget {
    fn display_handle(
        &self,
    ) -> Result<winit::raw_window_handle::DisplayHandle<'_>, winit::raw_window_handle::HandleError>
    {
        // SAFETY: caller guarantees the underlying display is still alive.
        Ok(unsafe { winit::raw_window_handle::DisplayHandle::borrow_raw(self.display) })
    }
}

// ─── Shared GPU init helper (desktop only) ───────────────────────────────────

/// Create a `GpuDevicePool` + `RenderSurface` from a `SendSyncHandlePair`.
///
/// Shared by all GPU-backed factories (VelloGpu, VelloHybrid, WgpuInstanced).
#[cfg(not(target_arch = "wasm32"))]
fn init_gpu_surface(
    pair: &SendSyncHandlePair,
    size: SurfaceSize,
    backend: RenderBackend,
) -> Result<(GpuDevicePool, vello::util::RenderSurface<'static>, usize), SurfaceError> {
    let target = WinitSurfaceTarget {
        window: pair.0,
        display: pair.1,
    };

    let mut gpu_pool = GpuDevicePool::new();

    let surface_with_lifetime = pollster::block_on(gpu_pool.create_surface(
        target,
        size.width,
        size.height,
        PresentMode::AutoNoVsync,
    ))
    .map_err(|e| SurfaceError::InitFailed(format!("{backend:?}: {e}")))?;

    let dev_id = surface_with_lifetime.dev_id;

    // SAFETY: The surface's implicit lifetime is tied to the window handle
    // passed to `create_surface`.  That window is an `Arc<Window>` owned by
    // `WinitWindowProvider`, which lives alongside (and outlives) this
    // `WindowRenderState` inside the runtime.  Erasing the lifetime to
    // `'static` is safe in this specific ownership topology.
    let mut surface: vello::util::RenderSurface<'static> =
        unsafe { std::mem::transmute(surface_with_lifetime) };

    // Force usage flags every backend may need over the window's
    // lifetime (`COPY_SRC` for screenshot read-back, `COPY_DST` for
    // CPU rasteriser uploads, `RENDER_ATTACHMENT` for instanced).
    // Vello defaults to `STORAGE_BINDING | TEXTURE_BINDING` which
    // breaks live backend swapping — once you go GPU→CPU on the
    // same window the next frame panics with
    // `Validation Error … COPY_DST`.
    {
        let device = &gpu_pool.devices[dev_id].device;
        let old = &surface.target_texture;
        let extent = old.size();
        let new_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("uzor_target_texture"),
            size: extent,
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::STORAGE_BINDING
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_SRC
                | wgpu::TextureUsages::COPY_DST
                | wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });
        let new_view = new_texture.create_view(&wgpu::TextureViewDescriptor::default());
        surface.target_texture = new_texture;
        surface.target_view = new_view;
    }

    Ok((gpu_pool, surface, dev_id))
}

/// Extract a `SendSyncHandlePair` from a `RawHandle::RawWindowHandle`.
#[cfg(not(target_arch = "wasm32"))]
fn extract_handle_pair<'a>(
    handle: &'a RawHandle,
    backend: RenderBackend,
) -> Result<&'a SendSyncHandlePair, SurfaceError> {
    let RawHandle::RawWindowHandle(any) = handle else {
        return Err(SurfaceError::HandleMismatch(backend));
    };

    any.downcast_ref::<SendSyncHandlePair>().ok_or_else(|| {
        SurfaceError::InitFailed(
            "expected SendSyncHandlePair inside RawHandle — \
             use WinitWindowProvider to obtain the handle"
                .into(),
        )
    })
}

// ─── Desktop-only factories ───────────────────────────────────────────────────
// VelloGpuSurfaceFactory, TinySkiaSurfaceFactory, VelloCpuSurfaceFactory,
// VelloHybridSurfaceFactory, and WgpuInstancedSurfaceFactory all require a
// native OS window and wgpu / softbuffer. They are compiled out on wasm32.

// ─── VelloGpuSurfaceFactory ───────────────────────────────────────────────────

/// Surface factory for the [`RenderBackend::VelloGpu`] path.
///
/// On [`create_render_state`](RenderSurfaceFactory::create_render_state) it:
///
/// 1. Creates a `GpuDevicePool` (wgpu device + queue).
/// 2. Creates a `RenderSurface` bound to the OS window handle.
/// 3. Creates a vello `Renderer`.
/// 4. Moves **all three** into [`WindowRenderState::Gpu`].
#[cfg(not(target_arch = "wasm32"))]
pub struct VelloGpuSurfaceFactory;

#[cfg(not(target_arch = "wasm32"))]
impl VelloGpuSurfaceFactory {
    /// Create a new factory.
    pub fn new() -> Self {
        Self
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for VelloGpuSurfaceFactory {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl RenderSurfaceFactory for VelloGpuSurfaceFactory {
    fn create_render_state(
        &self,
        handle: &RawHandle,
        backend: RenderBackend,
        size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        if !matches!(backend, RenderBackend::VelloGpu) {
            return Err(SurfaceError::UnsupportedBackend(backend));
        }

        let pair = extract_handle_pair(handle, backend)?;
        let (gpu_pool, surface, dev_id) = init_gpu_surface(pair, size, backend)?;

        let device = &gpu_pool.devices[dev_id].device;

        let renderer = Renderer::new(
            device,
            RendererOptions {
                use_cpu: false,
                antialiasing_support: AaSupport::all(),
                num_init_threads: std::num::NonZeroUsize::new(1),
                pipeline_cache: None,
            },
        )
        .map_err(|e| SurfaceError::InitFailed(e.to_string()))?;

        Ok(WindowRenderState::new_gpu(gpu_pool, surface, renderer, dev_id))
    }

    fn supports(&self, handle: &RawHandle, backend: RenderBackend) -> bool {
        matches!(backend, RenderBackend::VelloGpu)
            && matches!(handle, RawHandle::RawWindowHandle(_))
    }
}

// ─── TinySkiaSurfaceFactory ───────────────────────────────────────────────────

/// Surface factory for the [`RenderBackend::TinySkia`] CPU software path.
///
/// Constructs a [`WindowRenderState`] backed by a `TinySkiaCpuRenderContext`
/// plus a [`SoftwarePresenter`] for OS-window presentation without a GPU.
///
/// Build via [`TinySkiaSurfaceFactory::with_presenter`] when a software surface
/// is needed, or [`TinySkiaSurfaceFactory::new`] when the presenter will be
/// supplied separately.
#[cfg(not(target_arch = "wasm32"))]
pub struct TinySkiaSurfaceFactory {
    presenter: Mutex<Option<Box<dyn SoftwarePresenter>>>,
}

#[cfg(not(target_arch = "wasm32"))]
impl TinySkiaSurfaceFactory {
    /// Create the factory without a presenter.
    ///
    /// Callers that need a software surface must call
    /// [`with_presenter`](Self::with_presenter) instead; using this constructor
    /// and then calling `create_render_state` will return a
    /// [`SurfaceError::HandleUnavailable`] error.
    pub fn new() -> Self {
        Self { presenter: Mutex::new(None) }
    }

    /// Create the factory with a pre-built software presenter.
    ///
    /// Obtain the presenter from
    /// [`WindowProvider::create_software_presenter`](uzor::layout::window::WindowProvider::create_software_presenter).
    /// The presenter is moved into the factory and transferred to the
    /// [`WindowRenderState`] on the first call to [`create_render_state`].
    pub fn with_presenter(presenter: Box<dyn SoftwarePresenter>) -> Self {
        Self { presenter: Mutex::new(Some(presenter)) }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for TinySkiaSurfaceFactory {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl RenderSurfaceFactory for TinySkiaSurfaceFactory {
    fn create_render_state(
        &self,
        handle: &RawHandle,
        backend: RenderBackend,
        size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        if !matches!(backend, RenderBackend::TinySkia) {
            return Err(SurfaceError::UnsupportedBackend(backend));
        }

        // Software-presenter path (legacy / headless tests).
        if let Some(presenter) = self
            .presenter
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .take()
        {
            return Ok(WindowRenderState::new_cpu(size.width, size.height, presenter));
        }

        // Default path: render into a tiny-skia pixmap, upload as a
        // texture, blit through the wgpu swapchain.  Mirrors the
        // proven mlc submit path; identical for every spawned window.
        let pair = extract_handle_pair(handle, backend)?;
        let (gpu_pool, surface, dev_id) = init_gpu_surface(pair, size, backend)?;
        Ok(WindowRenderState::new_tiny_skia_gpu(gpu_pool, surface, dev_id))
    }

    fn supports(&self, _handle: &RawHandle, backend: RenderBackend) -> bool {
        matches!(backend, RenderBackend::TinySkia)
    }
}

// ─── VelloCpuSurfaceFactory ───────────────────────────────────────────────────

/// Surface factory for the [`RenderBackend::VelloCpu`] path.
///
/// Constructs a [`WindowRenderState`] backed by a `VelloCpuRenderContext`
/// plus a [`SoftwarePresenter`] for OS-window presentation without a GPU.
///
/// Build via [`VelloCpuSurfaceFactory::with_presenter`] when a software surface
/// is needed.
#[cfg(not(target_arch = "wasm32"))]
pub struct VelloCpuSurfaceFactory {
    /// Device pixel ratio.  Defaults to `1.0`.
    pub dpr: f64,
    presenter: Mutex<Option<Box<dyn SoftwarePresenter>>>,
}

#[cfg(not(target_arch = "wasm32"))]
impl VelloCpuSurfaceFactory {
    /// Create the factory with the given device pixel ratio but no presenter.
    ///
    /// Callers that need a software surface must call
    /// [`with_presenter`](Self::with_presenter) instead.
    pub fn new(dpr: f64) -> Self {
        Self { dpr, presenter: Mutex::new(None) }
    }

    /// Create the factory with a device pixel ratio and a software presenter.
    ///
    /// Obtain the presenter from
    /// [`WindowProvider::create_software_presenter`](uzor::layout::window::WindowProvider::create_software_presenter).
    pub fn with_presenter(dpr: f64, presenter: Box<dyn SoftwarePresenter>) -> Self {
        Self { dpr, presenter: Mutex::new(Some(presenter)) }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for VelloCpuSurfaceFactory {
    fn default() -> Self {
        Self::new(1.0)
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl RenderSurfaceFactory for VelloCpuSurfaceFactory {
    fn create_render_state(
        &self,
        handle: &RawHandle,
        backend: RenderBackend,
        size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        if !matches!(backend, RenderBackend::VelloCpu) {
            return Err(SurfaceError::UnsupportedBackend(backend));
        }

        // Software-presenter path (kept for headless tests).
        if let Some(presenter) = self
            .presenter
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .take()
        {
            return Ok(WindowRenderState::new_vello_cpu(self.dpr, presenter));
        }

        // Default path: render into a vello-cpu pixmap, upload as a
        // texture, blit through the wgpu swapchain.
        let pair = extract_handle_pair(handle, backend)?;
        let (gpu_pool, surface, dev_id) = init_gpu_surface(pair, size, backend)?;
        Ok(WindowRenderState::new_vello_cpu_gpu(gpu_pool, surface, dev_id, self.dpr))
    }

    fn supports(&self, _handle: &RawHandle, backend: RenderBackend) -> bool {
        matches!(backend, RenderBackend::VelloCpu)
    }
}

// ─── VelloHybridSurfaceFactory ────────────────────────────────────────────────

/// Surface factory for the [`RenderBackend::VelloHybrid`] path.
///
/// Constructs a [`WindowRenderState::VelloHybrid`].  GPU surface and device
/// pool are initialised eagerly; the `vello_hybrid::Renderer` itself is
/// deferred to the first frame (requires the swapchain texture format, which
/// only becomes available when the first `get_current_texture` call is made).
#[cfg(not(target_arch = "wasm32"))]
pub struct VelloHybridSurfaceFactory {
    /// Device pixel ratio passed to the `VelloHybridRenderContext`.
    pub dpr: f64,
}

#[cfg(not(target_arch = "wasm32"))]
impl VelloHybridSurfaceFactory {
    /// Create the factory.
    pub fn new(dpr: f64) -> Self {
        Self { dpr }
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for VelloHybridSurfaceFactory {
    fn default() -> Self {
        Self::new(1.0)
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl RenderSurfaceFactory for VelloHybridSurfaceFactory {
    fn create_render_state(
        &self,
        handle: &RawHandle,
        backend: RenderBackend,
        size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        if !matches!(backend, RenderBackend::VelloHybrid) {
            return Err(SurfaceError::UnsupportedBackend(backend));
        }

        let pair = extract_handle_pair(handle, backend)?;
        let (gpu_pool, surface, dev_id) = init_gpu_surface(pair, size, backend)?;

        Ok(WindowRenderState::new_vello_hybrid(gpu_pool, surface, dev_id, self.dpr))
    }

    fn supports(&self, handle: &RawHandle, backend: RenderBackend) -> bool {
        matches!(backend, RenderBackend::VelloHybrid)
            && matches!(handle, RawHandle::RawWindowHandle(_))
    }
}

// ─── WgpuInstancedSurfaceFactory ─────────────────────────────────────────────

/// Surface factory for the [`RenderBackend::InstancedWgpu`] path.
///
/// Constructs a [`WindowRenderState::WgpuInstanced`].  GPU surface and device
/// pool are initialised eagerly; the `InstancedRenderer` itself is deferred
/// to the first frame (requires the swapchain texture format).
#[cfg(not(target_arch = "wasm32"))]
pub struct WgpuInstancedSurfaceFactory;

#[cfg(not(target_arch = "wasm32"))]
impl WgpuInstancedSurfaceFactory {
    /// Create the factory.
    pub fn new() -> Self {
        Self
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Default for WgpuInstancedSurfaceFactory {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl RenderSurfaceFactory for WgpuInstancedSurfaceFactory {
    fn create_render_state(
        &self,
        handle: &RawHandle,
        backend: RenderBackend,
        size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        if !matches!(backend, RenderBackend::InstancedWgpu) {
            return Err(SurfaceError::UnsupportedBackend(backend));
        }

        let pair = extract_handle_pair(handle, backend)?;
        let (gpu_pool, surface, dev_id) = init_gpu_surface(pair, size, backend)?;

        Ok(WindowRenderState::new_wgpu_instanced(gpu_pool, surface, dev_id))
    }

    fn supports(&self, handle: &RawHandle, backend: RenderBackend) -> bool {
        matches!(backend, RenderBackend::InstancedWgpu)
            && matches!(handle, RawHandle::RawWindowHandle(_))
    }
}

// ─── Canvas2dSurfaceFactory ───────────────────────────────────────────────────

/// Surface factory for the HTML Canvas 2D backend (wasm32 only).
///
/// On native targets this always returns [`SurfaceError::UnsupportedBackend`].
/// On `wasm32` targets it downcasts the [`RawHandle::Canvas`] payload to a
/// `web_sys::HtmlCanvasElement`, calls `getContext("2d")`, reads the device
/// pixel ratio from `window.devicePixelRatio`, and returns a fully initialized
/// [`WindowRenderState`] for DOM canvas rendering.
pub struct Canvas2dSurfaceFactory;

impl Canvas2dSurfaceFactory {
    /// Create the factory.
    pub fn new() -> Self {
        Self
    }
}

impl Default for Canvas2dSurfaceFactory {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(target_arch = "wasm32")]
impl RenderSurfaceFactory for Canvas2dSurfaceFactory {
    fn create_render_state(
        &self,
        handle: &RawHandle,
        backend: RenderBackend,
        _size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        if !matches!(backend, RenderBackend::Canvas2d) {
            return Err(SurfaceError::UnsupportedBackend(backend));
        }

        let RawHandle::Canvas(any) = handle else {
            return Err(SurfaceError::HandleMismatch(backend));
        };

        // The RawHandle::Canvas payload is a SendSyncCanvas (from uzor-window-web).
        let canvas = any
            .downcast_ref::<uzor_window_web::SendSyncCanvas>()
            .ok_or_else(|| {
                SurfaceError::InitFailed(
                    "expected SendSyncCanvas in RawHandle::Canvas — use WebWindowProvider".into(),
                )
            })?
            .0
            .clone();

        let raw_ctx = canvas
            .get_context("2d")
            .map_err(|e| {
                SurfaceError::InitFailed(format!("canvas.getContext(\"2d\") failed: {e:?}"))
            })?
            .ok_or_else(|| SurfaceError::InitFailed("canvas.getContext(\"2d\") returned null".into()))?;

        use wasm_bindgen::JsCast as _;
        let ctx2d = raw_ctx
            .dyn_into::<web_sys::CanvasRenderingContext2d>()
            .map_err(|_| {
                SurfaceError::InitFailed(
                    "getContext(\"2d\") object is not CanvasRenderingContext2d".into(),
                )
            })?;

        let dpr = web_sys::window()
            .map(|w| w.device_pixel_ratio())
            .unwrap_or(1.0);

        let render_ctx = uzor_render_canvas2d::Canvas2dRenderContext::new(ctx2d, dpr);

        Ok(WindowRenderState::new_canvas2d(canvas, render_ctx))
    }

    fn supports(&self, handle: &RawHandle, backend: RenderBackend) -> bool {
        matches!(backend, RenderBackend::Canvas2d) && matches!(handle, RawHandle::Canvas(_))
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl RenderSurfaceFactory for Canvas2dSurfaceFactory {
    fn create_render_state(
        &self,
        _handle: &RawHandle,
        backend: RenderBackend,
        _size: SurfaceSize,
    ) -> Result<WindowRenderState, SurfaceError> {
        Err(SurfaceError::UnsupportedBackend(backend))
    }

    fn supports(&self, _handle: &RawHandle, _backend: RenderBackend) -> bool {
        false
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
    use super::*;

    // Helper: a dummy handle that is not a RawWindowHandle (for mismatch tests).
    fn canvas_handle() -> RawHandle {
        RawHandle::Canvas(Box::new(42u32))
    }

    fn raw_window_handle_dummy() -> RawHandle {
        // We can't construct a real SendSyncHandlePair in unit tests, but we
        // can verify the discriminant check at the `supports` level, which
        // only looks at the handle variant and backend, not the contents.
        RawHandle::Canvas(Box::new(99u32))
    }

    // ── VelloGpuSurfaceFactory ────────────────────────────────────────────────

    #[test]
    fn vello_gpu_supports_correct_pair() {
        let f = VelloGpuSurfaceFactory::new();
        // `supports` only checks the discriminant, not whether the inner Any
        // can be downcast to SendSyncHandlePair — so we can test with a dummy
        // RawWindowHandle variant.
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(f.supports(&handle, RenderBackend::VelloGpu));
    }

    #[test]
    fn vello_gpu_rejects_wrong_backend() {
        let f = VelloGpuSurfaceFactory::new();
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(!f.supports(&handle, RenderBackend::TinySkia));
        assert!(!f.supports(&handle, RenderBackend::VelloCpu));
    }

    #[test]
    fn vello_gpu_rejects_canvas_handle() {
        let f = VelloGpuSurfaceFactory::new();
        assert!(!f.supports(&canvas_handle(), RenderBackend::VelloGpu));
    }

    // ── TinySkiaSurfaceFactory ────────────────────────────────────────────────

    #[test]
    fn tiny_skia_supports_any_handle() {
        let f = TinySkiaSurfaceFactory::new();
        // TinySkia doesn't care about the handle type.
        assert!(f.supports(&canvas_handle(), RenderBackend::TinySkia));
        assert!(f.supports(&raw_window_handle_dummy(), RenderBackend::TinySkia));
    }

    #[test]
    fn tiny_skia_rejects_wrong_backend() {
        let f = TinySkiaSurfaceFactory::new();
        assert!(!f.supports(&canvas_handle(), RenderBackend::VelloGpu));
        assert!(!f.supports(&canvas_handle(), RenderBackend::VelloCpu));
    }

    // ── VelloCpuSurfaceFactory ────────────────────────────────────────────────

    #[test]
    fn vello_cpu_supports_any_handle() {
        let f = VelloCpuSurfaceFactory::default();
        assert!(f.supports(&canvas_handle(), RenderBackend::VelloCpu));
        assert!(f.supports(&raw_window_handle_dummy(), RenderBackend::VelloCpu));
    }

    #[test]
    fn vello_cpu_rejects_wrong_backend() {
        let f = VelloCpuSurfaceFactory::default();
        assert!(!f.supports(&canvas_handle(), RenderBackend::VelloGpu));
        assert!(!f.supports(&canvas_handle(), RenderBackend::TinySkia));
    }

    // ── VelloHybridSurfaceFactory ─────────────────────────────────────────────

    #[test]
    fn vello_hybrid_supports_raw_window_handle() {
        let f = VelloHybridSurfaceFactory::default();
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(f.supports(&handle, RenderBackend::VelloHybrid));
    }

    #[test]
    fn vello_hybrid_rejects_canvas_handle() {
        let f = VelloHybridSurfaceFactory::default();
        assert!(!f.supports(&canvas_handle(), RenderBackend::VelloHybrid));
    }

    #[test]
    fn vello_hybrid_rejects_wrong_backend() {
        let f = VelloHybridSurfaceFactory::default();
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(!f.supports(&handle, RenderBackend::VelloGpu));
        assert!(!f.supports(&handle, RenderBackend::TinySkia));
    }

    // ── WgpuInstancedSurfaceFactory ───────────────────────────────────────────

    #[test]
    fn wgpu_instanced_supports_raw_window_handle() {
        let f = WgpuInstancedSurfaceFactory::new();
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(f.supports(&handle, RenderBackend::InstancedWgpu));
    }

    #[test]
    fn wgpu_instanced_rejects_canvas_handle() {
        let f = WgpuInstancedSurfaceFactory::new();
        assert!(!f.supports(&canvas_handle(), RenderBackend::InstancedWgpu));
    }

    #[test]
    fn wgpu_instanced_rejects_wrong_backend() {
        let f = WgpuInstancedSurfaceFactory::new();
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(!f.supports(&handle, RenderBackend::VelloGpu));
        assert!(!f.supports(&handle, RenderBackend::TinySkia));
    }

    // ── Canvas2dSurfaceFactory ────────────────────────────────────────────────

    #[test]
    fn canvas2d_never_supports() {
        let f = Canvas2dSurfaceFactory::new();
        // Canvas2d factory always returns false on native — no matching backend.
        assert!(!f.supports(&canvas_handle(), RenderBackend::VelloGpu));
        assert!(!f.supports(&canvas_handle(), RenderBackend::TinySkia));
        let handle = RawHandle::RawWindowHandle(Box::new(42u32));
        assert!(!f.supports(&handle, RenderBackend::VelloGpu));
    }
}