hydrolysis 0.1.0

A modern UI framework for Rust
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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
use super::*;
use core::num::NonZeroU32;
#[cfg(hydrolysis_macos_system_webview)]
use objc2::rc::Retained;
#[cfg(hydrolysis_macos_system_webview)]
use objc2_web_kit::WKWebView;
use shaderloom::CompiledShader;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use shaderloom::WgslModuleCache;
use waterui_graphics::input::SurfaceInputEvent;

const GPU_SURFACE_COMPOSITOR_SHADER: CompiledShader =
    include!(concat!(env!("OUT_DIR"), "/gpu_surface_compositor.rs"));

/// Builds a fresh `vello::Renderer` for the parallel-encode pool, matching the main
/// renderer's options (GPU-only, area AA, multi-core init).
fn build_pooled_vello_renderer(device: &wgpu::Device) -> vello::Renderer {
    vello::Renderer::new(
        device,
        vello::RendererOptions {
            use_cpu: false,
            antialiasing_support: vello::AaSupport::area_only(),
            num_init_threads: std::thread::available_parallelism().ok(),
            pipeline_cache: None,
        },
    )
    .expect("hydrolysis renderer: failed to create pooled vello renderer")
}

/// C2: encode independent Vello layers to per-layer textures across CPU cores.
///
/// Each worker checks a `vello::Renderer` out of `pool` (creating one on first use),
/// renders its scene to its own texture, and returns the texture + view tagged with the
/// originating `render_layers` index so the caller can composite in painter's order.
/// `vello::Renderer` is `!Sync`, so per-worker ownership (not sharing) is what makes this
/// sound; the GPU `Queue` is `Send + Sync` and each layer targets an independent texture,
/// so submission order is irrelevant.
fn encode_vello_layers_parallel(
    pool: &std::sync::Mutex<Vec<vello::Renderer>>,
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    scenes: Vec<(usize, &vello::Scene, PooledLayerTexture)>,
    width: u32,
    height: u32,
) -> Vec<(usize, PooledLayerTexture)> {
    #[cfg(not(target_arch = "wasm32"))]
    use rayon::prelude::*;

    let render_layer = |(index, scene, leased): (usize, &vello::Scene, PooledLayerTexture)| {
        let mut renderer = pool
            .lock()
            .expect("hydrolysis renderer: vello renderer pool poisoned")
            .pop()
            .unwrap_or_else(|| build_pooled_vello_renderer(device));

        let params = vello::RenderParams {
            base_color: vello::peniko::Color::TRANSPARENT,
            width,
            height,
            antialiasing_method: vello::AaConfig::Area,
        };
        renderer
            .render_to_texture(device, queue, scene, &leased.view, &params)
            .expect("hydrolysis renderer: failed to render vello layer scene");

        pool.lock()
            .expect("hydrolysis renderer: vello renderer pool poisoned")
            .push(renderer);

        (index, leased)
    };

    #[cfg(not(target_arch = "wasm32"))]
    let rendered = scenes.into_par_iter().map(render_layer).collect();
    #[cfg(target_arch = "wasm32")]
    let rendered = scenes.into_iter().map(render_layer).collect();
    rendered
}

#[derive(Default)]
pub(crate) struct Compositor {
    /// Pool of target-sized intermediate textures reused across frames for
    /// per-layer Vello encodes and active-layer masks. Allocating one per
    /// layer per frame is exactly the churn the pool exists to avoid; entries
    /// whose size no longer matches the target are dropped on acquire.
    pub(crate) layer_texture_pool: Vec<PooledLayerTexture>,
    /// Pool of `vello::Renderer` instances reused across frames for C2's parallel
    /// per-layer encoding. `vello::Renderer` is `!Sync` (it holds a `RefCell`), so each
    /// worker checks out its own instance; the `Mutex` only guards the free-list, not the
    /// (parallel) encode itself.
    pub(crate) vello_renderer_pool: std::sync::Mutex<Vec<vello::Renderer>>,
    pub(crate) gpu_surface_compositor: Option<GpuSurfaceCompositorState>,
    pub(crate) render_layers: Vec<RenderLayer>,
    pub(crate) active_scene_layers: Vec<ActiveSceneLayer>,
    pub(crate) active_filter_images: Vec<vello::peniko::ImageData>,
}

pub(crate) struct PooledLayerTexture {
    pub(crate) texture: wgpu::Texture,
    pub(crate) view: wgpu::TextureView,
}

impl Compositor {
    fn acquire_layer_texture(
        &mut self,
        device: &wgpu::Device,
        width: u32,
        height: u32,
    ) -> PooledLayerTexture {
        // All intermediate layer textures are target-sized, so a resize makes
        // every pooled entry stale at once; drop them instead of hoarding.
        self.layer_texture_pool
            .retain(|entry| entry.texture.width() == width && entry.texture.height() == height);
        self.layer_texture_pool.pop().unwrap_or_else(|| {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("hydrolysis_layer_texture"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::STORAGE_BINDING
                    | wgpu::TextureUsages::TEXTURE_BINDING
                    | wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            PooledLayerTexture { texture, view }
        })
    }

    fn release_layer_texture(&mut self, texture: PooledLayerTexture) {
        self.layer_texture_pool.push(texture);
    }
}

pub(crate) struct GpuSurfaceCompositorState {
    pub(crate) target_format: wgpu::TextureFormat,
    pub(crate) uniform_buffer: wgpu::Buffer,
    /// Number of 256-byte uniform slots `uniform_buffer` holds (one per
    /// composited layer); the buffer is recreated when a frame needs more.
    pub(crate) uniform_slot_capacity: usize,
    pub(crate) sampler: wgpu::Sampler,
    pub(crate) bind_group_layout: wgpu::BindGroupLayout,
    pub(crate) pipeline: wgpu::RenderPipeline,
    pub(crate) _white_mask_texture: wgpu::Texture,
    pub(crate) white_mask_view: wgpu::TextureView,
}

pub(crate) struct EmbeddedGpuSurfaceRuntime {
    surface: Option<GpuSurface>,
    env: Option<Environment>,
    setup_complete: bool,
    /// Whether the view handles its own keyboard, IME, pointer and scroll
    /// input. Sampled once at construction: the surface is moved out for the
    /// duration of async setup, and a target that disappeared for those frames
    /// would drop the focus it holds.
    wants_input_events: bool,
    msaa_samples: NonZeroU32,
    prefers_hdr: Option<bool>,
    output_format: wgpu::TextureFormat,
    output_texture: Option<wgpu::Texture>,
    output_view: Option<wgpu::TextureView>,
    gesture: GestureState,
    trackpad_pan_ending: bool,
    redraw_handle: RedrawHandle,
    /// An unserved redraw request: the view asked for another frame, input
    /// reached it, or an off-thread [`RedrawHandle`] fired. The handle's dirty
    /// flag is consumed by
    /// [`poll_gpu_surface_redraw_handles`](crate::HydrolysisRenderer::poll_gpu_surface_redraw_handles)
    /// at the top of the frame, well before the render path runs, so the
    /// request is recorded here instead of being left on the handle for
    /// [`Self::prepare_layer`] to find.
    pending_render: bool,
    /// What the retained [`Self::output_texture`] currently shows: the inputs
    /// the view was last rendered with. `None` means the texture holds nothing
    /// this runtime drew — before the first frame, after a resize or format
    /// change recreated it, after setup replaced the view's GPU resources, and
    /// while the surface renders straight into the window instead.
    ///
    /// This is the whole of the render-on-demand test: a frame whose inputs
    /// equal these, with nothing pending, would redraw the same pixels, so it
    /// composites the texture it already has.
    rendered_inputs: Option<RenderedFrameInputs>,
    /// First frame instant, fixed when the surface first renders; the frame
    /// clock's origin for `GpuFrame::elapsed`.
    start_time: Option<Instant>,
    /// Frame instant of the previous frame, for `GpuFrame::delta`. Advanced on
    /// skipped frames too: see [`Self::frame_timing`].
    last_frame_time: Option<Instant>,
}

/// Everything a rendered frame of an embedded surface depended on, besides the
/// clock. Two frames agreeing on all of it draw the same pixels, so the second
/// one does not have to run.
///
/// Pointer and gesture belong here because views sample them per frame rather
/// than requesting a redraw when they change: a particle field that repels
/// under the cursor, or a shader that highlights on hover, never calls
/// `GpuFrame::request_redraw`, and would freeze if only explicit requests
/// re-rendered it.
///
/// Comparing the whole struct is deliberate: a field added here without a
/// matching thought about staleness fails closed (an extra render) rather than
/// open (a stale texture).
#[derive(Clone, Copy, PartialEq)]
struct RenderedFrameInputs {
    size: (u32, u32),
    scale: f64,
    pointer: PointerState,
    gesture: GestureState,
}

#[derive(Clone)]
struct EmbeddedGpuSurfaceSetup {
    adapter: wgpu::Adapter,
    device: wgpu::Device,
    queue: wgpu::Queue,
    shader_cache: Arc<WgslModuleCache>,
    scene_renderer: Arc<waterui_graphics::SharedSceneRenderer>,
    host_redraw_handle: Option<RedrawHandle>,
}

#[derive(Clone)]
pub(crate) enum LayerShape {
    Rect(vello::kurbo::Rect),
    RoundedRect {
        path: vello::kurbo::BezPath,
        #[cfg_attr(
            not(hydrolysis_macos_system_webview),
            expect(
                dead_code,
                reason = "rounded geometry is consumed by macOS native-view clipping"
            )
        )]
        rect: vello::kurbo::Rect,
        #[cfg_attr(
            not(hydrolysis_macos_system_webview),
            expect(
                dead_code,
                reason = "rounded geometry is consumed by macOS native-view clipping"
            )
        )]
        corner_width: f64,
        #[cfg_attr(
            not(hydrolysis_macos_system_webview),
            expect(
                dead_code,
                reason = "rounded geometry is consumed by macOS native-view clipping"
            )
        )]
        corner_height: f64,
    },
    Path(vello::kurbo::BezPath),
}

#[derive(Clone)]
pub(crate) struct ActiveSceneLayer {
    pub(crate) alpha: f32,
    pub(crate) transform: vello::kurbo::Affine,
    pub(crate) shape: LayerShape,
}

/// Where a [`GpuSurfaceLayer`]'s runtime lives. The retained render tree owns
/// its runtime directly inside its `GpuSurfaceNode` (`Owned`), so a reactive
/// swap renders the new surface and a per-frame re-flush re-binds the same
/// runtime structurally — no cursor desync.
#[derive(Clone)]
pub(crate) enum GpuSurfaceSource {
    Owned(Rc<RefCell<EmbeddedGpuSurfaceRuntime>>),
}

#[derive(Clone)]
pub(crate) struct GpuSurfaceLayer {
    pub(crate) source: GpuSurfaceSource,
    pub(crate) transform: vello::kurbo::Affine,
    pub(crate) bounds: vello::kurbo::Rect,
    /// The surface's rect in window hit-test space, used to project the
    /// window pointer into surface-local coordinates at composite time.
    pub(crate) hit_rect: vello::kurbo::Rect,
    pub(crate) active_layers: Vec<ActiveSceneLayer>,
    pub(crate) direct_to_target: bool,
}

#[cfg(hydrolysis_macos_system_webview)]
#[derive(Clone)]
pub(crate) struct NativeViewLayer {
    pub(crate) view: Retained<WKWebView>,
    pub(crate) transform: vello::kurbo::Affine,
    pub(crate) bounds: vello::kurbo::Rect,
    pub(crate) active_layers: Vec<ActiveSceneLayer>,
    /// Where `WaterUI`-drawn interactive content covers this view, in window
    /// hit-test space, refreshed every frame by
    /// [`NativeViewOcclusion`](crate::renderer::NativeViewOcclusion). The view
    /// host refuses AppKit hits inside these rects so the content on top gets
    /// the click it visibly deserves.
    pub(crate) occlusion: Rc<RefCell<Vec<vello::kurbo::Rect>>>,
}

pub(crate) enum RenderLayer {
    Vello(vello::Scene),
    GpuSurface(GpuSurfaceLayer),
    #[cfg(hydrolysis_macos_system_webview)]
    NativeView(NativeViewLayer),
}

#[cfg(hydrolysis_macos_system_webview)]
pub(crate) struct HybridRenderSegment {
    layers: Vec<RenderLayer>,
}

#[cfg(hydrolysis_macos_system_webview)]
pub(crate) struct HybridComposition {
    pub(crate) segments: Vec<HybridRenderSegment>,
    pub(crate) native_views: Vec<NativeViewLayer>,
    pub(crate) transient_scene: Option<vello::Scene>,
}

pub(crate) struct PreparedGpuSurfaceLayer {
    pub(crate) view: wgpu::TextureView,
    pub(crate) uniform_bytes: [u8; 80],
    pub(crate) needs_redraw: bool,
}

pub(crate) fn take_gpu_surface_redraw_request(
    frame_requested_redraw: bool,
    redraw_handle: &RedrawHandle,
) -> bool {
    let external_redraw_requested = redraw_handle.take_dirty();
    frame_requested_redraw || external_redraw_requested
}

pub struct HydrolysisRenderTarget<'a> {
    pub adapter: &'a wgpu::Adapter,
    pub device: &'a wgpu::Device,
    pub queue: &'a wgpu::Queue,
    pub texture: Option<&'a wgpu::Texture>,
    pub view: &'a wgpu::TextureView,
    pub format: wgpu::TextureFormat,
    pub width: u32,
    pub height: u32,
    pub base_color: vello::peniko::Color,
}

pub(crate) struct DirectGpuSurfaceTarget<'a> {
    pub(crate) device: &'a wgpu::Device,
    pub(crate) queue: &'a wgpu::Queue,
    pub(crate) texture: &'a wgpu::Texture,
    pub(crate) view: wgpu::TextureView,
    pub(crate) format: wgpu::TextureFormat,
    pub(crate) width: u32,
    pub(crate) height: u32,
    /// Device pixels per logical unit, from the layer's transform.
    pub(crate) scale: f64,
    pub(crate) pointer: PointerState,
    pub(crate) now: Instant,
}

pub(crate) struct EmbeddedLayerTarget {
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) transform: vello::kurbo::Affine,
    pub(crate) bounds: vello::kurbo::Rect,
    /// The surface's rect in window hit-test space; the pointer is projected
    /// into surface-local pixels inside `prepare_layer`, which is where the
    /// layer's output pixel size is decided.
    pub(crate) hit_rect: vello::kurbo::Rect,
    pub(crate) pointer_position: Option<vello::kurbo::Point>,
    pub(crate) pointer_press_origin: Option<vello::kurbo::Point>,
    pub(crate) now: Instant,
}

/// Projects the window pointer into an embedded surface's local pixel space.
///
/// `hit_rect` is the surface's rect in window hit-test coordinates and
/// `(width, height)` its output texture size. The hover position maps only
/// while inside the rect; the press origin maps only when the press started on
/// this surface, so a drag that leaves the bounds keeps reporting its origin.
pub(crate) fn project_pointer_into_surface(
    pointer_position: Option<vello::kurbo::Point>,
    pointer_press_origin: Option<vello::kurbo::Point>,
    hit_rect: vello::kurbo::Rect,
    width: u32,
    height: u32,
) -> PointerState {
    if hit_rect.width() <= 0.0 || hit_rect.height() <= 0.0 {
        return PointerState::default();
    }
    #[allow(clippy::cast_possible_truncation)]
    let map = |point: vello::kurbo::Point| {
        waterui_core::layout::Point::new(
            ((point.x - hit_rect.x0) / hit_rect.width() * f64::from(width)) as f32,
            ((point.y - hit_rect.y0) / hit_rect.height() * f64::from(height)) as f32,
        )
    };
    let position = pointer_position
        .filter(|point| hit_rect.contains(*point))
        .map(map);
    let hit = pointer_press_origin
        .filter(|origin| hit_rect.contains(*origin))
        .map(map);
    PointerState { position, hit }
}

/// One layer fully prepared for the final composite pass: its content and mask
/// views (pooled textures ride along so they return to the pool afterwards)
/// plus the 80-byte compositor uniform.
struct ReadyLayerComposite {
    layer_view: wgpu::TextureView,
    layer_texture: Option<PooledLayerTexture>,
    mask_view: wgpu::TextureView,
    mask_texture: Option<PooledLayerTexture>,
    uniform_bytes: [u8; 80],
}

impl ActiveSceneLayer {
    pub(crate) fn push_to_scene(&self, scene: &mut vello::Scene) {
        match &self.shape {
            LayerShape::Rect(rect) => {
                scene.push_layer(
                    vello::peniko::Fill::NonZero,
                    vello::peniko::BlendMode::default(),
                    self.alpha,
                    self.transform,
                    rect,
                );
            }
            LayerShape::RoundedRect { path, .. } | LayerShape::Path(path) => {
                scene.push_layer(
                    vello::peniko::Fill::NonZero,
                    vello::peniko::BlendMode::default(),
                    self.alpha,
                    self.transform,
                    path,
                );
            }
        }
    }
}

impl GpuSurfaceCompositorState {
    /// Size of one compositor uniform in bytes (the shader-visible struct).
    const UNIFORM_SIZE: u64 = 80;
    /// Stride between per-layer uniform slots: WebGPU's guaranteed
    /// `min_uniform_buffer_offset_alignment`.
    const UNIFORM_SLOT_STRIDE: u64 = 256;
    const INITIAL_UNIFORM_SLOTS: usize = 8;

    fn create_uniform_buffer(device: &wgpu::Device, slots: usize) -> wgpu::Buffer {
        device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_uniform"),
            size: (slots as u64) * Self::UNIFORM_SLOT_STRIDE,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        })
    }

    fn ensure_uniform_capacity(&mut self, device: &wgpu::Device, slots: usize) {
        if slots <= self.uniform_slot_capacity {
            return;
        }
        let slots = slots.next_power_of_two();
        self.uniform_buffer = Self::create_uniform_buffer(device, slots);
        self.uniform_slot_capacity = slots;
    }

    pub(crate) fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target_format: wgpu::TextureFormat,
    ) -> Self {
        let uniform_buffer = Self::create_uniform_buffer(device, Self::INITIAL_UNIFORM_SLOTS);
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            ..Default::default()
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_bind_group_layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        // Every composited layer reads its own 256-byte-aligned
                        // slot of one shared buffer, selected per draw with a
                        // dynamic offset, so the whole composite is a single
                        // render pass and a single submit.
                        has_dynamic_offset: true,
                        min_binding_size: Some(
                            core::num::NonZeroU64::new(Self::UNIFORM_SIZE)
                                .expect("static compositor uniform size must be non-zero"),
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_pipeline_layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let (vertex_shader, fragment_shader) =
            GPU_SURFACE_COMPOSITOR_SHADER.create_render_stages(device, "vs_main", "fs_main");
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: vertex_shader.module(),
                entry_point: Some(vertex_shader.entry_point()),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[],
            },
            fragment: Some(wgpu::FragmentState {
                module: fragment_shader.module(),
                entry_point: Some(fragment_shader.entry_point()),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        let white_mask_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_white_mask"),
            size: wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            white_mask_texture.as_image_copy(),
            &[255, 255, 255, 255],
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(4),
                rows_per_image: Some(1),
            },
            wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
        );
        let white_mask_view =
            white_mask_texture.create_view(&wgpu::TextureViewDescriptor::default());

        Self {
            target_format,
            uniform_buffer,
            uniform_slot_capacity: Self::INITIAL_UNIFORM_SLOTS,
            sampler,
            bind_group_layout,
            pipeline,
            _white_mask_texture: white_mask_texture,
            white_mask_view,
        }
    }

    pub(crate) fn ensure_target_format(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target_format: wgpu::TextureFormat,
    ) {
        if self.target_format == target_format {
            return;
        }
        *self = Self::new(device, queue, target_format);
    }
}

impl EmbeddedGpuSurfaceRuntime {
    pub(crate) fn new(surface: GpuSurface, env: &Environment) -> Self {
        let msaa_samples = surface.msaa_sample_limit();
        let wants_input_events = surface.wants_input_events();
        let prefers_hdr = surface.resolved_hdr_preference().or_else(|| {
            env.get::<DynamicRangePreference>()
                .map(|preference| preference.0)
        });
        Self {
            surface: Some(surface),
            env: Some(env.clone()),
            setup_complete: false,
            wants_input_events,
            msaa_samples,
            prefers_hdr,
            output_format: wgpu::TextureFormat::Rgba8Unorm,
            output_texture: None,
            output_view: None,
            gesture: GestureState::new(),
            trackpad_pan_ending: false,
            redraw_handle: RedrawHandle::new(),
            pending_render: false,
            rendered_inputs: None,
            start_time: None,
            last_frame_time: None,
        }
    }

    /// Advances the surface's animation clock to the renderer's frame instant
    /// and returns `(elapsed, delta)` for this frame. Driving the clock from
    /// the frame instant (not wall time) keeps offscreen hosts that pump the
    /// clock deterministic.
    ///
    /// The clock runs on every window frame, including the ones
    /// [`Self::prepare_layer`] skips: `elapsed` is wall-clock from the
    /// surface's first frame, and `delta` is the step since the previous
    /// *window* frame rather than since the previous *rendered* one. A skip
    /// means the view declared its state frozen, so nothing moved during it;
    /// resuming with one frame's step continues the animation from where it
    /// paused, where measuring from the last render would hand it the whole
    /// idle gap (capped at 100ms) and jump it forward by time in which it
    /// deliberately did not move. A view that animates off `elapsed` requests
    /// redraws to do so and therefore never skips a frame in the first place.
    fn frame_timing(&mut self, now: Instant) -> (Duration, Duration) {
        let start = *self.start_time.get_or_insert(now);
        let elapsed = now.saturating_duration_since(start);
        let delta = self.last_frame_time.map_or_else(
            || Duration::from_secs_f32(1.0 / 60.0),
            |last| {
                now.saturating_duration_since(last)
                    .min(Duration::from_millis(100))
            },
        );
        self.last_frame_time = Some(now);
        (elapsed, delta)
    }

    /// Consumes an off-thread redraw request, recording it as pending so the
    /// render path still sees it: the poll that calls this runs at the top of
    /// the frame and would otherwise be the only thing that ever learns of it.
    pub(crate) fn take_external_redraw_request(&mut self) -> bool {
        let requested = self.redraw_handle.take_dirty();
        self.pending_render |= requested;
        requested
    }

    /// Marks the view as owing a frame and wakes the host that would sleep
    /// through it.
    fn request_render(&mut self) {
        self.pending_render = true;
        self.redraw_handle.request_redraw();
    }

    /// Folds a finished render's outcome into the pending-render state and
    /// reports whether the window must schedule another frame for it.
    ///
    /// Requests raised *during* the render — by the view itself, or by a signal
    /// watcher its scene content installed — land on the handle after the
    /// decision to render was taken, which is why they are collected here
    /// rather than left for the next frame's poll to race over.
    fn settle_after_render(&mut self, frame_requested_redraw: bool) -> bool {
        self.pending_render =
            take_gpu_surface_redraw_request(frame_requested_redraw, &self.redraw_handle);
        self.pending_render
    }

    /// Whether this surface's view handles its own input.
    pub(crate) const fn wants_input_events(&self) -> bool {
        self.wants_input_events
    }

    /// Delivers one backend-neutral input event to the view.
    ///
    /// Input reaching a surface whose view is still being set up has no
    /// receiver: the view is moved out for the duration of that async setup.
    pub(crate) fn input(&mut self, event: &SurfaceInputEvent) {
        let Some(surface) = self.surface.as_mut() else {
            tracing::trace!(
                target: "waterui::hydrolysis::input",
                event = ?event,
                "dropped an input event for a GpuSurface that is still setting up"
            );
            return;
        };
        surface.input(event);
        self.request_render();
    }

    /// The view's text caret, in logical surface-local coordinates.
    pub(crate) fn ime_caret(&self) -> Option<vello::kurbo::Rect> {
        self.surface.as_ref().and_then(GpuSurface::ime_caret)
    }

    pub(crate) fn handle_trackpad_pan(&mut self, dx: f32, dy: f32, phase: TouchPhase) -> bool {
        match phase {
            TouchPhase::Started => {
                self.gesture.pan_offset = waterui_core::layout::Point::new(dx, dy);
                self.gesture.active = true;
                self.trackpad_pan_ending = false;
            }
            TouchPhase::Moved => {
                if !self.gesture.active {
                    self.gesture.pan_offset = waterui_core::layout::Point::zero();
                    self.gesture.active = true;
                }
                self.trackpad_pan_ending = false;
                self.gesture.pan_offset.x += dx;
                self.gesture.pan_offset.y += dy;
            }
            TouchPhase::Ended => {
                if !self.gesture.active {
                    self.gesture.pan_offset = waterui_core::layout::Point::zero();
                    self.gesture.active = true;
                }
                self.gesture.pan_offset.x += dx;
                self.gesture.pan_offset.y += dy;
                self.trackpad_pan_ending = true;
            }
            TouchPhase::Cancelled => {
                self.trackpad_pan_ending = self.gesture.active;
            }
        }
        self.request_render();
        true
    }

    fn finish_trackpad_pan_frame(&mut self) {
        if self.trackpad_pan_ending {
            self.trackpad_pan_ending = false;
            self.gesture.active = false;
            self.request_render();
        }
    }

    /// Composites this surface into the window, rendering the view first only
    /// when this frame would produce something the retained output texture does
    /// not already hold.
    ///
    /// The window still redraws its whole scene every frame it runs — that part
    /// of Hydrolysis is not negotiable — but an embedded surface's texture is
    /// an *input* to that composite, retained across frames exactly like the
    /// render tree it hangs in. An idle QR code alongside an animating spinner
    /// pays one composite, not one render.
    pub(crate) fn prepare_layer(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target: EmbeddedLayerTarget,
    ) -> PreparedGpuSurfaceLayer {
        let top_left =
            target.transform * vello::kurbo::Point::new(target.bounds.x0, target.bounds.y0);
        let top_right =
            target.transform * vello::kurbo::Point::new(target.bounds.x1, target.bounds.y0);
        let bottom_right =
            target.transform * vello::kurbo::Point::new(target.bounds.x1, target.bounds.y1);
        let bottom_left =
            target.transform * vello::kurbo::Point::new(target.bounds.x0, target.bounds.y1);

        let layer_width =
            edge_length_in_pixels(top_left, top_right, target.width, target.height).max(1);
        let layer_height =
            edge_length_in_pixels(top_left, bottom_left, target.width, target.height).max(1);
        let output_format = self.output_format;
        // Recreating the texture discards whatever it held, so a resize or a
        // format change is itself a reason to render.
        self.ensure_output_target(device, layer_width, layer_height, output_format);

        let (elapsed, delta) = self.frame_timing(target.now);
        let view = self
            .output_view
            .as_ref()
            .expect("hydrolysis embedded GpuSurface missing output view")
            .clone();
        let inputs = RenderedFrameInputs {
            size: (layer_width, layer_height),
            scale: layer_device_scale(target.transform),
            pointer: project_pointer_into_surface(
                target.pointer_position,
                target.pointer_press_origin,
                target.hit_rect,
                layer_width,
                layer_height,
            ),
            gesture: self.gesture,
        };
        // An off-thread handle can fire between this frame's poll and here, so
        // the handle is consulted again rather than trusting `pending_render`
        // alone.
        let externally_requested = self.redraw_handle.take_dirty();
        let needs_redraw = if self.rendered_inputs == Some(inputs)
            && !self.pending_render
            && !externally_requested
        {
            tracing::trace!(
                width = layer_width,
                height = layer_height,
                "reusing an embedded Hydrolysis GPU surface's retained texture"
            );
            false
        } else {
            let texture = self
                .output_texture
                .as_ref()
                .expect("hydrolysis embedded GpuSurface missing output texture");
            let mut frame = GpuFrame::new(
                device,
                queue,
                texture,
                view.clone(),
                output_format,
                layer_width,
                layer_height,
                inputs.scale,
                inputs.pointer,
                inputs.gesture,
                elapsed,
                delta,
            );
            assert!(
                self.setup_complete,
                "hydrolysis embedded GpuSurface used before setup"
            );
            self.surface
                .as_mut()
                .expect("hydrolysis embedded GpuSurface missing after setup")
                .render(&mut frame);
            let frame_requested_redraw = frame.was_redraw_requested();
            drop(frame);
            self.rendered_inputs = Some(inputs);
            // Recorded before the pan settles: `inputs` is what the view was
            // handed, and ending the pan is a gesture change of its own, which
            // must reach the view on a frame of its own.
            self.finish_trackpad_pan_frame();
            self.settle_after_render(frame_requested_redraw)
        };
        let corners = [
            point_to_clip(top_left, target.width, target.height),
            point_to_clip(top_right, target.width, target.height),
            point_to_clip(bottom_right, target.width, target.height),
            point_to_clip(bottom_left, target.width, target.height),
        ];

        PreparedGpuSurfaceLayer {
            view,
            uniform_bytes: encode_compositor_uniform(corners, false),
            needs_redraw,
        }
    }

    /// Renders the view straight into the window's own texture, for a surface
    /// that covers the whole window with nothing above or below it.
    ///
    /// This path draws somewhere the retained output texture is not, so it
    /// leaves that texture holding pixels from before: a later frame that
    /// composites this surface again (an overlay appeared, so it is no longer
    /// alone) must render, not reuse.
    pub(crate) fn render_direct_to_target(&mut self, target: DirectGpuSurfaceTarget<'_>) -> bool {
        self.rendered_inputs = None;
        let (elapsed, delta) = self.frame_timing(target.now);
        let mut frame = GpuFrame::new(
            target.device,
            target.queue,
            target.texture,
            target.view,
            target.format,
            target.width,
            target.height,
            target.scale,
            target.pointer,
            self.gesture,
            elapsed,
            delta,
        );
        assert!(
            self.setup_complete,
            "hydrolysis embedded GpuSurface used before setup"
        );
        self.surface
            .as_mut()
            .expect("hydrolysis embedded GpuSurface missing after setup")
            .render(&mut frame);
        let frame_requested_redraw = frame.was_redraw_requested();
        drop(frame);
        self.finish_trackpad_pan_frame();
        self.settle_after_render(frame_requested_redraw)
    }

    async fn setup(
        runtime: Rc<RefCell<Self>>,
        resources: EmbeddedGpuSurfaceSetup,
        surface_format: wgpu::TextureFormat,
    ) {
        let (surface, env, msaa_samples, redraw_handle) = {
            let mut runtime = runtime.borrow_mut();
            if runtime.setup_complete && runtime.output_format == surface_format {
                return;
            }
            let surface = runtime
                .surface
                .take()
                .expect("hydrolysis embedded GpuSurface setup started concurrently");
            let env = runtime
                .env
                .take()
                .expect("hydrolysis embedded GpuSurface environment missing before setup");
            runtime.setup_complete = false;
            (
                surface,
                env,
                runtime.msaa_samples,
                runtime.redraw_handle.clone(),
            )
        };

        let wake_parent: Option<Arc<dyn Fn() + Send + Sync>> =
            resources.host_redraw_handle.as_ref().map(|handle| {
                let handle = handle.clone();
                Arc::new(move || handle.request_redraw()) as Arc<dyn Fn() + Send + Sync>
            });
        redraw_handle.set_waker(wake_parent);

        let mut surface = surface;
        let mut env = env;
        {
            // `GpuContext::new` resolves the surface's declared MSAA limit
            // against what the adapter actually supports for this format, so
            // the renderer sees a sample count it can really use rather than
            // the authoring-side cap.
            let context = GpuContext::new(
                &resources.adapter,
                &resources.device,
                &resources.queue,
                surface_format,
                resources.shader_cache.as_ref(),
                &resources.scene_renderer,
                msaa_samples,
                redraw_handle,
            );
            surface.setup(&context, &mut env).await;
        }
        let mut runtime = runtime.borrow_mut();
        runtime.surface = Some(surface);
        runtime.env = Some(env);
        runtime.output_format = surface_format;
        runtime.setup_complete = true;
        // Setup rebuilds the view's GPU resources, so nothing the old view left
        // in the output texture is still that view's output.
        runtime.rendered_inputs = None;
    }

    fn ensure_setup(
        runtime: &Rc<RefCell<Self>>,
        resources: EmbeddedGpuSurfaceSetup,
        signals: FrameSignals,
        surface_format: wgpu::TextureFormat,
    ) -> bool {
        {
            let runtime = runtime.borrow();
            if runtime.setup_complete && runtime.output_format == surface_format {
                return true;
            }
            if runtime.surface.is_none() {
                return false;
            }
        }

        let wake_host = resources.host_redraw_handle.clone();
        let runtime = Rc::clone(runtime);
        spawn_local(async move {
            Self::setup(runtime, resources, surface_format).await;
            signals.request_redraw();
            if let Some(handle) = wake_host {
                handle.request_redraw();
            }
        })
        .detach();
        false
    }

    pub(crate) fn output_format_for(
        &self,
        target_format: wgpu::TextureFormat,
    ) -> wgpu::TextureFormat {
        select_embedded_surface_format(target_format, self.prefers_hdr)
    }

    fn ensure_output_target(
        &mut self,
        device: &wgpu::Device,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
    ) {
        // The texture itself is the source of truth for what it can hold:
        // `setup` assigns `output_format` on its own, so a field comparison
        // would report a match while the texture is still the previous format.
        let matches_request = self.output_texture.as_ref().is_some_and(|texture| {
            texture.width() == width && texture.height() == height && texture.format() == format
        });
        if matches_request {
            return;
        }

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("hydrolysis_embedded_gpu_surface_target"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());

        self.output_format = format;
        self.output_texture = Some(texture);
        self.output_view = Some(view);
        // A fresh texture holds nothing; whatever the view drew at the old size
        // or format is gone with the texture that held it.
        self.rendered_inputs = None;
    }
}

fn select_embedded_surface_format(
    target_format: wgpu::TextureFormat,
    prefers_hdr_override: Option<bool>,
) -> wgpu::TextureFormat {
    let target_hdr = matches!(
        target_format,
        wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
    );
    let prefers_hdr = prefers_hdr_override.unwrap_or(true);
    if target_hdr && prefers_hdr {
        return wgpu::TextureFormat::Rgba16Float;
    }
    wgpu::TextureFormat::Rgba8Unorm
}

fn point_to_clip(point: vello::kurbo::Point, width: u32, height: u32) -> [f32; 2] {
    assert!(
        width != 0 && height != 0,
        "hydrolysis compositor target size must be non-zero"
    );

    let clip_x = ((point.x as f32) / (width as f32)) * 2.0 - 1.0;
    let clip_y = 1.0 - ((point.y as f32) / (height as f32)) * 2.0;
    [clip_x, clip_y]
}

/// Device pixels per logical unit for a composited layer.
///
/// A layer's transform maps logical layout coordinates onto the target's
/// physical pixel grid — the window's root transform is `Affine::scale(
/// scale_factor)` and every node transform composes onto it, which is why
/// [`point_to_clip`] normalizes transformed points by the *physical* target
/// size. Its uniform scale is therefore exactly the factor
/// [`edge_length_in_pixels`] applies before rounding: `layer_width ==
/// round(scale * bounds.width())`. Taking it from the transform rather than
/// from the rounded pixel ratio keeps the value steady at `2.0` on a Retina
/// display instead of jittering by a rounding step as the layer resizes, and it
/// matches what the browser widgets already publish to their own viewports.
fn layer_device_scale(transform: vello::kurbo::Affine) -> f64 {
    transform.determinant().abs().sqrt()
}

fn edge_length_in_pixels(
    start: vello::kurbo::Point,
    end: vello::kurbo::Point,
    target_width: u32,
    target_height: u32,
) -> u32 {
    assert!(
        target_width != 0 && target_height != 0,
        "hydrolysis compositor target size must be non-zero"
    );
    let dx = end.x - start.x;
    let dy = end.y - start.y;
    ((dx * dx + dy * dy).sqrt().round().max(1.0)) as u32
}

fn encode_compositor_uniform(corners: [[f32; 2]; 4], source_is_srgb: bool) -> [u8; 80] {
    let uvs = [[0.0f32, 0.0f32], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
    let mut bytes = [0u8; 80];
    for (index, corner) in corners.iter().enumerate() {
        let base = index * 16;
        write_f32(&mut bytes, base, corner[0]);
        write_f32(&mut bytes, base + 4, corner[1]);
        write_f32(&mut bytes, base + 8, uvs[index][0]);
        write_f32(&mut bytes, base + 12, uvs[index][1]);
    }
    write_f32(&mut bytes, 64, if source_is_srgb { 1.0 } else { 0.0 });
    bytes
}

fn write_f32(bytes: &mut [u8], offset: usize, value: f32) {
    bytes[offset..offset + 4].copy_from_slice(&value.to_ne_bytes());
}

impl HydrolysisRenderer {
    #[cfg(hydrolysis_macos_system_webview)]
    pub(crate) fn take_hybrid_composition(&mut self) -> Option<HybridComposition> {
        self.flush_vello_scene_layer();
        if !self
            .compositor
            .render_layers
            .iter()
            .any(|layer| matches!(layer, RenderLayer::NativeView(_)))
        {
            return None;
        }

        let mut segments = vec![HybridRenderSegment { layers: Vec::new() }];
        let mut native_views = Vec::new();
        for layer in core::mem::take(&mut self.compositor.render_layers) {
            match layer {
                RenderLayer::NativeView(layer) => {
                    native_views.push(layer);
                    segments.push(HybridRenderSegment { layers: Vec::new() });
                }
                layer => segments
                    .last_mut()
                    .expect("Hydrolysis hybrid composition must have a render segment")
                    .layers
                    .push(layer),
            }
        }
        assert!(
            segments.len() == native_views.len() + 1,
            "Hydrolysis hybrid composition segment count must bracket every native view"
        );
        Some(HybridComposition {
            segments,
            native_views,
            transient_scene: self.transient_scene.take(),
        })
    }

    #[cfg(hydrolysis_macos_system_webview)]
    pub(crate) fn render_hybrid_segment_to_surface(
        &mut self,
        segment: &mut HybridRenderSegment,
        transient_scene: Option<vello::Scene>,
        target: HydrolysisRenderTarget<'_>,
    ) {
        assert!(
            self.compositor.render_layers.is_empty(),
            "Hydrolysis hybrid composition cannot render over retained layers"
        );
        assert!(
            self.transient_scene.is_none(),
            "Hydrolysis hybrid composition cannot replace a transient scene"
        );
        self.compositor.render_layers = core::mem::take(&mut segment.layers);
        self.transient_scene = transient_scene;
        self.render_scene_to_surface(target);
        segment.layers = core::mem::take(&mut self.compositor.render_layers);
        assert!(
            self.transient_scene.is_none(),
            "Hydrolysis hybrid segment left a transient scene unconsumed"
        );
    }

    #[cfg(hydrolysis_macos_system_webview)]
    pub(crate) fn restore_hybrid_composition(&mut self, composition: HybridComposition) {
        let HybridComposition {
            segments,
            native_views,
            transient_scene,
        } = composition;
        assert!(
            transient_scene.is_none(),
            "Hydrolysis hybrid composition restored before rendering its transient scene"
        );
        assert!(
            segments.len() == native_views.len() + 1,
            "Hydrolysis hybrid composition segment count changed during rendering"
        );
        let segment_count = segments.len();
        let mut native_views = native_views.into_iter();
        let mut layers = Vec::new();
        for (index, segment) in segments.into_iter().enumerate() {
            layers.extend(segment.layers);
            if index + 1 < segment_count
                && let Some(native_view) = native_views.next()
            {
                layers.push(RenderLayer::NativeView(native_view));
            }
        }
        assert!(
            native_views.next().is_none(),
            "Hydrolysis hybrid composition did not restore every native view"
        );
        self.compositor.render_layers = layers;
    }

    fn embedded_gpu_surface_setup(
        &self,
        adapter: &wgpu::Adapter,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
    ) -> EmbeddedGpuSurfaceSetup {
        EmbeddedGpuSurfaceSetup {
            adapter: adapter.clone(),
            device: device.clone(),
            queue: queue.clone(),
            shader_cache: Arc::clone(&self.shader_cache),
            scene_renderer: Arc::clone(&self.scene_renderer),
            host_redraw_handle: self.host_redraw_handle.clone(),
        }
    }

    /// Await setup for every GPU surface reachable from the statically built
    /// retained tree. A `HydrolysisGpuView` calls this from its own async setup,
    /// making its first sized frame fully ready without polling or fixed retries.
    pub(crate) async fn setup_embedded_gpu_surfaces(&self, context: &GpuContext<'_>) {
        let runtimes = self.node_gpu_surfaces.clone();
        for runtime in runtimes {
            let surface_format = runtime.borrow().output_format_for(context.surface_format);
            EmbeddedGpuSurfaceRuntime::setup(
                runtime,
                self.embedded_gpu_surface_setup(context.adapter, context.device, context.queue),
                surface_format,
            )
            .await;
        }
    }

    pub fn render_scene_to_texture(&mut self, target: HydrolysisRenderTarget<'_>) {
        self.render_scene_to_surface(target);
    }

    fn ensure_gpu_surface_compositor_state(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target_format: wgpu::TextureFormat,
    ) {
        if self.compositor.gpu_surface_compositor.is_none() {
            self.compositor.gpu_surface_compositor =
                Some(GpuSurfaceCompositorState::new(device, queue, target_format));
            return;
        }
        self.compositor
            .gpu_surface_compositor
            .as_mut()
            .expect("hydrolysis renderer: missing gpu surface compositor state")
            .ensure_target_format(device, queue, target_format);
    }

    /// Renders a scene into a pooled target-sized texture, which the caller
    /// must hand back to the pool once the composite pass has sampled it.
    fn render_vello_layer_to_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        scene: &vello::Scene,
        width: u32,
        height: u32,
    ) -> PooledLayerTexture {
        let leased = self.compositor.acquire_layer_texture(device, width, height);
        let params = vello::RenderParams {
            base_color: vello::peniko::Color::TRANSPARENT,
            width,
            height,
            antialiasing_method: vello::AaConfig::Area,
        };
        self.vello_renderer
            .render_to_texture(device, queue, scene, &leased.view, &params)
            .expect("hydrolysis renderer: failed to render vello layer scene");
        leased
    }

    fn render_active_layers_mask_to_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        active_layers: &[ActiveSceneLayer],
    ) -> PooledLayerTexture {
        assert!(
            !active_layers.is_empty(),
            "hydrolysis renderer: active layer mask requires at least one layer"
        );
        let mut mask_scene = vello::Scene::new();
        for layer in active_layers {
            layer.push_to_scene(&mut mask_scene);
        }
        mask_scene.fill(
            vello::peniko::Fill::NonZero,
            vello::kurbo::Affine::IDENTITY,
            vello::peniko::Color::WHITE,
            None,
            &vello::kurbo::Rect::new(0.0, 0.0, f64::from(width), f64::from(height)),
        );
        for _ in 0..active_layers.len() {
            mask_scene.pop_layer();
        }
        self.render_vello_layer_to_texture(device, queue, &mask_scene, width, height)
    }

    fn default_compositor_mask_view(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target_format: wgpu::TextureFormat,
    ) -> wgpu::TextureView {
        self.ensure_gpu_surface_compositor_state(device, queue, target_format);
        self.compositor
            .gpu_surface_compositor
            .as_ref()
            .expect("hydrolysis renderer: missing gpu surface compositor state")
            .white_mask_view
            .clone()
    }

    fn clear_target_surface(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        target: &wgpu::TextureView,
        base_color: vello::peniko::Color,
    ) {
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("hydrolysis_surface_clear_encoder"),
        });
        let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("hydrolysis_surface_clear_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: target,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(color_to_wgpu(base_color)),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            occlusion_query_set: None,
            timestamp_writes: None,
            multiview_mask: None,
        });
        drop(_pass);
        queue.submit(std::iter::once(encoder.finish()));
    }

    /// Composites every prepared layer into the target in painter's order with
    /// one render pass and one submit. Each layer's uniform lives in its own
    /// dynamic-offset slot of the shared buffer, so nothing forces a
    /// submit-per-layer round trip.
    fn composite_ready_layers(
        &mut self,
        target: &HydrolysisRenderTarget<'_>,
        layers: &[ReadyLayerComposite],
    ) {
        self.ensure_gpu_surface_compositor_state(target.device, target.queue, target.format);
        let compositor = self
            .compositor
            .gpu_surface_compositor
            .as_mut()
            .expect("hydrolysis renderer: missing gpu surface compositor state");
        compositor.ensure_uniform_capacity(target.device, layers.len());

        let stride = GpuSurfaceCompositorState::UNIFORM_SLOT_STRIDE as usize;
        let mut uniform_bytes = vec![0u8; layers.len() * stride];
        for (index, layer) in layers.iter().enumerate() {
            let start = index * stride;
            uniform_bytes[start..start + layer.uniform_bytes.len()]
                .copy_from_slice(&layer.uniform_bytes);
        }
        target
            .queue
            .write_buffer(&compositor.uniform_buffer, 0, &uniform_bytes);

        let bind_groups: Vec<wgpu::BindGroup> = layers
            .iter()
            .map(|layer| {
                target.device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("hydrolysis_gpu_surface_compositor_bind_group"),
                    layout: &compositor.bind_group_layout,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                                buffer: &compositor.uniform_buffer,
                                offset: 0,
                                size: core::num::NonZeroU64::new(
                                    GpuSurfaceCompositorState::UNIFORM_SIZE,
                                ),
                            }),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::Sampler(&compositor.sampler),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::TextureView(&layer.layer_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 3,
                            resource: wgpu::BindingResource::TextureView(&layer.mask_view),
                        },
                    ],
                })
            })
            .collect();

        let mut encoder = target
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("hydrolysis_gpu_surface_compositor_encoder"),
            });
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("hydrolysis_gpu_surface_compositor_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: target.view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(color_to_wgpu(target.base_color)),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            occlusion_query_set: None,
            timestamp_writes: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&compositor.pipeline);
        for (index, bind_group) in bind_groups.iter().enumerate() {
            let offset = (index as u64) * GpuSurfaceCompositorState::UNIFORM_SLOT_STRIDE;
            #[allow(clippy::cast_possible_truncation)]
            pass.set_bind_group(0, bind_group, &[offset as u32]);
            pass.draw(0..6, 0..1);
        }
        drop(pass);
        target.queue.submit(std::iter::once(encoder.finish()));
    }

    pub fn render_scene_to_surface(&mut self, target: HydrolysisRenderTarget<'_>) {
        assert!(
            matches!(
                target.format.remove_srgb_suffix(),
                wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm
            ) || matches!(
                target.format,
                wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
            ),
            "hydrolysis renderer: unsupported surface format {:?}",
            target.format
        );

        self.flush_vello_scene_layer();
        let fullscreen_uniform =
            encode_compositor_uniform([[-1.0, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]], true);
        let mut render_layers = core::mem::take(&mut self.compositor.render_layers);
        let transient_layer_count =
            if let Some(scene) = self.transient_scene.take().filter(scene_has_content) {
                render_layers.push(RenderLayer::Vello(scene));
                1
            } else {
                0
            };
        if render_layers.is_empty() {
            self.clear_target_surface(target.device, target.queue, target.view, target.base_color);
            return;
        }
        if let [RenderLayer::GpuSurface(layer)] = render_layers.as_slice()
            && layer.direct_to_target
        {
            let texture = target
                .texture
                .expect("hydrolysis direct GpuSurface render requires target texture");
            let direct_target = DirectGpuSurfaceTarget {
                device: target.device,
                queue: target.queue,
                texture,
                view: target.view.clone(),
                format: target.format,
                width: target.width,
                height: target.height,
                scale: layer_device_scale(layer.transform),
                pointer: project_pointer_into_surface(
                    self.hit_test.pointer_position,
                    self.hit_test.pointer_press_origin,
                    layer.hit_rect,
                    target.width,
                    target.height,
                ),
                now: self.frame_instant(),
            };
            let GpuSurfaceSource::Owned(runtime) = &layer.source;
            if !EmbeddedGpuSurfaceRuntime::ensure_setup(
                runtime,
                self.embedded_gpu_surface_setup(target.adapter, target.device, target.queue),
                self.frame_signals(),
                target.format,
            ) {
                self.clear_target_surface(
                    target.device,
                    target.queue,
                    target.view,
                    target.base_color,
                );
                self.compositor.render_layers = render_layers;
                return;
            }
            let needs_redraw = runtime.borrow_mut().render_direct_to_target(direct_target);
            self.compositor.render_layers = render_layers;
            if needs_redraw {
                self.request_redraw();
            }
            return;
        }
        let mut needs_redraw = false;

        // Phase 1 — prepare every layer's content and mask textures. All the
        // per-layer content work (parallel Vello encodes, embedded GpuSurface
        // renders, mask rasterization) lands here, before any composite state
        // is touched.
        //
        // C2: when there are 2+ independent Vello layers, encode them to
        // per-layer pooled textures across CPU cores up front; the loop below
        // consumes the results in painter's order. A single Vello layer keeps
        // the sequential path (nothing to parallelize), and GpuSurface layers
        // are unaffected.
        let mut encoded_vello: Vec<Option<PooledLayerTexture>> =
            (0..render_layers.len()).map(|_| None).collect();
        {
            let vello_indices: Vec<usize> = render_layers
                .iter()
                .enumerate()
                .filter_map(|(index, layer)| match layer {
                    RenderLayer::Vello(_) => Some(index),
                    RenderLayer::GpuSurface(_) => None,
                    #[cfg(hydrolysis_macos_system_webview)]
                    RenderLayer::NativeView(_) => {
                        panic!("Hydrolysis native views require hybrid window composition")
                    }
                })
                .collect();
            if vello_indices.len() > 1 {
                let vello_scenes: Vec<(usize, &vello::Scene, PooledLayerTexture)> = vello_indices
                    .iter()
                    .map(|&index| {
                        let leased = self.compositor.acquire_layer_texture(
                            target.device,
                            target.width,
                            target.height,
                        );
                        let RenderLayer::Vello(scene) = &render_layers[index] else {
                            panic!("hydrolysis renderer: vello layer index changed type");
                        };
                        (index, scene, leased)
                    })
                    .collect();
                for (index, leased) in encode_vello_layers_parallel(
                    &self.compositor.vello_renderer_pool,
                    target.device,
                    target.queue,
                    vello_scenes,
                    target.width,
                    target.height,
                ) {
                    encoded_vello[index] = Some(leased);
                }
            }
        }

        let mut ready: Vec<ReadyLayerComposite> = Vec::with_capacity(render_layers.len());
        for (layer_index, layer) in render_layers.iter().enumerate() {
            match layer {
                RenderLayer::Vello(scene) => {
                    tracing::trace!(
                        layer_index,
                        paths = scene.encoding().n_paths,
                        segments = scene.encoding().n_path_segments,
                        "compositing Hydrolysis Vello layer"
                    );
                    let leased = match encoded_vello[layer_index].take() {
                        Some(leased) => leased,
                        None => self.render_vello_layer_to_texture(
                            target.device,
                            target.queue,
                            scene,
                            target.width,
                            target.height,
                        ),
                    };
                    let mask_view = self.default_compositor_mask_view(
                        target.device,
                        target.queue,
                        target.format,
                    );
                    ready.push(ReadyLayerComposite {
                        layer_view: leased.view.clone(),
                        layer_texture: Some(leased),
                        mask_view,
                        mask_texture: None,
                        uniform_bytes: fullscreen_uniform,
                    });
                }
                // Embedded GPU surfaces render serially by design: `GpuView` is a
                // user-facing, main-thread contract (`!Send` setup/render futures,
                // `&mut Environment`), so parallelizing this loop would force
                // `Send` onto every user renderer. Vello layers get their
                // parallelism in `encode_vello_layers_parallel` instead.
                RenderLayer::GpuSurface(layer) => {
                    tracing::trace!(
                        layer_index,
                        bounds = ?layer.bounds,
                        transform = ?layer.transform,
                        "compositing Hydrolysis GPU surface layer"
                    );
                    // A transform that collapses to zero area — a scale
                    // animation passing through zero — projects the surface
                    // onto no pixels, so there is nothing to composite and no
                    // device scale the renderer could draw against.
                    if layer_device_scale(layer.transform) <= 0.0 {
                        continue;
                    }
                    let embedded_target = EmbeddedLayerTarget {
                        width: target.width,
                        height: target.height,
                        transform: layer.transform,
                        bounds: layer.bounds,
                        hit_rect: layer.hit_rect,
                        pointer_position: self.hit_test.pointer_position,
                        pointer_press_origin: self.hit_test.pointer_press_origin,
                        now: self.frame_instant(),
                    };
                    let GpuSurfaceSource::Owned(runtime) = &layer.source;
                    let output_format = runtime.borrow().output_format_for(target.format);
                    if !EmbeddedGpuSurfaceRuntime::ensure_setup(
                        runtime,
                        self.embedded_gpu_surface_setup(
                            target.adapter,
                            target.device,
                            target.queue,
                        ),
                        self.frame_signals(),
                        output_format,
                    ) {
                        needs_redraw = true;
                        continue;
                    }
                    let prepared = runtime.borrow_mut().prepare_layer(
                        target.device,
                        target.queue,
                        embedded_target,
                    );
                    if prepared.needs_redraw {
                        needs_redraw = true;
                    }
                    let (mask_view, mask_texture) = if layer.active_layers.is_empty() {
                        (
                            self.default_compositor_mask_view(
                                target.device,
                                target.queue,
                                target.format,
                            ),
                            None,
                        )
                    } else {
                        let leased = self.render_active_layers_mask_to_texture(
                            target.device,
                            target.queue,
                            target.width,
                            target.height,
                            &layer.active_layers,
                        );
                        (leased.view.clone(), Some(leased))
                    };
                    ready.push(ReadyLayerComposite {
                        layer_view: prepared.view,
                        layer_texture: None,
                        mask_view,
                        mask_texture,
                        uniform_bytes: prepared.uniform_bytes,
                    });
                }
                #[cfg(hydrolysis_macos_system_webview)]
                RenderLayer::NativeView(_) => {
                    panic!("Hydrolysis native views require hybrid window composition")
                }
            }
        }

        // Phase 2 — one render pass, one submit, painter's order.
        if ready.is_empty() {
            self.clear_target_surface(target.device, target.queue, target.view, target.base_color);
        } else {
            self.composite_ready_layers(&target, &ready);
        }
        for layer in ready {
            if let Some(leased) = layer.layer_texture {
                self.compositor.release_layer_texture(leased);
            }
            if let Some(leased) = layer.mask_texture {
                self.compositor.release_layer_texture(leased);
            }
        }
        for _ in 0..transient_layer_count {
            render_layers.pop();
        }
        self.compositor.render_layers = render_layers;

        if needs_redraw {
            self.request_redraw();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct GestureProbe;

    impl waterui_graphics::GpuView for GestureProbe {
        async fn setup(&mut self, _ctx: &GpuContext<'_>, _env: &mut Environment) {}

        fn render(&mut self, _frame: &mut GpuFrame) {}
    }

    #[test]
    fn trackpad_pan_reaches_one_active_frame_before_settling() {
        let mut runtime =
            EmbeddedGpuSurfaceRuntime::new(GpuSurface::new(GestureProbe), &Environment::new());

        assert!(runtime.handle_trackpad_pan(3.0, -2.0, TouchPhase::Started));
        assert!(runtime.handle_trackpad_pan(24.0, -12.0, TouchPhase::Moved));
        assert_eq!(
            runtime.gesture.pan_offset,
            waterui_core::layout::Point::new(27.0, -14.0)
        );
        assert!(runtime.gesture.active);

        assert!(runtime.handle_trackpad_pan(2.0, -1.0, TouchPhase::Ended));
        assert_eq!(
            runtime.gesture.pan_offset,
            waterui_core::layout::Point::new(29.0, -15.0)
        );
        assert!(runtime.gesture.active);
        assert!(runtime.trackpad_pan_ending);

        runtime.finish_trackpad_pan_frame();
        assert!(!runtime.gesture.active);
        assert!(!runtime.trackpad_pan_ending);
    }

    #[test]
    fn embedded_surface_inherits_dynamic_range_metadata() {
        let mut env = Environment::new();
        env.insert(DynamicRangePreference(false));
        let runtime = EmbeddedGpuSurfaceRuntime::new(GpuSurface::new(GestureProbe), &env);
        assert_eq!(runtime.prefers_hdr, Some(false));

        let explicit = EmbeddedGpuSurfaceRuntime::new(
            GpuSurface::new(GestureProbe).prefer_hdr_surface(),
            &env,
        );
        assert_eq!(explicit.prefers_hdr, Some(true));
    }
}