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
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
use waterui::cursor::CursorStyle;
use waterui::window::{Window as WuiWindow, WindowState};
use waterui_graphics::RedrawHandle;

#[cfg(any(feature = "winit", all(target_arch = "wasm32", feature = "web")))]
use waterui_graphics::gpu_surface::preferred_surface_format;

/// Input button mapped from a platform pointer event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerButton {
    Primary,
    Secondary,
    Middle,
    Back,
    Forward,
    Other(u16),
}

/// Physical pointer source reported by the platform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerKind {
    Mouse,
    Touch,
    Pen,
}

/// Input key state mapped from a platform keyboard event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyState {
    Pressed,
    Released,
}

/// Platform-agnostic key identifier.
///
/// This is the vocabulary `WaterUI`'s own widgets and the embedded browser
/// bridges match on. New code should read [`InputEvent::Key`]'s `logical_key`
/// and `physical_code` instead — the W3C UI Events pair, which is what GPU
/// surfaces receive and what the browser engines will move to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyCode {
    Character(String),
    Named(String),
    Unidentified,
}

impl KeyCode {
    /// The W3C UI Events logical key this identifier denotes.
    ///
    /// A producer holding the platform's own key event maps that directly into
    /// [`InputEvent::Key`]'s `logical_key`, which is strictly better. This is
    /// for the synthetic keystrokes a test driver injects, where the
    /// identifier is the only thing there is.
    #[must_use]
    pub fn to_w3c_key(&self) -> keyboard_types::Key {
        let unidentified = keyboard_types::Key::Named(keyboard_types::NamedKey::Unidentified);
        match self {
            Self::Character(value) => keyboard_types::Key::Character(value.clone()),
            // The W3C vocabulary has no named "Space": it is the character the
            // key types.
            Self::Named(value) if value == "Space" => {
                keyboard_types::Key::Character(" ".to_owned())
            }
            Self::Named(value) => value.parse().unwrap_or(unidentified),
            Self::Unidentified => unidentified,
        }
    }
}

/// Active key modifiers snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Modifiers {
    pub shift: bool,
    pub control: bool,
    pub alt: bool,
    pub super_key: bool,
}

impl From<Modifiers> for keyboard_types::Modifiers {
    fn from(modifiers: Modifiers) -> Self {
        let mut result = Self::empty();
        result.set(Self::SHIFT, modifiers.shift);
        result.set(Self::CONTROL, modifiers.control);
        result.set(Self::ALT, modifiers.alt);
        result.set(Self::META, modifiers.super_key);
        result
    }
}

/// IME purpose for the focused text input target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextInputPurpose {
    Normal,
    Password,
}

pub use waterui_backend_core::input::TouchPhase;

/// Focused text-input area used for IME activation and candidate-window placement.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextInputState {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub purpose: TextInputPurpose,
}

/// Input events emitted by a windowing backend.
#[derive(Debug, Clone, PartialEq)]
pub enum InputEvent {
    PointerDown {
        id: u64,
        kind: PointerKind,
        x: f32,
        y: f32,
        button: PointerButton,
    },
    PointerUp {
        id: u64,
        kind: PointerKind,
        x: f32,
        y: f32,
        button: PointerButton,
    },
    PointerMove {
        id: u64,
        kind: PointerKind,
        x: f32,
        y: f32,
    },
    PointerCancel {
        id: u64,
        kind: PointerKind,
    },
    Moved {
        x: f32,
        y: f32,
    },
    Scroll {
        x: f32,
        y: f32,
        dx: f32,
        dy: f32,
        is_line_delta: bool,
    },
    TrackpadPan {
        x: f32,
        y: f32,
        dx: f32,
        dy: f32,
        phase: TouchPhase,
    },
    Magnification {
        x: f32,
        y: f32,
        delta: f32,
        phase: TouchPhase,
    },
    Rotation {
        x: f32,
        y: f32,
        delta: f32,
        phase: TouchPhase,
    },
    TextInput {
        text: String,
    },
    Key {
        key: KeyCode,
        /// The logical key in the W3C UI Events vocabulary — what the layout
        /// and modifiers produce. Unlike `key`, this is never suppressed when
        /// the same keystroke also produces text: an embedded engine needs the
        /// real `keydown` alongside the insertion, exactly as the web does.
        logical_key: keyboard_types::Key,
        /// The physical key in the W3C UI Events vocabulary — where it sits on
        /// the keyboard, independent of layout.
        physical_code: keyboard_types::Code,
        /// Whether the platform generated this press by auto-repeat.
        repeat: bool,
        state: KeyState,
        modifiers: Modifiers,
    },
    ModifiersChanged(Modifiers),
    ImePreedit {
        text: String,
        /// Caret offset within `text`, in bytes, when the platform reports one.
        caret: Option<usize>,
    },
    ImeCommit {
        text: String,
    },
    ImeDisabled,
    Resize {
        width: u32,
        height: u32,
    },
    CloseRequested,
}

/// Errors raised by surface acquisition/presentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SurfaceError {
    Timeout,
    Occluded,
    Outdated,
    Lost,
    Validation,
}

impl core::fmt::Display for SurfaceError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(match self {
            Self::Timeout => "surface acquisition timed out",
            Self::Occluded => "surface is occluded",
            Self::Outdated => "surface configuration is outdated",
            Self::Lost => "surface was lost",
            Self::Validation => "surface acquisition failed validation",
        })
    }
}

impl std::error::Error for SurfaceError {}

/// A frame acquired from a `SurfaceProvider`.
pub enum SurfaceFrame {
    Offscreen {
        texture: wgpu::Texture,
        view: wgpu::TextureView,
    },
    #[cfg(feature = "winit")]
    Window {
        output: wgpu::SurfaceTexture,
        view: wgpu::TextureView,
    },
    #[cfg(all(target_arch = "wasm32", feature = "web"))]
    Browser {
        output: wgpu::SurfaceTexture,
        view: wgpu::TextureView,
    },
}

impl SurfaceFrame {
    #[must_use]
    pub fn texture(&self) -> &wgpu::Texture {
        match self {
            Self::Offscreen { texture, .. } => texture,
            #[cfg(feature = "winit")]
            Self::Window { output, .. } => &output.texture,
            #[cfg(all(target_arch = "wasm32", feature = "web"))]
            Self::Browser { output, .. } => &output.texture,
        }
    }

    #[must_use]
    pub fn view(&self) -> &wgpu::TextureView {
        match self {
            Self::Offscreen { view, .. } => view,
            #[cfg(feature = "winit")]
            Self::Window { view, .. } => view,
            #[cfg(all(target_arch = "wasm32", feature = "web"))]
            Self::Browser { view, .. } => view,
        }
    }
}

#[cfg(any(feature = "winit", all(target_arch = "wasm32", feature = "web")))]
fn select_hydrolysis_surface_format(caps: &wgpu::SurfaceCapabilities) -> wgpu::TextureFormat {
    let preferred = preferred_surface_format(caps);
    if supports_hydrolysis_surface_format(preferred) {
        return normalize_surface_format(caps, preferred);
    }

    if let Some(format) = caps
        .formats
        .iter()
        .copied()
        .find(|format| supports_hydrolysis_surface_format(*format))
    {
        return normalize_surface_format(caps, format);
    }

    panic!(
        "hydrolysis surface: requires one of Rgba16Float/Rgba32Float/Rgba8/Bgra8 surface formats, got {:?}",
        caps.formats
    );
}

#[cfg(any(feature = "winit", all(target_arch = "wasm32", feature = "web")))]
fn supports_hydrolysis_surface_format(format: wgpu::TextureFormat) -> bool {
    matches!(
        format.remove_srgb_suffix(),
        wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Bgra8Unorm
    ) || matches!(
        format,
        wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
    )
}

#[cfg(any(feature = "winit", all(target_arch = "wasm32", feature = "web")))]
fn normalize_surface_format(
    caps: &wgpu::SurfaceCapabilities,
    format: wgpu::TextureFormat,
) -> wgpu::TextureFormat {
    if format.is_srgb() {
        let linear = format.remove_srgb_suffix();
        if caps.formats.contains(&linear) {
            return linear;
        }
    }
    format
}

#[cfg(any(feature = "winit", all(target_arch = "wasm32", feature = "web")))]
fn acquire_surface_texture(
    surface: &wgpu::Surface<'_>,
) -> Result<wgpu::SurfaceTexture, SurfaceError> {
    match surface.get_current_texture() {
        wgpu::CurrentSurfaceTexture::Success(output)
        | wgpu::CurrentSurfaceTexture::Suboptimal(output) => Ok(output),
        wgpu::CurrentSurfaceTexture::Timeout => Err(SurfaceError::Timeout),
        wgpu::CurrentSurfaceTexture::Occluded => Err(SurfaceError::Occluded),
        wgpu::CurrentSurfaceTexture::Outdated => Err(SurfaceError::Outdated),
        wgpu::CurrentSurfaceTexture::Lost => Err(SurfaceError::Lost),
        wgpu::CurrentSurfaceTexture::Validation => Err(SurfaceError::Validation),
    }
}

/// Rendering surface abstraction consumed by hydrolysis runner/renderer.
pub trait SurfaceProvider {
    fn adapter(&self) -> &wgpu::Adapter;
    fn device(&self) -> &wgpu::Device;
    fn queue(&self) -> &wgpu::Queue;
    fn acquire(&mut self) -> Result<SurfaceFrame, SurfaceError>;
    fn present(&mut self, frame: SurfaceFrame);
    fn size(&self) -> (u32, u32);
    fn format(&self) -> wgpu::TextureFormat;
    fn resize(&mut self, width: u32, height: u32);
}

/// Window abstraction consumed by hydrolysis runner.
pub trait PlatformWindow: 'static {
    fn surface(&mut self) -> &mut dyn SurfaceProvider;
    fn apply_properties(&mut self, window: &WuiWindow);
    /// Applies the window's effective content-size limits (logical units).
    ///
    /// Explicit `Window::min_size`/`max_size` values take precedence; otherwise
    /// each limit comes from the content's layout negotiation. Targets without
    /// per-window runtime size limits (offscreen surfaces, web canvases, fixed
    /// embedded displays) keep this default no-op.
    fn set_size_limits(
        &mut self,
        min: Option<waterui_core::layout::Size>,
        max: Option<waterui_core::layout::Size>,
    ) {
        let _ = (min, max);
    }
    /// Whether this window acts on content-derived size limits.
    ///
    /// Deriving them costs four extra whole-tree measure passes per frame, so a
    /// surface that cannot resize to fit its content — offscreen capture, an
    /// embedded GPU host, a fixed-size shell — leaves this `false` and never pays
    /// for them. Defaults to `false` alongside the no-op [`Self::set_size_limits`].
    fn applies_size_limits(&self) -> bool {
        false
    }
    fn drain_events(&mut self) -> Vec<InputEvent>;
    fn request_redraw(&self);
    /// Returns a thread-safe wake bridge for nested GPU surfaces.
    ///
    /// Windowed platforms override this when their native window can be woken
    /// from a `RedrawHandle`. Offscreen and single-threaded hosts may keep the
    /// default and rely on their explicit render pump.
    fn gpu_surface_redraw_handle(&self) -> Option<RedrawHandle> {
        None
    }
    fn scale_factor(&self) -> f64;
    /// The refresh rate (Hz) of the display this window is on, if known.
    ///
    /// Drives the game-engine continuous-render frame budget and the diagnostics
    /// slow-frame threshold. Returns `None` on headless/offscreen/web paths with no
    /// monitor information, where the renderer falls back to its default pacing.
    fn refresh_rate_hz(&self) -> Option<f64> {
        None
    }
    fn sync_text_input_state(&mut self, state: Option<TextInputState>);
    fn set_cursor_style(&mut self, style: CursorStyle);
}

/// The adapter, device and queue an [`OffscreenSurface`] renders on.
///
/// A wgpu device is a heavyweight, driver-allocated resource, and on a machine
/// whose only adapter is a software rasterizer it is heavyweight in *system*
/// memory too. A process that builds one offscreen surface — a snapshot, a
/// preview, a `waterui-testing` host — pays for exactly one and never notices.
/// A process that builds hundreds, because it measures a fresh runtime per
/// sample, pays hundreds of times and exhausts the machine.
///
/// Such a caller creates one context and hands a clone to every surface. The
/// device is shared; everything a measurement is actually about — the view
/// tree, the renderer, the retained scene — is still built fresh per surface.
///
/// This owns the device to the end of the last clone's life, so it drains it on
/// the way out — see `drain_device_before_teardown`. Every headless test builds
/// one of these, and on a runner without a GPU they were the ones dying on drop.
#[derive(Clone, Debug)]
pub struct OffscreenGpuContext {
    /// Shared so the device is drained once, when the last surface using it
    /// goes away. `drain_device_before_teardown` blocks until the device is
    /// idle with no timeout, so running it per clone would make every surface's
    /// drop wait out the work of every *other* surface still on that device.
    inner: std::sync::Arc<OffscreenGpuContextInner>,
}

#[derive(Debug)]
struct OffscreenGpuContextInner {
    adapter: wgpu::Adapter,
    device: wgpu::Device,
    queue: wgpu::Queue,
}

impl Drop for OffscreenGpuContextInner {
    fn drop(&mut self) {
        waterui_graphics::shared_context::drain_device_before_teardown(&self.device);
    }
}

impl OffscreenGpuContext {
    /// Lets the device release everything dropped since the last call.
    ///
    /// Non-blocking: it processes the destruction queue rather than waiting for
    /// the device to go idle. Call it once the renderer and surface that used
    /// this device are both gone — a process that builds and drops many of them
    /// in sequence otherwise keeps every one of their allocations outstanding
    /// until the device itself is torn down.
    pub fn reclaim(&self) {
        if let Err(error) = self.inner.device.poll(wgpu::PollType::Poll) {
            tracing::warn!("GPU device did not reclaim dropped resources: {error}");
        }
    }

    /// Requests a context on the adapter WaterUI would render an application on.
    pub async fn new() -> Self {
        Self::new_with_adapter_selection(AdapterSelection::PRODUCTION).await
    }

    /// Requests a context for WaterUI test hosts.
    ///
    /// Unlike a production context, this allows compute-capable software
    /// adapters so CI can run Hydrolysis accessibility tests on llvmpipe
    /// without opting the runtime path into fallback adapters.
    #[cfg(any(test, feature = "testing"))]
    pub async fn new_for_tests() -> Self {
        Self::new_with_adapter_selection(AdapterSelection::TEST).await
    }

    /// Blocking [`Self::new_for_tests`], for synchronous test harnesses.
    #[cfg(any(test, feature = "testing"))]
    #[must_use]
    pub fn new_for_tests_blocking() -> Self {
        pollster::block_on(Self::new_for_tests())
    }

    async fn new_with_adapter_selection(selection: AdapterSelection) -> Self {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
        let adapter =
            request_hydrolysis_adapter(&instance, None, "hydrolysis offscreen surface", selection)
                .await;

        ensure_compute_capable_adapter(
            &adapter,
            "hydrolysis offscreen surface",
            "failed to find compute-capable wgpu adapter",
        );
        let required_limits = required_device_limits(&adapter);
        let required_features =
            waterui_graphics::shared_context::required_media_features(adapter.features());
        let (device, queue) = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("hydrolysis-offscreen-device"),
                required_features,
                required_limits,
                memory_hints: wgpu::MemoryHints::Performance,
                experimental_features: wgpu::ExperimentalFeatures::default(),
                trace: wgpu::Trace::default(),
            })
            .await
            .expect("hydrolysis offscreen surface: failed to request wgpu device");

        Self {
            inner: std::sync::Arc::new(OffscreenGpuContextInner {
                adapter,
                device,
                queue,
            }),
        }
    }
}

/// Headless offscreen rendering surface.
///
/// Dropping one lets the device reclaim the textures it allocated. That is a
/// non-blocking maintain, not the full drain the device gets at teardown: a
/// process that builds surfaces in sequence must not leave every surface's
/// allocations outstanding until the last one goes away — on a software
/// rasterizer that runs the machine out of memory — but neither should each
/// drop wait out the queued work of the other surfaces sharing the device.
pub struct OffscreenSurface {
    gpu: OffscreenGpuContext,
    width: u32,
    height: u32,
    format: wgpu::TextureFormat,
    last_presented: Option<wgpu::Texture>,
}

fn should_force_fallback_adapter() -> bool {
    std::env::var_os("WATER_HYDROLYSIS_FORCE_FALLBACK_ADAPTER").is_some()
}

#[derive(Clone, Copy, Debug)]
struct AdapterSelection {
    #[cfg_attr(
        target_arch = "wasm32",
        expect(
            dead_code,
            reason = "WebGPU adapter selection cannot enumerate software adapters"
        )
    )]
    allow_software_adapter: bool,
}

impl AdapterSelection {
    const PRODUCTION: Self = Self {
        allow_software_adapter: false,
    };

    #[cfg(any(test, feature = "testing"))]
    const TEST: Self = Self {
        allow_software_adapter: true,
    };

    fn force_fallback_adapter(self) -> bool {
        should_force_fallback_adapter()
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn allow_software_adapter(self) -> bool {
        self.allow_software_adapter || self.force_fallback_adapter()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(not(target_arch = "wasm32"))]
struct AdapterPreference {
    backend_rank: u8,
    device_type_rank: u8,
}

#[cfg(not(target_arch = "wasm32"))]
impl AdapterPreference {
    fn for_info(info: &wgpu::AdapterInfo) -> Self {
        Self {
            backend_rank: backend_rank(info.backend),
            device_type_rank: device_type_rank(info.device_type),
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
const fn backend_rank(backend: wgpu::Backend) -> u8 {
    if cfg!(target_os = "windows") {
        match backend {
            wgpu::Backend::Dx12 => 0,
            wgpu::Backend::Vulkan => 1,
            wgpu::Backend::Metal => 2,
            wgpu::Backend::Gl => 3,
            wgpu::Backend::BrowserWebGpu => 4,
            wgpu::Backend::Noop => 5,
        }
    } else if cfg!(target_os = "macos") {
        match backend {
            wgpu::Backend::Metal => 0,
            wgpu::Backend::Vulkan => 1,
            wgpu::Backend::Dx12 => 2,
            wgpu::Backend::Gl => 3,
            wgpu::Backend::BrowserWebGpu => 4,
            wgpu::Backend::Noop => 5,
        }
    } else {
        match backend {
            wgpu::Backend::Vulkan => 0,
            wgpu::Backend::Metal => 1,
            wgpu::Backend::Dx12 => 2,
            wgpu::Backend::Gl => 3,
            wgpu::Backend::BrowserWebGpu => 4,
            wgpu::Backend::Noop => 5,
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
const fn device_type_rank(device_type: wgpu::DeviceType) -> u8 {
    match device_type {
        wgpu::DeviceType::DiscreteGpu => 0,
        wgpu::DeviceType::IntegratedGpu => 1,
        wgpu::DeviceType::VirtualGpu => 2,
        wgpu::DeviceType::Other => 3,
        wgpu::DeviceType::Cpu => 4,
    }
}

fn is_compute_capable_adapter(adapter: &wgpu::Adapter) -> bool {
    let downlevel_caps = adapter.get_downlevel_capabilities();
    let limits = adapter.limits();
    downlevel_caps
        .flags
        .contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
        && limits.max_compute_workgroups_per_dimension > 0
}

async fn request_hydrolysis_adapter(
    instance: &wgpu::Instance,
    compatible_surface: Option<&wgpu::Surface<'_>>,
    context: &str,
    selection: AdapterSelection,
) -> wgpu::Adapter {
    #[cfg(all(target_arch = "wasm32", feature = "web"))]
    {
        let adapter = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface,
                force_fallback_adapter: selection.force_fallback_adapter(),
            })
            .await
            .expect("hydrolysis adapter selection: failed to find web adapter");
        log_selected_adapter(context, &adapter);
        return adapter;
    }

    #[cfg(not(all(target_arch = "wasm32", feature = "web")))]
    {
        if selection.force_fallback_adapter() {
            let adapter = instance
                .request_adapter(&wgpu::RequestAdapterOptions {
                    power_preference: wgpu::PowerPreference::HighPerformance,
                    compatible_surface,
                    force_fallback_adapter: true,
                })
                .await
                .expect("hydrolysis adapter selection: failed to find fallback adapter");
            log_selected_adapter(context, &adapter);
            return adapter;
        }

        let backends = wgpu::Backends::from_env().unwrap_or(wgpu::Backends::all());
        let mut best_candidate: Option<(AdapterPreference, wgpu::Adapter)> = None;
        let mut inspected_adapters: Vec<String> = Vec::new();

        for adapter in instance.enumerate_adapters(backends).await {
            let info = adapter.get_info();
            let surface_supported = compatible_surface
                .as_ref()
                .is_none_or(|surface| adapter.is_surface_supported(surface));
            let limits = adapter.limits();
            let compute_capable = is_compute_capable_adapter(&adapter);

            tracing::info!(
                target: "hydrolysis::gpu",
                context,
                adapter = ?info,
                surface_supported,
                compute_capable,
                max_compute_workgroups_per_dimension = limits.max_compute_workgroups_per_dimension,
                "hydrolysis adapter candidate"
            );

            if !surface_supported {
                continue;
            }

            inspected_adapters.push(format!(
                "'{}' ({:?}, {:?}, compute={}, max_compute_workgroups_per_dimension={})",
                info.name,
                info.backend,
                info.device_type,
                compute_capable,
                limits.max_compute_workgroups_per_dimension
            ));

            if info.backend == wgpu::Backend::Noop
                || (info.device_type == wgpu::DeviceType::Cpu
                    && !selection.allow_software_adapter())
            {
                tracing::info!(
                    target: "hydrolysis::gpu",
                    context,
                    adapter = ?info,
                    "skipping software/noop adapter because fallback adapter was not requested"
                );
                continue;
            }

            if !compute_capable {
                continue;
            }

            let preference = AdapterPreference::for_info(&info);
            match &best_candidate {
                Some((best_preference, _)) if *best_preference <= preference => {}
                _ => best_candidate = Some((preference, adapter)),
            }
        }

        let (_, adapter) = best_candidate.unwrap_or_else(|| {
            if inspected_adapters.is_empty() {
                panic!(
                    "{context}: failed to find a surface-compatible wgpu adapter for requested backends {:?}. \
Set WGPU_BACKEND to an available backend or install/update the platform GPU driver.",
                    backends
                );
            }

            panic!(
                "{context}: failed to find a compute-capable modern adapter. \
Surface-compatible adapters inspected: {}. \
Set WATER_HYDROLYSIS_FORCE_FALLBACK_ADAPTER=1 to explicitly allow software fallback adapters for diagnostics.",
                inspected_adapters.join("; ")
            );
        });

        log_selected_adapter(context, &adapter);
        adapter
    }
}

fn log_selected_adapter(context: &str, adapter: &wgpu::Adapter) {
    let info = adapter.get_info();
    tracing::info!(
        target: "hydrolysis::gpu",
        context,
        force_fallback_adapter = should_force_fallback_adapter(),
        adapter = ?info,
        "selected wgpu adapter"
    );
}

impl Drop for OffscreenSurface {
    fn drop(&mut self) {
        self.last_presented = None;
        self.gpu.reclaim();
    }
}

impl core::fmt::Debug for OffscreenSurface {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("OffscreenSurface")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("format", &self.format)
            .finish_non_exhaustive()
    }
}

impl OffscreenSurface {
    pub async fn new(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        Self::on_context(OffscreenGpuContext::new().await, width, height, format)
    }

    /// Creates an offscreen surface for WaterUI test hosts.
    ///
    /// Unlike production surfaces, this constructor allows compute-capable
    /// software adapters so CI can run Hydrolysis accessibility tests on
    /// llvmpipe without opting the runtime path into fallback adapters.
    #[cfg(any(test, feature = "testing"))]
    pub async fn new_for_tests(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        Self::on_context(
            OffscreenGpuContext::new_for_tests().await,
            width,
            height,
            format,
        )
    }

    /// Creates a surface on an already-requested [`OffscreenGpuContext`].
    ///
    /// Every surface built on one context shares its device, so a process that
    /// needs many surfaces requests a device once instead of once per surface.
    #[must_use]
    pub fn on_context(
        gpu: OffscreenGpuContext,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
    ) -> Self {
        Self {
            gpu,
            width: width.max(1),
            height: height.max(1),
            format,
            last_presented: None,
        }
    }

    #[must_use]
    pub fn new_blocking(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        pollster::block_on(Self::new(width, height, format))
    }

    #[must_use]
    pub fn last_presented(&self) -> Option<&wgpu::Texture> {
        self.last_presented.as_ref()
    }
}

fn required_device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits {
    let adapter_limits = adapter.limits();
    let downlevel_caps = adapter.get_downlevel_capabilities();
    let base_limits = if downlevel_caps.is_webgpu_compliant()
        || downlevel_caps
            .flags
            .contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
    {
        wgpu::Limits::default()
    } else {
        wgpu::Limits::downlevel_webgl2_defaults()
    };

    base_limits
        .using_resolution(adapter_limits.clone())
        .using_alignment(adapter_limits)
}

fn ensure_compute_capable_adapter(
    adapter: &wgpu::Adapter,
    context: &str,
    no_compute_message: &str,
) {
    let limits = adapter.limits();
    if is_compute_capable_adapter(adapter) {
        return;
    }

    let info = adapter.get_info();
    let fallback_hint = if cfg!(target_os = "windows") {
        " On Windows, try forcing DX12 WARP: set WGPU_BACKEND=dx12 and WATER_HYDROLYSIS_FORCE_FALLBACK_ADAPTER=1."
    } else {
        ""
    };
    panic!(
        "{context}: {no_compute_message}. Selected adapter '{}' ({:?}) reports max_compute_workgroups_per_dimension = {}. \
Hydrolysis requires compute shader support. On virtual machines, enable hardware 3D acceleration and update VM graphics tools/driver, \
or run on a host with a compute-capable GPU.{fallback_hint}",
        info.name, info.backend, limits.max_compute_workgroups_per_dimension
    );
}

impl SurfaceProvider for OffscreenSurface {
    fn adapter(&self) -> &wgpu::Adapter {
        &self.gpu.inner.adapter
    }

    fn device(&self) -> &wgpu::Device {
        &self.gpu.inner.device
    }

    fn queue(&self) -> &wgpu::Queue {
        &self.gpu.inner.queue
    }

    fn acquire(&mut self) -> Result<SurfaceFrame, SurfaceError> {
        let texture = self.last_presented.take().unwrap_or_else(|| {
            self.gpu
                .inner
                .device
                .create_texture(&wgpu::TextureDescriptor {
                    label: Some("hydrolysis-offscreen-frame"),
                    size: wgpu::Extent3d {
                        width: self.width,
                        height: self.height,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format: self.format,
                    usage: wgpu::TextureUsages::TEXTURE_BINDING
                        | wgpu::TextureUsages::COPY_SRC
                        | wgpu::TextureUsages::STORAGE_BINDING
                        | wgpu::TextureUsages::RENDER_ATTACHMENT,
                    view_formats: &[],
                })
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        Ok(SurfaceFrame::Offscreen { texture, view })
    }

    fn present(&mut self, frame: SurfaceFrame) {
        match frame {
            SurfaceFrame::Offscreen { texture, .. } => {
                self.last_presented = Some(texture);
            }
            #[cfg(feature = "winit")]
            SurfaceFrame::Window { .. } => {
                panic!("hydrolysis offscreen surface received a window frame");
            }
            #[cfg(all(target_arch = "wasm32", feature = "web"))]
            SurfaceFrame::Browser { .. } => {
                panic!("hydrolysis offscreen surface received a browser frame");
            }
        }
    }

    fn size(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    fn format(&self) -> wgpu::TextureFormat {
        self.format
    }

    fn resize(&mut self, width: u32, height: u32) {
        let width = width.max(1);
        let height = height.max(1);
        if (width, height) != (self.width, self.height) {
            self.width = width;
            self.height = height;
            self.last_presented = None;
        }
    }
}

/// Headless platform window backed by an offscreen texture.
#[derive(Debug)]
pub struct OffscreenWindow {
    surface: OffscreenSurface,
    scale_factor: f64,
    /// Last applied (min, max) content-size limits, recorded so tests can
    /// assert what the runner derived; offscreen surfaces have no real window
    /// to constrain.
    size_limits: Option<(
        Option<waterui_core::layout::Size>,
        Option<waterui_core::layout::Size>,
    )>,
}

impl OffscreenWindow {
    #[must_use]
    pub fn new(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        Self {
            surface: OffscreenSurface::new_blocking(width, height, format),
            scale_factor: 1.0,
            size_limits: None,
        }
    }

    /// Creates an offscreen window for WaterUI test hosts.
    ///
    /// This keeps production adapter selection strict while allowing
    /// `waterui-testing` to run on compute-capable software adapters in CI.
    /// Requests a device of its own; a caller that builds several windows
    /// should request one [`OffscreenGpuContext`] and use [`Self::on_context`].
    #[cfg(any(test, feature = "testing"))]
    #[must_use]
    pub fn new_for_tests(width: u32, height: u32, format: wgpu::TextureFormat) -> Self {
        Self::on_context(
            OffscreenGpuContext::new_for_tests_blocking(),
            width,
            height,
            format,
        )
    }

    /// Creates a window on an already-requested [`OffscreenGpuContext`], so
    /// every window built on that context shares its device.
    #[must_use]
    pub fn on_context(
        gpu: OffscreenGpuContext,
        width: u32,
        height: u32,
        format: wgpu::TextureFormat,
    ) -> Self {
        Self {
            surface: OffscreenSurface::on_context(gpu, width, height, format),
            scale_factor: 1.0,
            size_limits: None,
        }
    }

    /// Renders at `scale_factor` physical pixels per logical pixel.
    ///
    /// Layout stays in logical units; only the surface allocation and the
    /// reported [`PlatformWindow::scale_factor`] change, so a 2x offscreen
    /// window produces a HiDPI-sharp image of the very same layout.
    /// Sets the physical-pixels-per-logical-pixel ratio, reallocating the
    /// surface to match. See [`Self::with_scale_factor`].
    pub fn set_scale_factor(&mut self, scale_factor: f64) {
        assert!(
            scale_factor.is_finite() && scale_factor > 0.0,
            "offscreen scale factor must be finite and positive, got {scale_factor}"
        );
        let logical_width = f64::from(self.surface.size().0) / self.scale_factor;
        let logical_height = f64::from(self.surface.size().1) / self.scale_factor;
        self.scale_factor = scale_factor;
        self.resize_to_logical(logical_width, logical_height);
    }

    #[must_use]
    pub fn with_scale_factor(mut self, scale_factor: f64) -> Self {
        assert!(
            scale_factor.is_finite() && scale_factor > 0.0,
            "offscreen scale factor must be finite and positive, got {scale_factor}"
        );
        self.set_scale_factor(scale_factor);
        self
    }

    fn resize_to_logical(&mut self, width: f64, height: f64) {
        let physical = |value: f64| (value * self.scale_factor).round().max(1.0) as u32;
        self.surface.resize(physical(width), physical(height));
    }

    #[must_use]
    pub fn surface_ref(&self) -> &OffscreenSurface {
        &self.surface
    }

    /// The last (min, max) content-size limits the runner applied, for tests.
    #[must_use]
    pub fn applied_size_limits(
        &self,
    ) -> Option<(
        Option<waterui_core::layout::Size>,
        Option<waterui_core::layout::Size>,
    )> {
        self.size_limits
    }
}

impl PlatformWindow for OffscreenWindow {
    fn surface(&mut self) -> &mut dyn SurfaceProvider {
        &mut self.surface
    }

    fn apply_properties(&mut self, window: &WuiWindow) {
        if window.state.get() == WindowState::Closed {
            return;
        }
        let frame = window.frame.get();
        // `frame` is in logical units; the surface is allocated in physical
        // pixels, so the scale factor has to be applied here or a HiDPI window
        // would rasterize at one physical pixel per logical pixel.
        self.resize_to_logical(
            f64::from(frame.width().max(1.0)),
            f64::from(frame.height().max(1.0)),
        );
    }

    fn set_size_limits(
        &mut self,
        min: Option<waterui_core::layout::Size>,
        max: Option<waterui_core::layout::Size>,
    ) {
        self.size_limits = Some((min, max));
    }

    fn applies_size_limits(&self) -> bool {
        true
    }

    fn drain_events(&mut self) -> Vec<InputEvent> {
        Vec::new()
    }

    fn request_redraw(&self) {}

    fn scale_factor(&self) -> f64 {
        self.scale_factor
    }

    fn sync_text_input_state(&mut self, _state: Option<TextInputState>) {}

    fn set_cursor_style(&mut self, _style: CursorStyle) {}
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
mod web_impl;

#[cfg(all(feature = "winit", target_os = "macos"))]
mod macos_display_link;

#[cfg(feature = "winit")]
mod winit_impl {
    #[cfg(hydrolysis_macos_system_webview)]
    use std::collections::{HashMap, HashSet};
    use std::sync::Arc;

    use nami::Signal;
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2::runtime::NSObjectProtocol;
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2::{
        DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained,
    };
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2_app_kit::NSView;
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2_core_graphics::CGPath;
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2_foundation::{NSPoint, NSRect, NSSize};
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2_quartz_core::{CAMetalLayer, CAShapeLayer};
    #[cfg(hydrolysis_macos_system_webview)]
    use objc2_web_kit::WKWebView;
    use waterui::window::WindowState;
    #[cfg(hydrolysis_macos_system_webview)]
    use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
    use winit::{
        dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize},
        event::{
            ElementState, Ime, KeyEvent, MouseButton, MouseScrollDelta,
            TouchPhase as WinitTouchPhase, WindowEvent,
        },
        keyboard::{Key, ModifiersState},
        window::{
            Cursor as WinitCursor, CursorIcon, Fullscreen, ImePurpose, Window as NativeWindow,
            WindowId,
        },
    };

    use super::{
        CursorStyle, InputEvent, KeyCode, KeyState, Modifiers, PlatformWindow, PointerButton,
        PointerKind, RedrawHandle, SurfaceError, SurfaceFrame, SurfaceProvider, TextInputPurpose,
        TextInputState, TouchPhase,
    };

    #[derive(Clone)]
    pub struct WinitGpuContext {
        instance: wgpu::Instance,
        adapter: wgpu::Adapter,
        device: wgpu::Device,
        queue: wgpu::Queue,
    }

    pub struct WinitSurface {
        surface: wgpu::Surface<'static>,
        gpu: WinitGpuContext,
        config: wgpu::SurfaceConfiguration,
    }

    impl core::fmt::Debug for WinitSurface {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("WinitSurface")
                .field("config", &self.config)
                .finish_non_exhaustive()
        }
    }

    impl WinitSurface {
        fn from_surface(
            surface: wgpu::Surface<'static>,
            gpu: WinitGpuContext,
            width: u32,
            height: u32,
        ) -> Self {
            let caps = surface.get_capabilities(&gpu.adapter);
            let format = super::select_hydrolysis_surface_format(&caps);
            let alpha_mode = caps
                .alpha_modes
                .iter()
                .copied()
                .find(|mode| {
                    matches!(
                        mode,
                        wgpu::CompositeAlphaMode::PreMultiplied
                            | wgpu::CompositeAlphaMode::PostMultiplied
                    )
                })
                .unwrap_or(caps.alpha_modes[0]);
            let config = wgpu::SurfaceConfiguration {
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                format,
                width: width.max(1),
                height: height.max(1),
                present_mode: wgpu::PresentMode::AutoVsync,
                alpha_mode,
                view_formats: vec![],
                desired_maximum_frame_latency: 2,
            };
            surface.configure(&gpu.device, &config);
            Self {
                surface,
                gpu,
                config,
            }
        }

        pub async fn new(
            window: Arc<NativeWindow>,
            shared_gpu: Option<&WinitGpuContext>,
        ) -> (Self, WinitGpuContext) {
            let (gpu, surface) = match shared_gpu {
                Some(gpu) => {
                    let surface = gpu
                        .instance
                        .create_surface(window.clone())
                        .expect("hydrolysis winit surface: failed to create shared surface");
                    (gpu.clone(), surface)
                }
                None => {
                    let instance =
                        wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
                    let surface = instance
                        .create_surface(window.clone())
                        .expect("hydrolysis winit surface: failed to create surface");
                    let adapter = super::request_hydrolysis_adapter(
                        &instance,
                        Some(&surface),
                        "hydrolysis winit surface",
                        super::AdapterSelection::PRODUCTION,
                    )
                    .await;

                    super::ensure_compute_capable_adapter(
                        &adapter,
                        "hydrolysis winit surface",
                        "failed to find compute-capable wgpu adapter",
                    );
                    let required_limits = super::required_device_limits(&adapter);
                    let required_features =
                        waterui_graphics::shared_context::required_media_features(
                            adapter.features(),
                        );
                    let (device, queue) = adapter
                        .request_device(&wgpu::DeviceDescriptor {
                            label: Some("hydrolysis-winit-device"),
                            required_features,
                            required_limits,
                            memory_hints: wgpu::MemoryHints::Performance,
                            experimental_features: wgpu::ExperimentalFeatures::default(),
                            trace: wgpu::Trace::default(),
                        })
                        .await
                        .expect("hydrolysis winit surface: failed to request device");
                    (
                        WinitGpuContext {
                            instance,
                            adapter,
                            device,
                            queue,
                        },
                        surface,
                    )
                }
            };

            let size = window.inner_size();
            (
                Self::from_surface(surface, gpu.clone(), size.width, size.height),
                gpu,
            )
        }

        #[cfg(hydrolysis_macos_system_webview)]
        fn for_core_animation_layer(
            layer: &CAMetalLayer,
            gpu: &WinitGpuContext,
            width: u32,
            height: u32,
        ) -> Self {
            let target = wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(
                std::ptr::from_ref(layer).cast_mut().cast(),
            );
            // SAFETY: the layer handed to `create_surface_unsafe` is the window's own
            // `CAMetalLayer`, which the window keeps alive for at least as long as the
            // surface created from it.
            let surface = unsafe {
                gpu.instance
                    .create_surface_unsafe(target)
                    .expect("Hydrolysis failed to create a Metal overlay surface")
            };
            Self::from_surface(surface, gpu.clone(), width, height)
        }
    }

    impl SurfaceProvider for WinitSurface {
        fn adapter(&self) -> &wgpu::Adapter {
            &self.gpu.adapter
        }

        fn device(&self) -> &wgpu::Device {
            &self.gpu.device
        }

        fn queue(&self) -> &wgpu::Queue {
            &self.gpu.queue
        }

        fn acquire(&mut self) -> Result<SurfaceFrame, SurfaceError> {
            let output = super::acquire_surface_texture(&self.surface)?;
            let view = output
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default());
            Ok(SurfaceFrame::Window { output, view })
        }

        fn present(&mut self, frame: SurfaceFrame) {
            match frame {
                SurfaceFrame::Window { output, .. } => output.present(),
                SurfaceFrame::Offscreen { .. } => {
                    panic!("hydrolysis winit surface received an offscreen frame")
                }
            }
        }

        fn size(&self) -> (u32, u32) {
            (self.config.width, self.config.height)
        }

        fn format(&self) -> wgpu::TextureFormat {
            self.config.format
        }

        fn resize(&mut self, width: u32, height: u32) {
            self.config.width = width.max(1);
            self.config.height = height.max(1);
            self.surface.configure(&self.gpu.device, &self.config);
        }
    }

    #[cfg(hydrolysis_macos_system_webview)]
    struct MacOverlaySurface {
        layer: Retained<CAMetalLayer>,
        surface: WinitSurface,
    }

    /// Whether an AppKit rect contains a point, in the same coordinate space.
    #[cfg(hydrolysis_macos_system_webview)]
    fn ns_rect_contains(rect: NSRect, point: NSPoint) -> bool {
        point.x >= rect.origin.x
            && point.y >= rect.origin.y
            && point.x < rect.origin.x + rect.size.width
            && point.y < rect.origin.y + rect.size.height
    }

    #[cfg(hydrolysis_macos_system_webview)]
    struct NativeViewContainerIvars {
        /// Where `WaterUI` draws interactive content over the hosted native
        /// view, in this container's *superview* coordinate space — the space
        /// `hitTest:` is given its point in.
        occluded: core::cell::RefCell<Vec<NSRect>>,
    }

    #[cfg(hydrolysis_macos_system_webview)]
    define_class!(
        #[unsafe(super(NSView))]
        #[name = "WuiHydrolysisNativeViewContainer"]
        #[thread_kind = MainThreadOnly]
        #[ivars = NativeViewContainerIvars]
        struct NativeViewContainer;

        unsafe impl NSObjectProtocol for NativeViewContainer {}

        impl NativeViewContainer {
            /// Refuses hits where `WaterUI` painted interactive content on top.
            ///
            /// Raising the overlay's `zPosition` fixed only what the user sees:
            /// a `CALayer` is not in AppKit's hit-test chain, so a snackbar,
            /// dialog or menu drawn over a `WKWebView` rendered above it and
            /// still handed every click to the page underneath. Returning `nil`
            /// lets the event fall through to the winit content view, where
            /// Hydrolysis's own hit test finds the target that is visibly on
            /// top.
            ///
            /// The view is returned unowned, as `hitTest:` is defined to: the
            /// pointer travels straight through from the superclass, so it is a
            /// raw pointer rather than a `Retained` here.
            #[unsafe(method(hitTest:))]
            fn hit_test(&self, point: NSPoint) -> *mut NSView {
                if self
                    .ivars()
                    .occluded
                    .borrow()
                    .iter()
                    .any(|rect| ns_rect_contains(*rect, point))
                {
                    return core::ptr::null_mut();
                }
                // SAFETY: main-thread call to `NSView`'s own implementation,
                // which is what this override defers to for every other point.
                unsafe { msg_send![super(self), hitTest: point] }
            }
        }
    );

    #[cfg(hydrolysis_macos_system_webview)]
    impl NativeViewContainer {
        fn new(mtm: MainThreadMarker) -> Retained<Self> {
            let this = Self::alloc(mtm).set_ivars(NativeViewContainerIvars {
                occluded: core::cell::RefCell::new(Vec::new()),
            });
            // SAFETY: `initWithFrame:` is `NSView`'s designated initializer, and
            // `-> Retained<Self>` is the signature objc2 expects here.
            unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] }
        }

        fn set_occluded(&self, rects: Vec<NSRect>) {
            self.ivars().occluded.replace(rects);
        }
    }

    #[cfg(hydrolysis_macos_system_webview)]
    struct MacNativeViewHost {
        web_view: Retained<WKWebView>,
        container: Retained<NativeViewContainer>,
        rounded_clip_views: Vec<Retained<NSView>>,
    }

    #[cfg(hydrolysis_macos_system_webview)]
    impl MacNativeViewHost {
        fn new(web_view: Retained<WKWebView>, root_view: &NSView) -> Self {
            let mtm = MainThreadMarker::new()
                .expect("Hydrolysis hybrid composition must run on the AppKit main thread");
            let container = NativeViewContainer::new(mtm);
            container.setWantsLayer(true);
            container
                .layer()
                .expect("Hydrolysis native WebView container must have a Core Animation layer")
                .setMasksToBounds(true);
            container.addSubview(&web_view);
            root_view.addSubview(&container);
            Self {
                web_view,
                container,
                rounded_clip_views: Vec::new(),
            }
        }

        fn set_rounded_clip_count(&mut self, count: usize) {
            if self.rounded_clip_views.len() == count {
                return;
            }
            self.web_view.removeFromSuperview();
            for clip_view in self.rounded_clip_views.drain(..) {
                clip_view.removeFromSuperview();
            }

            let mtm = MainThreadMarker::new()
                .expect("Hydrolysis hybrid composition must run on the AppKit main thread");
            for _ in 0..count {
                let clip_view = NSView::new(mtm);
                clip_view.setWantsLayer(true);
                clip_view
                    .layer()
                    .expect("Hydrolysis rounded clip view must have a Core Animation layer")
                    .setMasksToBounds(true);
                self.rounded_clip_views.push(clip_view);
            }

            let mut parent: &NSView = &self.container;
            for clip_view in &self.rounded_clip_views {
                parent.addSubview(clip_view);
                parent = clip_view;
            }
            parent.addSubview(&self.web_view);
        }
    }

    #[cfg(hydrolysis_macos_system_webview)]
    #[derive(Clone, Copy)]
    struct MacRoundedClip {
        rect: vello::kurbo::Rect,
        corner_width: f64,
        corner_height: f64,
    }

    #[cfg(hydrolysis_macos_system_webview)]
    fn assert_axis_aligned_positive(transform: vello::kurbo::Affine, operation: &str) -> [f64; 6] {
        let coefficients = transform.as_coeffs();
        let epsilon = f64::EPSILON * 64.0;
        assert!(
            coefficients[1].abs() <= epsilon && coefficients[2].abs() <= epsilon,
            "Hydrolysis native WebView {operation} requires an axis-aligned transform"
        );
        assert!(
            coefficients[0].is_finite()
                && coefficients[3].is_finite()
                && coefficients[0] > 0.0
                && coefficients[3] > 0.0,
            "Hydrolysis native WebView {operation} requires positive finite axis scales"
        );
        coefficients
    }

    #[cfg(hydrolysis_macos_system_webview)]
    fn appkit_root_rect(
        physical_rect: vello::kurbo::Rect,
        logical_height: f64,
        scale_factor: f64,
        flipped: bool,
    ) -> NSRect {
        let x = physical_rect.x0 / scale_factor;
        let y_from_top = physical_rect.y0 / scale_factor;
        let width = physical_rect.width() / scale_factor;
        let height = physical_rect.height() / scale_factor;
        let y = if flipped {
            y_from_top
        } else {
            logical_height - y_from_top - height
        };
        NSRect::new(NSPoint::new(x, y), NSSize::new(width, height))
    }

    #[cfg(hydrolysis_macos_system_webview)]
    struct MacHybridCompositor {
        gpu: WinitGpuContext,
        native_views: HashMap<usize, MacNativeViewHost>,
        overlays: Vec<MacOverlaySurface>,
    }

    #[cfg(hydrolysis_macos_system_webview)]
    impl core::fmt::Debug for MacHybridCompositor {
        fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            formatter
                .debug_struct("MacHybridCompositor")
                .field("native_view_count", &self.native_views.len())
                .field("overlay_count", &self.overlays.len())
                .finish_non_exhaustive()
        }
    }

    #[cfg(hydrolysis_macos_system_webview)]
    impl MacHybridCompositor {
        fn new(gpu: WinitGpuContext) -> Self {
            Self {
                gpu,
                native_views: HashMap::new(),
                overlays: Vec::new(),
            }
        }

        fn root_view(window: &NativeWindow) -> &NSView {
            let handle = window
                .window_handle()
                .expect("Hydrolysis macOS window must expose an AppKit handle");
            let RawWindowHandle::AppKit(appkit) = handle.as_raw() else {
                panic!("Hydrolysis macOS window returned a non-AppKit handle");
            };
            // SAFETY: winit hands out the window's live `NSView` pointer, and the
            // borrow does not outlive the window handle it came from.
            unsafe { appkit.ns_view.cast::<NSView>().as_ref() }
        }

        fn sync(
            &mut self,
            window: &NativeWindow,
            native_views: &[crate::renderer::NativeViewLayer],
            physical_width: u32,
            physical_height: u32,
            scale_factor: f64,
        ) {
            assert!(
                scale_factor.is_finite() && scale_factor > 0.0,
                "Hydrolysis hybrid composition received invalid scale factor {scale_factor}"
            );
            let root_view = Self::root_view(window);
            root_view.setWantsLayer(true);
            let root_layer = root_view
                .layer()
                .expect("Hydrolysis macOS root view must have a Core Animation layer");
            let logical_height = f64::from(physical_height) / scale_factor;
            let mut active = HashSet::new();

            for (index, placement) in native_views.iter().enumerate() {
                let id = Retained::as_ptr(&placement.view) as usize;
                active.insert(id);
                let coefficients = placement.transform.as_coeffs();
                let epsilon = f64::EPSILON * 64.0;
                assert!(
                    coefficients[1].abs() <= epsilon && coefficients[2].abs() <= epsilon,
                    "Hydrolysis native WebView currently requires an axis-aligned transform"
                );
                assert!(
                    coefficients[0].is_finite()
                        && coefficients[3].is_finite()
                        && coefficients[0] > 0.0
                        && coefficients[3] > 0.0,
                    "Hydrolysis native WebView requires positive finite axis scales"
                );
                let transformed = placement.transform.transform_rect_bbox(placement.bounds);
                let mut opacity = 1.0f32;
                let mut visible = transformed;
                let mut rounded_clips = Vec::new();
                for active_layer in &placement.active_layers {
                    assert!(
                        active_layer.alpha.is_finite() && (0.0..=1.0).contains(&active_layer.alpha),
                        "Hydrolysis native WebView received invalid layer opacity {}",
                        active_layer.alpha
                    );
                    opacity *= active_layer.alpha;
                    match &active_layer.shape {
                        crate::renderer::LayerShape::Rect(rect) => {
                            assert_axis_aligned_positive(
                                active_layer.transform,
                                "rectangular clipping",
                            );
                            let clip = active_layer.transform.transform_rect_bbox(*rect);
                            visible = visible.intersect(clip);
                        }
                        crate::renderer::LayerShape::RoundedRect {
                            rect,
                            corner_width,
                            corner_height,
                            ..
                        } => {
                            let clip_transform = active_layer.transform;
                            let clip_coefficients =
                                assert_axis_aligned_positive(clip_transform, "rounded clipping");
                            let clip = clip_transform.transform_rect_bbox(*rect);
                            visible = visible.intersect(clip);
                            rounded_clips.push(MacRoundedClip {
                                rect: clip,
                                corner_width: corner_width * clip_coefficients[0],
                                corner_height: corner_height * clip_coefficients[3],
                            });
                        }
                        crate::renderer::LayerShape::Path(_) => {
                            panic!(
                                "Hydrolysis native WebView does not support non-rectangular path masks"
                            )
                        }
                    }
                }
                let host = self
                    .native_views
                    .entry(id)
                    .or_insert_with(|| MacNativeViewHost::new(placement.view.clone(), root_view));
                host.set_rounded_clip_count(rounded_clips.len());

                let container_frame =
                    appkit_root_rect(visible, logical_height, scale_factor, root_view.isFlipped());
                let web_view_frame = appkit_root_rect(
                    transformed,
                    logical_height,
                    scale_factor,
                    root_view.isFlipped(),
                );
                host.container.setFrame(container_frame);
                host.container
                    .setHidden(visible.is_zero_area() || opacity == 0.0);
                // The renderer republishes these every frame in window hit-test
                // space, which is logical points measured from the top-left, so
                // they convert with a scale factor of 1. `hitTest:` is given its
                // point in the root view's space, which is what this produces.
                host.container.set_occluded(
                    placement
                        .occlusion
                        .borrow()
                        .iter()
                        .map(|rect| {
                            appkit_root_rect(*rect, logical_height, 1.0, root_view.isFlipped())
                        })
                        .collect(),
                );
                let local_bounds = NSRect::new(
                    NSPoint::ZERO,
                    NSSize::new(container_frame.size.width, container_frame.size.height),
                );
                let web_view_local_frame = NSRect::new(
                    NSPoint::new(
                        web_view_frame.origin.x - container_frame.origin.x,
                        web_view_frame.origin.y - container_frame.origin.y,
                    ),
                    web_view_frame.size,
                );
                host.web_view.setFrame(web_view_local_frame);
                host.web_view.setWantsLayer(true);

                for (clip_view, rounded_clip) in host.rounded_clip_views.iter().zip(&rounded_clips)
                {
                    clip_view.setFrame(local_bounds);
                    let clip_layer = clip_view
                        .layer()
                        .expect("Hydrolysis rounded clip view must have a Core Animation layer");
                    let clip_root_frame = appkit_root_rect(
                        rounded_clip.rect,
                        logical_height,
                        scale_factor,
                        root_view.isFlipped(),
                    );
                    let clip_local_rect = NSRect::new(
                        NSPoint::new(
                            clip_root_frame.origin.x - container_frame.origin.x,
                            clip_root_frame.origin.y - container_frame.origin.y,
                        ),
                        clip_root_frame.size,
                    );
                    let mask = CAShapeLayer::layer();
                    mask.setFrame(local_bounds);
                    // SAFETY: main-thread Core Graphics call with a by-value rect and
                    // radii; the returned path is owned by this scope.
                    let path = unsafe {
                        CGPath::with_rounded_rect(
                            clip_local_rect,
                            rounded_clip.corner_width / scale_factor,
                            rounded_clip.corner_height / scale_factor,
                            core::ptr::null(),
                        )
                    };
                    mask.setPath(Some(&path));
                    // SAFETY: main-thread message send to layers this window owns;
                    // `mask` is retained by the layer for as long as it is set.
                    unsafe {
                        clip_layer.setMask(Some(&mask));
                    }
                }

                let container_layer = host
                    .container
                    .layer()
                    .expect("Hydrolysis native WebView container must have a Core Animation layer");
                container_layer.setOpacity(opacity);
                container_layer.setZPosition((index * 2 + 1) as f64);
            }

            self.native_views.retain(|id, host| {
                if active.contains(id) {
                    true
                } else {
                    host.container.removeFromSuperview();
                    false
                }
            });

            while self.overlays.len() < native_views.len() {
                let layer = CAMetalLayer::layer();
                layer.setOpaque(false);
                layer.setFramebufferOnly(false);
                root_layer.addSublayer(&layer);
                let surface = WinitSurface::for_core_animation_layer(
                    &layer,
                    &self.gpu,
                    physical_width,
                    physical_height,
                );
                self.overlays.push(MacOverlaySurface { layer, surface });
            }
            while self.overlays.len() > native_views.len() {
                let overlay = self
                    .overlays
                    .pop()
                    .expect("Hydrolysis overlay count changed during removal");
                overlay.layer.removeFromSuperlayer();
            }

            let logical_width = f64::from(physical_width) / scale_factor;
            for (index, overlay) in self.overlays.iter_mut().enumerate() {
                overlay.layer.setFrame(NSRect::new(
                    NSPoint::ZERO,
                    NSSize::new(logical_width, logical_height),
                ));
                overlay.layer.setContentsScale(scale_factor);
                overlay.layer.setDrawableSize(NSSize::new(
                    f64::from(physical_width),
                    f64::from(physical_height),
                ));
                overlay.layer.setZPosition((index * 2 + 2) as f64);
                overlay.surface.resize(physical_width, physical_height);
            }
        }

        fn clear(&mut self) {
            for (_, host) in self.native_views.drain() {
                host.container.removeFromSuperview();
            }
            for overlay in self.overlays.drain(..) {
                overlay.layer.removeFromSuperlayer();
            }
        }

        fn overlay_surface(&mut self, index: usize) -> &mut WinitSurface {
            &mut self
                .overlays
                .get_mut(index)
                .unwrap_or_else(|| {
                    panic!("Hydrolysis requested missing hybrid overlay surface {index}")
                })
                .surface
        }
    }

    #[derive(Debug)]
    pub struct WinitWindow {
        window: Arc<NativeWindow>,
        surface: WinitSurface,
        pending_surface_size: Option<PhysicalSize<u32>>,
        pending_events: Vec<InputEvent>,
        pointer_position: (f32, f32),
        modifiers: Modifiers,
        applied_text_input_state: Option<TextInputState>,
        current_cursor_style: CursorStyle,
        /// Last applied (min, max) content-size limits, so per-frame application
        /// only reaches winit when the effective limits actually change.
        applied_size_limits: Option<(
            Option<waterui_core::layout::Size>,
            Option<waterui_core::layout::Size>,
        )>,
        /// Explicit ProMotion opt-in: declares the 120Hz frame-rate demand to
        /// the window server while redraws are being requested. `None` before
        /// macOS 14.
        #[cfg(target_os = "macos")]
        frame_rate_demand: Option<super::macos_display_link::FrameRateDemandLink>,
        #[cfg(hydrolysis_macos_system_webview)]
        hybrid_compositor: MacHybridCompositor,
    }

    impl WinitWindow {
        pub async fn new(window: Arc<NativeWindow>) -> Self {
            Self::new_with_shared_gpu(window, None).await.0
        }

        pub async fn new_with_shared_gpu(
            window: Arc<NativeWindow>,
            shared_gpu: Option<&WinitGpuContext>,
        ) -> (Self, WinitGpuContext) {
            let (surface, gpu) = WinitSurface::new(window.clone(), shared_gpu).await;
            (
                Self {
                    #[cfg(target_os = "macos")]
                    frame_rate_demand: super::macos_display_link::FrameRateDemandLink::attach(
                        &window,
                    ),
                    #[cfg(hydrolysis_macos_system_webview)]
                    hybrid_compositor: MacHybridCompositor::new(gpu.clone()),
                    window,
                    surface,
                    pending_surface_size: None,
                    pending_events: Vec::new(),
                    pointer_position: (0.0, 0.0),
                    modifiers: Modifiers::default(),
                    applied_text_input_state: None,
                    current_cursor_style: CursorStyle::Arrow,
                    applied_size_limits: None,
                },
                gpu,
            )
        }

        #[must_use]
        pub fn id(&self) -> WindowId {
            self.window.id()
        }

        #[must_use]
        pub fn native_window(&self) -> &NativeWindow {
            self.window.as_ref()
        }

        #[cfg(hydrolysis_macos_system_webview)]
        pub(crate) fn sync_hybrid_composition(
            &mut self,
            native_views: &[crate::renderer::NativeViewLayer],
            physical_width: u32,
            physical_height: u32,
        ) {
            self.hybrid_compositor.sync(
                &self.window,
                native_views,
                physical_width,
                physical_height,
                self.window.scale_factor(),
            );
        }

        #[cfg(hydrolysis_macos_system_webview)]
        pub(crate) fn clear_hybrid_composition(&mut self) {
            self.hybrid_compositor.clear();
        }

        #[cfg(hydrolysis_macos_system_webview)]
        pub(crate) fn hybrid_overlay_surface(&mut self, index: usize) -> &mut dyn SurfaceProvider {
            self.hybrid_compositor.overlay_surface(index)
        }

        pub fn handle_window_event(&mut self, event: &WindowEvent) {
            match event {
                WindowEvent::CloseRequested => {
                    self.pending_events.push(InputEvent::CloseRequested);
                }
                WindowEvent::Resized(size) => {
                    self.pending_surface_size = Some(*size);
                    self.pending_events.push(InputEvent::Resize {
                        width: size.width.max(1),
                        height: size.height.max(1),
                    });
                }
                WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                    assert!(
                        scale_factor.is_finite() && *scale_factor > 0.0,
                        "hydrolysis winit backend received invalid scale factor {scale_factor}"
                    );
                    let size = self.window.inner_size();
                    self.pending_surface_size = Some(size);
                    self.pending_events.push(InputEvent::Resize {
                        width: size.width.max(1),
                        height: size.height.max(1),
                    });
                }
                WindowEvent::Moved(position) => {
                    let logical = position.to_logical::<f64>(self.window.scale_factor());
                    self.pending_events.push(InputEvent::Moved {
                        x: logical.x as f32,
                        y: logical.y as f32,
                    });
                }
                WindowEvent::CursorMoved { position, .. } => {
                    self.pointer_position =
                        map_cursor_position(position, self.window.scale_factor());
                    tracing::trace!(
                        target: "waterui::hydrolysis::input_raw",
                        event = "cursor_moved",
                        x = self.pointer_position.0,
                        y = self.pointer_position.1,
                        "winit raw input event"
                    );
                    self.pending_events.push(InputEvent::PointerMove {
                        id: 0,
                        kind: PointerKind::Mouse,
                        x: self.pointer_position.0,
                        y: self.pointer_position.1,
                    });
                }
                WindowEvent::CursorLeft { .. } => {
                    self.pending_events.push(InputEvent::PointerCancel {
                        id: 0,
                        kind: PointerKind::Mouse,
                    });
                }
                WindowEvent::MouseInput { state, button, .. } => {
                    let mapped_button = map_button(*button);
                    let (x, y) = self.pointer_position;
                    tracing::trace!(
                        target: "waterui::hydrolysis::input_raw",
                        event = "mouse_input",
                        x,
                        y,
                        state = ?state,
                        button = ?mapped_button,
                        "winit raw input event"
                    );
                    match state {
                        ElementState::Pressed => {
                            self.pending_events.push(InputEvent::PointerDown {
                                id: 0,
                                kind: PointerKind::Mouse,
                                x,
                                y,
                                button: mapped_button,
                            });
                        }
                        ElementState::Released => {
                            self.pending_events.push(InputEvent::PointerUp {
                                id: 0,
                                kind: PointerKind::Mouse,
                                x,
                                y,
                                button: mapped_button,
                            });
                        }
                    }
                }
                WindowEvent::Touch(touch) => {
                    let position = map_cursor_position(&touch.location, self.window.scale_factor());
                    self.pointer_position = position;
                    let (x, y) = position;
                    let event = match touch.phase {
                        WinitTouchPhase::Started => InputEvent::PointerDown {
                            id: touch.id,
                            kind: PointerKind::Touch,
                            x,
                            y,
                            button: PointerButton::Primary,
                        },
                        WinitTouchPhase::Moved => InputEvent::PointerMove {
                            id: touch.id,
                            kind: PointerKind::Touch,
                            x,
                            y,
                        },
                        WinitTouchPhase::Ended => InputEvent::PointerUp {
                            id: touch.id,
                            kind: PointerKind::Touch,
                            x,
                            y,
                            button: PointerButton::Primary,
                        },
                        WinitTouchPhase::Cancelled => InputEvent::PointerCancel {
                            id: touch.id,
                            kind: PointerKind::Touch,
                        },
                    };
                    self.pending_events.push(event);
                }
                WindowEvent::MouseWheel { delta, phase, .. } => {
                    let (dx, dy, is_line_delta) =
                        map_scroll_delta(delta, self.window.scale_factor());
                    if is_line_delta {
                        self.pending_events.push(InputEvent::Scroll {
                            x: self.pointer_position.0,
                            y: self.pointer_position.1,
                            dx,
                            dy,
                            is_line_delta,
                        });
                    } else {
                        self.pending_events.push(InputEvent::TrackpadPan {
                            x: self.pointer_position.0,
                            y: self.pointer_position.1,
                            dx,
                            dy,
                            phase: map_touch_phase(*phase),
                        });
                    }
                }
                WindowEvent::PinchGesture { delta, phase, .. } => {
                    self.pending_events.push(InputEvent::Magnification {
                        x: self.pointer_position.0,
                        y: self.pointer_position.1,
                        delta: *delta as f32,
                        phase: map_touch_phase(*phase),
                    });
                }
                WindowEvent::RotationGesture { delta, phase, .. } => {
                    self.pending_events.push(InputEvent::Rotation {
                        x: self.pointer_position.0,
                        y: self.pointer_position.1,
                        delta: *delta,
                        phase: map_touch_phase(*phase),
                    });
                }
                WindowEvent::ModifiersChanged(modifiers) => {
                    self.modifiers = modifiers.state().into();
                    self.pending_events
                        .push(InputEvent::ModifiersChanged(self.modifiers));
                }
                WindowEvent::KeyboardInput { event, .. } => {
                    if event.state == ElementState::Pressed
                        && should_emit_keyboard_text(self.modifiers)
                        && let Some(text) = keyboard_text_payload(event)
                    {
                        tracing::trace!(
                            target: "waterui::hydrolysis::input_raw",
                            event = "keyboard_text",
                            text = text.as_str(),
                            "winit raw input event"
                        );
                        self.pending_events.push(InputEvent::TextInput { text });
                    }
                    tracing::trace!(
                        target: "waterui::hydrolysis::input_raw",
                        event = "keyboard_input",
                        state = ?event.state,
                        logical_key = ?event.logical_key,
                        modifiers = ?self.modifiers,
                        "winit raw input event"
                    );
                    self.pending_events.push(InputEvent::Key {
                        key: map_key_event(event, self.modifiers),
                        logical_key: ui_events_winit::keyboard::from_winit_key(
                            event.logical_key.clone(),
                        ),
                        physical_code: ui_events_winit::keyboard::from_winit_code(
                            event.physical_key,
                        ),
                        repeat: event.repeat,
                        state: match event.state {
                            ElementState::Pressed => KeyState::Pressed,
                            ElementState::Released => KeyState::Released,
                        },
                        modifiers: self.modifiers,
                    });
                }
                WindowEvent::Ime(ime) => match ime {
                    Ime::Preedit(text, caret) => {
                        tracing::trace!(
                            target: "waterui::hydrolysis::input_raw",
                            event = "ime_preedit",
                            text = text.as_str(),
                            "winit raw input event"
                        );
                        self.pending_events.push(InputEvent::ImePreedit {
                            text: text.clone(),
                            // winit reports the pre-edit selection as a byte
                            // range; the caret sits at its start.
                            caret: caret.map(|(start, _)| start),
                        });
                    }
                    Ime::Commit(text) => {
                        tracing::trace!(
                            target: "waterui::hydrolysis::input_raw",
                            event = "ime_commit",
                            text = text.as_str(),
                            "winit raw input event"
                        );
                        self.pending_events
                            .push(InputEvent::ImeCommit { text: text.clone() });
                    }
                    Ime::Disabled => {
                        tracing::trace!(
                            target: "waterui::hydrolysis::input_raw",
                            event = "ime_disabled",
                            "winit raw input event"
                        );
                        self.pending_events.push(InputEvent::ImeDisabled);
                    }
                    Ime::Enabled => {}
                },
                _ => {}
            }
        }
    }

    fn map_cursor_position(position: &PhysicalPosition<f64>, scale_factor: f64) -> (f32, f32) {
        assert!(
            scale_factor.is_finite() && scale_factor > 0.0,
            "hydrolysis winit backend received invalid scale factor {scale_factor}"
        );
        let logical = position.to_logical::<f64>(scale_factor);
        (logical.x as f32, logical.y as f32)
    }

    fn map_scroll_delta(delta: &MouseScrollDelta, scale_factor: f64) -> (f32, f32, bool) {
        assert!(
            scale_factor.is_finite() && scale_factor > 0.0,
            "hydrolysis winit backend received invalid scale factor {scale_factor}"
        );
        match delta {
            MouseScrollDelta::LineDelta(dx, dy) => (*dx, *dy, true),
            MouseScrollDelta::PixelDelta(delta) => {
                let logical = delta.to_logical::<f64>(scale_factor);
                (logical.x as f32, logical.y as f32, false)
            }
        }
    }

    impl PlatformWindow for WinitWindow {
        fn surface(&mut self) -> &mut dyn SurfaceProvider {
            if let Some(size) = self.pending_surface_size.take() {
                self.surface.resize(size.width, size.height);
            }
            &mut self.surface
        }

        fn applies_size_limits(&self) -> bool {
            true
        }

        fn set_size_limits(
            &mut self,
            min: Option<waterui_core::layout::Size>,
            max: Option<waterui_core::layout::Size>,
        ) {
            if self.applied_size_limits == Some((min, max)) {
                return;
            }
            self.window.set_min_inner_size(
                min.map(|size| LogicalSize::new(f64::from(size.width), f64::from(size.height))),
            );
            self.window.set_max_inner_size(
                max.map(|size| LogicalSize::new(f64::from(size.width), f64::from(size.height))),
            );
            self.applied_size_limits = Some((min, max));
        }

        fn apply_properties(&mut self, window: &waterui::window::Window) {
            self.window.set_title(window.display_title().get().as_str());
            self.window.set_resizable(window.resizable);
            self.window.set_decorations(!matches!(
                window.style,
                waterui::window::WindowStyle::Borderless
            ));
            let frame = window.frame.get();
            let target_size = LogicalSize::new(frame.width() as f64, frame.height() as f64);
            let mut target_position = LogicalPosition::new(frame.x() as f64, frame.y() as f64);
            if let Some(monitor) = self.window.current_monitor() {
                let scale_factor = self.window.scale_factor();
                let monitor_position = monitor.position().to_logical::<f64>(scale_factor);
                let monitor_size = monitor.size().to_logical::<f64>(scale_factor);
                let max_x = (monitor_position.x + monitor_size.width - target_size.width)
                    .max(monitor_position.x);
                let max_y = (monitor_position.y + monitor_size.height - target_size.height)
                    .max(monitor_position.y);
                target_position.x = target_position.x.clamp(monitor_position.x, max_x);
                target_position.y = target_position.y.clamp(monitor_position.y, max_y);
            }
            let current_position = self
                .window
                .outer_position()
                .ok()
                .map(|value| value.to_logical::<f64>(self.window.scale_factor()));
            if current_position.is_none_or(|current| {
                (current.x - target_position.x).abs() > 0.5
                    || (current.y - target_position.y).abs() > 0.5
            }) {
                self.window.set_outer_position(target_position);
            }
            let current_size = self
                .window
                .inner_size()
                .to_logical::<f64>(self.window.scale_factor());
            if (current_size.width - target_size.width).abs() > 0.5
                || (current_size.height - target_size.height).abs() > 0.5
            {
                let _ = self.window.request_inner_size(target_size);
            }
            match window.state.get() {
                WindowState::Normal => {
                    self.window.set_minimized(false);
                    self.window.set_fullscreen(None);
                }
                WindowState::Minimized => {
                    self.window.set_minimized(true);
                }
                WindowState::Fullscreen => {
                    self.window
                        .set_fullscreen(Some(Fullscreen::Borderless(None)));
                }
                WindowState::Closed => {
                    self.window.set_visible(false);
                }
            }
        }

        fn drain_events(&mut self) -> Vec<InputEvent> {
            core::mem::take(&mut self.pending_events)
        }

        fn request_redraw(&self) {
            self.window.request_redraw();
            // Hold the ProMotion frame-rate demand while frames are being
            // requested, so animations run at 120Hz on high-refresh panels.
            #[cfg(target_os = "macos")]
            if let Some(demand) = &self.frame_rate_demand {
                demand.hold_demand();
            }
        }

        fn gpu_surface_redraw_handle(&self) -> Option<RedrawHandle> {
            let handle = RedrawHandle::new();
            let window = Arc::clone(&self.window);
            handle.set_waker(Some(Arc::new(move || window.request_redraw())));
            Some(handle)
        }

        fn scale_factor(&self) -> f64 {
            self.window.scale_factor()
        }

        fn refresh_rate_hz(&self) -> Option<f64> {
            self.window
                .current_monitor()
                .and_then(|monitor| monitor.refresh_rate_millihertz())
                .map(|millihertz| f64::from(millihertz) / 1000.0)
        }

        fn sync_text_input_state(&mut self, state: Option<TextInputState>) {
            if self.applied_text_input_state == state {
                return;
            }
            if self.applied_text_input_state.is_some() != state.is_some() {
                self.window.set_ime_allowed(state.is_some());
            }
            self.applied_text_input_state = state;

            let Some(state) = state else {
                return;
            };

            let purpose = match state.purpose {
                TextInputPurpose::Normal => ImePurpose::Normal,
                TextInputPurpose::Password => ImePurpose::Password,
            };
            self.window.set_ime_purpose(purpose);
            let scale_factor = self.window.scale_factor();
            assert!(
                scale_factor.is_finite() && scale_factor > 0.0,
                "hydrolysis winit backend received invalid scale factor {scale_factor}"
            );
            let cursor_origin =
                LogicalPosition::new(state.x, state.y).to_physical::<f64>(scale_factor);
            let cursor_size = LogicalSize::new(state.width.max(1.0), state.height.max(1.0))
                .to_physical::<f64>(scale_factor);
            self.window.set_ime_cursor_area(
                PhysicalPosition::new(
                    cursor_origin.x.round() as i32,
                    cursor_origin.y.round() as i32,
                ),
                PhysicalSize::new(
                    cursor_size.width.ceil() as u32,
                    cursor_size.height.ceil() as u32,
                ),
            );
        }

        fn set_cursor_style(&mut self, style: CursorStyle) {
            if self.current_cursor_style == style {
                return;
            }
            self.current_cursor_style = style;
            self.window
                .set_cursor(WinitCursor::Icon(map_cursor_style(style)));
        }
    }

    impl From<ModifiersState> for Modifiers {
        fn from(value: ModifiersState) -> Self {
            Self {
                shift: value.shift_key(),
                control: value.control_key(),
                alt: value.alt_key(),
                super_key: value.super_key(),
            }
        }
    }

    fn map_touch_phase(phase: WinitTouchPhase) -> TouchPhase {
        match phase {
            WinitTouchPhase::Started => TouchPhase::Started,
            WinitTouchPhase::Moved => TouchPhase::Moved,
            WinitTouchPhase::Ended => TouchPhase::Ended,
            WinitTouchPhase::Cancelled => TouchPhase::Cancelled,
        }
    }

    fn map_button(button: MouseButton) -> PointerButton {
        match button {
            MouseButton::Left => PointerButton::Primary,
            MouseButton::Right => PointerButton::Secondary,
            MouseButton::Middle => PointerButton::Middle,
            MouseButton::Back => PointerButton::Back,
            MouseButton::Forward => PointerButton::Forward,
            MouseButton::Other(value) => PointerButton::Other(value),
        }
    }

    fn map_key(key: &Key) -> KeyCode {
        match key {
            Key::Character(value) => KeyCode::Character(value.to_string()),
            Key::Named(value) => KeyCode::Named(format!("{value:?}")),
            _ => KeyCode::Unidentified,
        }
    }

    fn should_emit_keyboard_text(modifiers: Modifiers) -> bool {
        !(modifiers.control || modifiers.alt || modifiers.super_key)
    }

    fn map_key_event(event: &KeyEvent, modifiers: Modifiers) -> KeyCode {
        if should_emit_keyboard_text(modifiers)
            && keyboard_text_payload(event).is_some()
            && matches!(event.logical_key, Key::Character(_))
        {
            return KeyCode::Unidentified;
        }
        map_key(&event.logical_key)
    }

    fn keyboard_text_payload(event: &KeyEvent) -> Option<String> {
        let text = event.text.as_ref()?;
        if text.is_empty() || text.chars().all(char::is_control) {
            return None;
        }
        Some(text.to_string())
    }

    fn map_cursor_style(style: CursorStyle) -> CursorIcon {
        match style {
            CursorStyle::Arrow => CursorIcon::Default,
            CursorStyle::PointingHand => CursorIcon::Pointer,
            CursorStyle::IBeam => CursorIcon::Text,
            CursorStyle::Crosshair => CursorIcon::Crosshair,
            CursorStyle::OpenHand => CursorIcon::Grab,
            CursorStyle::ClosedHand => CursorIcon::Grabbing,
            CursorStyle::NotAllowed => CursorIcon::NotAllowed,
            CursorStyle::ResizeLeft => CursorIcon::WResize,
            CursorStyle::ResizeRight => CursorIcon::EResize,
            CursorStyle::ResizeUp => CursorIcon::NResize,
            CursorStyle::ResizeDown => CursorIcon::SResize,
            CursorStyle::ResizeLeftRight => CursorIcon::EwResize,
            CursorStyle::ResizeUpDown => CursorIcon::NsResize,
            CursorStyle::Move => CursorIcon::Move,
            CursorStyle::Wait => CursorIcon::Wait,
            CursorStyle::Copy => CursorIcon::Copy,
            _ => panic!("unsupported CursorStyle variant in hydrolysis winit backend"),
        }
    }

    pub use WinitGpuContext as ExportedWinitGpuContext;
    pub use WinitWindow as ExportedWinitWindow;

    #[cfg(test)]
    mod tests {
        use winit::dpi::PhysicalPosition;
        use winit::event::MouseScrollDelta;

        use super::{map_cursor_position, map_scroll_delta, should_emit_keyboard_text};
        use crate::platform::Modifiers;

        #[test]
        fn cursor_position_is_converted_to_logical_coordinates() {
            let (x, y) = map_cursor_position(&PhysicalPosition::new(384.5, 216.25), 2.0);
            assert_eq!(x, 192.25);
            assert_eq!(y, 108.125);
        }

        #[test]
        fn pixel_scroll_delta_is_converted_to_logical_space() {
            let (dx, dy, is_line_delta) = map_scroll_delta(
                &MouseScrollDelta::PixelDelta(PhysicalPosition::new(120.0, -48.5)),
                2.0,
            );
            assert_eq!(dx, 60.0);
            assert_eq!(dy, -24.25);
            assert!(!is_line_delta);
        }

        #[test]
        fn line_scroll_delta_is_preserved() {
            let (dx, dy, is_line_delta) =
                map_scroll_delta(&MouseScrollDelta::LineDelta(-2.0, 3.5), 2.0);
            assert_eq!(dx, -2.0);
            assert_eq!(dy, 3.5);
            assert!(is_line_delta);
        }

        #[test]
        fn command_modified_characters_are_reserved_for_shortcuts() {
            assert!(should_emit_keyboard_text(Modifiers {
                shift: true,
                ..Modifiers::default()
            }));
            assert!(!should_emit_keyboard_text(Modifiers {
                control: true,
                ..Modifiers::default()
            }));
            assert!(!should_emit_keyboard_text(Modifiers {
                super_key: true,
                ..Modifiers::default()
            }));
            assert!(!should_emit_keyboard_text(Modifiers {
                alt: true,
                ..Modifiers::default()
            }));
        }

        #[test]
        fn cursor_position_panics_with_invalid_scale_factor() {
            let result = std::panic::catch_unwind(|| {
                let _ = map_cursor_position(&PhysicalPosition::new(120.0, 80.0), 0.0);
            });
            assert!(result.is_err());
        }
    }
}

#[cfg(all(target_arch = "wasm32", feature = "web"))]
pub use web_impl::ExportedBrowserWindow as BrowserWindow;

#[cfg(feature = "winit")]
pub(crate) use winit_impl::ExportedWinitGpuContext as WinitGpuContext;

#[cfg(feature = "winit")]
pub use winit_impl::ExportedWinitWindow as WinitWindow;