Skip to main content

redjs_webgpu/
canvas.rs

1//! GPUCanvasContext with a native host presenter and bounded readback fallback.
2//!
3//! JSC owns logical contexts; expired drawing buffers can move into a native
4//! frame owner without retaining CPU pixels. Readback completions are fenced
5//! by context/resize epochs, and no JSC value crosses onto a GPU worker.
6use super::*;
7use std::collections::HashSet;
8use std::sync::{Condvar, Weak};
9use std::time::{Duration, Instant};
10
11/// A published canvas buffer: completed CPU pixels or an ordered native frame.
12#[derive(Debug)]
13pub struct PresentedFrame {
14    /// Bitmap dimensions, zero for a constant-black marker.
15    pub width: u32,
16    pub height: u32,
17    /// Tightly packed premultiplied RGBA8; empty for a constant-black marker.
18    pub rgba: Vec<u8>,
19    /// Paint black at `present_size(key)` without allocating a bitmap.
20    pub opaque_blank: bool,
21    /// Optional host-owned GPU frame. `rgba` is empty until an explicit snapshot.
22    pub native: Option<Arc<NativePresentation>>,
23}
24
25/// A borrowed canvas buffer. A presenter must submit its reads before returning.
26pub struct NativeSource<'a> {
27    pub client: &'a Arc<Client>,
28    pub texture: &'a Arc<wgpu::Texture>,
29    pub format: wgpu::TextureFormat,
30    pub width: u32,
31    pub height: u32,
32    pub opaque: bool,
33}
34
35/// Native texture format is straight-alpha BGRA8 on the renderer's own device.
36/// The pointer is borrowed only for the synchronous copy callback.
37///
38/// # Safety
39/// Implementors must keep a valid ID3D11Texture2D alive and acquired throughout
40/// the callback, then release/flush it before subsequent wgpu queue work.
41/// The callback may panic; cleanup must still run. No JSC callback is allowed.
42pub unsafe trait NativeFrame: std::fmt::Debug + Send + Sync {
43    fn copy_d3d11(&self, copy: &mut dyn FnMut(*mut c_void) -> bool) -> Result<bool, String>;
44
45    /// Exposes a BGRA8 D3D12 resource in RENDER_TARGET state and a readiness
46    /// fence signalled on the producer queue. The consumer waits on its GPU
47    /// queue, restores the state after copying, and retains this frame until
48    /// its own copy fence completes. No JS callback is allowed here.
49    fn copy_d3d12(
50        &self,
51        _copy: &mut dyn FnMut(*mut c_void, *mut c_void, u64) -> bool,
52    ) -> Result<bool, String> {
53        Ok(false)
54    }
55}
56
57pub trait NativePresenter: Send + Sync {
58    /// None means unsupported; the bounded asynchronous readback is the fallback.
59    fn prepare(&self, source: NativeSource<'_>) -> Result<Option<Arc<dyn NativeFrame>>, String>;
60}
61fn presenter_slot() -> &'static std::sync::RwLock<Option<Arc<dyn NativePresenter>>> {
62    static PRESENTER: OnceLock<std::sync::RwLock<Option<Arc<dyn NativePresenter>>>> =
63        OnceLock::new();
64    PRESENTER.get_or_init(Default::default)
65}
66pub fn set_presenter(presenter: Option<Arc<dyn NativePresenter>>) {
67    *presenter_slot().write().unwrap() = presenter;
68}
69
70pub struct NativePresentation {
71    pub frame: Arc<dyn NativeFrame>,
72    // The expired JS texture is no longer in its client's destroy list. This
73    // owner retains exact original pixels for export and destroys it on drop,
74    // even if JS keeps the expired texture wrapper alive indefinitely.
75    source: Arc<wgpu::Texture>,
76    snapshot_client: Arc<Client>,
77    format: wgpu::TextureFormat,
78    width: u32,
79    height: u32,
80    opaque: bool,
81}
82impl std::fmt::Debug for NativePresentation {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("NativePresentation")
85            .field("width", &self.width)
86            .field("height", &self.height)
87            .finish()
88    }
89}
90impl Drop for NativePresentation {
91    fn drop(&mut self) {
92        self.source.destroy();
93    }
94}
95impl NativePresentation {
96    /// Explicit readback only; normal display visits `frame` instead.
97    pub fn snapshot(&self) -> Result<Arc<PresentedFrame>, String> {
98        SNAPSHOTS.fetch_add(1, Ordering::Relaxed);
99        let f = readback::snapshot_sync(
100            &self.snapshot_client,
101            self.source.clone(),
102            self.format,
103            self.width,
104            self.height,
105            self.opaque,
106        )?;
107        Ok(Arc::new(PresentedFrame {
108            width: f.width,
109            height: f.height,
110            rgba: f.rgba,
111            opaque_blank: false,
112            native: None,
113        }))
114    }
115}
116static NATIVE_FRAMES: AtomicU64 = AtomicU64::new(0);
117static READBACK_FRAMES: AtomicU64 = AtomicU64::new(0);
118static SNAPSHOTS: AtomicU64 = AtomicU64::new(0);
119/// (native display frames, asynchronous display readbacks, explicit snapshots).
120pub fn presentation_stats() -> (u64, u64, u64) {
121    (
122        NATIVE_FRAMES.load(Ordering::Relaxed),
123        READBACK_FRAMES.load(Ordering::Relaxed),
124        SNAPSHOTS.load(Ordering::Relaxed),
125    )
126}
127#[derive(Clone)]
128struct Configuration {
129    client: Arc<Client>,
130    format: wgpu::TextureFormat,
131    format_name: String,
132    usage: wgpu::TextureUsages,
133    views: Vec<wgpu::TextureFormat>,
134    view_names: Vec<String>,
135    opaque: bool,
136}
137struct State {
138    width: u32,
139    height: u32,
140    epoch: u64,
141    serial: u64,
142    config: Option<Configuration>,
143    current: Option<Arc<texture::Texture>>,
144    deferred: Option<(u64, Arc<texture::Texture>)>,
145    reader: Option<readback::Reader>,
146    pending: HashSet<u64>,
147    last_serial: u64,
148    last_error: Option<String>,
149    generation: u64,
150    last: Arc<PresentedFrame>,
151    enabled: bool,
152}
153pub(super) struct Surface {
154    key: Option<u64>,
155    context: redjs::context::ContextId,
156    state: Mutex<State>,
157    changed: Condvar,
158}
159struct Record {
160    global: usize,
161    surface: Weak<Surface>,
162}
163fn all() -> &'static Mutex<Vec<Record>> {
164    static A: OnceLock<Mutex<Vec<Record>>> = OnceLock::new();
165    A.get_or_init(Default::default)
166}
167fn shown() -> &'static Mutex<HashMap<u64, Weak<Surface>>> {
168    static A: OnceLock<Mutex<HashMap<u64, Weak<Surface>>>> = OnceLock::new();
169    A.get_or_init(Default::default)
170}
171static CHANGED: AtomicBool = AtomicBool::new(false);
172fn generation() -> u64 {
173    static N: AtomicU64 = AtomicU64::new(1);
174    (1 << 63) | N.fetch_add(1, Ordering::Relaxed)
175}
176fn clear(opaque: bool) -> Arc<PresentedFrame> {
177    Arc::new(PresentedFrame {
178        width: 0,
179        height: 0,
180        rgba: Vec::new(),
181        opaque_blank: opaque,
182        native: None,
183    })
184}
185fn notify(s: &Surface, st: &State) {
186    s.changed.notify_all();
187    if st.enabled && s.key.is_some() {
188        CHANGED.store(true, Ordering::Release);
189        redjs::web::wake(s.context);
190    }
191}
192fn discard(t: Option<Arc<texture::Texture>>) {
193    if let Some(t) = t {
194        t.destroyed.store(true, Ordering::Release);
195        t.raw.destroy();
196    }
197}
198impl Drop for Surface {
199    fn drop(&mut self) {
200        let st = self.state.get_mut().unwrap_or_else(|e| e.into_inner());
201        discard(st.current.take());
202        discard(st.deferred.take().map(|(_, t)| t));
203        if let Some(key) = self.key {
204            let mut m = shown().lock().unwrap();
205            if m.get(&key)
206                .is_some_and(|w| std::ptr::eq(w.as_ptr(), self as *const Self))
207            {
208                m.remove(&key);
209                CHANGED.store(true, Ordering::Release);
210            }
211        }
212    }
213}
214fn reset(s: &Surface, config: Option<Configuration>, dimensions: Option<(u32, u32)>) {
215    let mut st = s.state.lock().unwrap();
216    discard(st.current.take());
217    discard(st.deferred.take().map(|(_, t)| t));
218    st.epoch = st.epoch.wrapping_add(1);
219    st.pending.clear();
220    let (w, h) = dimensions.unwrap_or((st.width, st.height));
221    let opaque = config.as_ref().is_some_and(|c| c.opaque) && w > 0 && h > 0;
222    st.config = config;
223    st.reader = None;
224    st.last_error = None;
225    st.last = clear(opaque);
226    st.generation = generation();
227    if let Some((w, h)) = dimensions {
228        st.width = w;
229        st.height = h;
230    }
231    notify(s, &st);
232}
233
234/// Published frames only. Native hosts enforce queue ordering during import.
235pub fn present(key: u64, since: u64) -> Option<(u64, Arc<PresentedFrame>)> {
236    let s = shown().lock().unwrap().get(&key)?.upgrade()?;
237    let st = s.state.lock().unwrap();
238    (st.enabled && st.generation != since).then(|| (st.generation, st.last.clone()))
239}
240pub fn present_size(key: u64) -> Option<(u32, u32)> {
241    let s = shown().lock().unwrap().get(&key)?.upgrade()?;
242    let st = s.state.lock().unwrap();
243    st.enabled.then_some((st.width, st.height))
244}
245pub fn take_presented_changed() -> bool {
246    CHANGED.swap(false, Ordering::AcqRel)
247}
248/// Keep the weak slot so a retained DOM canvas can be inserted again.
249pub fn unregister_present(key: u64) {
250    let s = shown().lock().unwrap().get(&key).and_then(Weak::upgrade);
251    if let Some(s) = s {
252        let mut st = s.state.lock().unwrap();
253        if st.enabled {
254            st.enabled = false;
255            CHANGED.store(true, Ordering::Release);
256        }
257    }
258}
259pub fn register_present(key: u64) {
260    let s = shown().lock().unwrap().get(&key).and_then(Weak::upgrade);
261    if let Some(s) = s {
262        let mut st = s.state.lock().unwrap();
263        if !st.enabled {
264            st.enabled = true;
265            CHANGED.store(true, Ordering::Release);
266        }
267    }
268}
269
270pub(crate) unsafe fn create(g: *mut c_void, owner: u64, w: u32, h: u32, key: Option<u64>) -> u64 {
271    let context = redjs::context::id_of(g).unwrap();
272    let _ = redjs::web::waker(context);
273    let surface = Arc::new(Surface {
274        key,
275        context,
276        state: Mutex::new(State {
277            width: w,
278            height: h,
279            epoch: 0,
280            serial: 0,
281            config: None,
282            current: None,
283            deferred: None,
284            reader: None,
285            pending: HashSet::new(),
286            last_serial: 0,
287            last_error: None,
288            generation: generation(),
289            last: clear(false),
290            enabled: key.is_some(),
291        }),
292        changed: Condvar::new(),
293    });
294    all().lock().unwrap().push(Record {
295        global: g as usize,
296        surface: Arc::downgrade(&surface),
297    });
298    if let Some(k) = key {
299        shown().lock().unwrap().insert(k, Arc::downgrade(&surface));
300        CHANGED.store(true, Ordering::Release);
301    }
302    let o = Val::new(g, wrap(g, Kind::Canvas, None, Resource::Canvas(surface)));
303    let slot = slots(g).0;
304    glue::rjs_define(g, o.v, slot, owner, 1 | 2);
305    o.v
306}
307fn slots(g: *mut c_void) -> (*mut c_void, *mut c_void, *mut c_void) {
308    let m = states().lock().unwrap();
309    let c = m[&(g as usize)].classes.as_ref().unwrap();
310    (
311        c.s_gpu_canvas as *mut c_void,
312        c.s_gpu_device as *mut c_void,
313        c.s_gpu_texture as *mut c_void,
314    )
315}
316unsafe fn surface(g: *mut c_void, v: u64) -> Option<Arc<Surface>> {
317    let cls = {
318        let m = states().lock().unwrap();
319        *m.get(&(g as usize))?
320            .classes
321            .as_ref()?
322            .hosts
323            .get(&Kind::Canvas)? as capi::JSClassRef
324    };
325    let h = host_data::<Handle>(g, cls, v)?;
326    if let Resource::Canvas(s) = &h.resource {
327        Some(s.clone())
328    } else {
329        None
330    }
331}
332pub(crate) unsafe fn is_context(g: *mut c_void, v: u64) -> bool {
333    surface(g, v).is_some()
334}
335unsafe fn this_surface(g: *mut c_void, cf: *mut c_void) -> Result<Arc<Surface>, ()> {
336    let h = this(g, cf, Kind::Canvas)?;
337    let Resource::Canvas(s) = h.resource else {
338        unreachable!()
339    };
340    Ok(s)
341}
342pub(crate) unsafe fn resize(g: *mut c_void, ctx: u64, w: u32, h: u32) -> Result<(), ()> {
343    let Some(s) = surface(g, ctx) else {
344        return invalid(g, "Not a GPUCanvasContext");
345    };
346    let config = s.state.lock().unwrap().config.clone();
347    reset(&s, config, Some((w, h)));
348    glue::rjs_define(g, ctx, slots(g).2, UNDEF, 1 | 2);
349    Ok(())
350}
351#[redjs::host_fn]
352unsafe fn get_canvas(g: *mut c_void, cf: *mut c_void) -> u64 {
353    run(g, || {
354        this_surface(g, cf)?;
355        Ok(get_a(g, cf_this(cf), slots(g).0))
356    })
357}
358#[redjs::host_fn]
359unsafe fn configure(g: *mut c_void, cf: *mut c_void) -> u64 {
360    run(g, || {
361        let s = this_surface(g, cf)?;
362        let d = Val::new(g, cf_arg(cf, 0));
363        let device = field(g, d.v, "device")?;
364        let h = handle(g, device.v, Kind::Device)?;
365        let c = client(g, &h)?;
366        let name = text(g, field(g, d.v, "format")?.v, "")?;
367        let format = match name.as_str() {
368            "rgba8unorm" => wgpu::TextureFormat::Rgba8Unorm,
369            "bgra8unorm" => wgpu::TextureFormat::Bgra8Unorm,
370            _ => {
371                return Ok(redjs::webapi::domexception::throw(
372                    g,
373                    "NotSupportedError",
374                    "Canvas presentation currently supports rgba8unorm and bgra8unorm",
375                ))
376            }
377        };
378        let bits = uint(g, field(g, d.v, "usage")?.v, 16)?;
379        let Some(usage) = wgpu::TextureUsages::from_bits(bits) else {
380            invalid(g, "Invalid GPUCanvasConfiguration usage flags")?;
381            unreachable!()
382        };
383        if usage.is_empty() {
384            invalid(g, "Canvas texture usage cannot be empty")?;
385        }
386        if !c
387            .context
388            .adapter
389            .get_texture_format_features(format)
390            .allowed_usages
391            .contains(usage)
392        {
393            invalid(g, "Canvas format does not support requested usage")?;
394        }
395        if format == wgpu::TextureFormat::Bgra8Unorm
396            && usage.contains(wgpu::TextureUsages::STORAGE_BINDING)
397            && !c.features.contains(wgpu::Features::BGRA8UNORM_STORAGE)
398        {
399            invalid(g, "bgra8unorm-storage was not enabled")?;
400        }
401        let mut views = Vec::new();
402        let mut names = Vec::new();
403        for v in seq(g, field(g, d.v, "viewFormats")?.v)? {
404            let name = text(g, v.v, "")?;
405            let f = texture::parse_format(g, v.v)?;
406            if f.remove_srgb_suffix() != format {
407                invalid(
408                    g,
409                    "Canvas view format is incompatible with its texture format",
410                )?;
411            }
412            views.push(f);
413            names.push(name);
414        }
415        if text(g, field(g, d.v, "colorSpace")?.v, "srgb")? != "srgb" {
416            return Ok(redjs::webapi::domexception::throw(
417                g,
418                "NotSupportedError",
419                "Only sRGB canvas presentation is supported",
420            ));
421        }
422        let tone = field(g, d.v, "toneMapping")?;
423        if text(g, field(g, tone.v, "mode")?.v, "standard")? != "standard" {
424            return Ok(redjs::webapi::domexception::throw(
425                g,
426                "NotSupportedError",
427                "Extended tone mapping is not supported",
428            ));
429        }
430        let alpha = text(g, field(g, d.v, "alphaMode")?.v, "opaque")?;
431        if !["opaque", "premultiplied"].contains(&alpha.as_str()) {
432            invalid(g, "Invalid GPUCanvasAlphaMode")?;
433        }
434        if let Err(e) = c.check() {
435            return Ok(redjs::webapi::domexception::throw(
436                g,
437                "InvalidStateError",
438                &e,
439            ));
440        }
441        reset(
442            &s,
443            Some(Configuration {
444                client: c,
445                format,
446                format_name: name,
447                usage,
448                views,
449                view_names: names,
450                opaque: alpha == "opaque",
451            }),
452            None,
453        );
454        glue::rjs_define(g, cf_this(cf), slots(g).1, device.v, 1 | 2);
455        glue::rjs_define(g, cf_this(cf), slots(g).2, UNDEF, 1 | 2);
456        Ok(UNDEF)
457    })
458}
459#[redjs::host_fn]
460unsafe fn unconfigure(g: *mut c_void, cf: *mut c_void) -> u64 {
461    run(g, || {
462        let s = this_surface(g, cf)?;
463        reset(&s, None, None);
464        glue::rjs_define(g, cf_this(cf), slots(g).1, UNDEF, 1 | 2);
465        glue::rjs_define(g, cf_this(cf), slots(g).2, UNDEF, 1 | 2);
466        Ok(UNDEF)
467    })
468}
469#[redjs::host_fn]
470unsafe fn configuration(g: *mut c_void, cf: *mut c_void) -> u64 {
471    run(g, || {
472        let s = this_surface(g, cf)?;
473        let config = s.state.lock().unwrap().config.clone();
474        let Some(c) = config else { return Ok(NULL) };
475        let o = Val::new(g, new_object(g, UNDEF));
476        define(g, o.v, "device", get_a(g, cf_this(cf), slots(g).1), 0);
477        define(g, o.v, "format", js_string(g, &c.format_name), 0);
478        define(g, o.v, "usage", enc_f64(c.usage.bits() as f64), 0);
479        define(
480            g,
481            o.v,
482            "alphaMode",
483            js_string(g, if c.opaque { "opaque" } else { "premultiplied" }),
484            0,
485        );
486        define(g, o.v, "colorSpace", js_string(g, "srgb"), 0);
487        let a = Val::new(g, new_array(g));
488        for (i, n) in c.view_names.iter().enumerate() {
489            let v = js_string(g, n);
490            set_i(g, a.v, i as u32, v);
491        }
492        define(g, o.v, "viewFormats", a.v, 0);
493        let tone = Val::new(g, new_object(g, UNDEF));
494        define(g, tone.v, "mode", js_string(g, "standard"), 0);
495        define(g, o.v, "toneMapping", tone.v, 0);
496        Ok(o.v)
497    })
498}
499#[redjs::host_fn]
500unsafe fn current_texture(g: *mut c_void, cf: *mut c_void) -> u64 {
501    run(g, || {
502        let s = this_surface(g, cf)?;
503        let (c, w, h, existing, epoch) = {
504            let st = s.state.lock().unwrap();
505            let Some(c) = st.config.clone() else {
506                return Ok(redjs::webapi::domexception::throw(
507                    g,
508                    "InvalidStateError",
509                    "GPUCanvasContext is not configured",
510                ));
511            };
512            (c, st.width, st.height, st.current.clone(), st.epoch)
513        };
514        if let Err(e) = c.client.check() {
515            return Ok(redjs::webapi::domexception::throw(
516                g,
517                "InvalidStateError",
518                &e,
519            ));
520        }
521        if existing.is_some() {
522            return Ok(get_a(g, cf_this(cf), slots(g).2));
523        }
524        if w == 0
525            || h == 0
526            || w > c.client.limits.max_texture_dimension_2d
527            || h > c.client.limits.max_texture_dimension_2d
528        {
529            return Ok(redjs::webapi::domexception::throw(
530                g,
531                "OperationError",
532                "Canvas dimensions are zero or exceed the device limit",
533            ));
534        }
535        let size = wgpu::Extent3d {
536            width: w,
537            height: h,
538            depth_or_array_layers: 1,
539        };
540        let raw = Arc::new(checked(g, &c.client, || {
541            c.client
542                .context
543                .device
544                .create_texture(&wgpu::TextureDescriptor {
545                    label: Some("GPUCanvasContext drawing buffer"),
546                    size,
547                    mip_level_count: 1,
548                    sample_count: 1,
549                    dimension: wgpu::TextureDimension::D2,
550                    format: c.format,
551                    usage: c.usage
552                        | wgpu::TextureUsages::COPY_SRC
553                        | wgpu::TextureUsages::TEXTURE_BINDING,
554                    view_formats: &c.views,
555                })
556        }));
557        c.client.track_texture(&raw);
558        let t = Arc::new(texture::Texture {
559            raw,
560            size,
561            usage: c.usage,
562            destroyed: AtomicBool::new(false),
563            mip_levels: 1,
564            samples: 1,
565            dimension: "2d".into(),
566            format_name: c.format_name.clone(),
567            canvas: true,
568        });
569        {
570            let mut st = s.state.lock().unwrap();
571            if st.epoch != epoch {
572                discard(Some(t));
573                return Ok(redjs::webapi::domexception::throw(
574                    g,
575                    "InvalidStateError",
576                    "Canvas was reconfigured",
577                ));
578            }
579            discard(st.deferred.take().map(|(_, t)| t));
580            st.serial = st.serial.wrapping_add(1);
581            st.current = Some(t.clone());
582        }
583        let o = Val::new(
584            g,
585            wrap(g, Kind::Texture, Some(c.client), Resource::Texture(t)),
586        );
587        glue::rjs_define(g, o.v, slots(g).0, cf_this(cf), 1 | 2);
588        glue::rjs_define(g, cf_this(cf), slots(g).2, o.v, 1 | 2);
589        Ok(o.v)
590    })
591}
592
593fn blank(w: u32, h: u32, opaque: bool) -> Result<Arc<PresentedFrame>, String> {
594    let n = (w as usize)
595        .checked_mul(h as usize)
596        .and_then(|n| n.checked_mul(4))
597        .ok_or("Canvas size overflow")?;
598    if n > 256 * 1024 * 1024 {
599        return Err("Canvas snapshot exceeds the 256 MiB limit".into());
600    }
601    let mut rgba = vec![0; n];
602    if opaque {
603        for p in rgba.chunks_exact_mut(4) {
604            p[3] = 255;
605        }
606    }
607    Ok(Arc::new(PresentedFrame {
608        width: w,
609        height: h,
610        rgba,
611        opaque_blank: false,
612        native: None,
613    }))
614}
615fn snapshot(s: &Surface) -> Result<Arc<PresentedFrame>, String> {
616    let mut st = s.state.lock().unwrap();
617    let c = st.config.clone();
618    let native = st
619        .current
620        .clone()
621        .or_else(|| st.deferred.as_ref().map(|(_, t)| t.clone()));
622    if let (Some(c), Some(t)) = (c.clone(), native) {
623        if c.client.check().is_ok() {
624            let (w, h) = (st.width, st.height);
625            drop(st);
626            SNAPSHOTS.fetch_add(1, Ordering::Relaxed);
627            let f = readback::snapshot_sync(&c.client, t.raw.clone(), c.format, w, h, c.opaque)?;
628            return Ok(Arc::new(PresentedFrame {
629                width: f.width,
630                height: f.height,
631                rgba: f.rgba,
632                opaque_blank: false,
633                native: None,
634            }));
635        }
636    }
637    let valid = c.as_ref().is_some_and(|c| c.client.check().is_ok());
638    let deadline = Instant::now() + Duration::from_secs(30);
639    while valid && !st.pending.is_empty() {
640        let remaining = deadline.saturating_duration_since(Instant::now());
641        if remaining.is_zero() {
642            return Err("Canvas snapshot timed out".into());
643        }
644        let (next, timeout) = s.changed.wait_timeout(st, remaining).unwrap();
645        st = next;
646        if timeout.timed_out() && !st.pending.is_empty() {
647            return Err("Canvas snapshot timed out".into());
648        }
649    }
650    if st.last.width > 0 && st.last.height > 0 {
651        let last = st.last.clone();
652        drop(st);
653        return if let Some(native) = &last.native {
654            native.snapshot()
655        } else {
656            Ok(last)
657        };
658    }
659    if valid {
660        if let Some(e) = &st.last_error {
661            return Err(e.clone());
662        }
663    }
664    blank(st.width, st.height, c.as_ref().is_some_and(|c| c.opaque))
665}
666fn straight(frame: &PresentedFrame) -> Vec<u8> {
667    let mut rgba = frame.rgba.clone();
668    for p in rgba.chunks_exact_mut(4) {
669        let a = p[3] as u32;
670        if a == 0 {
671            p[..3].fill(0);
672        } else if a != 255 {
673            for c in &mut p[..3] {
674                *c = ((u32::from(*c) * 255 + a / 2) / a).min(255) as u8;
675            }
676        }
677    }
678    rgba
679}
680pub(crate) unsafe fn pixels(g: *mut c_void, v: u64) -> Option<Result<(Vec<u8>, u32, u32), String>> {
681    let s = surface(g, v)?;
682    Some(snapshot(&s).map(|f| (straight(&f), f.width, f.height)))
683}
684/// Used by native 2D draws without round-tripping premultiplied pixels.
685pub(crate) unsafe fn premul_pixels(
686    g: *mut c_void,
687    v: u64,
688) -> Option<Result<(Vec<u8>, u32, u32), String>> {
689    let s = surface(g, v)?;
690    Some(snapshot(&s).map(|f| (f.rgba.clone(), f.width, f.height)))
691}
692fn capture(s: &Arc<Surface>) {
693    let (t, serial, epoch, c, w, h) = {
694        let mut st = s.state.lock().unwrap();
695        if !st.enabled {
696            return;
697        }
698        let Some(c) = st.config.clone() else {
699            return;
700        };
701        let active = st
702            .current
703            .take()
704            .map(|t| (st.serial, t))
705            .or_else(|| st.deferred.take());
706        let Some((serial, t)) = active else {
707            return;
708        };
709        t.destroyed.store(true, Ordering::Release);
710        if c.client.check().is_err() {
711            discard(Some(t));
712            return;
713        }
714        (t, serial, st.epoch, c, st.width, st.height)
715    };
716    if s.key.is_some() {
717        let presenter = presenter_slot().read().unwrap().clone();
718        if let Some(presenter) = presenter {
719            let result = c.client.checked(|| {
720                presenter.prepare(NativeSource {
721                    client: &c.client,
722                    texture: &t.raw,
723                    format: c.format,
724                    width: w,
725                    height: h,
726                    opaque: c.opaque,
727                })
728            });
729            match result {
730                Ok(Some(frame)) if c.client.release_presented_texture(&t.raw) => {
731                    let native = Arc::new(NativePresentation {
732                        frame,
733                        source: t.raw.clone(),
734                        snapshot_client: Client::new(c.client.context.clone()),
735                        format: c.format,
736                        width: w,
737                        height: h,
738                        opaque: c.opaque,
739                    });
740                    let mut st = s.state.lock().unwrap();
741                    if st.epoch == epoch && serial >= st.last_serial {
742                        // Older fallback readbacks cannot improve this native frame.
743                        // Drop their lease and do not make exports wait for them.
744                        st.reader = None;
745                        st.pending.clear();
746                        st.last_serial = serial;
747                        st.last_error = None;
748                        st.last = Arc::new(PresentedFrame {
749                            width: w,
750                            height: h,
751                            rgba: Vec::new(),
752                            opaque_blank: false,
753                            native: Some(native),
754                        });
755                        st.generation = generation();
756                        NATIVE_FRAMES.fetch_add(1, Ordering::Relaxed);
757                        notify(s, &st);
758                    }
759                    return;
760                }
761                Err(e) => {
762                    static WARNED: AtomicBool = AtomicBool::new(false);
763                    if !WARNED.swap(true, Ordering::Relaxed) {
764                        eprintln!(
765                            "[webgpu] Native presenter failed; using asynchronous readback: {e}"
766                        );
767                    }
768                }
769                _ => {}
770            }
771        }
772    }
773    let reader = {
774        let mut st = s.state.lock().unwrap();
775        if st.epoch != epoch {
776            discard(Some(t));
777            return;
778        }
779        st.pending.insert(serial);
780        st.reader
781            .get_or_insert_with(|| readback::Reader::new(&c.client))
782            .clone()
783    };
784    let weak = Arc::downgrade(s);
785    let result = reader.request(
786        &c.client,
787        t.raw.clone(),
788        c.format,
789        w,
790        h,
791        c.opaque,
792        Box::new(move |result| {
793            if let Some(s) = weak.upgrade() {
794                let mut st = s.state.lock().unwrap();
795                if st.epoch != epoch {
796                    return;
797                }
798                st.pending.remove(&serial);
799                match result {
800                    Ok(f) if serial >= st.last_serial => {
801                        st.last_serial = serial;
802                        st.last_error = None;
803                        st.last = Arc::new(PresentedFrame {
804                            width: f.width,
805                            height: f.height,
806                            rgba: f.rgba,
807                            opaque_blank: false,
808                            native: None,
809                        });
810                        st.generation = generation();
811                    }
812                    Err(e) if serial >= st.last_serial => st.last_error = Some(e),
813                    _ => {}
814                }
815                notify(&s, &st);
816            }
817        }),
818    );
819    match result {
820        Ok(true) => {
821            if s.key.is_some() {
822                READBACK_FRAMES.fetch_add(1, Ordering::Relaxed);
823            }
824            t.raw.destroy();
825        }
826        Ok(false) => {
827            let mut st = s.state.lock().unwrap();
828            if st.epoch == epoch {
829                st.pending.remove(&serial);
830                st.deferred = Some((serial, t));
831                s.changed.notify_all();
832                drop(st);
833                reader.wake_when_available(s.context);
834            } else {
835                discard(Some(t));
836            }
837        }
838        Err(e) => {
839            let mut st = s.state.lock().unwrap();
840            if st.epoch == epoch {
841                st.pending.remove(&serial);
842                st.last_error = Some(e);
843                notify(s, &st);
844            }
845            discard(Some(t));
846        }
847    }
848}
849/// Present only at the end of the host pump, after the whole rAF batch and its
850/// microtasks. No canvas texture expires between two callbacks in one frame.
851pub(crate) unsafe fn pump(g: *mut c_void) {
852    if glue::rjs_in_js(g) != 0 {
853        return;
854    }
855    let surfaces: Vec<_> = {
856        let mut a = all().lock().unwrap();
857        a.retain(|r| r.surface.strong_count() > 0);
858        a.iter()
859            .filter(|r| r.global == g as usize)
860            .filter_map(|r| r.surface.upgrade())
861            .collect()
862    };
863    for s in surfaces {
864        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| capture(&s)));
865    }
866}
867// Staging buffers belong to the shared native reader, not to a JS device.
868// Release this canvas's reader lease promptly when its logical client is lost.
869pub(super) fn device_destroyed(id: u64) {
870    let surfaces: Vec<_> = all()
871        .lock()
872        .unwrap()
873        .iter()
874        .filter_map(|r| r.surface.upgrade())
875        .collect();
876    for s in surfaces {
877        let mut st = s.state.lock().unwrap();
878        if st.config.as_ref().is_some_and(|c| c.client.id == id) {
879            discard(st.current.take());
880            discard(st.deferred.take().map(|(_, t)| t));
881            st.reader = None;
882            st.epoch = st.epoch.wrapping_add(1);
883            st.pending.clear();
884            st.last_error = None;
885            if st.last.native.is_some() {
886                st.last = clear(st.config.as_ref().is_some_and(|c| c.opaque));
887                st.generation = generation();
888                notify(&s, &st);
889            }
890            s.changed.notify_all();
891        }
892    }
893}
894
895pub(crate) fn forget(gone: redjs::context::Gone) {
896    let surfaces: Vec<_> = {
897        let mut a = all().lock().unwrap();
898        let surfaces = a
899            .iter()
900            .filter(|r| r.global == gone.key)
901            .filter_map(|r| r.surface.upgrade())
902            .collect();
903        a.retain(|r| r.global != gone.key);
904        surfaces
905    };
906    for s in surfaces {
907        reset(&s, None, None);
908        if let Some(key) = s.key {
909            unregister_present(key);
910        }
911    }
912}
913
914#[redjs::host_fn]
915unsafe fn h_context(g: *mut c_void, cf: *mut c_void) -> u64 {
916    run(g, || {
917        let owner = cf_arg(cf, 0);
918        if !is_cell(owner) {
919            invalid(g, "Canvas owner must be an object")?;
920        }
921        let w = uint(g, cf_arg(cf, 1), 0)?;
922        let h = uint(g, cf_arg(cf, 2), 0)?;
923        let key = num(g, cf_arg(cf, 3), 0)?;
924        Ok(create(g, owner, w, h, (key != 0).then_some(key)))
925    })
926}
927#[redjs::host_fn]
928unsafe fn h_resize(g: *mut c_void, cf: *mut c_void) -> u64 {
929    run(g, || {
930        let w = uint(g, cf_arg(cf, 1), 0)?;
931        let h = uint(g, cf_arg(cf, 2), 0)?;
932        resize(g, cf_arg(cf, 0), w, h)?;
933        Ok(UNDEF)
934    })
935}
936unsafe fn capture_args(
937    g: *mut c_void,
938    cf: *mut c_void,
939) -> Result<(Arc<PresentedFrame>, String, Option<f64>), ()> {
940    let Some(s) = surface(g, cf_arg(cf, 0)) else {
941        invalid(g, "Not a GPUCanvasContext")?;
942        unreachable!()
943    };
944    let ty = text(g, cf_arg(cf, 1), "image/png")?;
945    let q = if cf_arg(cf, 2) == UNDEF {
946        None
947    } else {
948        Some(to_number(g, cf_arg(cf, 2))?)
949    };
950    let f = snapshot(&s).map_err(|e| {
951        redjs::webapi::domexception::throw(g, "OperationError", &e);
952    })?;
953    Ok((f, ty, q))
954}
955#[redjs::host_fn]
956unsafe fn h_data_url(g: *mut c_void, cf: *mut c_void) -> u64 {
957    run(g, || {
958        let (f, ty, q) = capture_args(g, cf)?;
959        let rgba = straight(&f);
960        Ok(js_string(
961            g,
962            &redjs::webapi::canvas2d::encode::data_url(&rgba, f.width, f.height, &ty, q),
963        ))
964    })
965}
966#[redjs::host_fn]
967unsafe fn h_blob(g: *mut c_void, cf: *mut c_void) -> u64 {
968    run(g, || {
969        let (f, ty, q) = capture_args(g, cf)?;
970        if f.width == 0 || f.height == 0 {
971            return Ok(NULL);
972        }
973        let (mime, data) =
974            redjs::webapi::canvas2d::encode::encode(&straight(&f), f.width, f.height, &ty, q);
975        Ok(redjs::webapi::blob::create(
976            g,
977            redjs::webapi::util::state(g).blob.proto,
978            data,
979            mime,
980        ))
981    })
982}
983pub(crate) unsafe fn convert_to_blob(g: *mut c_void, ctx: u64, options: u64) -> u64 {
984    run(g, || {
985        let Some(s) = surface(g, ctx) else {
986            invalid(g, "Not a GPUCanvasContext")?;
987            unreachable!()
988        };
989        let o = Val::new(g, options);
990        let ty = text(g, field(g, o.v, "type")?.v, "image/png")?;
991        let v = field(g, o.v, "quality")?;
992        let q = if v.v == UNDEF {
993            None
994        } else {
995            Some(to_number(g, v.v)?)
996        };
997        let (w, h) = {
998            let st = s.state.lock().unwrap();
999            (st.width, st.height)
1000        };
1001        if w == 0 || h == 0 {
1002            return Ok(redjs::webapi::domexception::rejected(
1003                g,
1004                "IndexSizeError",
1005                "Canvas has no pixels",
1006            ));
1007        }
1008        let f = snapshot(&s).map_err(|e| {
1009            redjs::webapi::domexception::throw(g, "OperationError", &e);
1010        })?;
1011        Ok(async_op(
1012            g,
1013            vec![ctx],
1014            async move {
1015                Ok(redjs::webapi::canvas2d::encode::encode(
1016                    &straight(&f),
1017                    f.width,
1018                    f.height,
1019                    &ty,
1020                    q,
1021                ))
1022            },
1023            |g, (mime, bytes)| {
1024                redjs::webapi::blob::create(
1025                    g,
1026                    redjs::webapi::util::state(g).blob.proto,
1027                    bytes,
1028                    mime,
1029                )
1030            },
1031        ))
1032    })
1033}
1034pub(crate) unsafe fn transfer(g: *mut c_void, ctx: u64) -> u64 {
1035    run(g, || {
1036        let Some(s) = surface(g, ctx) else {
1037            invalid(g, "Not a GPUCanvasContext")?;
1038            unreachable!()
1039        };
1040        let f = snapshot(&s).map_err(|e| {
1041            redjs::webapi::domexception::throw(g, "OperationError", &e);
1042        })?;
1043        let config = s.state.lock().unwrap().config.clone();
1044        reset(&s, config, None);
1045        glue::rjs_define(g, ctx, slots(g).2, UNDEF, 1 | 2);
1046        Ok(redjs::webapi::image::create_bitmap(
1047            g,
1048            redjs::webapi::image::BitmapData::new(f.width, f.height, straight(&f)),
1049        ))
1050    })
1051}
1052pub(super) unsafe fn install(g: *mut c_void) {
1053    class(
1054        g,
1055        Kind::Canvas,
1056        "GPUCanvasContext",
1057        &[
1058            ("configure", 1, configure),
1059            ("unconfigure", 0, unconfigure),
1060            ("getConfiguration", 0, configuration),
1061            ("getCurrentTexture", 0, current_texture),
1062        ],
1063        &[("canvas", get_canvas)],
1064    );
1065    let global = glue::rjs_global(g);
1066    for (name, arity, f) in [
1067        ("__rjs_webgpu_context", 4, h_context as HostFn),
1068        ("__rjs_webgpu_resize", 3, h_resize),
1069        ("__rjs_webgpu_data_url", 3, h_data_url),
1070        ("__rjs_webgpu_blob", 3, h_blob),
1071    ] {
1072        define(g, global, name, make_fn(g, name, arity, f), 2);
1073    }
1074}