euv-core 0.48.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
use super::*;

/// Default initialization for `WebPlatform`.
impl Default for WebPlatform {
    /// Creates an empty browser WebAssembly platform backend.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized web platform.
    fn default() -> Self {
        let initial_hidden: bool = web_document_hidden();
        Self {
            next_id: 1,
            windows: HashMap::new(),
            pending_events: Vec::new(),
            clipboard_cache: None,
            last_hidden: initial_hidden,
            last_online: web_navigator_online(),
            last_theme: web_system_theme(),
            last_locale: web_navigator_locale(),
            last_safe_area: SafeAreaInsets::default(),
            refresh_rate_hz: FALLBACK_REFRESH_RATE_HZ,
            pump_paused: initial_hidden,
            needs_frame: true,
            raf_scheduled: false,
            raf_handle: 0,
        }
    }
}

/// Browser system event injection, demand-driven `rAF`, and `ResizeObserver` helpers for `WebPlatform`.
impl WebPlatform {
    /// Marks the web surface dirty so the demand-driven `requestAnimationFrame` scheduler wakes immediately.
    pub fn request_demand_frame(&mut self) {
        self.set_needs_frame(true);
    }

    /// Marks the web surface idle so `requestAnimationFrame` sleeps at 0 Hz until input, signal, or animation wakes it.
    pub fn mark_frame_idle(&mut self) {
        self.set_needs_frame(false);
        self.set_raf_scheduled(false);
        self.set_raf_handle(0);
        let _: bool = take_frame_needed();
    }

    /// Returns whether a new `requestAnimationFrame` callback should be scheduled right now.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when unpaused, dirty, and no `rAF` callback is already pending.
    #[must_use]
    pub fn should_schedule_raf(&self) -> bool {
        !self.get_pump_paused()
            && (self.get_needs_frame() || is_frame_needed())
            && !self.get_raf_scheduled()
    }

    /// Schedules a demand-driven `window.requestAnimationFrame(callback)` only if dirty and not already armed.
    ///
    /// # Arguments
    ///
    /// - `&Function` - JavaScript `requestAnimationFrame` callback function.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when a new `rAF` callback was scheduled.
    pub fn schedule_demand_raf(&mut self, callback: &Function) -> bool {
        if !self.should_schedule_raf() {
            return false;
        }
        if let Some(win) = window()
            && let Ok(handle) = win.request_animation_frame(callback)
        {
            self.set_raf_scheduled(true);
            self.set_raf_handle(handle);
            return true;
        }
        false
    }

    /// Cancels any pending browser `requestAnimationFrame` callback so hidden/idle tabs burn zero CPU.
    pub fn cancel_pending_raf(&mut self) {
        let handle: i32 = self.get_raf_handle();
        if handle != 0 {
            if let Some(win) = window() {
                drop(win.cancel_animation_frame(handle));
            }
            self.set_raf_handle(0);
        }
        self.set_raf_scheduled(false);
    }

    /// Attaches a `ResizeObserver` to the canvas backing `id` so resize events arrive without layout polling.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window handle.
    /// - `&Function` - Callback invoked when the canvas box changes.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `ResizeObserver` was created and attached.
    pub fn attach_resize_observer(&mut self, id: WindowId, callback: &Function) -> bool {
        let Some(rec) = self.get_mut_windows().get_mut(&id) else {
            return false;
        };
        let WebWindowRecord {
            canvas,
            resize_observer,
            ..
        } = rec;
        if let Some(prev) = resize_observer.take() {
            web_disconnect_resize_observer(&prev);
        }
        if let Some(el) = canvas.as_ref()
            && let Some(obs) = web_attach_resize_observer(el, callback)
        {
            *resize_observer = Some(obs);
            return true;
        }
        false
    }

    /// Returns the active browser graphics context tier (`WebGpu`, `WebGl2`, or `Canvas2d`) for `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Web window identifier.
    ///
    /// # Returns
    ///
    /// - `Option<WebCanvasContextKind>` - Active context kind if `id` exists.
    #[must_use]
    pub fn canvas_context_kind(&self, id: WindowId) -> Option<WebCanvasContextKind> {
        self.get_windows()
            .get(&id)
            .map(WebWindowRecord::get_context_kind)
    }

    /// Returns the active Web presentation mode (`GpuDirect`, `GpuUpload`, or `Software`) for `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Web window identifier.
    ///
    /// # Returns
    ///
    /// - `Option<WebPresentationMode>` - Active presentation mode.
    #[must_use]
    pub fn presentation_mode(&self, id: WindowId) -> Option<WebPresentationMode> {
        self.get_windows()
            .get(&id)
            .map(WebWindowRecord::get_presentation_mode)
    }

    /// Returns whether a CPU software framebuffer mirror is currently active on Web window `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Web window identifier.
    ///
    /// # Returns
    ///
    /// - `bool` - `false` on `GpuDirect`; `true` on `GpuUpload` or `Software`.
    #[must_use]
    pub fn cpu_mirror_active(&self, id: WindowId) -> bool {
        self.get_windows()
            .get(&id)
            .map(WebWindowRecord::get_cpu_mirror_active)
            .unwrap_or(true)
    }

    /// Returns the latest truthful browser presentation telemetry snapshot for `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Web window identifier.
    ///
    /// # Returns
    ///
    /// - `Option<WebPresentTelemetry>` - Latest presentation telemetry with `SubmissionProxy` timing tag.
    #[must_use]
    pub fn last_present_telemetry(&self, id: WindowId) -> Option<WebPresentTelemetry> {
        self.get_windows()
            .get(&id)
            .map(WebWindowRecord::get_last_telemetry)
    }

    /// Records a browser `requestAnimationFrame` callback strictly as `WebPresentTimingSource::SubmissionProxy` (never fake compositor proof).
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window identifier.
    pub fn record_raf_submission_proxy(&mut self, id: WindowId) {
        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
            let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
            tel.set_present_timing_source(WebPresentTimingSource::SubmissionProxy);
            tel.set_raf_callback_count(tel.get_raf_callback_count().saturating_add(1));
            rec.set_last_telemetry(tel);
        }
    }

    /// Renders GPU primitive `batches` directly via WebGL2 uber-shader (`GpuDirect`, `cpu_mirror_active = false`, `upload_bytes = 0`).
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window identifier.
    /// - `u32` - Physical surface width in pixels.
    /// - `u32` - Physical surface height in pixels.
    /// - `Color` - Surface clear color.
    /// - `&[GpuBatch]` - Ordered GPU primitive draw batches.
    ///
    /// # Returns
    ///
    /// - `Result<WebPresentTelemetry, PlatformError>` - Direct GPU presentation telemetry (`cpu_mirror_active = false`).
    pub fn present_gl2_direct_batches(
        &mut self,
        id: WindowId,
        width: u32,
        height: u32,
        clear_color: Color,
        batches: &[GpuBatch],
    ) -> Result<WebPresentTelemetry, PlatformError> {
        let rec: &mut WebWindowRecord = self
            .get_mut_windows()
            .get_mut(&id)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        let drawn: u32 = {
            let WebWindowRecord {
                canvas,
                gl2,
                gl2_direct_program,
                gl2_direct_view_loc,
                gl2_direct_rect_loc,
                gl2_direct_color_loc,
                ..
            } = rec;
            let (Some(gl), Some(prog)) = (gl2.as_ref(), gl2_direct_program.as_ref()) else {
                return Err(PlatformError::SurfaceError(
                    ERR_WEB_GL2_DIRECT_MISSING.to_string(),
                ));
            };
            if let Some(el) = canvas.as_ref() {
                if el.width() != width.max(1) {
                    el.set_width(width.max(1));
                }
                if el.height() != height.max(1) {
                    el.set_height(height.max(1));
                }
            }
            web_draw_gl2_direct_batches(
                gl,
                prog,
                gl2_direct_view_loc.as_ref(),
                gl2_direct_rect_loc.as_ref(),
                gl2_direct_color_loc.as_ref(),
                width,
                height,
                clear_color,
                batches,
            )
        };
        let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
        tel.set_mode(WebPresentationMode::GpuDirect);
        tel.set_cpu_mirror_active(false);
        tel.set_upload_bytes(0);
        tel.set_primitive_count(drawn);
        tel.set_present_timing_source(WebPresentTimingSource::SubmissionProxy);
        tel.set_active_canvas_generation(rec.get_active_canvas_generation());
        rec.set_presentation_mode(WebPresentationMode::GpuDirect);
        rec.set_cpu_mirror_active(false);
        rec.set_last_telemetry(tel);
        Ok(tel)
    }

    /// Starts an independent-canvas handoff to `target_mode`, creating a hidden sibling `<canvas>` whenever switching context families (`WebGl2` <-> `Canvas2d`).
    ///
    /// NEVER calls `getContext("2d")` and `getContext("webgl2")` on the same `<canvas>`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window identifier.
    /// - `WebPresentationMode` - Candidate presentation mode.
    ///
    /// # Returns
    ///
    /// - `Result<bool, PlatformError>` - `Ok(true)` when a hidden standby `<canvas>` was allocated; `Ok(false)` when mode switched in-place on the same WebGL2 context.
    pub fn begin_canvas_handoff(
        &mut self,
        id: WindowId,
        target_mode: WebPresentationMode,
    ) -> Result<bool, PlatformError> {
        let rec: &mut WebWindowRecord = self
            .get_mut_windows()
            .get_mut(&id)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        let target_ctx_kind: WebCanvasContextKind = match target_mode {
            WebPresentationMode::GpuDirect | WebPresentationMode::GpuUpload => {
                WebCanvasContextKind::WebGl2
            }
            WebPresentationMode::Software => WebCanvasContextKind::Canvas2d,
        };
        if rec.get_context_kind() == target_ctx_kind {
            if target_mode == WebPresentationMode::GpuDirect && rec.gl2_direct_program.is_none() {
                return Err(PlatformError::SurfaceError(
                    ERR_WEB_GL2_DIRECT_MISSING.to_string(),
                ));
            }
            let cpu_mirror: bool = target_mode != WebPresentationMode::GpuDirect;
            rec.set_presentation_mode(target_mode);
            rec.set_cpu_mirror_active(cpu_mirror);
            let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
            tel.set_mode(target_mode);
            tel.set_cpu_mirror_active(cpu_mirror);
            tel.set_present_timing_source(WebPresentTimingSource::SubmissionProxy);
            rec.set_last_telemetry(tel);
            return Ok(false);
        }
        let phys_w: u32 = rec.get_state().get_physical_width().max(1);
        let phys_h: u32 = rec.get_state().get_physical_height().max(1);
        let next_gen: u64 = rec.get_active_canvas_generation().saturating_add(1);
        let parent_el: Option<Element> = rec
            .canvas
            .as_ref()
            .and_then(|c: &HtmlCanvasElement| c.parent_element());
        let standby_surface: WebCanvasSurface = match web_create_independent_standby_canvas(
            parent_el.as_ref(),
            target_mode,
            phys_w,
            phys_h,
        ) {
            Ok(surface) => surface,
            Err(err) => {
                let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
                tel.set_handoff_aborts(tel.get_handoff_aborts().saturating_add(1));
                rec.set_last_telemetry(tel);
                return Err(err);
            }
        };
        let WebWindowRecord { standby_canvas, .. } = rec;
        if let Some(prev) = standby_canvas.take() {
            prev.canvas.remove();
        }
        *standby_canvas = Some(WebStandbyCanvasTarget {
            generation: next_gen,
            target_mode,
            context_kind: standby_surface.context_kind,
            canvas: standby_surface.canvas,
            webgpu_ctx: standby_surface.webgpu_ctx,
            gl2: standby_surface.gl2,
            gl2_direct_program: standby_surface.gl2_direct_program,
            gl2_direct_view_loc: standby_surface.gl2_direct_view_loc,
            gl2_direct_rect_loc: standby_surface.gl2_direct_rect_loc,
            gl2_direct_color_loc: standby_surface.gl2_direct_color_loc,
            gl2_program: standby_surface.gl2_program,
            gl2_texture: standby_surface.gl2_texture,
            gl2_view_loc: standby_surface.gl2_view_loc,
            gl2_tex_width: 0,
            gl2_tex_height: 0,
            ctx2d: standby_surface.ctx2d,
            ready: false,
            ready_width: 0,
            ready_height: 0,
            ready_scene_version: 0,
        });
        Ok(true)
    }

    /// Pre-warms the hidden standby `<canvas>` with a complete candidate first frame matching `(width, height, scene_version)`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window identifier.
    /// - `Option<&Framebuffer>` - Rendered CPU framebuffer for `GpuUpload` or `Software` standby pre-warming.
    /// - `Option<&[GpuBatch]>` - GPU batches for `GpuDirect` standby pre-warming.
    /// - `Color` - Clear color for `GpuDirect` pre-warming.
    /// - `u64` - Active scene version bound to this candidate first frame.
    ///
    /// # Returns
    ///
    /// - `Result<bool, PlatformError>` - `Ok(true)` when the standby canvas rendered cleanly and is ready for frame-boundary swap.
    pub fn prewarm_standby_canvas(
        &mut self,
        id: WindowId,
        framebuffer: Option<&Framebuffer>,
        batches: Option<&[GpuBatch]>,
        clear_color: Color,
        scene_version: u64,
    ) -> Result<bool, PlatformError> {
        let rec: &mut WebWindowRecord = self
            .get_mut_windows()
            .get_mut(&id)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        let rec_state: WindowState = rec.get_state();
        let phys_w: u32 = rec_state.get_physical_width().max(1);
        let phys_h: u32 = rec_state.get_physical_height().max(1);
        let WebWindowRecord { standby_canvas, .. } = rec;
        let Some(standby) = standby_canvas.as_mut() else {
            return Ok(false);
        };
        let warm_res: Result<(), PlatformError> = match standby.target_mode {
            WebPresentationMode::GpuDirect => {
                if let (Some(gl), Some(prog)) =
                    (standby.gl2.as_ref(), standby.gl2_direct_program.as_ref())
                {
                    let slice: &[GpuBatch] = batches.unwrap_or(&[]);
                    let _: u32 = web_draw_gl2_direct_batches(
                        gl,
                        prog,
                        standby.gl2_direct_view_loc.as_ref(),
                        standby.gl2_direct_rect_loc.as_ref(),
                        standby.gl2_direct_color_loc.as_ref(),
                        phys_w,
                        phys_h,
                        clear_color,
                        slice,
                    );
                    Ok(())
                } else {
                    Err(PlatformError::SurfaceError(
                        ERR_WEB_GL2_DIRECT_MISSING.to_string(),
                    ))
                }
            }
            WebPresentationMode::GpuUpload => {
                if let Some(fb) = framebuffer {
                    let mut tmp: WebWindowRecord = WebWindowRecord {
                        config: WindowConfig::default(),
                        state: rec_state,
                        canvas_id: 0,
                        context_kind: standby.context_kind,
                        presentation_mode: WebPresentationMode::GpuUpload,
                        cpu_mirror_active: true,
                        active_canvas_generation: standby.generation,
                        canvas: Some(standby.canvas.clone()),
                        webgpu_ctx: None,
                        gl2: standby.gl2.clone(),
                        gl2_direct_program: None,
                        gl2_direct_view_loc: None,
                        gl2_direct_rect_loc: None,
                        gl2_direct_color_loc: None,
                        gl2_program: standby.gl2_program.clone(),
                        gl2_texture: standby.gl2_texture.clone(),
                        gl2_view_loc: standby.gl2_view_loc.clone(),
                        gl2_tex_width: standby.gl2_tex_width,
                        gl2_tex_height: standby.gl2_tex_height,
                        ctx2d: None,
                        standby_canvas: None,
                        last_telemetry: WebPresentTelemetry::default(),
                        resize_observer: None,
                    };
                    let uploaded: Option<u64> =
                        web_present_gl2_region(&mut tmp, fb, DamageRegion::full())?;
                    standby.gl2_tex_width = tmp.get_gl2_tex_width();
                    standby.gl2_tex_height = tmp.get_gl2_tex_height();
                    if uploaded.is_some() {
                        Ok(())
                    } else {
                        Err(PlatformError::SurfaceError(
                            ERR_WEB_GL2_CONTEXT_MISSING.to_string(),
                        ))
                    }
                } else {
                    Err(PlatformError::SurfaceError(
                        ERR_WEB_PRESENT_FAILED.to_string(),
                    ))
                }
            }
            WebPresentationMode::Software => {
                if let (Some(ctx2d), Some(fb)) = (standby.ctx2d.as_ref(), framebuffer) {
                    let _: u64 = web_present_image_data_region(
                        Some(&standby.canvas),
                        ctx2d,
                        fb,
                        DamageRegion::full(),
                    )?;
                    Ok(())
                } else {
                    Err(PlatformError::SurfaceError(
                        ERR_WEB_CTX2D_MISSING.to_string(),
                    ))
                }
            }
        };
        match warm_res {
            Ok(()) => {
                standby.ready = true;
                standby.ready_width = phys_w;
                standby.ready_height = phys_h;
                standby.ready_scene_version = scene_version;
                Ok(true)
            }
            Err(err) => {
                self.abort_canvas_handoff(id);
                Err(err)
            }
        }
    }

    /// Atomically swaps visibility/z-index from the active `<canvas>` to the pre-warmed standby `<canvas>` at a frame boundary and retires the old canvas only after commit.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window identifier.
    /// - `u32` - Current expected physical surface width.
    /// - `u32` - Current expected physical surface height.
    /// - `u64` - Current expected scene revision.
    ///
    /// # Returns
    ///
    /// - `Result<bool, PlatformError>` - `Ok(true)` when atomic swap committed; `Ok(false)` when standby was missing, stale, or mismatched (keeping old canvas active).
    pub fn commit_canvas_handoff_at_frame_boundary(
        &mut self,
        id: WindowId,
        expected_width: u32,
        expected_height: u32,
        expected_scene_version: u64,
    ) -> Result<bool, PlatformError> {
        let rec: &mut WebWindowRecord = self
            .get_mut_windows()
            .get_mut(&id)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        let WebWindowRecord { standby_canvas, .. } = rec;
        let is_valid: bool = standby_canvas
            .as_ref()
            .map(|s: &WebStandbyCanvasTarget| {
                s.ready
                    && s.ready_width == expected_width.max(1)
                    && s.ready_height == expected_height.max(1)
                    && s.ready_scene_version == expected_scene_version
            })
            .unwrap_or(false);
        if !is_valid {
            self.abort_canvas_handoff(id);
            return Ok(false);
        }
        let Some(standby) = standby_canvas.take() else {
            return Ok(false);
        };
        let active_style: String =
            format!("{WEB_CANVAS_STYLE_PREFIX}{WEB_CURSOR_POINTER}{WEB_CANVAS_STYLE_SUFFIX}");
        drop(standby.canvas.set_attribute(WEB_ATTR_STYLE, &active_style));
        drop(
            standby
                .canvas
                .set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_ACTIVE),
        );
        let old_canvas: Option<HtmlCanvasElement> = rec.canvas.replace(standby.canvas);
        if let Some(prev) = old_canvas {
            drop(prev.set_attribute(WEB_ATTR_STYLE, WEB_STANDBY_CANVAS_STYLE));
            drop(prev.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_STANDBY));
            prev.remove();
        }
        let cpu_mirror: bool = standby.target_mode != WebPresentationMode::GpuDirect;
        rec.set_context_kind(standby.context_kind);
        rec.set_presentation_mode(standby.target_mode);
        rec.set_cpu_mirror_active(cpu_mirror);
        rec.set_active_canvas_generation(standby.generation);
        rec.webgpu_ctx = standby.webgpu_ctx;
        rec.gl2 = standby.gl2;
        rec.gl2_direct_program = standby.gl2_direct_program;
        rec.gl2_direct_view_loc = standby.gl2_direct_view_loc;
        rec.gl2_direct_rect_loc = standby.gl2_direct_rect_loc;
        rec.gl2_direct_color_loc = standby.gl2_direct_color_loc;
        rec.gl2_program = standby.gl2_program;
        rec.gl2_texture = standby.gl2_texture;
        rec.gl2_view_loc = standby.gl2_view_loc;
        rec.set_gl2_tex_width(standby.gl2_tex_width);
        rec.set_gl2_tex_height(standby.gl2_tex_height);
        rec.ctx2d = standby.ctx2d;
        let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
        tel.set_mode(standby.target_mode);
        tel.set_cpu_mirror_active(cpu_mirror);
        tel.set_present_timing_source(WebPresentTimingSource::SubmissionProxy);
        tel.set_active_canvas_generation(standby.generation);
        tel.set_handoff_swaps_completed(tel.get_handoff_swaps_completed().saturating_add(1));
        rec.set_last_telemetry(tel);
        Ok(true)
    }

    /// Aborts any pending standby canvas handoff, removing the hidden candidate `<canvas>` without disturbing the active canvas.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target web window identifier.
    pub fn abort_canvas_handoff(&mut self, id: WindowId) {
        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
            let WebWindowRecord { standby_canvas, .. } = rec;
            if let Some(prev) = standby_canvas.take() {
                prev.canvas.remove();
                let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
                tel.set_handoff_aborts(tel.get_handoff_aborts().saturating_add(1));
                rec.set_last_telemetry(tel);
            }
        }
    }

    /// Updates the measured browser `requestAnimationFrame` refresh rate across open web windows.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform backend.
    /// - `f32` - Measured browser presentation rate in Hertz.
    pub fn update_refresh_rate_hz(&mut self, hz: f32) {
        let pacing: FramePacingConfig = compute_frame_pacing(hz);
        let preferred_hz: f32 = pacing.get_preferred_hz();
        self.set_refresh_rate_hz(preferred_hz);
        let rounded: u32 = preferred_hz.round() as u32;
        for rec in self.get_mut_windows().values_mut() {
            rec.get_mut_state()
                .get_mut_display()
                .set_refresh_rate_hz(rounded);
        }
    }

    /// Re-queries CSS `env(safe-area-inset-*)` and dispatches `WindowEvent::SafeAreaChanged` when changed.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform backend.
    pub fn sync_safe_area(&mut self) {
        let measured: SafeAreaInsets = web_query_safe_area_insets();
        if measured != self.get_last_safe_area() {
            self.set_last_safe_area(measured);
            let mut updates: Vec<(WindowId, SafeAreaInsets)> =
                Vec::with_capacity(self.get_windows().len());
            for (&wid, rec) in self.get_mut_windows().iter_mut() {
                let effective: SafeAreaInsets =
                    if rec.get_state().get_fullscreen() == FullscreenMode::Windowed {
                        measured
                    } else {
                        SafeAreaInsets::default()
                    };
                rec.get_mut_state().set_safe_area(effective);
                updates.push((wid, effective));
            }
            for (wid, effective) in updates.into_iter() {
                self.get_mut_pending_events()
                    .push(WindowEvent::SafeAreaChanged(wid, effective));
            }
        }
    }

    /// Enqueues a browser `SystemEvent` (e.g. from DOM visibility/focus/online/hashchange listeners).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform backend.
    /// - `SystemEvent` - System event to enqueue.
    pub fn push_system_event(&mut self, event: SystemEvent) {
        match &event {
            SystemEvent::Background => {
                self.set_pump_paused(true);
            }
            SystemEvent::Foreground => {
                self.set_pump_paused(false);
            }
            _ => {}
        }
        self.get_mut_pending_events()
            .push(WindowEvent::System(event));
    }
}

/// `WindowController` implementation for Browser WebAssembly.
impl WindowController for WebPlatform {
    /// Applies a `WindowCommand` against the browser document and `HTMLCanvasElement`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    /// - `WindowCommand` - Command to apply.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Execution status.
    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
        match command {
            WindowCommand::SetTitle(id, title) => {
                let rec: &mut WebWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                if let Some(doc) = window().and_then(|w: Window| w.document()) {
                    doc.set_title(&title);
                }
                rec.get_mut_config().set_title(title);
                Ok(())
            }
            WindowCommand::SetSize(id, width, height) => {
                let rec: &mut WebWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                let w: u32 = width.max(1);
                let h: u32 = height.max(1);
                let live_dpr: f32 = window()
                    .map(|bw: Window| {
                        let raw: f64 = bw.device_pixel_ratio();
                        if raw.is_finite() && raw > 0.0 {
                            (raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
                        } else {
                            1.0
                        }
                    })
                    .unwrap_or_else(|| {
                        rec.get_state()
                            .get_scale_factor()
                            .clamp(WEB_DPR_MIN, WEB_DPR_MAX)
                    });
                rec.get_mut_state().set_scale_factor(live_dpr);
                let dpr_f64: f64 = live_dpr as f64;
                let (css_w, css_h): (f64, f64) = {
                    let WebWindowRecord { canvas, .. } = rec;
                    if let Some(el) = canvas.as_ref() {
                        let rect: DomRect = el.get_bounding_client_rect();
                        if rect.width() >= 1.0
                            && rect.height() >= 1.0
                            && (rect.width() - (w as f64)).abs() <= 1.5
                            && (rect.height() - (h as f64)).abs() <= 1.5
                        {
                            (rect.width(), rect.height())
                        } else {
                            (w as f64, h as f64)
                        }
                    } else {
                        (w as f64, h as f64)
                    }
                };
                let phys_w: u32 = (css_w * dpr_f64)
                    .round()
                    .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
                let phys_h: u32 = (css_h * dpr_f64)
                    .round()
                    .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
                let WebWindowRecord { canvas, .. } = rec;
                if let Some(el) = canvas.as_ref() {
                    if el.width() != phys_w {
                        el.set_width(phys_w);
                    }
                    if el.height() != phys_h {
                        el.set_height(phys_h);
                    }
                    let css_style: String = format!(
                        "{WEB_CANVAS_STYLE_PREFIX}{WEB_CURSOR_DEFAULT}{WEB_CANVAS_STYLE_SUFFIX}"
                    );
                    drop(el.set_attribute(WEB_ATTR_STYLE, &css_style));
                }
                rec.get_mut_config().set_width(w);
                rec.get_mut_config().set_height(h);
                rec.get_mut_state()
                    .set_logical_width((phys_w as f32) / live_dpr);
                rec.get_mut_state()
                    .set_logical_height((phys_h as f32) / live_dpr);
                rec.get_mut_state().set_physical_width(phys_w);
                rec.get_mut_state().set_physical_height(phys_h);
                self.sync_safe_area();
                Ok(())
            }
            WindowCommand::SetFullscreen(id, mode) => {
                let want_fs: bool = mode != FullscreenMode::Windowed;
                let next_safe: SafeAreaInsets = if want_fs {
                    SafeAreaInsets::default()
                } else {
                    web_query_safe_area_insets()
                };
                {
                    let rec: &mut WebWindowRecord = self
                        .get_mut_windows()
                        .get_mut(&id)
                        .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                    rec.get_mut_config().set_fullscreen(mode);
                    rec.get_mut_state().set_fullscreen(mode);
                    rec.get_mut_state().set_safe_area(next_safe);
                }
                self.set_last_safe_area(next_safe);
                self.get_mut_pending_events()
                    .push(WindowEvent::SafeAreaChanged(id, next_safe));
                web_set_fullscreen(want_fs);
                Ok(())
            }
            WindowCommand::SetRenderMode(id, mode) => {
                let rec: &mut WebWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().get_mut_render().set_mode(mode);
                Ok(())
            }
            WindowCommand::RequestRedraw(id) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                self.set_needs_frame(true);
                self.get_mut_pending_events()
                    .push(WindowEvent::RedrawRequested(id));
                Ok(())
            }
            WindowCommand::Close(id) => {
                let rec: WebWindowRecord = self
                    .get_mut_windows()
                    .remove(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                let WebWindowRecord {
                    canvas,
                    resize_observer,
                    ..
                } = rec;
                if let Some(obs) = resize_observer {
                    web_disconnect_resize_observer(&obs);
                }
                if let Some(el) = canvas {
                    el.remove();
                }
                Ok(())
            }
            WindowCommand::SetCursor(id, cursor) => {
                let rec: &WebWindowRecord = self
                    .get_windows()
                    .get(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                let css_cursor: &str = match cursor {
                    CursorIcon::Default => WEB_CURSOR_DEFAULT,
                    CursorIcon::Pointer => WEB_CURSOR_POINTER,
                    CursorIcon::Text => WEB_CURSOR_TEXT,
                    CursorIcon::Crosshair => WEB_CURSOR_CROSSHAIR,
                    CursorIcon::NotAllowed => WEB_CURSOR_NOT_ALLOWED,
                    CursorIcon::Grab => WEB_CURSOR_GRAB,
                    CursorIcon::Grabbing => WEB_CURSOR_GRABBING,
                    CursorIcon::Move => WEB_CURSOR_MOVE,
                    CursorIcon::EwResize => WEB_CURSOR_EW_RESIZE,
                    CursorIcon::NsResize => WEB_CURSOR_NS_RESIZE,
                };
                let WebWindowRecord { canvas, .. } = rec;
                if let Some(el) = canvas.as_ref() {
                    let css_style: String =
                        format!("{WEB_CANVAS_STYLE_PREFIX}{css_cursor}{WEB_CANVAS_STYLE_SUFFIX}");
                    drop(el.set_attribute(WEB_ATTR_STYLE, &css_style));
                }
                Ok(())
            }
            WindowCommand::SetPosition(id, _, _)
            | WindowCommand::SetResizable(id, _)
            | WindowCommand::SetDecorations(id, _)
            | WindowCommand::SetAlwaysOnTop(id, _)
            | WindowCommand::SetVisible(id, _)
            | WindowCommand::SetIme(id, _, _)
            | WindowCommand::SetStatusBarStyle(id, _) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                Ok(())
            }
        }
    }
}

/// `PlatformBackend` implementation for Browser WebAssembly.
impl PlatformBackend for WebPlatform {
    /// Returns `PlatformKind::Web`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `PlatformKind` - `PlatformKind::Web`.
    fn kind(&self) -> PlatformKind {
        PlatformKind::Web
    }

    /// Returns browser capability flags.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `PlatformCapabilities` - Web capability flags.
    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities::for_platform(PlatformKind::Web)
    }

    /// Creates a browser canvas surface configured with device pixel ratio and dark mode detection.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    /// - `&WindowConfig` - Declarative window config.
    ///
    /// # Returns
    ///
    /// - `Result<WindowState, PlatformError>` - Initial window state.
    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
        let dpr: f32 = web_device_pixel_ratio();
        let reuse_existing: bool = self.get_windows().is_empty();
        let surface: WebCanvasSurface = web_create_canvas(config, dpr, reuse_existing)?;
        let raw_id: u64 = self.get_next_id();
        let id: WindowId = WindowId::new(raw_id);
        self.set_next_id(raw_id.wrapping_add(1));
        let mut state: WindowState = WindowState::from_config(id, config, dpr);
        let phys_w: u32 = surface.canvas.width().max(1);
        let phys_h: u32 = surface.canvas.height().max(1);
        state.set_physical_width(phys_w);
        state.set_physical_height(phys_h);
        state.set_logical_width((phys_w as f32) / dpr);
        state.set_logical_height((phys_h as f32) / dpr);
        state.set_system_theme(web_system_theme());
        let safe_area: SafeAreaInsets = if config.get_fullscreen() == FullscreenMode::Windowed {
            web_query_safe_area_insets()
        } else {
            SafeAreaInsets::default()
        };
        state.set_safe_area(safe_area);
        state
            .get_mut_display()
            .set_refresh_rate_hz(self.get_refresh_rate_hz().round() as u32);
        self.set_last_safe_area(safe_area);
        self.set_needs_frame(true);
        let _: bool = web_attach_device_motion_listeners();
        let cpu_mirror: bool = surface.presentation_mode != WebPresentationMode::GpuDirect;
        self.get_mut_windows().insert(
            id,
            WebWindowRecord {
                config: config.clone(),
                state,
                canvas_id: raw_id as u32,
                context_kind: surface.context_kind,
                presentation_mode: surface.presentation_mode,
                cpu_mirror_active: cpu_mirror,
                active_canvas_generation: 1,
                canvas: Some(surface.canvas),
                webgpu_ctx: surface.webgpu_ctx,
                gl2: surface.gl2,
                gl2_direct_program: surface.gl2_direct_program,
                gl2_direct_view_loc: surface.gl2_direct_view_loc,
                gl2_direct_rect_loc: surface.gl2_direct_rect_loc,
                gl2_direct_color_loc: surface.gl2_direct_color_loc,
                gl2_program: surface.gl2_program,
                gl2_texture: surface.gl2_texture,
                gl2_view_loc: surface.gl2_view_loc,
                gl2_tex_width: 0,
                gl2_tex_height: 0,
                ctx2d: surface.ctx2d,
                standby_canvas: None,
                last_telemetry: WebPresentTelemetry {
                    mode: surface.presentation_mode,
                    cpu_mirror_active: cpu_mirror,
                    upload_bytes: 0,
                    primitive_count: 0,
                    present_timing_source: WebPresentTimingSource::SubmissionProxy,
                    active_canvas_generation: 1,
                    handoff_swaps_completed: 0,
                    handoff_aborts: 0,
                    raf_callback_count: 0,
                },
                resize_observer: None,
            },
        );
        Ok(state)
    }

    /// Queries live `WindowState` for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    /// - `WindowId` - Window handle.
    ///
    /// # Returns
    ///
    /// - `Option<WindowState>` - Window state if open.
    fn window_state(&self, id: WindowId) -> Option<WindowState> {
        self.get_windows().get(&id).map(WebWindowRecord::get_state)
    }

    /// Returns `RawWindowHandle::WebCanvas` for WebGPU / WebGL2 surface binding.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    /// - `WindowId` - Window handle.
    ///
    /// # Returns
    ///
    /// - `RawWindowHandle` - Web canvas handle.
    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
        match self.get_windows().get(&id) {
            Some(rec) => RawWindowHandle::WebCanvas {
                canvas_id: rec.get_canvas_id(),
            },
            None => RawWindowHandle::Headless,
        }
    }

    /// Drains queued web events and polls live browser visibility, connectivity, theme, and locale transitions.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Pending events.
    fn poll_events(&mut self) -> Vec<WindowEvent> {
        let cur_hidden: bool = web_document_hidden();
        if cur_hidden != self.get_last_hidden() {
            self.set_last_hidden(cur_hidden);
            self.set_pump_paused(cur_hidden);
            let lc_ev: SystemEvent = if cur_hidden {
                SystemEvent::Background
            } else {
                SystemEvent::Foreground
            };
            self.get_mut_pending_events()
                .push(WindowEvent::System(lc_ev));
        }
        let cur_online: bool = web_navigator_online();
        if cur_online != self.get_last_online() {
            self.set_last_online(cur_online);
            let net: NetworkStatus = if cur_online {
                NetworkStatus::Online
            } else {
                NetworkStatus::Offline
            };
            self.get_mut_pending_events()
                .push(WindowEvent::System(SystemEvent::NetworkStatusChanged(net)));
        }
        let cur_theme: ThemeMode = web_system_theme();
        if cur_theme != self.get_last_theme() {
            self.set_last_theme(cur_theme);
            if let Some(&wid) = self.get_windows().keys().next() {
                self.get_mut_pending_events()
                    .push(WindowEvent::ThemeChanged(wid, cur_theme));
            } else {
                self.get_mut_pending_events()
                    .push(WindowEvent::System(SystemEvent::ThemeChanged(cur_theme)));
            }
        }
        let cur_locale: String = web_navigator_locale();
        if cur_locale != *self.get_last_locale() {
            self.set_last_locale(cur_locale.clone());
            self.get_mut_pending_events()
                .push(WindowEvent::System(SystemEvent::LocaleChanged(cur_locale)));
        }
        if let Some(motion) = web_take_pending_device_motion() {
            self.get_mut_pending_events()
                .push(WindowEvent::System(SystemEvent::DeviceMotion(motion)));
        }
        take(self.get_mut_pending_events())
    }

    /// Pauses or resumes the browser `requestAnimationFrame` pump flag.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    /// - `bool` - `true` when hidden/backgrounded; `false` when foregrounded.
    fn set_frame_pump_paused(&mut self, paused: bool) {
        self.set_pump_paused(paused);
        if paused {
            self.cancel_pending_raf();
        } else {
            self.set_needs_frame(true);
        }
    }

    /// Returns whether the web `requestAnimationFrame` pump is currently paused for background freeze.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when paused in background.
    fn is_frame_pump_paused(&self) -> bool {
        self.get_pump_paused()
    }

    /// Blits `framebuffer` directly onto the browser WebGL2 or Canvas2D context.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    /// - `WindowId` - Window handle.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Presentation status.
    fn present_framebuffer(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
    ) -> Result<(), PlatformError> {
        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
    }

    /// Blits only the damaged physical rectangle of `framebuffer` onto the browser WebGL2 texture or Canvas2D fallback.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    /// - `WindowId` - Window handle.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    /// - `DamageRegion` - Damaged physical pixel region.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Presentation status.
    fn present_framebuffer_region(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
        damage: DamageRegion,
    ) -> Result<(), PlatformError> {
        let rec: &mut WebWindowRecord = self
            .get_mut_windows()
            .get_mut(&id)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        if let Some(upload_bytes) = web_present_gl2_region(rec, framebuffer, damage)? {
            let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
            tel.set_mode(WebPresentationMode::GpuUpload);
            tel.set_cpu_mirror_active(true);
            tel.set_upload_bytes(upload_bytes);
            tel.set_primitive_count(0);
            tel.set_present_timing_source(WebPresentTimingSource::SubmissionProxy);
            tel.set_active_canvas_generation(rec.get_active_canvas_generation());
            rec.set_presentation_mode(WebPresentationMode::GpuUpload);
            rec.set_cpu_mirror_active(true);
            rec.set_last_telemetry(tel);
            return Ok(());
        }
        let uploaded_2d: Option<u64> = {
            let WebWindowRecord { canvas, ctx2d, .. } = rec;
            if let Some(ctx) = ctx2d.as_ref() {
                Some(web_present_image_data_region(
                    canvas.as_ref(),
                    ctx,
                    framebuffer,
                    damage,
                )?)
            } else {
                None
            }
        };
        if let Some(upload_bytes) = uploaded_2d {
            let mut tel: WebPresentTelemetry = rec.get_last_telemetry();
            tel.set_mode(WebPresentationMode::Software);
            tel.set_cpu_mirror_active(true);
            tel.set_upload_bytes(upload_bytes);
            tel.set_primitive_count(0);
            tel.set_present_timing_source(WebPresentTimingSource::SubmissionProxy);
            tel.set_active_canvas_generation(rec.get_active_canvas_generation());
            rec.set_presentation_mode(WebPresentationMode::Software);
            rec.set_cpu_mirror_active(true);
            rec.set_last_telemetry(tel);
        }
        Ok(())
    }

    /// Reads cached clipboard text.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Clipboard contents.
    fn read_clipboard(&self) -> Option<String> {
        let Self {
            clipboard_cache, ..
        } = self;
        clipboard_cache.clone()
    }

    /// Writes `text` into clipboard cache.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable web platform.
    /// - `&str` - Clipboard text.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Write status.
    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
        self.set_clipboard_cache(Some(text.to_string()));
        let _: bool = write_system_clipboard(text);
        Ok(())
    }

    /// Queries the browser's live dark/light appearance preference.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `ThemeMode` - Active appearance mode.
    fn system_theme(&self) -> ThemeMode {
        web_system_theme()
    }

    /// Returns the measured browser display refresh rate in Hertz.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Active browser presentation cadence in Hertz.
    fn display_refresh_rate_hz(&self) -> f32 {
        self.get_refresh_rate_hz()
    }
}