frust-shell-desktop 0.5.2

Desktop shell for Frust: winit window and event loop, input, rendering and the extension seam used by the per-OS desktop shells.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
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
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
//! The winit 0.30 [`ApplicationHandler`] that drives a Frust app in a desktop
//! preview window.
//!
//! Ownership mirrors the shared platform bootstrap: the shell owns
//! the shared [`TextContext`], the [`RenderRoot`], the application
//! `State`/`build`, and a [`FrameExecutor`](crate::render::FrameExecutor).
//! The executor owns the render stack — either on this (the UI) thread (the
//! single-thread fallback) or on a dedicated render thread (the
//! split, chosen by the `FRUST_NO_RENDER_THREAD` kill switch — see
//! [`crate::render`]). Each on-demand frame runs the UI passes in Masonry order
//! (the v0 subset) on this thread — rebuild → layout → paint — then hands the
//! finished scene to the executor for encode → acquire → submit.
//!
//! The host clipboard is the other thread this file owns. A lazily spawned
//! `frust-clipboard` worker ([`ClipboardWorker`]) holds the process's one
//! `arboard::Clipboard` and runs every read and write on its own thread,
//! because a clipboard read blocks for as long as the process that owns the
//! selection takes to answer — measured at 24 s on X11 against a stopped
//! owner. A successful read returns as a [`ShellUserEvent::ClipboardPaste`]
//! user event and becomes one top-level `EditCommand::Paste` dispatch in
//! `user_event`.
//!
//! It also owns an `accesskit_winit` [`Adapter`]: created in
//! `resumed` with the same [`EventLoopProxy`](winit::event_loop::EventLoopProxy)
//! the [`ShellUserEvent`] wake mechanism already uses (extended with an
//! [`ShellUserEvent::Accessibility`] variant), forwarded every
//! [`WindowEvent`] via [`Adapter::process_event`] (its documented contract:
//! *"This must be called whenever a new window event is received"*), and fed a
//! fresh [`accesskit::TreeUpdate`](frust_core::accesskit::TreeUpdate) —
//! built from [`RenderRoot::semantics`]/[`RenderRoot::semantics_if_changed`] —
//! post-layout in `RedrawRequested`. Platform `ActionRequest`s arrive back
//! through the same proxy and route into
//! [`RenderRoot::perform_accessibility_action`]. Adapter creation cannot panic
//! without a real platform a11y bus present: `accesskit_winit`'s unix backend
//! only lazily connects to AT-SPI/D-Bus and stays inert (`update_if_active`
//! becomes a no-op) until an assistive-technology client actually activates it
//! — safe to construct in a headless/no-AT-client CI environment.

use std::any::Any;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};

use accesskit_winit::{
    Adapter, Event as AccessibilityEvent, WindowEvent as AccessibilityWindowEvent,
};
use anyhow::Result;
use frust_core::FrameTime;
use frust_core::RenderRoot;
use frust_core::SemanticsUpdate;
use frust_core::accesskit::{Tree, TreeId, TreeUpdate};
use frust_core::event::{
    CursorIcon, EditCommand, EventOutcome, ImeContentType, ImeEvent, InputEvent, Key, KeyEvent,
    Modifiers, NamedKey, PointerButton, PointerEvent, PointerPhase, ScaleEvent, ScalePhase,
    ScrollDelta,
};
use frust_core::input::WHEEL_LINE_PX;
use frust_core::insets::WindowInsets;
use frust_core::view::View;
use frust_reactive::{FrameWaker, ReactiveRuntime, TrackedScope, provide_context};
use frust_scene::{Scene, SceneBuilder};
use frust_shell_common::font_registry::FontRegistryWatcher;
use frust_shell_common::perf::UiSpans;
use frust_shell_common::{
    SurfaceSize, ThemeOverrideWatcher, WindowMetricsPublisher, default_theme,
    effective_brightness_for_platform_change, render_thread_enabled,
};
use frust_text::TextContext;
use frust_theme::{Brightness, Theme};
use kurbo::{Affine, Point, Size};
use winit::application::ApplicationHandler;
use winit::dpi::{LogicalPosition, LogicalSize};
use winit::event::{ElementState, Ime, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::keyboard::{Key as WinitKey, ModifiersState, NamedKey as WinitNamedKey};
use winit::window::{
    CursorIcon as WinitCursorIcon, ImePurpose, Theme as WinitTheme, Window, WindowAttributes,
    WindowId,
};

use crate::config::DesktopConfig;
use crate::extensions::{CloseAction, DesktopExtensions, NoExtensions};
use crate::paced_wake::{ControlFlowIntent, next_paced_wake, paced_wake_action};
use crate::platform_view::DesktopPlatformViews;
use crate::render::FrameExecutor;

/// Initial preview-window size, in logical pixels.
const INITIAL_SIZE: LogicalSize<u32> = LogicalSize::new(800, 600);

/// The env/compile-time var overriding [`INITIAL_SIZE`]: `<width>x<height>` in
/// logical pixels (e.g. `2560x1440`). Measurement knob — see
/// [`parse_window_size`] and [`window_size_config`]. Same
/// compile-time-`option_env!`-or-runtime-`std::env::var` shape as
/// `FRUST_TRACE`/`FRUST_NO_RENDER_THREAD`, runtime winning: it exists so a
/// large-surface device/desktop gate (a macOS 5K display, say) can be measured
/// without an accessibility-scripted window move, which loses the window.
const WINDOW_SIZE_VAR: &str = "FRUST_WINDOW_SIZE";

/// The env/compile-time var maximizing the preview window at creation
/// (`1`/`true`, case-insensitive; every other value, including unset, leaves
/// it un-maximized). Measurement knob, same shape as [`WINDOW_SIZE_VAR`]. When
/// both knobs are set, [`WINDOW_SIZE_VAR`] is still applied but maximizing
/// wins visually — the OS ignores a requested inner size for a window it
/// maximizes at creation.
const WINDOW_MAXIMIZED_VAR: &str = "FRUST_WINDOW_MAXIMIZED";

/// Where an effective [`WINDOW_SIZE_VAR`]/[`WINDOW_MAXIMIZED_VAR`] value came
/// from, for the one-line-once log [`window_size_config`] emits — the same
/// "which build ran" evidence `frust-render`'s own `frust-render tier=engine
/// …`/`frust-perf render-path …`/`frust-render surface-caps: …` log lines
/// (`frust-render`'s `renderer`/`context` modules) carry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum WindowKnobSource {
    /// Neither knob's env var carried a non-empty value — the byte-identical
    /// default path (800x600, not maximized).
    Default,
    /// A non-empty value came from the compile-time `option_env!` half (baked
    /// in by `frust build --define`).
    Define,
    /// A non-empty value came from the runtime process environment — wins
    /// over a compile-time define when both are set.
    Env,
}

impl std::fmt::Display for WindowKnobSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            WindowKnobSource::Default => "default",
            WindowKnobSource::Define => "define",
            WindowKnobSource::Env => "env",
        })
    }
}

/// Resolves one `FRUST_*` string-valued knob's raw value plus which half
/// supplied it, checking both the compile-time (`option_env!`) and runtime
/// (`std::env::var`) halves like `frust-render::context::env_str` — **runtime
/// wins**: a non-empty runtime value is returned even when a compile-time
/// value is also set; an empty (`""`) runtime value is treated as unset and
/// falls through to the compile-time half. Not shared with `frust-render`'s
/// copy (that one is crate-private to `frust-render`) — this crate's write
/// scope is `app_handler.rs` alone, so the shape is duplicated rather than
/// promoted to a shared crate.
fn resolved_window_knob(
    compile_time: Option<&'static str>,
    runtime: Option<String>,
) -> (Option<String>, WindowKnobSource) {
    fn non_empty(value: Option<String>) -> Option<String> {
        value.filter(|v| !v.is_empty())
    }
    if let Some(value) = non_empty(runtime) {
        (Some(value), WindowKnobSource::Env)
    } else if let Some(value) = non_empty(compile_time.map(str::to_string)) {
        (Some(value), WindowKnobSource::Define)
    } else {
        (None, WindowKnobSource::Default)
    }
}

/// Parses one `<width>x<height>` dimension: strictly `^[0-9]+$`, and at least
/// 1 (a 0-sized axis is not a window).
fn parse_window_dimension(raw: &str) -> Option<u32> {
    if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    raw.parse::<u32>().ok().filter(|value| *value >= 1)
}

/// Parses a raw [`WINDOW_SIZE_VAR`] value (already resolved by
/// [`resolved_window_knob`]) into a logical window size.
///
/// Strict: `^[0-9]+x[0-9]+$`, both components at least 1 — no surrounding
/// whitespace inside either component, no sign, no decimal point, exactly one
/// `x` separator (surrounding whitespace on the whole value is trimmed first,
/// matching every other `FRUST_*` string knob's parser). An unset or empty
/// value falls back to [`INITIAL_SIZE`] silently — that is simply "the knob
/// wasn't touched". Any other value (missing/extra `x`, non-digit characters,
/// a zero component, a component too large for `u32`) also falls back to
/// `INITIAL_SIZE`, but logs one `log::warn!` naming the offending value, since
/// that case is far more likely a typo than a deliberate default.
fn parse_window_size(raw: Option<&str>) -> LogicalSize<u32> {
    let Some(trimmed) = raw.map(str::trim).filter(|v| !v.is_empty()) else {
        return INITIAL_SIZE;
    };
    if let Some((width_raw, height_raw)) = trimmed.split_once('x')
        && let (Some(width), Some(height)) = (
            parse_window_dimension(width_raw),
            parse_window_dimension(height_raw),
        )
    {
        return LogicalSize::new(width, height);
    }
    log::warn!(
        "frust-shell-desktop: invalid {WINDOW_SIZE_VAR} value {trimmed:?}, expected \
         <width>x<height> in logical pixels (e.g. 1280x720) with both at least 1, falling back \
         to {}x{}",
        INITIAL_SIZE.width,
        INITIAL_SIZE.height
    );
    INITIAL_SIZE
}

/// Parses a raw [`WINDOW_MAXIMIZED_VAR`] value (already resolved by
/// [`resolved_window_knob`]) into whether the preview window should be
/// created maximized.
///
/// `1` and `true` (case-insensitive, surrounding whitespace trimmed) enable
/// it; every other value, including unset, leaves the window un-maximized.
/// Deliberately no warn-on-unrecognised arm: unlike
/// [`parse_window_size`]'s strict grammar this is a plain flag, and the
/// effective value is logged either way by [`window_size_config`].
fn parse_window_maximized(raw: Option<&str>) -> bool {
    raw.map(str::trim)
        .is_some_and(|value| matches!(value.to_ascii_lowercase().as_str(), "1" | "true"))
}

/// The process-wide effective preview-window size/maximized configuration,
/// resolved once from [`WINDOW_SIZE_VAR`]/[`WINDOW_MAXIMIZED_VAR`]
/// (compile-time-or-runtime, see [`resolved_window_knob`]) and cached — a
/// knob change requires a fresh process, matching every other `FRUST_*` knob.
/// Logs the effective choice exactly once — a captured log proves which
/// configuration a run used, the same evidentiary role `frust-render`'s own
/// `tier=engine`/render-path/surface-caps log lines carry.
fn window_size_config() -> (LogicalSize<u32>, bool, WindowKnobSource) {
    static CONFIG: OnceLock<(LogicalSize<u32>, bool, WindowKnobSource)> = OnceLock::new();
    *CONFIG.get_or_init(|| {
        let (size_raw, size_source) = resolved_window_knob(
            option_env!("FRUST_WINDOW_SIZE"),
            std::env::var(WINDOW_SIZE_VAR).ok(),
        );
        let (maximized_raw, maximized_source) = resolved_window_knob(
            option_env!("FRUST_WINDOW_MAXIMIZED"),
            std::env::var(WINDOW_MAXIMIZED_VAR).ok(),
        );
        let size = parse_window_size(size_raw.as_deref());
        let maximized = parse_window_maximized(maximized_raw.as_deref());
        // Whichever of the two independent knobs was set from the
        // higher-precedence half decides the reported source (`Env` >
        // `Define` > `Default`) — a single log line describes the whole
        // window configuration, not each knob separately.
        let source = size_source.max(maximized_source);
        log::info!(
            "frust-shell-desktop window size={}x{} logical maximized={maximized} source={source}",
            size.width,
            size.height
        );
        (size, maximized, source)
    })
}

/// User events posted to the desktop event loop from off the UI thread.
///
/// Winit's [`ControlFlow::Wait`] idles the loop until an event arrives, so a
/// signal write on a background thread would otherwise never surface. The
/// [`FrameWaker`] installed in [`run_desktop`] fires on the clean→dirty edge of
/// a tracked signal and sends one of these through the loop's `EventLoopProxy`,
/// waking the loop to pump local tasks and schedule a redraw. Kept an enum (not
/// a unit type) so future user-driven events can be added without changing the
/// loop's user-event type.
///
/// The proxy is how *every* off-UI-thread answer re-enters this shell, not
/// just a wake: the render thread reports back through it, and so does the
/// clipboard worker thread, whose [`ShellUserEvent::ClipboardPaste`] carries
/// the text of a finished read (see [`ClipboardWorker`]).
///
/// [`ShellUserEvent::Accessibility`] is the second producer of
/// this same proxy: `accesskit_winit`'s [`Adapter::with_event_loop_proxy`]
/// requires its `T: From<accesskit_winit::Event>` bound, satisfied below. Its
/// payload (an [`accesskit::ActionRequest`](frust_core::accesskit::ActionRequest)
/// wrapper) is neither `Copy` nor `PartialEq`, so this enum can no longer
/// derive those either — every existing use already matched/constructed it by
/// value, so nothing downstream needed to change.
///
/// `pub` only so [`DesktopEventLoopBuilder`](crate::DesktopEventLoopBuilder)
/// — the type the builder-stage extension hook takes — can name the loop's
/// user-event type; `#[doc(hidden)]` keeps it out of published docs, the same
/// escape the `paced_wake` module uses for its test-only visibility.
#[doc(hidden)]
#[derive(Debug)]
pub enum ShellUserEvent {
    /// One or more tracked signals became dirty since the last frame — pump the
    /// UI-thread local task queue and request a redraw.
    SignalsDirty,
    /// An `accesskit_winit` adapter event: an initial-tree pull, a platform
    /// accessibility action request, or a deactivation notice — see
    /// [`ShellHandler::handle_accessibility_event`].
    Accessibility(AccessibilityEvent),
    /// The render thread (split path) needs another frame — a stale-swapchain
    /// reconfigure consumed the last handed-off scene, so the UI thread must
    /// repaint and re-hand one off. Routed through the proxy (rather than a
    /// direct `request_redraw` from the render thread) so winit's dirty-driven
    /// `ControlFlow::Wait` model is preserved.
    RenderNeedsRedraw,
    /// The render thread lost the surface and needs it re-created (split path).
    /// Re-creation reads the window handle, which winit only yields on the main
    /// thread, so the render thread routes the request here and the UI thread
    /// re-runs the detached surface creation and hands a fresh one across, then
    /// requests a repaint.
    RenderRecreateSurface,
    /// The render thread hit an unrecoverable init error (surface creation
    /// failed). Surfaced back so `run_desktop` returns it as `Err`, mirroring the
    /// inline path's fatal handling.
    RenderFatal(anyhow::Error),
    /// The clipboard worker thread read the host clipboard and got text (see
    /// [`ClipboardWorker`]): the UI thread turns it into exactly one
    /// top-level `EditCommand::Paste` dispatch. A read that failed — for any
    /// reason, including the host's misleading "the clipboard is empty" —
    /// posts nothing at all, so this variant is only ever a successful answer.
    ClipboardPaste(PasteText),
    /// The devtools service queued a request that needs UI-thread state (a
    /// widget-tree snapshot, an injected event). This shell idles under
    /// [`ControlFlow::Wait`], so the queue is drained on the loop turn this
    /// event produces — the desktop half of `frust_shell_common::devtools`'s
    /// UI-thread hop.
    #[cfg(feature = "devtools")]
    Devtools,
}

impl From<AccessibilityEvent> for ShellUserEvent {
    fn from(event: AccessibilityEvent) -> Self {
        ShellUserEvent::Accessibility(event)
    }
}

/// Text one clipboard read produced, on its way from the clipboard worker
/// thread to the UI thread inside [`ShellUserEvent::ClipboardPaste`].
///
/// A newtype for exactly one reason: its [`Debug`] **redacts** the text.
/// Clipboard contents are user data — a password manager's paste is the
/// motivating case — and this payload rides an enum anything logging a loop
/// turn formats wholesale, so the redaction has to live on the payload itself.
/// Mirrors [`EditCommand`]'s own redacting `Debug` in `frust-core`.
///
/// `pub` (and re-exported `#[doc(hidden)]` from the crate root) only because it
/// appears in [`ShellUserEvent`]'s variant — never part of this shell's
/// intended API.
#[doc(hidden)]
pub struct PasteText(String);

impl PasteText {
    /// Unwrap the text for the [`EditCommand::Paste`] dispatch that answers the
    /// request — its single consumer, on the UI thread.
    fn into_string(self) -> String {
        self.0
    }
}

impl std::fmt::Debug for PasteText {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("PasteText").field(&"<redacted>").finish()
    }
}

/// How long [`ShellHandler::shutdown_clipboard`] waits for the clipboard worker
/// to let go of the host clipboard before the process moves on.
///
/// Bounded deliberately. The wait exists so a copy made just before the app
/// quits survives it (see [`spawn_clipboard_worker`]), and `arboard`'s own
/// handover to a clipboard manager caps itself at 100 ms inside that drop, so
/// half a second is ample for the healthy case. It is deliberately *not* enough
/// to sit out a hung read the shutdown request is queued behind: a host whose
/// selection owner is not answering has nothing to hand over anyway, and
/// quitting must not wait on it. Runs after `run_app` has returned, with no
/// window and no event loop left to stall.
const CLIPBOARD_SHUTDOWN_WAIT: Duration = Duration::from_millis(500);

/// One unit of work for the clipboard worker thread — see [`ClipboardWorker`].
enum ClipboardRequest {
    /// Read the host clipboard. Text answers the UI thread with
    /// [`ShellUserEvent::ClipboardPaste`]; every failure answers nothing.
    Read,
    /// Write this text to the host clipboard (a copy or a cut).
    Write(String),
    /// Stop the loop, drop the `arboard::Clipboard`, then acknowledge — the
    /// teardown handshake [`ShellHandler::shutdown_clipboard`] drives once the
    /// event loop has returned.
    Shutdown,
}

/// The clipboard failure kinds this shell warns about — one [`log::warn!`] per
/// kind per run (see [`ClipboardWarnings`]). A missing or hung clipboard
/// repeats on every copy and every paste, and a warning per keystroke would be
/// its own defect.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClipboardFailure {
    /// `arboard::Clipboard::new()` failed: no reachable clipboard mechanism at
    /// all (a headless Linux session with neither X11 nor Wayland, say).
    Unavailable,
    /// The read came back `arboard::Error::ContentNotAvailable`, whose message
    /// — *"The clipboard contents were not available in the requested format or
    /// the clipboard is empty"* — is not trustworthy: `arboard` returns it both
    /// for a genuinely empty clipboard and for a selection owner that never
    /// answered, which is the X11 case this worker exists for. There its
    /// `get_text` reaches this error only after exhausting six candidate
    /// target atoms, each with its own 4 s window — a worst-case total, not
    /// six independent recovery chances, since a late answer is rescued only
    /// when it lands inside the window currently being tried (see
    /// [`ClipboardWorker`]'s `# Why a thread at all` for the measured
    /// evidence). The two causes are indistinguishable from here, so the
    /// warning says so rather than repeating the host's claim.
    Unanswered,
    /// The read failed some other way.
    ReadFailed,
    /// The write failed: the copy or cut is lost.
    WriteFailed,
}

/// A clipboard operation's failure: the [`ClipboardFailure`] kind the warn-once
/// bookkeeping keys on, plus the host's own message.
struct ClipboardError {
    kind: ClipboardFailure,
    detail: String,
}

impl ClipboardError {
    fn new(kind: ClipboardFailure, detail: impl Into<String>) -> Self {
        Self {
            kind,
            detail: detail.into(),
        }
    }
}

/// Which [`ClipboardFailure`] kinds have already been logged this run, owned by
/// the worker thread's loop.
#[derive(Default)]
struct ClipboardWarnings {
    unavailable: bool,
    unanswered: bool,
    read_failed: bool,
    write_failed: bool,
}

impl ClipboardWarnings {
    /// `true` the first time `kind` is seen and `false` after, so the caller
    /// logs exactly one line per kind. Kinds are independent: a host that can
    /// neither read nor write still says both things once.
    fn first_time(&mut self, kind: ClipboardFailure) -> bool {
        let seen = match kind {
            ClipboardFailure::Unavailable => &mut self.unavailable,
            ClipboardFailure::Unanswered => &mut self.unanswered,
            ClipboardFailure::ReadFailed => &mut self.read_failed,
            ClipboardFailure::WriteFailed => &mut self.write_failed,
        };
        let first = !*seen;
        *seen = true;
        first
    }
}

/// The worker thread's view of the host clipboard.
///
/// A seam, not an abstraction tier: [`ArboardClipboard`] is the only shipped
/// implementation and nothing outside this file sees this trait. It exists so
/// [`clipboard_loop`] — plumbing that otherwise needs a window, an event loop
/// and a real desktop session to reach — can be unit-tested against a fake.
trait ClipboardAccess {
    /// Read the clipboard's text. Blocking by nature: on X11 this is the call
    /// measured at 24 005 ms against a stopped selection owner.
    fn read(&mut self) -> Result<String, ClipboardError>;
    /// Write `text` to the clipboard.
    fn write(&mut self, text: &str) -> Result<(), ClipboardError>;
}

/// **The** host clipboard instance: one `arboard::Clipboard`, created lazily on
/// the clipboard worker thread's first request and owned by that thread — only
/// ever that thread — until the worker stops.
///
/// # The ownership rule
///
/// One instance, one owner, the process's lifetime. On X11 (and Wayland) the
/// clipboard's content is served *live* by whichever process claimed the
/// selection, so the instance that claimed it has to stay alive and reachable
/// or the copy vanishes the moment it drops, on any desktop with no clipboard
/// manager running to adopt it. That rules out constructing one per call (the
/// shape `plugins/clipboard/src/desktop.rs` uses — correct there, since a
/// plugin has no "for as long as the app runs" owner to hold one), and it rules
/// out sharing one behind a lock, which would put the UI thread straight back
/// into the waiting business a hung read creates. So **both** operations run
/// here, serialised on this one thread, and the UI thread reaches them only by
/// posting a [`ClipboardRequest`].
///
/// That serialisation has one visible consequence, accepted deliberately: a
/// copy issued while a read is hung waits behind it instead of overtaking it.
/// It is delayed, never lost. The alternative — a second instance on the UI
/// thread for writes — would mean two `Clipboard` instances touching one host
/// clipboard concurrently, which `plugins/clipboard`'s own notes record as
/// having crashed `arboard`'s macOS `NSPasteboard` backend. The single queue
/// also keeps a copy and a paste issued after it in order, which two threads
/// racing one host clipboard would not.
///
/// Creating the instance *on* the worker rather than moving one across also
/// keeps every platform backend on the thread that will use it, which is the
/// pattern `NSPasteboard` is safe under: never shared, never concurrent.
#[derive(Default)]
struct ArboardClipboard {
    clipboard: Option<arboard::Clipboard>,
}

impl ArboardClipboard {
    /// The instance, created on first use.
    ///
    /// A `new()` failure is reported as [`ClipboardFailure::Unavailable`] and
    /// retried on the next request rather than latched forever: the attempt
    /// costs the *worker* thread a failed connection, never the event loop, and
    /// a session that gains a clipboard mid-run (an X server reappearing behind
    /// a reconnecting remote display) then simply starts working. The warning
    /// is still emitted exactly once, by [`ClipboardWarnings`].
    fn get(&mut self) -> Result<&mut arboard::Clipboard, ClipboardError> {
        if self.clipboard.is_none() {
            self.clipboard = Some(arboard::Clipboard::new().map_err(|err| {
                ClipboardError::new(
                    ClipboardFailure::Unavailable,
                    format!("the host clipboard is unavailable ({err})"),
                )
            })?);
        }
        // Just filled above when it was empty, so this is `Some`; spelled
        // `ok_or_else` rather than `expect` because nothing on a clipboard path
        // may panic.
        self.clipboard.as_mut().ok_or_else(|| {
            ClipboardError::new(
                ClipboardFailure::Unavailable,
                "the host clipboard is unavailable",
            )
        })
    }
}

impl ClipboardAccess for ArboardClipboard {
    fn read(&mut self) -> Result<String, ClipboardError> {
        match self.get()?.get_text() {
            Ok(text) => Ok(text),
            // The misleading one — see `ClipboardFailure::Unanswered`.
            Err(arboard::Error::ContentNotAvailable) => Err(ClipboardError::new(
                ClipboardFailure::Unanswered,
                "the host reported no text in the requested format",
            )),
            Err(err) => Err(ClipboardError::new(
                ClipboardFailure::ReadFailed,
                err.to_string(),
            )),
        }
    }

    fn write(&mut self, text: &str) -> Result<(), ClipboardError> {
        self.get()?
            .set_text(text)
            .map_err(|err| ClipboardError::new(ClipboardFailure::WriteFailed, err.to_string()))
    }
}

/// The one-per-kind warning line for `err`. `elapsed` is how long the host took
/// to fail — the number that makes a hung selection owner visible in a log,
/// where the measured X11 case spends ~24 000 ms before failing.
fn clipboard_warning(err: &ClipboardError, elapsed: Duration) -> String {
    let ms = elapsed.as_millis();
    match err.kind {
        ClipboardFailure::Unavailable => format!(
            "frust-shell-desktop: {}; copy/cut/paste no-op until it comes back \
             (logged once)",
            err.detail
        ),
        ClipboardFailure::Unanswered => format!(
            "frust-shell-desktop: the host clipboard produced no text for a paste after {ms} ms \
             ({}); the host reports the same error whether the clipboard is empty or its \
             selection owner never answered, so the paste is dropped rather than guessed at \
             (logged once)",
            err.detail
        ),
        ClipboardFailure::ReadFailed => format!(
            "frust-shell-desktop: failed to read the host clipboard for a paste after {ms} ms \
             ({}); the paste is dropped (logged once)",
            err.detail
        ),
        ClipboardFailure::WriteFailed => format!(
            "frust-shell-desktop: failed to write the host clipboard ({}); the copy/cut is lost \
             (logged once)",
            err.detail
        ),
    }
}

/// The clipboard worker thread's whole loop: take one [`ClipboardRequest`] at a
/// time, run it against the host clipboard, and answer a successful read by
/// handing `answer` the [`ShellUserEvent::ClipboardPaste`] to post back into
/// the event loop.
///
/// Every failure is warned once per [`ClipboardFailure`] kind and dispatches
/// **nothing** — never a panic, never an `unwrap`, and in particular never a
/// synthesized empty paste, which would silently clear a selection the user
/// meant to replace.
///
/// Returns when a [`ClipboardRequest::Shutdown`] arrives or the request channel
/// closes (the `ShellHandler` was dropped without the handshake).
///
/// Generic over its collaborators purely so it is testable: the shipped call
/// site passes [`ArboardClipboard`] and a closure posting through the
/// [`EventLoopProxy`](winit::event_loop::EventLoopProxy), while the unit tests
/// below pass a fake clipboard and a collecting closure — which is as far into
/// this plumbing as anything can reach without a window.
/// Re-opens the paste coalescing gate ([`ClipboardWorker::read_in_flight`]) as
/// it drops.
///
/// The gate closes before a [`ClipboardRequest::Read`] is sent and must re-open
/// once the answer — or the decision not to send one — is behind us. Doing that
/// in `Drop` rather than on the way out of the match arm is what stops a panic
/// inside a platform clipboard backend from wedging paste for the rest of the
/// run: the worker thread unwinds, this guard still runs, the gate re-opens,
/// and the next paste request therefore reaches
/// [`ShellHandler::send_clipboard_request`], whose failing send is what detects
/// the dead worker and warns. Left on the success path instead, the flag would
/// stay `true` forever and
/// [`ShellHandler::request_clipboard_read`] would coalesce every later paste
/// away silently, with no warning and no route to recovery.
///
/// Release builds pin `panic = "abort"`, so the process is gone either way and
/// this guard is a debug-build concern — which is precisely where a developer
/// needs the diagnosis.
struct ReadGate<'a>(&'a AtomicBool);

impl Drop for ReadGate<'_> {
    fn drop(&mut self) {
        self.0.store(false, Ordering::Release);
    }
}

fn clipboard_loop<A: ClipboardAccess>(
    requests: &Receiver<ClipboardRequest>,
    access: &mut A,
    answer: &mut dyn FnMut(ShellUserEvent),
    read_in_flight: &AtomicBool,
) {
    let mut warnings = ClipboardWarnings::default();
    while let Ok(request) = requests.recv() {
        let started = Instant::now();
        match request {
            ClipboardRequest::Read => {
                // Re-opens the coalescing gate on the way out of this arm —
                // including out of a panic unwinding from the backend. See
                // `ReadGate` and `ShellHandler::request_clipboard_read`.
                let _gate = ReadGate(read_in_flight);
                match access.read() {
                    Ok(text) => answer(ShellUserEvent::ClipboardPaste(PasteText(text))),
                    Err(err) => {
                        if warnings.first_time(err.kind) {
                            log::warn!("{}", clipboard_warning(&err, started.elapsed()));
                        }
                    }
                }
            }
            ClipboardRequest::Write(text) => {
                if let Err(err) = access.write(&text)
                    && warnings.first_time(err.kind)
                {
                    log::warn!("{}", clipboard_warning(&err, started.elapsed()));
                }
            }
            ClipboardRequest::Shutdown => break,
        }
    }
}

/// Spawn the clipboard worker thread and hand back the UI thread's
/// [`ClipboardWorker`] handle, or `None` when the thread could not be spawned —
/// warned here, because the caller latches the failure and never retries.
fn spawn_clipboard_worker(
    proxy: winit::event_loop::EventLoopProxy<ShellUserEvent>,
) -> Option<ClipboardWorker> {
    let (requests_tx, requests_rx) = channel::<ClipboardRequest>();
    let (stopped_tx, stopped_rx) = channel::<()>();
    let read_in_flight = Arc::new(AtomicBool::new(false));
    let worker_in_flight = Arc::clone(&read_in_flight);

    let spawned = std::thread::Builder::new()
        .name("frust-clipboard".to_string())
        .spawn(move || {
            let mut access = ArboardClipboard::default();
            clipboard_loop(
                &requests_rx,
                &mut access,
                // `send_event` fails only once the loop has closed (a shutdown
                // race) — benign, exactly like the frame waker's own send.
                &mut |event| {
                    let _ = proxy.send_event(event);
                },
                &worker_in_flight,
            );
            // Drop the instance here, on the thread that owns it and *before*
            // acknowledging: on X11 `arboard`'s own `Drop` is what offers the
            // selection to a clipboard manager, so a copy made just before the
            // app quits survives the app. The bounded wait on the other end of
            // `stopped` exists for exactly this send.
            drop(access);
            let _ = stopped_tx.send(());
        });

    match spawned {
        // The join handle is dropped on purpose: the thread is detached and
        // stopped through its channel, never joined. Joining would hand the UI
        // thread back the unbounded wait this whole change removes.
        Ok(_detached) => Some(ClipboardWorker {
            requests: requests_tx,
            stopped: stopped_rx,
            read_in_flight,
        }),
        Err(err) => {
            log::warn!(
                "frust-shell-desktop: could not spawn the clipboard worker thread ({err}); \
                 copy/cut/paste no-op for the rest of this run"
            );
            None
        }
    }
}

/// The UI thread's handle on the clipboard worker thread — the whole of this
/// shell's clipboard access from the event loop's side.
///
/// # Why a thread at all
///
/// Reading the host clipboard blocks for as long as the *other* process owning
/// the selection takes to answer, and on X11 that is unbounded in practice:
/// measured at 24 005 ms against a stopped selection owner, because `arboard`'s
/// X11 backend tries its `ConvertSelection` round trip once per candidate
/// target atom, each with its own 4 s bound, before giving up on that atom and
/// moving to the next. That 24 s is a worst-case TOTAL across all six atoms,
/// not six independent chances at recovery: once an atom's 4 s window has
/// lapsed, an owner answering late does not rescue the read — recovery needs
/// the owner to answer within the window currently being tried. Measured on
/// the same rig: an owner SIGSTOPped then resumed at +4.9 s (after the first
/// atom's window had already lapsed at 4 s) never recovered — every remaining
/// atom timed out and the full 24 004 ms warning fired even though the owner
/// was serving normally from +4.9 s on; an owner resumed at +2.9 s (inside the
/// first atom's own window) answered within ~5 ms of the resume. Run on the
/// winit event-loop thread — as this shell did until this change — that
/// worst case is 24 s with no frames, no input, no resize and no close: a
/// window indistinguishable from a hung app.
/// `frust-core` was designed for the answer to arrive late (see
/// `EventCtx::request_paste`: *"The answer is a new dispatch, never a return
/// value"*), so only the shell had to move.
///
/// This handle is therefore one-way plumbing: [`ClipboardRequest`]s go down the
/// channel, and the worker's single answer — text from a successful read —
/// comes back into the loop as a [`ShellUserEvent::ClipboardPaste`] user event
/// through the [`EventLoopProxy`](winit::event_loop::EventLoopProxy), which
/// [`ShellHandler::user_event`] turns into a fresh, top-level
/// `EditCommand::Paste` dispatch. Nothing here ever waits on the worker except
/// the bounded teardown handshake ([`CLIPBOARD_SHUTDOWN_WAIT`]).
///
/// This supersedes the plan's decision D11 — "one lazily created
/// `arboard::Clipboard` for the process lifetime **on the UI thread**" — on the
/// measured evidence above. The instance rule D11 was protecting is kept whole:
/// one instance, one owner, the process's lifetime. It simply lives on the
/// worker thread now, and a write reaches it as a request rather than a direct
/// call; see [`ArboardClipboard`].
struct ClipboardWorker {
    /// Requests to the worker. A `send` fails only once the worker has stopped
    /// (its thread panicked inside a platform backend), which the UI side
    /// treats as "no clipboard for the rest of this run".
    requests: Sender<ClipboardRequest>,
    /// The worker's acknowledgement that it has dropped its
    /// `arboard::Clipboard` — see [`spawn_clipboard_worker`] and
    /// [`CLIPBOARD_SHUTDOWN_WAIT`].
    stopped: Receiver<()>,
    /// Whether a read is queued or running — the coalescing gate. Held from the
    /// request until the worker's read arm ends, which is once the answer has
    /// been posted rather than once the UI thread has taken it.
    ///
    /// While a read is hung, no further read is started behind it, so a user
    /// pressing Ctrl+V six more times at
    /// a frozen selection owner does not buy six more 24 s reads, nor six late
    /// pastes landing minutes later in whatever holds focus by then. Two
    /// presses far enough apart to be two keystrokes are never coalesced: a
    /// healthy read answers in 1-2 ms.
    read_in_flight: Arc<AtomicBool>,
}

/// The dispatch a clipboard answer becomes: exactly one top-level
/// [`EditCommand::Paste`] carrying the text the worker read.
///
/// Says nothing about *whether* the answer should be dispatched at all — that
/// is [`paste_answer_dispatch`]'s question, and it is a separate one, because
/// focus routing alone hands a late answer to whichever field holds focus when
/// it lands rather than to the one that asked.
fn paste_input_event(text: PasteText) -> InputEvent {
    InputEvent::EditCommand(EditCommand::Paste(text.into_string()))
}

/// The dispatch a clipboard answer becomes, or `None` when the answer no longer
/// belongs to the focus session that asked for it.
///
/// `asked_in` is the session recorded when the read was requested
/// ([`ShellHandler::paste_session`]); `live` is
/// [`RenderRoot::focus_epoch`] read again at the moment the answer arrives.
///
/// The comparison is the whole of the guard, and it is needed because focus
/// routing covers only half the hazard. A session that was *released* while the
/// read was outstanding does drop the answer on its own — with nothing focused
/// the synthesized command reaches no widget (`EventCtx::request_paste`'s own
/// contract). A focus *move*, though, leaves a field standing to receive it,
/// and that field never asked for a paste; the clip the user meant for one
/// field is silently typed into another. That is what this refuses.
///
/// [`RenderRoot::focus_epoch`] is the right counter for the question and
/// `focus_ime_generation` is not: this one advances once per honoured focus
/// claim and once per session release and on nothing else, so it moves when
/// focus crosses two fields publishing identical surfaces, and stands still
/// through an edit or a caret move inside the one session. Both accessors
/// document the contrast.
///
/// `None` for `asked_in` means nothing on record addresses this answer, so it
/// is not this shell's to deliver: either nothing asked, or an earlier answer
/// already took the record — which is how a second read that raced the
/// coalescing gate open loses its own answer. See
/// [`ShellHandler::paste_session`] for why that is the accepted cost.
///
/// [`RenderRoot::focus_epoch`]: frust_core::RenderRoot::focus_epoch
fn paste_answer_dispatch(asked_in: Option<u64>, live: u64, text: PasteText) -> Option<InputEvent> {
    (asked_in == Some(live)).then(move || paste_input_event(text))
}

/// Run `build` over `state` in a desktop preview window until it is closed.
///
/// Blocks the calling thread on the winit event loop. The event loop is
/// on-demand ([`ControlFlow::Wait`]): frames are produced only in response to a
/// redraw request (state change on rebuild, or a resize), never free-running.
///
/// The zero-config entry point: delegates to [`run_desktop_with`] with a
/// default [`DesktopConfig`] (title `"Frust"`, no icon, no menu, close quits)
/// and [`NoExtensions`], so the dev preview behaves exactly as it did before
/// either seam existed. A per-OS shell crate calls [`run_desktop_with`]
/// instead.
pub fn run_desktop<State, Build, V>(state: State, build: Build) -> Result<()>
where
    State: 'static,
    V: View<State>,
    Build: FnMut(&mut State) -> V + 'static,
{
    run_desktop_with(state, build, DesktopConfig::default(), NoExtensions)
}

/// [`run_desktop`] with the app's desktop identity ([`DesktopConfig`]) and a
/// per-OS extension set ([`DesktopExtensions`]) supplied.
///
/// This is the entry point the facade calls once it knows which platform shell
/// it is running under: `frust-shell-macos`/`-windows`/`-linux` each construct
/// their own `E` (handing it the same `config`, which they read for identity
/// this core only carries — `app_id`, `window_icon`, `menu_spec`) and call
/// here. Generic over `E` rather than boxed — see [`crate::extensions`]'s
/// module docs.
pub fn run_desktop_with<State, Build, V, E>(
    state: State,
    build: Build,
    config: DesktopConfig,
    mut extensions: E,
) -> Result<()>
where
    State: 'static,
    V: View<State>,
    Build: FnMut(&mut State) -> V + 'static,
    E: DesktopExtensions,
{
    // Install the stderr `log::Log` sink once, so `frust-shell-common::perf`'s
    // `log::info!` startup-span/frame-stats lines below are actually visible
    // (desktop had no logger at all before this — see `logger`'s module docs).
    crate::logger::init_once();

    // The shell-owned monotonic epoch every per-frame `FrameTime` is measured
    // from (time enters from the shell). Captured before any GPU/thread
    // setup so the render thread's startup line and the UI thread's frame clock
    // share one origin.
    let epoch = Instant::now();

    // winit 0.30 has no `EventLoop::<T>::new()` — the typed-user-event loop is
    // built through the builder only. The builder is held in a local (rather
    // than built off a temporary) so the extension's builder-stage hook can
    // install platform builder extensions winit accepts nowhere else — a
    // Windows message hook for menu accelerators being the motivating case.
    let mut builder = EventLoop::<ShellUserEvent>::with_user_event();
    extensions.on_event_loop_builder(&mut builder);
    let event_loop = builder.build()?;
    event_loop.set_control_flow(ControlFlow::Wait);

    // A tracked signal write on any thread fires this waker, which sends a user
    // event through the proxy to wake the `Wait` loop. `send_event` fails only
    // once the loop has closed (a shutdown race) — benign, so its result is
    // ignored. `ReactiveRuntime::init` must run on this (the UI) thread: it
    // claims the thread as owner of the local task queue `pump_local` drains.
    let proxy = event_loop.create_proxy();
    // A second clone is kept on the handler (`accesskit_proxy`) so `resumed` can
    // hand the accesskit_winit `Adapter` its own event-loop proxy — the waker
    // closure below consumes its own clone, so neither producer starves.
    let accesskit_proxy = proxy.clone();
    // A third, for the clipboard worker thread the handler spawns lazily on the
    // first copy/cut/paste: it answers a paste request with
    // `ShellUserEvent::ClipboardPaste` from off the event-loop thread.
    let clipboard_proxy = proxy.clone();
    let waker: FrameWaker = Arc::new(move || {
        let _ = proxy.send_event(ShellUserEvent::SignalsDirty);
    });
    let runtime = ReactiveRuntime::init(waker);

    // Devtools, compiled in only under this crate's `devtools` feature. Started
    // here because both of its prerequisites first exist at this point: the
    // stderr logger installed above (the discovery line must reach a
    // developer's terminal) and an `EventLoopProxy` to wake the `Wait` loop
    // with when a backend request needs the UI thread. Never load-bearing — a
    // bind failure or `FRUST_DEVTOOLS=0` just means no devtools this run.
    #[cfg(feature = "devtools")]
    {
        let devtools_proxy = event_loop.create_proxy();
        frust_shell_common::devtools::start(
            frust_shell_common::devtools::app_name_from_process(),
            Some(Box::new(move || {
                // Fails only once the loop has closed (a shutdown race) — the
                // same benign case the frame waker above ignores.
                let _ = devtools_proxy.send_event(ShellUserEvent::Devtools);
            })),
        );
    }

    // Pick the frame executor once at startup from the `FRUST_NO_RENDER_THREAD`
    // kill switch. The split path spawns a dedicated render
    // thread that owns the `RenderContext` + `SurfaceRenderer` wholesale (both
    // `Send`); the inline path keeps them on this (the UI) thread — the fallback
    // preserved for comparison against the split.
    let executor = if render_thread_enabled() {
        let render_proxy = event_loop.create_proxy();
        FrameExecutor::Split(crate::render::spawn_render_thread(render_proxy))
    } else {
        FrameExecutor::Inline(Box::default())
    };

    let mut handler = ShellHandler {
        state,
        build,
        config,
        extensions,
        runtime,
        scope: TrackedScope::new(),
        root: RenderRoot::new(),
        text_ctx: TextContext::new(),
        executor,
        scene: Scene::new(),
        platform_views: DesktopPlatformViews::new(),
        cursor: Point::ZERO,
        modifiers: Modifiers::default(),
        secondary_down_delivered: false,
        compose: ComposeLatch::default(),
        ime_sync: ImeSync::default(),
        cursor_icon: CursorIcon::Default,
        window: None,
        accesskit_proxy,
        clipboard_proxy,
        adapter: None,
        // The generation `RenderRoot::new()` starts at (0); the first rebuild
        // always dirties it to a different value (a first `rebuild_view` always
        // returns non-empty `ChangeFlags` — see `RenderRoot::rebuild`), so the
        // first post-layout `semantics_if_changed` check below is guaranteed to
        // see a change and push the initial tree.
        semantics_seen: 0,
        fatal: None,
        epoch,
        // The seeded base theme (`base_theme`: a design system's
        // `set_default_theme`, else the built-in `Theme::neutral()` fallback),
        // carrying that base's own brightness only until `resumed` seeds the
        // window's real preference (`brightness_from_winit` there overwrites
        // `brightness` unconditionally, so a seeded base's own starting
        // brightness never leaks into a light-preference platform).
        theme: base_theme(default_theme()),
        theme_seeded: false,
        // No brightness reported to the extension yet, so the first
        // resolution (`resumed`'s seed) counts as a change and fires the hook.
        brightness_notified: None,
        theme_override: ThemeOverrideWatcher::new(),
        theme_override_active: false,
        font_registry: FontRegistryWatcher::new(),
        paced_wake: None,
        anim_pacing: !frust_shell_common::anim_pacing_kill_switch_engaged(),
        window_metrics: WindowMetricsPublisher::new(),
        // Spawned lazily on the first clipboard action — see the `clipboard`
        // field's doc.
        clipboard: None,
        clipboard_unreachable_logged: false,
        // Nothing has asked for a paste yet — see the field's doc.
        paste_session: None,
    };

    // Construction-time font drain: apply any fonts registered via
    // `frust::register_app_fonts` before `run` (app construction) into the
    // shell-owned `TextContext` before the first layout — inline, on this UI
    // thread. Pre-first-layout, so no invalidation/relayout is needed; the
    // per-frame poll in `RedrawRequested` picks up any later registration.
    handler.font_registry.drain_into(&mut handler.text_ctx);

    // The loop's own result is held rather than propagated with `?` so the
    // clipboard worker is always stopped — including on the error path. The
    // handshake is what gives a copy made just before quitting its chance to
    // reach a clipboard manager; see `ShellHandler::shutdown_clipboard`.
    let loop_result = event_loop.run_app(&mut handler);
    handler.shutdown_clipboard();
    loop_result?;
    finish(handler.fatal)
}

/// The base [`Theme`] this shell seeds itself from: the design-system-supplied
/// default (`frust_shell_common::set_default_theme`, read back through
/// [`default_theme`]) when a plugin seeded one, else the shell's own built-in
/// [`Theme::neutral`] fallback.
///
/// A seeded default supplies only the *starting point*: unlike an app-forced
/// override (`set_app_theme`) it does not pin brightness — every call site
/// below still derives `brightness` from the platform's own preference against
/// this base, so a design-system default keeps following system dark mode.
///
/// The fallback is deliberately the design-language-free
/// [`Theme::neutral`] — system fonts, no bundled font bytes: a shell names no
/// design system of its own, so an app that installs none gets the neutral
/// floor rather than someone's brand. A design system supplies both halves
/// itself (its base theme through `set_default_theme`, its font bytes through
/// `frust_shell_common::font_registry::register_app_fonts`).
///
/// Takes the slot's value as an argument rather than reading the process-global
/// itself, so the fallback ladder is unit-testable without touching a
/// process-wide slot that has no reset; every call site passes
/// [`default_theme()`](default_theme).
fn base_theme(seeded: Option<Theme>) -> Theme {
    seeded.unwrap_or_else(Theme::neutral)
}

/// The theme a cleared app-theme override reverts to: the seeded base
/// ([`base_theme`] — a design system's `set_default_theme`, else the built-in
/// fallback) at the platform's *current* brightness, never the cleared
/// override's own pinned one.
///
/// Extracted so the `clear_app_theme` arm below and its unit tests run one
/// implementation: a test that recomputed this in its own body would stay green
/// if the arm regressed to an unconditional `Theme::neutral()` — the exact
/// regression this ladder exists to prevent.
fn reverted_theme(seeded: Option<Theme>, platform: Brightness) -> Theme {
    let mut theme = base_theme(seeded);
    theme.brightness = platform;
    theme
}

/// The active-theme decision for one [`ThemeOverrideWatcher::poll`] result —
/// the precedence ladder's top two rungs as one pure function, shared by the
/// per-frame poll arm in `RedrawRequested` and its unit tests.
///
/// Returns `None` when the poll reported no change (the shell leaves its theme
/// alone), else the new active theme paired with whether an app-forced override
/// is now pinning it (`ShellHandler::theme_override_active`).
///
/// `seeded`/`platform` are suppliers rather than values because only the
/// cleared-override arm needs them: reading the process-global default slot
/// ([`default_theme`] — a `Mutex` lock plus a whole-`Theme` clone) and querying
/// the window's reported appearance would otherwise become per-frame cost for a
/// poll that reports "nothing changed" on all but a handful of frames.
fn theme_after_override_poll(
    polled: Option<Option<Theme>>,
    seeded: impl FnOnce() -> Option<Theme>,
    platform: impl FnOnce() -> Brightness,
) -> Option<(Theme, bool)> {
    match polled {
        // `set_app_theme`: the forced theme wins wholesale — neither the seeded
        // default nor the platform's brightness is even consulted (the
        // override-wins rule).
        Some(Some(theme)) => Some((theme, true)),
        // `clear_app_theme`: back to the seeded base at the platform's own
        // current brightness.
        Some(None) => Some((reverted_theme(seeded(), platform()), false)),
        None => None,
    }
}

/// Re-derive `theme`'s brightness from a platform appearance report, honouring
/// the override-wins rule ([`effective_brightness_for_platform_change`]): an
/// app-forced override pins brightness, a design-system-seeded default does not
/// — `theme` still IS that base, so flipping it in place re-derives light/dark
/// against the design system's own tokens.
///
/// Extracted for the same reason as [`reverted_theme`]: the
/// `WindowEvent::ThemeChanged` arm and the seed-ladder tests share one
/// implementation.
fn follow_platform_brightness(theme: &mut Theme, override_active: bool, platform: Brightness) {
    theme.brightness =
        effective_brightness_for_platform_change(override_active, theme.brightness, platform);
}

/// Applies the resolved window-size configuration ([`window_size_config`]) to
/// an in-progress [`WindowAttributes`]: the logical inner size always, plus
/// `with_maximized(true)` when the maximized knob is on. A free function
/// (rather than inlined in [`window_attributes`]) so the "known
/// size/maximized in, attributes out" step is unit-testable host-side without
/// touching the process environment.
fn apply_window_size(
    attributes: WindowAttributes,
    size: LogicalSize<u32>,
    maximized: bool,
) -> WindowAttributes {
    let attributes = attributes.with_inner_size(size);
    if maximized {
        attributes.with_maximized(true)
    } else {
        attributes
    }
}

/// Assemble the preview window's [`WindowAttributes`] from the app's
/// [`DesktopConfig`], then hand them to the extension's pre-create hook.
///
/// The core's own attributes come first so an extension can override any of
/// them:
/// * the title, from [`DesktopConfig::window_title`] (the configured
///   `app_name`, else the `"Frust"` fallback this shell used to hardcode);
/// * the initial logical size — [`INITIAL_SIZE`] by default, overridable via
///   the [`WINDOW_SIZE_VAR`]/[`WINDOW_MAXIMIZED_VAR`] measurement knobs (see
///   [`window_size_config`]);
/// * `visible(false)` — the accessibility adapter must be constructed before
///   the window is ever shown (see [`Adapter::with_event_loop_proxy`]'s
///   contract), so `resumed` makes it visible itself once that is done.
///
/// A free function taking the extension rather than a `ShellHandler` method so
/// the config→attributes→hook composition is unit-testable with a spy, without
/// a live event loop.
fn window_attributes(
    config: &DesktopConfig,
    extensions: &mut impl DesktopExtensions,
) -> WindowAttributes {
    let (size, maximized, _source) = window_size_config();
    let attributes = WindowAttributes::default()
        .with_title(config.window_title())
        .with_visible(false);
    let attributes = apply_window_size(attributes, size, maximized);
    extensions.on_window_attributes(attributes)
}

/// The brightness (if any) to report through
/// [`DesktopExtensions::on_theme_brightness_changed`], given the last value
/// reported and the shell's current resolved one.
///
/// `last` is `None` before the first report, so the initial resolution counts
/// as a change: a platform shell learns the starting brightness rather than
/// having to guess it and wait for a flip. Afterwards only a genuine difference
/// fires — the hook's "actually changed" contract, which matters because its
/// call site sits inside `apply_theme` (see there) and would otherwise fire on
/// every re-push, including ones that swap one dark theme for another.
fn brightness_change_to_notify(
    last: Option<Brightness>,
    current: Brightness,
) -> Option<Brightness> {
    (last != Some(current)).then_some(current)
}

/// Turns a post-loop `ShellHandler::fatal` into the `run_desktop` result.
///
/// Pulled out of `run_desktop` so the "surface a stashed init error as `Err`"
/// behavior is unit-testable without driving a real winit event loop.
fn finish(fatal: Option<anyhow::Error>) -> Result<()> {
    match fatal {
        Some(err) => Err(err),
        None => Ok(()),
    }
}

/// Apply a [`ControlFlowIntent`] (the winit-free decision from the
/// `paced_wake` module) to the live event loop. [`ControlFlowIntent::Unchanged`]
/// is a deliberate no-op — the paint-time paced-only case leaves the loop
/// parked on whatever it already is, for the next `about_to_wait` to
/// resolve. Pulled out so the translation from intent to `set_control_flow`
/// is one place shared by both the paint and `about_to_wait` call sites.
fn apply_control_flow(event_loop: &ActiveEventLoop, intent: ControlFlowIntent) {
    match intent {
        ControlFlowIntent::Wait => event_loop.set_control_flow(ControlFlow::Wait),
        ControlFlowIntent::WaitUntil(deadline) => {
            event_loop.set_control_flow(ControlFlow::WaitUntil(deadline))
        }
        ControlFlowIntent::Unchanged => {}
    }
}

/// Convert a winit physical-pixel position into logical (density-independent)
/// pixels by the window's `scale_factor`.
///
/// winit reports `CursorMoved`/`PixelDelta` in **physical** pixels (verified
/// empirically on macOS — a HiDPI window reports positions at 2× the logical
/// point value); the widget tree lays out and hit-tests in the same logical
/// space the layout pass uses, so every pointer coordinate is
/// divided by the scale factor at the shell boundary. Pulled out as a free
/// function so the conversion is unit-testable without a live window.
fn physical_to_logical(x: f64, y: f64, scale: f64) -> Point {
    Point::new(x / scale, y / scale)
}

/// Map a winit [`MouseScrollDelta`] to our [`ScrollDelta`], bridging both the
/// unit and the sign convention at the shell boundary.
///
/// Units: wheel notches stay [`ScrollDelta::Lines`] (the ScrollView widget
/// converts to px at 40 px/line); a precision trackpad's `PixelDelta` is
/// physical, so it is divided by the scale factor into logical pixels like
/// every other coordinate.
///
/// Sign: winit reports the direction the **content** moves — a positive `y`
/// moves the content down, revealing what sits above it (a natural-scroll
/// preference is resolved by the OS before winit sees the delta, so this holds
/// on every platform). Frust's scrollable widgets accumulate `offset + dy`,
/// where a growing offset reveals **later** content — the opposite sense, on
/// both axes. Both axes are therefore negated here, at the one boundary that
/// knows winit's convention; everything downstream sees only frust's. The
/// negation is load-bearing, not redundant sign-juggling: dropping it inverts
/// scrolling in every desktop app, and correcting it in a widget instead would
/// invert the touch/fling and programmatic paths that already agree.
///
/// Pulled out as a free function (the call site reads `scale` off a live
/// `Window`) so the mapping stays a pure, directly unit-testable function.
fn map_scroll_delta(delta: MouseScrollDelta, scale: f64) -> ScrollDelta {
    match delta {
        MouseScrollDelta::LineDelta(x, y) => ScrollDelta::Lines(-(x as f64), -(y as f64)),
        MouseScrollDelta::PixelDelta(px) => ScrollDelta::Pixels(-px.x / scale, -px.y / scale),
    }
}

/// Multiplicative rate for the ctrl/⌘+wheel desktop zoom mapping: each
/// wheel-notch "line" of vertical delta scales the view by a factor of
/// `exp(WHEEL_SCALE_RATE_PER_LINE)` (~10% per notch).
///
/// **Community-approximate**: there is no published "the" wheel-zoom rate —
/// this is chosen to match the feel of ctrl+wheel zoom in mainstream
/// browsers and image viewers, where a handful of notches noticeably zooms
/// the view without a single notch feeling abrupt.
const WHEEL_SCALE_RATE_PER_LINE: f64 = 0.1;

/// Map a winit [`MouseScrollDelta`] to a multiplicative
/// [`ScaleEvent::scale_delta`] for the ctrl/⌘+wheel desktop zoom mapping.
///
/// Both delta shapes are first reduced to a line-equivalent vertical count —
/// a `LineDelta` is already in lines; a `PixelDelta` is physical, so it is
/// converted to logical px via `scale` and then to a line-equivalent count by
/// dividing by [`WHEEL_LINE_PX`], the same constant `ScrollView` uses for a
/// precision-trackpad delta — then fed through
/// `exp(WHEEL_SCALE_RATE_PER_LINE * lines)`.
///
/// Sign: unlike [`map_scroll_delta`], the vertical component is **not**
/// negated here. Winit's raw positive `y` is the wheel-up gesture (see that
/// function's sign note — it is what `map_scroll_delta` negates into a
/// negative `ScrollDelta`, which this function never produces), and wheel up
/// must zoom in, so a positive raw `y` must map directly to a
/// `scale_delta > 1.0`.
///
/// Pulled out as a free function, the same shape as [`map_scroll_delta`], so
/// the mapping stays pure and directly unit-testable.
fn map_wheel_scale_delta(delta: MouseScrollDelta, scale: f64) -> f64 {
    let lines = match delta {
        MouseScrollDelta::LineDelta(_, y) => y as f64,
        MouseScrollDelta::PixelDelta(px) => (px.y / scale) / WHEEL_LINE_PX,
    };
    (WHEEL_SCALE_RATE_PER_LINE * lines).exp()
}

/// Whether `modifiers` holds the desktop ctrl/⌘+wheel zoom chord: ⌘ (`meta`)
/// on macOS, `ctrl` on every other desktop OS (Linux, Windows) — the
/// convention mainstream browsers and image viewers use for a discrete wheel
/// zoom step.
///
/// Takes `is_macos` as a plain `bool` rather than gating the whole function
/// behind `#[cfg(target_os = "macos")]`, so the OS branch itself stays
/// directly unit-testable on any host — the same split `frust-paths`' per-OS
/// directory-resolution helpers use. The call site passes `cfg!(target_os =
/// "macos")`.
fn wheel_zoom_chord_held(modifiers: Modifiers, is_macos: bool) -> bool {
    if is_macos {
        modifiers.meta
    } else {
        modifiers.ctrl
    }
}

/// Map winit's wheel/pinch gesture bracket ([`TouchPhase`]) to [`ScalePhase`].
///
/// Shared by the `MouseWheel` zoom mapping and macOS's `PinchGesture`: an
/// ordinary notch wheel reports `Moved` for every tick with no bracket of its
/// own (a lone [`ScalePhase::Update`] stream), while a bracketed gesture —
/// trackpad-driven scroll momentum, or a real pinch — reports `Started`/
/// `Ended` around it. [`TouchPhase::Cancelled`] maps to
/// [`ScalePhase::End`] too: [`ScalePhase`] carries no cancelled variant (see
/// its docs).
fn map_gesture_phase(phase: TouchPhase) -> ScalePhase {
    match phase {
        TouchPhase::Started => ScalePhase::Begin,
        TouchPhase::Moved => ScalePhase::Update,
        TouchPhase::Ended | TouchPhase::Cancelled => ScalePhase::End,
    }
}

/// Map a winit [`MouseButton`] to our [`PointerButton`] vocabulary, or `None`
/// for a button we forward nothing for yet (Middle/Back/Forward — dropped
/// rather than misreported, until those gestures are specced; `PointerButton`
/// itself already models `Middle`, but nothing in this shell dispatches it
/// yet, so it stays out of the mapping alongside the two winit variants that
/// have no `PointerButton` counterpart at all).
///
/// Pulled out as a free function so the mapping stays pure and directly
/// unit-testable, the same shape as [`map_scroll_delta`] below.
fn map_mouse_button(button: MouseButton) -> Option<PointerButton> {
    match button {
        MouseButton::Left => Some(PointerButton::Primary),
        MouseButton::Right => Some(PointerButton::Secondary),
        _ => None,
    }
}

/// Whether a mapped button's press/release should reach the tree at all, given
/// the phase, whether a pointer gesture is currently captured
/// ([`RenderRoot::is_pointer_captured`]), and the delivery latch this gate owns
/// (`ShellHandler::secondary_down_delivered`, threaded in by `&mut`).
///
/// Primary is never gated: it is the button a capture belongs to, and its whole
/// gesture must reach the tree.
///
/// Secondary is gated to keep two invariants at once:
///
/// - **A secondary press never disturbs a live capture.** `RenderRoot` tracks
///   capture as a single root-level flag, not one per button, and releases it
///   on phase alone — never button-checked (see `RenderRoot::event`). A
///   secondary `Down` routed to a mid-drag capturer would hand it a transition
///   it never asked for, and a secondary `Up` would clear the flag out from
///   under a still-live primary gesture. So a secondary `Down` arriving while
///   captured is dropped.
/// - **Pairing: the tree never sees an unpaired secondary event.** A widget's
///   press contract is a `Down` followed by its own `Up`, so dropping a release
///   whose press *was* delivered is as wrong as delivering a release whose press
///   was not — a stateless "drop while captured" rule does exactly that when a
///   capture opens between the two (a right-click that opened a context menu
///   whose `Up` then vanishes, leaving the menu's own press state armed). The
///   latch therefore records what happened to the `Down`, and the `Up` follows
///   it regardless of what the capture flag says by then.
///
/// Pulled out as a free function so the decision stays directly unit-testable
/// without a live `RenderRoot`, the same shape as [`map_scroll_delta`].
fn mouse_button_should_dispatch(
    button: PointerButton,
    phase: PointerPhase,
    pointer_captured: bool,
    secondary_down_delivered: &mut bool,
) -> bool {
    if button != PointerButton::Secondary {
        return true;
    }
    match phase {
        PointerPhase::Down => {
            let deliver = !pointer_captured;
            *secondary_down_delivered = deliver;
            deliver
        }
        PointerPhase::Up => {
            let deliver = *secondary_down_delivered;
            *secondary_down_delivered = false;
            deliver
        }
        // `MouseInput` is the only caller and produces just the two phases
        // above; a pointer `Move`/`Cancel` is built elsewhere (`CursorMoved`
        // makes its own Primary event) and never reaches this gate.
        PointerPhase::Move | PointerPhase::Cancel => true,
    }
}

/// Map a winit [`WinitNamedKey`] to our editing-semantics [`NamedKey`] set,
/// or `None` for a named key we carry no editing semantics for
/// (function keys, media keys, etc. — those fall through to `KeyboardInput`
/// being dropped rather than misreported as text).
///
/// `Copy`/`Cut`/`Paste`/`Insert` are the dedicated hardware clipboard keys
/// some full-size/multimedia keyboards carry (see each [`NamedKey`] variant's
/// own doc) — mapped straight through like every other editing-semantics key
/// here, so [`map_key_event`] delivers them as [`Key::Named`] and the
/// `KeyboardInput` arm dispatches an [`InputEvent::Key`] the tree's own
/// chord decode turns into an [`InputEvent::EditCommand`], the same as it
/// would for a `Cmd+C`/`Ctrl+C` modifier chord.
fn map_named_key(key: WinitNamedKey) -> Option<NamedKey> {
    Some(match key {
        WinitNamedKey::Enter => NamedKey::Enter,
        WinitNamedKey::Backspace => NamedKey::Backspace,
        WinitNamedKey::Delete => NamedKey::Delete,
        WinitNamedKey::ArrowLeft => NamedKey::ArrowLeft,
        WinitNamedKey::ArrowRight => NamedKey::ArrowRight,
        WinitNamedKey::ArrowUp => NamedKey::ArrowUp,
        WinitNamedKey::ArrowDown => NamedKey::ArrowDown,
        WinitNamedKey::Home => NamedKey::Home,
        WinitNamedKey::End => NamedKey::End,
        WinitNamedKey::Escape => NamedKey::Escape,
        WinitNamedKey::Tab => NamedKey::Tab,
        WinitNamedKey::Copy => NamedKey::Copy,
        WinitNamedKey::Cut => NamedKey::Cut,
        WinitNamedKey::Paste => NamedKey::Paste,
        WinitNamedKey::Insert => NamedKey::Insert,
        _ => return None,
    })
}

/// Map winit's window [`WinitTheme`] (`None` when the platform can't report a
/// preference) to a [`Brightness`], defaulting to [`Brightness::Light`].
///
/// Pulled out as a free function so the seed-and-flip mapping is unit-testable
/// without a live window (winit's `Window::theme()` needs a real window).
fn brightness_from_winit(theme: Option<WinitTheme>) -> Brightness {
    match theme {
        Some(WinitTheme::Dark) => Brightness::Dark,
        _ => Brightness::Light,
    }
}

/// Map winit's [`ModifiersState`] bitflags to our [`Modifiers`] chord.
fn map_modifiers(state: ModifiersState) -> Modifiers {
    Modifiers {
        shift: state.shift_key(),
        ctrl: state.control_key(),
        alt: state.alt_key(),
        meta: state.super_key(),
    }
}

/// Map a winit `KeyboardInput`'s fields into our [`KeyEvent`], or `None` when
/// it produces nothing worth dispatching.
///
/// Takes the individual fields off `winit::event::KeyEvent` (rather than the
/// struct itself, whose `platform_specific` field is private to winit and so
/// can't be constructed in this crate's tests) so the mapping stays a pure,
/// directly unit-testable function.
///
/// Named keys ([`WinitKey::Named`]) map through [`map_named_key`]; anything
/// else falls back to the key's resolved `text` (already dead-key/smart-quote
/// resolved by the platform) as [`Key::Character`]. The spacebar is the one
/// named key that resolves to a character instead: winit models it as
/// [`WinitNamedKey::Space`] (never `Character(" ")`), but it types a space
/// rather than carrying editing semantics, so it takes the character path with
/// its `text` payload — falling back to `" "` on a platform that sends none.
/// Either character path is dropped **while** `composing` is
/// set (the dedupe rule: while an IME
/// [`Ime::Preedit`] is active, `Ime::Commit` is the authoritative source for the
/// composed text, not `KeyboardInput.text`). `repeat` passes through unfiltered
/// — callers decide whether to honor auto-repeat. Only key-down (`Pressed`)
/// events map; releases produce `None` (spec: `KeyEvent` has no up/down phase).
///
/// # The ctrl/meta `text`-less fallback
///
/// Winit's `KeyEvent.text` is documented as the resolved text a keypress
/// *would* produce, but it is not populated on every backend while a
/// Ctrl (or, on macOS, Cmd) chord is held — an unmodified `Ctrl+C` can arrive
/// with `text: None` even though `logical_key` is still
/// `Key::Character("c")` (the unshifted letter the key produces with no
/// modifier). Requiring `text` unconditionally would silently drop the whole
/// chord instead of letting a widget's own decode see it as
/// `Key::Character("c")` with `modifiers.ctrl` set. So when `logical_key`
/// is itself a [`WinitKey::Character`] and `text` came back empty while
/// ctrl or meta is held, this falls back to the logical key's own string
/// instead of giving up — the same text a keypress with no modifier held
/// would have produced. Unconditionally trusting `logical_key` regardless of
/// modifiers would be wrong (it is the *unmodified* character, not
/// necessarily what plain typing should insert), so the fallback stays
/// scoped to the documented ctrl/meta case rather than replacing the `text`
/// path outright.
///
/// Measured on Linux/X11 (2026-09-13, KDE on Xorg, winit at this workspace's
/// pin): `text` IS populated under Ctrl for the whole chord set tried —
/// Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+A — so this arm never fires on that backend.
/// It is retained for the macOS Cmd case it was written for, which this
/// observation does not disprove, and for the backends (including Wayland)
/// this one rig's session never exercised.
fn map_key_event(
    logical_key: &WinitKey,
    text: Option<&str>,
    state: ElementState,
    repeat: bool,
    modifiers: Modifiers,
    composing: bool,
) -> Option<KeyEvent> {
    if state != ElementState::Pressed {
        return None;
    }
    let key = match logical_key {
        // Space is a named key that types text, so it resolves to a character
        // ahead of the editing-semantics mapping below — `map_named_key` carries
        // no `NamedKey` for it, and letting it fall through there would drop the
        // event and leave every text widget unable to receive a space.
        WinitKey::Named(WinitNamedKey::Space) => {
            if composing {
                return None;
            }
            Key::Character(text.unwrap_or(" ").to_string())
        }
        WinitKey::Named(named) => Key::Named(map_named_key(*named)?),
        // The ctrl/meta `text`-less fallback (see this function's doc) — scoped
        // to `Character` keys only, so `Unidentified`/`Dead` still requires a
        // resolved `text` payload exactly as before.
        WinitKey::Character(resolved) if text.is_none() && (modifiers.ctrl || modifiers.meta) => {
            if composing {
                return None;
            }
            Key::Character(resolved.to_string())
        }
        _ => {
            if composing {
                return None;
            }
            Key::Character(text?.to_string())
        }
    };
    Some(KeyEvent {
        key,
        modifiers,
        repeat,
    })
}

/// Tracks whether an IME preedit (marked-text) composition is currently in
/// progress, purely from the `WindowEvent::Ime` stream — the dedupe latch
/// [`map_key_event`] consults so `KeyboardInput`-derived `Character` events are
/// suppressed while `Ime::Preedit`/`Ime::Commit` are the authoritative source
/// (winit reportedly withholds `KeyboardInput` during preedit on macOS, but we
/// dedupe defensively cross-platform per the task's research note).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
struct ComposeLatch {
    active: bool,
}

impl ComposeLatch {
    /// Observe one `WindowEvent::Ime` variant, updating the latch and mapping
    /// it to our [`ImeEvent`] in the same pass (the mapping and the
    /// dedupe-state transition are the same decision, so they live together).
    ///
    /// An empty-text `Preedit` closes the latch (per winit's contract it
    /// precedes a `Commit`); `Commit`/`Enabled`/`Disabled` also close it — each
    /// ends or restarts a composition session.
    fn observe(&mut self, ime: &Ime) -> ImeEvent {
        match ime {
            Ime::Preedit(text, cursor) => {
                self.active = !text.is_empty();
                ImeEvent::Compose {
                    text: text.clone(),
                    cursor: *cursor,
                }
            }
            Ime::Commit(text) => {
                self.active = false;
                ImeEvent::Commit(text.clone())
            }
            Ime::Enabled => {
                self.active = false;
                ImeEvent::Enabled
            }
            Ime::Disabled => {
                self.active = false;
                ImeEvent::Disabled
            }
        }
    }

    /// Whether a `KeyboardInput`-derived `Character` event should be dropped
    /// because a composition is currently in progress.
    fn is_composing(&self) -> bool {
        self.active
    }
}

/// Map a published [`ImeContentType`] onto the nearest winit [`ImePurpose`].
///
/// **This is the full extent of what pinned winit 0.30.13 offers for this
/// hint, and it is a weak one.** [`Window::set_ime_purpose`] docs itself as
/// unsupported on every backend *except* Wayland — iOS, Android, Web,
/// Windows, X11, and macOS are all listed explicitly as no-ops. Where it
/// *is* honoured (Wayland, via the compositor's own input-method/OSK), it is
/// a cosmetic hint, not a security boundary: winit has no secure-text-entry
/// concept, so plaintext still crosses the same `Ime`/`KeyboardInput` event
/// stream either way (see [`frust_core::event::ImeState`]'s own
/// "residual exposure" note, which already documents this for the mobile
/// shells — the same limit applies here, just with a much smaller platform
/// footprint that actually honours it).
///
/// `ImePurpose` distinguishes exactly `Normal`/`Password`/`Terminal`, so
/// [`NoSuggestions`](ImeContentType::NoSuggestions) has nothing more precise
/// to map onto than `Normal` — desktop has no channel to ask a platform IME
/// to suppress suggestions/learning without also claiming secure entry it
/// can't actually deliver on this backend. [`Terminal`](ImeContentType::Terminal)
/// is the one variant this backend can map exactly: winit's own `Terminal`
/// purpose exists for precisely this raw byte-entry case ("input into a
/// terminal" per its doc comment), so unlike `NoSuggestions` it does not fall
/// back to `Normal`.
///
/// Recorded in `docs/SHELLS_ARCHITECTURE.md`'s IME section.
fn ime_purpose_for(content_type: ImeContentType) -> ImePurpose {
    match content_type {
        ImeContentType::Terminal => ImePurpose::Terminal,
        other if other.is_secret() => ImePurpose::Password,
        _ => ImePurpose::Normal,
    }
}

/// Map a resolved framework [`CursorIcon`] onto winit's own cursor vocabulary.
///
/// The single place in the framework where a cursor name touches a platform:
/// core carries the request platform-neutrally (see
/// [`frust_core::event::EventCtx::set_cursor`]) and this is the desktop
/// translation. Every framework variant has an exact winit counterpart in the
/// pinned `winit 0.30.13` (which sources its icons from `cursor-icon`, whose
/// names follow CSS), so nothing here approximates.
///
/// The wildcard arm is not dead code: [`CursorIcon`] is `#[non_exhaustive]`, so a
/// variant added later must compile here and *degrade* to the platform arrow
/// rather than break the build or invent a shape.
fn winit_cursor_for(icon: CursorIcon) -> WinitCursorIcon {
    match icon {
        CursorIcon::Default => WinitCursorIcon::Default,
        CursorIcon::Pointer => WinitCursorIcon::Pointer,
        CursorIcon::Text => WinitCursorIcon::Text,
        CursorIcon::Grab => WinitCursorIcon::Grab,
        CursorIcon::Grabbing => WinitCursorIcon::Grabbing,
        CursorIcon::ColResize => WinitCursorIcon::ColResize,
        CursorIcon::RowResize => WinitCursorIcon::RowResize,
        CursorIcon::NotAllowed => WinitCursorIcon::NotAllowed,
        _ => WinitCursorIcon::Default,
    }
}

/// The winit cursor (if any) to push, given the shape last pushed and the one
/// [`RenderRoot::cursor`] now resolves to.
///
/// `None` means "say nothing to winit": the resolved cursor re-resolves on every
/// pointer `Move`, so an unguarded `set_cursor` would fire a platform call on
/// every mouse motion for a value that had not moved. Split out as a free
/// function for [`brightness_change_to_notify`]'s reason — the change decision is
/// then unit-testable without a live window.
fn cursor_change_to_apply(last: CursorIcon, current: CursorIcon) -> Option<WinitCursorIcon> {
    (last != current).then(|| winit_cursor_for(current))
}

/// Cached view of what we last told winit about the platform IME, so
/// [`ShellHandler::sync_ime`] only calls
/// `set_ime_allowed`/`set_ime_cursor_area`/`set_ime_purpose` on an actual
/// change rather than every dispatched event.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
struct ImeSync {
    /// The last `set_ime_allowed` value sent to winit.
    allowed: bool,
    /// The last `set_ime_cursor_area` position/size sent to winit, if any.
    cursor_area: Option<(LogicalPosition<f64>, LogicalSize<f64>)>,
    /// The last [`ImePurpose`] sent to winit via `set_ime_purpose` — see
    /// [`ime_purpose_for`] for how far that call actually reaches.
    purpose: ImePurpose,
}

/// Owns everything a running desktop app needs across frames.
struct ShellHandler<State: 'static, Build, V: View<State>, E> {
    state: State,
    build: Build,
    /// The app's desktop identity, threaded in from [`run_desktop_with`]. Read
    /// by this core only for the window title (see [`window_attributes`]); the
    /// rest of it is the per-OS shells' business, and they hold their own copy.
    config: DesktopConfig,
    /// The per-OS extension set — [`NoExtensions`] for the zero-config preview.
    /// Static, not boxed (see [`crate::extensions`]'s module docs), so a hook
    /// that a shell leaves at its default costs nothing at runtime.
    extensions: E,
    /// The process-wide reactive runtime, initialized on this (UI) thread in
    /// [`run_desktop`]. Per-frame rebuilds run under its root [`Owner`], and
    /// [`ReactiveRuntime::pump_local`] drains the UI-thread local task queue on
    /// each wake and frame.
    runtime: &'static ReactiveRuntime,
    /// Records which signals the last rebuild read, so a later write to any of
    /// them dirties the scope and (via the frame waker) wakes the loop for one
    /// more frame. Re-tracked from scratch every rebuild.
    scope: TrackedScope,
    root: RenderRoot<State, V>,
    text_ctx: TextContext,
    /// The frame executor: either the render-thread split or
    /// the single-thread fallback, chosen once at startup from the
    /// `FRUST_NO_RENDER_THREAD` kill switch. Owns the `RenderContext` +
    /// `SurfaceRenderer` (inline) or the render-thread handle (split), and all
    /// the encode→present + perf recording that used to live inline here (see
    /// [`crate::render`]). Declared before `window` so its `Drop` (which joins
    /// the render thread) runs while the shell still holds a window `Arc`, so the
    /// window is destroyed on the main thread.
    executor: FrameExecutor,
    /// Reused across frames; `reset()` each frame rather than reallocated. In the
    /// split path a finished scene is moved out (replaced with a fresh one) to
    /// cross the handoff channel; inline reuses it in place.
    scene: Scene,
    /// The platform-view host: the shared differ plus this shell's sequencing
    /// around it (ingest after paint, push to the extension after submit, and
    /// the surface-recreate/suspend resets). Costs nothing until a
    /// `platform_view` widget actually paints — see [`crate::platform_view`].
    platform_views: DesktopPlatformViews,
    /// Last known cursor position in logical pixels, updated on every
    /// `CursorMoved`. `MouseInput` (button press/release) carries no position of
    /// its own, so it reuses this — mirroring how winit models the two events.
    cursor: Point,
    /// Current modifier chord, updated by `ModifiersChanged` — which winit
    /// delivers *before* the `KeyboardInput` that uses it, so this is always
    /// current by the time a key event is mapped.
    modifiers: Modifiers,
    /// Whether the last secondary (right) `Down` was actually dispatched to the
    /// tree — the latch [`mouse_button_should_dispatch`] pairs a secondary
    /// release against, so the tree never sees an unpaired one.
    secondary_down_delivered: bool,
    /// Tracks whether an IME preedit composition is in progress, so
    /// `KeyboardInput`-derived `Character` events can be deduped against it.
    compose: ComposeLatch,
    /// What we last told winit about the platform IME (`set_ime_allowed`/
    /// `set_ime_cursor_area`), so [`ShellHandler::sync_ime`] only calls them on
    /// an actual change.
    ime_sync: ImeSync,
    /// The cursor shape last pushed to winit via `Window::set_cursor` — the change
    /// gate behind [`ShellHandler::sync_cursor`]. Seeded with
    /// [`CursorIcon::Default`], which is the shape a fresh window already has, so
    /// the first push happens only when a widget actually asks for something else.
    /// Named apart from `cursor` above deliberately: that one is the pointer's
    /// *position*, this one its *shape*.
    cursor_icon: CursorIcon,
    /// Created lazily in `resumed()` (macOS requires window creation there).
    window: Option<Arc<Window>>,
    /// A clone of the wake proxy handed to the `accesskit_winit` [`Adapter`] at
    /// creation — kept separate from the `FrameWaker`'s own clone
    /// (`run_desktop`) so `resumed` can construct the adapter without needing
    /// to unpick it from the (already-moved-into-a-closure) waker.
    accesskit_proxy: winit::event_loop::EventLoopProxy<ShellUserEvent>,
    /// The event-loop proxy the clipboard worker thread answers a paste
    /// through, cloned into that thread when it is spawned. Held separately
    /// from `accesskit_proxy` so each producer owns its own handle, the same
    /// way the frame waker and the render thread do.
    clipboard_proxy: winit::event_loop::EventLoopProxy<ShellUserEvent>,
    /// The `accesskit_winit` platform adapter, created once in
    /// `resumed` alongside the window (it must be constructed before the
    /// window is first shown — see [`Adapter::with_event_loop_proxy`]'s
    /// contract). `None` only before the first `resumed` call.
    adapter: Option<Adapter>,
    /// The [`RenderRoot::semantics_generation`] value last pushed to the
    /// adapter (the dirty gate) — compared every `RedrawRequested`
    /// via [`RenderRoot::semantics_if_changed`] so an unchanged tree is never
    /// re-walked/re-pushed.
    semantics_seen: u64,
    /// Set when `resumed` hits an unrecoverable init error; `event_loop.exit()`
    /// only stops the loop (it can't return an `Err`), so the error is stashed
    /// here and re-raised by `run_desktop` once `run_app` returns.
    fatal: Option<anyhow::Error>,
    /// The shell-owned monotonic epoch the per-frame [`FrameTime`] is measured
    /// from. `frust-core` never reads a clock itself (time enters from
    /// the shell) — the desktop shell samples `epoch.elapsed()` at paint and hands
    /// the nanosecond delta to [`RenderRoot::paint`]. This stays the
    /// desktop clock; only the mobile shells swap in a platform vsync timestamp.
    epoch: Instant,
    /// The app's active theme — the seeded base ([`base_theme`]: a design
    /// system's `set_default_theme`, else the built-in fallback) until an
    /// app-forced override replaces it. The shell owns the appearance
    /// state: its `brightness` is seeded from the window's reported preference
    /// in `resumed` and flipped live on `WindowEvent::ThemeChanged`. On every
    /// change the shell re-boxes it into [`RenderRoot::set_theme`] (so widgets
    /// read it via `PaintCtx::theme_as`) and `provide_context`s a clone under
    /// the root owner (so app code reads it via `use_context::<Theme>()`).
    theme: Theme,
    /// Whether the initial theme has been pushed to the render root / context
    /// yet — seeded once in the first `resumed`, before the first rebuild.
    theme_seeded: bool,
    /// The brightness last reported through
    /// [`DesktopExtensions::on_theme_brightness_changed`], `None` before the
    /// first report. The change gate behind that hook's "fires only when the
    /// resolved brightness actually changes" contract — see
    /// [`brightness_change_to_notify`] and [`ShellHandler::apply_theme`].
    brightness_notified: Option<Brightness>,
    /// Polls the process-wide app-facing theme override slot
    /// (`frust::set_app_theme`/`clear_app_theme`) once per
    /// frame, before rebuild in `RedrawRequested` — see
    /// `frust_shell_common::theme_override`'s module docs.
    theme_override: ThemeOverrideWatcher,
    /// Whether an app-forced theme override is currently active. While `true`,
    /// `WindowEvent::ThemeChanged` must not flip `self.theme`'s brightness —
    /// the override wins entirely until `clear_app_theme` runs (see
    /// `effective_brightness_for_platform_change`).
    theme_override_active: bool,
    /// Polls the process-wide app-facing pending-font registry
    /// (`frust::register_app_fonts`) once per frame, before rebuild in
    /// `RedrawRequested` (beside `theme_override`) — draining any late
    /// registration into `text_ctx`. Also drained once at construction time (in
    /// `run_desktop`, before the first frame). See
    /// `frust_shell_common::font_registry`'s module docs.
    font_registry: FontRegistryWatcher,
    /// Animation pacing (frame-gate pacing): the desktop shell has no skip gate
    /// (it is dirty-driven under `ControlFlow::Wait`), so it paces a paced-only
    /// decorative loop by scheduling a *delayed* redraw instead of the immediate
    /// `request_redraw` a `needs_frame` normally triggers. When a paint returns
    /// `needs_frame_paced_only` and nothing else needs the next frame, this
    /// holds the `Instant` the next paced redraw is due; `about_to_wait` parks
    /// the loop on `ControlFlow::WaitUntil(that)` and fires the redraw when it
    /// elapses. `None` when no paced redraw is pending.
    paced_wake: Option<Instant>,
    /// Whether animation pacing is enabled (the [`FRUST_NO_ANIM_PACING`] kill
    /// switch, resolved once at construction). When `false` a paced-only frame
    /// falls back to the immediate `request_redraw` every-vsync path.
    ///
    /// [`FRUST_NO_ANIM_PACING`]: frust_shell_common::frame_gate::NO_ANIM_PACING_VAR
    anim_pacing: bool,
    /// Change detector for the app-facing [`WindowMetrics`](frust_core::WindowMetrics)
    /// context: seeded in `resumed` (before the first frame) and re-polled on
    /// `WindowEvent::Resized` — never per frame in `RedrawRequested`, which only
    /// *reads* `inner_size()`/`scale_factor()`. See
    /// [`ShellHandler::push_window_metrics`] for why the guard is load-bearing.
    ///
    /// Desktop is the shell that had **no** insets arm at all: winit 0.30
    /// exposes no cross-platform safe-area/inset accessor (its only `safe_area`
    /// support is internal to the iOS backend), so the metrics published here
    /// carry [`WindowInsets::default`] — zero occlusion, which is the truth for
    /// a decorated desktop window. Mobile's own standalone `WindowInsets`
    /// context is unaffected.
    window_metrics: WindowMetricsPublisher,
    /// The clipboard worker thread's handle — spawned lazily, on the first
    /// copy/cut/paste, and then held for the rest of the process's lifetime.
    /// `None` until that first use, and again for the rest of the run once the
    /// worker could not be spawned or has stopped (see
    /// [`clipboard_unreachable_logged`](ShellHandler::clipboard_unreachable_logged)).
    ///
    /// The host clipboard is never touched from this thread: the one
    /// process-lifetime `arboard::Clipboard` lives on the worker, which is what
    /// keeps a 24-second X11 read off the event loop. [`ClipboardWorker`]
    /// carries the measured evidence and the reply path; [`ArboardClipboard`]
    /// carries why one instance, never one per call, and why a write is routed
    /// to the same thread rather than made here.
    clipboard: Option<ClipboardWorker>,
    /// Whether the clipboard *worker* has already been reported unreachable —
    /// a thread that would not spawn, or a send to one that stopped — via
    /// [`log::warn!`]. Latched: a host that cannot run the worker gets exactly
    /// one warning for the whole run rather than one per copy/cut/paste, and is
    /// never retried, matching this file's shape for a host-integration failure
    /// that cannot recover mid-run. Failures *inside* a running worker (no
    /// reachable clipboard mechanism, a selection owner that never answers) are
    /// warned once per kind on the worker itself — see [`ClipboardWarnings`].
    clipboard_unreachable_logged: bool,
    /// The focus session ([`RenderRoot::focus_epoch`]) recorded by the most
    /// recent paste request — `None` before anything has asked, and again as
    /// soon as an answer takes it. Nothing else clears it, so a value outlasts
    /// a read that answered nothing; the next request overwrites it, and no
    /// answer can reach this slot without one.
    ///
    /// An `EditCommand::Paste` is focus-routed and carries text but no identity
    /// of its own, so an answer that arrives after focus has moved lands in
    /// whichever field holds focus by then: a field that never asked for it.
    /// The host read is asynchronous and its wait belongs to another process —
    /// 24 seconds, measured, against an unresponsive X11 selection owner (see
    /// [`ClipboardWorker`]) — and a Tab press inside a window that wide is an
    /// ordinary thing for a user to do. So the asking session is recorded here
    /// when the request is drained and compared against the live one when the
    /// answer arrives; see [`ShellHandler::request_clipboard_read`] and
    /// [`paste_answer_dispatch`].
    ///
    /// # One slot, however many reads are out
    ///
    /// More than one read genuinely can be outstanding, so this slot does not
    /// describe what is in flight and does not try to. The coalescing gate
    /// ([`ClipboardWorker::read_in_flight`]) re-opens as the worker's read arm
    /// ends — after the answer has been posted through the proxy, but before
    /// the UI thread has consumed it — so a paste request raised inside that
    /// window finds the gate open and starts a second read instead of folding
    /// into the first.
    ///
    /// One slot is still enough, because an answer is decided against this
    /// value alone and there are only three outcomes. It names the live
    /// session: deliver, into a session in which a paste was requested, since
    /// nothing but a request ever writes here. It names one since gone: drop.
    /// It is empty, an earlier answer having taken it: drop. None of the three
    /// asks which read an answer came from, so threading an identity through
    /// [`ClipboardRequest`] and [`ShellUserEvent`] would buy a pairing the
    /// decision never consults.
    ///
    /// # A surplus answer is dropped
    ///
    /// The record is taken, not copied, so one recorded request is answered
    /// once. A second read that does get past the gate therefore finds the slot
    /// empty when its answer lands: two presses close enough together to race
    /// it, inside one *unchanged* session, now produce one paste where this
    /// shell previously produced two. That is a real lost paste, and the
    /// tolerable direction of one — a paste that did not happen is a keystroke
    /// away, and a paste that landed in the wrong field is not.
    ///
    /// # Why the record is not simply left standing
    ///
    /// Letting it survive its answer is the obvious-looking repair for that
    /// lost paste, and it is wrong. Two fields and one race:
    ///
    /// 1. Field A holds the session. It asks, the record becomes A's, a read
    ///    starts.
    /// 2. The worker reads, posts its answer, and the gate re-opens. The UI
    ///    thread has not drained that answer yet.
    /// 3. Focus moves to field B, which asks **once**. The record is
    ///    overwritten to B's, and the gate being open, a *second* read starts.
    /// 4. Both answers now meet a record naming B and a live session of B, so
    ///    both match.
    ///
    /// Left standing, the record hands B the clip twice for the one press it
    /// made. Taken, the second answer finds nothing on record and is dropped,
    /// and B gets the single paste it asked for.
    ///
    /// Note what does *not* save the standing record: "every value here is a
    /// session in which a paste was requested" stays true throughout that
    /// sequence. It is simply not enough, because it says nothing about how
    /// many answers one ask may absorb. Consuming the record is what bounds
    /// that at one.
    ///
    /// So the lost paste above is paid for knowingly. A paste that did not
    /// happen inserts nothing and costs a keystroke; a duplicate inserts text
    /// the user never asked for, and has to be noticed before it can be undone.
    /// A text field wants the stronger of those two guarantees.
    ///
    /// [`RenderRoot::focus_epoch`]: frust_core::RenderRoot::focus_epoch
    paste_session: Option<u64>,
}

impl<State, Build, V, E> ShellHandler<State, Build, V, E>
where
    State: 'static,
    V: View<State>,
    Build: FnMut(&mut State) -> V + 'static,
    E: DesktopExtensions,
{
    /// Deliver one input event to the tree and schedule a frame if it dirtied
    /// state. This is the dirty-driven half of the desktop model: the
    /// event pass never repaints, it only sets `needs_redraw`, which we turn into
    /// a single `request_redraw()` so the `Wait` loop wakes for exactly one frame.
    ///
    /// Also re-syncs the platform IME ([`ShellHandler::sync_ime`]), the
    /// cursor shape ([`ShellHandler::sync_cursor`]), and the host clipboard
    /// ([`ShellHandler::sync_clipboard`]) after every dispatch, in that
    /// order: a focus change, blur, caret move, cursor request, or clipboard
    /// write/paste-request can all happen as a side effect of any event, not
    /// just keyboard/IME/pointer ones.
    ///
    /// The event pass itself runs under the reactive root [`Owner`] — see
    /// [`event_under_owner`], which is what makes `use_context` work from a
    /// press handler.
    ///
    /// [`Owner`]: frust_reactive::Owner
    fn dispatch(&mut self, window: &Window, event: InputEvent) {
        let outcome = event_under_owner(self.runtime, &mut self.root, &mut self.state, &event);
        self.sync_ime(window);
        self.sync_cursor(window);
        self.sync_clipboard();
        if outcome.needs_redraw {
            window.request_redraw();
        }
    }

    /// Push the cursor shape [`RenderRoot::cursor`] resolved to winit, but only
    /// when it differs from the last one pushed.
    ///
    /// Called from [`ShellHandler::dispatch`] beside
    /// [`sync_ime`](ShellHandler::sync_ime), and for the same reason: the shape can
    /// move as a side effect of any event, not just a pointer one, since a handler
    /// on any pass can change what the *next* `Move` resolves. It is deliberately
    /// **not** tied to a frame — a cursor is a window property, not something
    /// painted, so a hover that changes nothing but the shape costs one platform
    /// call and no repaint.
    ///
    /// The change gate ([`cursor_change_to_apply`]) is load-bearing rather than
    /// cosmetic: the resolved cursor re-resolves on every pointer `Move`, so an
    /// unguarded push would call into the platform on every single mouse motion.
    fn sync_cursor(&mut self, window: &Window) {
        let resolved = self.root.cursor();
        if let Some(winit_icon) = cursor_change_to_apply(self.cursor_icon, resolved) {
            window.set_cursor(winit_icon);
            self.cursor_icon = resolved;
        }
    }

    /// Query [`RenderRoot::ime_state`] and push any *changed* IME-relevant
    /// state to winit: `set_ime_allowed` on an active-transition,
    /// `set_ime_cursor_area` (logical caret rect) when active and the caret
    /// moved, and `set_ime_purpose` when [`ImeState::content_type`] changes
    /// (see [`ime_purpose_for`] for exactly how little that last call reaches
    /// — pinned winit honours it on Wayland only, and even there it is a
    /// cosmetic hint, not secure entry). All three calls are gated behind
    /// [`ImeSync`]'s cache so a steady-state focused field with an unmoving
    /// caret and unchanged content type doesn't re-issue them every event.
    ///
    /// [`ImeState::content_type`]: frust_core::event::ImeState::content_type
    fn sync_ime(&mut self, window: &Window) {
        let ime_state = self.root.ime_state();
        let active = ime_state.as_ref().is_some_and(|s| s.active);
        let purpose = ime_state
            .as_ref()
            .map_or(ImePurpose::Normal, |s| ime_purpose_for(s.content_type));

        if active != self.ime_sync.allowed {
            window.set_ime_allowed(active);
            self.ime_sync.allowed = active;
            if !active {
                self.ime_sync.cursor_area = None;
            }
        }

        if purpose != self.ime_sync.purpose {
            window.set_ime_purpose(purpose);
            self.ime_sync.purpose = purpose;
        }

        if active && let Some(caret) = ime_state.and_then(|s| s.caret) {
            let area = (
                LogicalPosition::new(caret.x0, caret.y0),
                LogicalSize::new(caret.width(), caret.height()),
            );
            if self.ime_sync.cursor_area != Some(area) {
                window.set_ime_cursor_area(area.0, area.1);
                self.ime_sync.cursor_area = Some(area);
            }
        }
    }

    /// Ensure the clipboard worker thread exists, spawning it on first use.
    ///
    /// Lazy for the same reason the `arboard::Clipboard` instance it owns is:
    /// an app that never copies or pastes should pay for neither a thread nor
    /// an X11 connection. A spawn failure is warned once (inside
    /// [`spawn_clipboard_worker`]) and then latched — the worker is not
    /// retried, and every clipboard action for the rest of the run is a silent
    /// no-op.
    fn ensure_clipboard_worker(&mut self) {
        if self.clipboard.is_none() && !self.clipboard_unreachable_logged {
            self.clipboard = spawn_clipboard_worker(self.clipboard_proxy.clone());
            self.clipboard_unreachable_logged = self.clipboard.is_none();
        }
    }

    /// Hand one [`ClipboardRequest`] to the worker.
    ///
    /// Returns immediately — a channel send, never a touch of the host
    /// clipboard. A send that fails means the worker thread is gone (it
    /// panicked inside a platform clipboard backend): drop the handle, warn
    /// once, and no-op for the rest of the run.
    fn send_clipboard_request(&mut self, request: ClipboardRequest) {
        self.ensure_clipboard_worker();
        let worker_lost = self
            .clipboard
            .as_ref()
            .is_some_and(|worker| worker.requests.send(request).is_err());
        if worker_lost {
            self.clipboard = None;
            self.clipboard_unreachable_logged = true;
            log::warn!(
                "frust-shell-desktop: the clipboard worker thread has stopped; copy/cut/paste \
                 no-op for the rest of this run"
            );
        }
    }

    /// Ask the worker for a paste, unless one is already outstanding, and
    /// record the focus session that is doing the asking.
    ///
    /// The coalescing gate ([`ClipboardWorker::read_in_flight`]) is the
    /// difference between a hung selection owner costing one dropped paste and
    /// costing a queue of them: the swap publishes "a read is outstanding"
    /// before the request is sent, and the worker clears it once the answer —
    /// or the decision not to send one — is behind it.
    ///
    /// # The recorded session is the most recent asker, not the first
    ///
    /// Because a request can be coalesced into a read someone else started, the
    /// asker and the reader need not be the same session, and the recorded
    /// value has to belong to one of them deliberately. It is overwritten on
    /// every request, so the single answer serves whoever asked last.
    ///
    /// That is the only choice that can deliver anything at all in the case
    /// where the two differ. An answer can no longer reach the earlier
    /// session once focus has left it; keeping the earlier
    /// session on record would therefore throw the answer away *and* leave the
    /// field now focused — which explicitly asked for a paste — with nothing.
    /// Overwriting cannot misdeliver either: every value written here is a
    /// session in which a paste was requested, and [`paste_answer_dispatch`]
    /// still requires it to
    /// be the live one when the answer lands.
    fn request_clipboard_read(&mut self) {
        self.ensure_clipboard_worker();
        // Written before the coalescing branch: a request folded into a read
        // already under way is still a request, and still names who to answer.
        self.paste_session = Some(self.root.focus_epoch());
        let outstanding = self
            .clipboard
            .as_ref()
            .is_some_and(|worker| worker.read_in_flight.swap(true, Ordering::AcqRel));
        if outstanding {
            log::debug!(
                "frust-shell-desktop: a clipboard read is still outstanding; coalescing this \
                 paste request into it"
            );
            return;
        }
        self.send_clipboard_request(ClipboardRequest::Read);
    }

    /// Drain the tree's one-shot clipboard write / paste-request slots
    /// ([`RenderRoot::take_clipboard_write`]/[`RenderRoot::take_paste_request`])
    /// and hand each to the clipboard worker thread, after every dispatch —
    /// beside [`sync_ime`](ShellHandler::sync_ime) and
    /// [`sync_cursor`](ShellHandler::sync_cursor), for the same reason: either
    /// slot can fill as a side effect of any event, not just a keyboard one (a
    /// widget's own chord decode, an edit-menu command, …).
    ///
    /// Neither branch touches the host clipboard from here. Both are channel
    /// sends that return at once, which is the whole point: the read one of
    /// them stands in for blocks for as long as another process feels like
    /// taking — 24 s, measured, on X11 (see [`ClipboardWorker`]). That is also
    /// why this method no longer takes the window: a paste answer is not
    /// dispatched from inside it any more, but from
    /// [`ShellHandler::user_event`] when the worker posts one back.
    ///
    /// Which retires the re-entrancy note this method used to carry. It once
    /// answered a paste request with a nested [`ShellHandler::dispatch`] call
    /// and had to argue that the recursion was bounded at depth one; the answer
    /// now arrives as a fresh user event on a later loop turn, so there is no
    /// nesting left to bound.
    ///
    /// [`RenderRoot::take_clipboard_write`]: frust_core::RenderRoot::take_clipboard_write
    /// [`RenderRoot::take_paste_request`]: frust_core::RenderRoot::take_paste_request
    fn sync_clipboard(&mut self) {
        if let Some(text) = self.root.take_clipboard_write() {
            self.send_clipboard_request(ClipboardRequest::Write(text));
        }

        if self.root.take_paste_request() {
            self.request_clipboard_read();
        }
    }

    /// Stop the clipboard worker and wait, briefly, for it to let go of the
    /// host clipboard — the teardown half of the ownership rule (see
    /// [`ArboardClipboard`]): while this process owns an X11 selection it is
    /// also the process serving it, and `arboard` offers that content to a
    /// clipboard manager only when its instance drops. Called once, from
    /// [`run_desktop`], after `run_app` has returned.
    ///
    /// Bounded by [`CLIPBOARD_SHUTDOWN_WAIT`] and never fatal: a worker stuck
    /// in a hung read — with the shutdown request sitting behind it in the
    /// queue — is left to the process exit, because a host whose selection
    /// owner is not answering has nothing to hand over anyway.
    fn shutdown_clipboard(&mut self) {
        let Some(worker) = self.clipboard.take() else {
            return;
        };
        if worker.requests.send(ClipboardRequest::Shutdown).is_ok() {
            let _ = worker.stopped.recv_timeout(CLIPBOARD_SHUTDOWN_WAIT);
        }
    }

    /// Push the current [`Theme`] to both delivery paths and schedule a repaint.
    ///
    /// 1. `RenderRoot::set_theme` boxes a clone so widgets recover it during
    ///    layout/paint via `PaintCtx::theme_as` (the type-erased widget path).
    /// 2. `provide_context` under the reactive root owner re-provides a clone so
    ///    a `Component::build`'s `use_context::<Theme>()` resolves it on the next
    ///    rebuild (the app-code path). Re-providing under the same owner replaces
    ///    the previous value, so a live dark-mode flip is observed next frame.
    /// 3. [`DesktopExtensions::on_theme_brightness_changed`] fires when the
    ///    resolved brightness actually moved, gated by
    ///    [`brightness_change_to_notify`] — an override swapping one dark theme
    ///    for another moves the theme without moving the brightness.
    ///
    /// Called once to seed the theme in `resumed` and again on every
    /// `WindowEvent::ThemeChanged` and every per-frame app-override poll that
    /// reports a change — i.e. every point at which the shell's resolved
    /// brightness can move, which is why the hook fires from this single funnel
    /// rather than from three separately-remembered call sites.
    fn apply_theme(&mut self, window: &Window) {
        self.root.set_theme(Box::new(self.theme.clone()));
        let theme = self.theme.clone();
        self.runtime.with_owner(move || provide_context(theme));
        if let Some(brightness) =
            brightness_change_to_notify(self.brightness_notified, self.theme.brightness)
        {
            self.brightness_notified = Some(brightness);
            self.extensions.on_theme_brightness_changed(brightness);
        }
        window.request_redraw();
    }

    /// `provide_context` the window's [`WindowMetrics`](frust_core::WindowMetrics)
    /// under the reactive root owner — **only when it actually changed**
    /// ([`WindowMetricsPublisher::poll`] returns `None` otherwise) — so a
    /// `Component::build`'s `use_context::<WindowMetrics>()` resolves the current
    /// window shape on the next rebuild. The app-code delivery path
    /// [`ShellHandler::apply_theme`] already uses for [`Theme`], with the
    /// change guard added.
    ///
    /// **The guard is load-bearing, not an optimization.** `provide_context` is a
    /// plain map insert that notifies nothing on its own, but re-providing once
    /// per frame from `RedrawRequested` would still pay a lock write plus an
    /// allocation for no observable benefit — the value only ever becomes
    /// visible on the next rebuild, which a genuine input change already
    /// drives. So this is called only where an input genuinely moves: `resumed`
    /// (the seed, before the first frame) and `WindowEvent::Resized`. A
    /// scale-factor change needs no separate arm — winit guarantees a
    /// following `Resized`.
    ///
    /// `physical` is winit's device-pixel `inner_size`, divided by `scale` into
    /// the same logical space the layout pass below uses, so the published size
    /// is logical exactly as on Android/iOS. Insets are
    /// [`WindowInsets::default`] (see the `window_metrics` field doc).
    ///
    /// Unlike `apply_theme` this requests **no** redraw of its own: both call
    /// sites already do (`resumed`'s theme seed, `Resized`'s own
    /// `request_redraw`), and a metrics publish that forced a frame on its own
    /// would defeat the guard's purpose.
    fn push_window_metrics(&mut self, physical: (u32, u32), scale: f64) {
        let Some(metrics) = self
            .window_metrics
            .poll(physical, scale, WindowInsets::default())
        else {
            return; // unchanged — no re-provide, no app-wide rebuild
        };
        self.runtime.with_owner(move || provide_context(metrics));
    }

    /// Handle one `accesskit_winit` adapter event delivered through the
    /// event-loop proxy.
    ///
    /// * `InitialTreeRequested` — the adapter activated (an AT client
    ///   connected) and has no tree yet: pull one fresh
    ///   [`RenderRoot::semantics`] pass and push it, recording the generation so
    ///   the next `RedrawRequested` dirty-check doesn't immediately re-push the
    ///   same tree.
    /// * `ActionRequested` — forward straight to
    ///   [`RenderRoot::perform_accessibility_action`] (the same synthesized
    ///   pointer-event path a real tap/click would take — see
    ///   `docs/ARCHITECTURE.md`'s Semantics pass); request a redraw if it
    ///   mutated state.
    /// * `AccessibilityDeactivated` — the AT client detached; nothing to clean
    ///   up (`Adapter::update_if_active` already becomes a no-op on its own).
    fn handle_accessibility_event(&mut self, event: AccessibilityEvent) {
        let Some(adapter) = self.adapter.as_mut() else {
            return;
        };
        match event.window_event {
            AccessibilityWindowEvent::InitialTreeRequested => {
                let update = self.root.semantics();
                self.semantics_seen = self.root.semantics_generation();
                let scale = self
                    .window
                    .as_ref()
                    .map_or(1.0, |window| window.scale_factor());
                adapter.update_if_active(|| build_tree_update(&update, scale));
            }
            AccessibilityWindowEvent::ActionRequested(request) => {
                // Same reactive-owner wrap as `dispatch`: the action is routed
                // through synthesized pointer events, so it lands in the very
                // same `Widget::event` handlers a real click would and needs the
                // ambient `Owner` just as much (see [`event_under_owner`]).
                let runtime = self.runtime;
                let outcome = runtime.with_owner(|| {
                    self.root.perform_accessibility_action(
                        &mut self.state,
                        request.target_node,
                        request.action,
                    )
                });
                if outcome.needs_redraw
                    && let Some(window) = self.window.as_ref()
                {
                    window.request_redraw();
                }
            }
            AccessibilityWindowEvent::AccessibilityDeactivated => {}
        }
    }
}

/// Deliver one input event to the widget tree **under the reactive runtime's
/// root [`Owner`]**, so context lookups work from inside an event handler.
///
/// # Why the wrap is needed
///
/// `reactive_graph`'s `use_context` resolves by walking up from
/// `Owner::current()`, and `Owner::with` *restores* the previous owner when it
/// returns — so outside the per-frame rebuild wrap there is no current owner at
/// all. An unwrapped event pass therefore gives every handler
/// `use_context::<T>() == None`, even for a context the shell itself provided
/// (`Theme`, `WindowMetrics`) — the whole app looks unthemed from a press
/// handler. See the `event_pass_*` tests below.
///
/// # Owner identity: the root owner, not a fresh child
///
/// The pass shares the rebuild's owner rather than opening a child scope. A
/// child scope would have to be created (and disposed) per input event —
/// including per pointer `Move` — which the "no per-event allocation" budget
/// rules out, and a handler's `provide_context` would silently evaporate on
/// dispose instead of being visible to the next rebuild. The cost of sharing is
/// that a handler calling `provide_context` writes into the app-wide root owner;
/// that matches what a root `Component::build` already does.
///
/// # No `TrackedScope`: deliberately untracked
///
/// The rebuild wrap pairs `with_owner` with `TrackedScope::track`; this one must
/// **not**. `track` clears the scope's recorded sources and its dirty flag on
/// entry, so tracking an event pass would (a) throw away the dependency set the
/// last rebuild recorded, silently unsubscribing the frame loop from every
/// signal the view reads, and (b) swallow a wake that arrived since that
/// rebuild. A handler that *writes* a signal still wakes the shell exactly as
/// before — the write notifies the rebuild scope, which is subscribed from its
/// own `track` pass.
///
/// [`Owner`]: frust_reactive::Owner
fn event_under_owner<State: 'static, V: View<State>>(
    runtime: &ReactiveRuntime,
    root: &mut RenderRoot<State, V>,
    state: &mut State,
    event: &InputEvent,
) -> EventOutcome {
    runtime.with_owner(|| root.event(state, event))
}

/// Build an accesskit [`TreeUpdate`] from one [`RenderRoot::semantics`] pull:
/// a full-tree push every time (stable node ids make this valid
/// — see `frust_core::semantics`'s module docs), rooted with
/// [`TreeId::ROOT`] and the update's already-root-defaulted focus id
/// ([`SemanticsUpdate::focus_id`]). Pure and unit-testable without a live
/// window/adapter.
///
/// # HiDPI: stamping the root transform
///
/// `RenderRoot::semantics` (`frust_core`'s `SemanticsCtx::bounds`) reports
/// every node's `bounds` in LOGICAL pixels — the widget tree's own layout
/// unit, the same one `RedrawRequested` lays out in before scaling the scene
/// for paint. AccessKit itself expects PHYSICAL pixels: accesskit's
/// `Node::transform` doc reads "AccessKit expects the final transformed
/// coordinates to be relative to the origin of the tree's container (e.g.
/// window), in physical pixels, with the y coordinate being top-down." The
/// same doc says a node's `bounds` sit "in the coordinate space of the
/// nearest ancestor with a non-`None` transform", so stamping a single
/// `Affine::scale(scale)` on the ROOT node converts the whole tree — no
/// per-node rescale needed. At `scale == 1.0` (the Linux/X11 default) this is
/// a no-op: accesskit's own guidance is to leave `transform` as `None`
/// ("This should be `None` if it would be set to the identity transform")
/// rather than stamp an explicit identity, so the root is left untouched.
fn build_tree_update(update: &SemanticsUpdate, scale: f64) -> TreeUpdate {
    let mut nodes = update.nodes.clone();
    if scale != 1.0
        && let Some((_, root_node)) = nodes.iter_mut().find(|(id, _)| *id == update.root)
    {
        root_node.set_transform(Box::new(frust_core::accesskit::Affine::scale(scale)));
    }
    TreeUpdate {
        nodes,
        tree: Some(Tree::new(update.root)),
        tree_id: TreeId::ROOT,
        focus: update.focus_id(),
    }
}

/// The devtools UI-thread view of this shell (see
/// `frust_shell_common::devtools`): read the retained tree, and deliver a
/// synthetic event through the shell's ordinary [`ShellHandler::dispatch`] —
/// the same helper every winit event goes through, so an injected tap is
/// hit-tested, IME-synced and redraw-scheduled exactly like a real one.
#[cfg(feature = "devtools")]
impl<State, Build, V, E> frust_shell_common::devtools::DevtoolsUi
    for ShellHandler<State, Build, V, E>
where
    State: 'static,
    V: View<State>,
    Build: FnMut(&mut State) -> V + 'static,
    E: DesktopExtensions,
{
    fn inspect(&self) -> Vec<frust_core::InspectNode> {
        self.root.inspect()
    }

    fn dispatch(&mut self, event: InputEvent) {
        // No window yet (an injection racing startup): dropping the event is
        // the honest answer — there is nothing laid out to hit-test against,
        // and `dispatch` needs the window for the IME re-sync and the redraw.
        if let Some(window) = self.window.clone() {
            ShellHandler::dispatch(self, &window, event);
        }
    }
}

impl<State, Build, V, E> ApplicationHandler<ShellUserEvent> for ShellHandler<State, Build, V, E>
where
    State: 'static,
    V: View<State>,
    Build: FnMut(&mut State) -> V + 'static,
    E: DesktopExtensions,
{
    /// A tracked-signal write from any thread routes here via the frame waker →
    /// [`winit::event_loop::EventLoopProxy::send_event`]. Pump the UI-thread
    /// local task queue first (a completing local task may have driven the
    /// write), then request a redraw so the next frame re-runs `build` and
    /// re-tracks. The waker can fire before the window exists (an early
    /// background spawn), so a redraw is only requested when a window is present
    /// — the first rebuild after `resumed` re-tracks regardless.
    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: ShellUserEvent) {
        self.runtime.pump_local();
        match event {
            // A signal write, or a render-thread redraw request (stale-swapchain
            // reconfigure / SurfaceLost recovery in the split path) — both mean
            // "repaint" and both go through the proxy so the `Wait` loop stays
            // dirty-driven (idle CPU near zero).
            ShellUserEvent::SignalsDirty | ShellUserEvent::RenderNeedsRedraw => {
                if let Some(window) = self.window.as_ref() {
                    window.request_redraw();
                }
            }
            ShellUserEvent::Accessibility(event) => self.handle_accessibility_event(event),
            // The clipboard worker answered a paste request (see
            // `ClipboardWorker`): dispatch it as a fresh, top-level edit
            // command, on this loop turn rather than nested inside the pass
            // that asked. Two things withhold it. No window means the answer
            // outlived the window it was asked for — the same answer
            // `DevtoolsUi::dispatch` gives an injection racing startup. A focus
            // session that has moved since the request means the answer belongs
            // to nobody who asked for it, and dispatching it would type the
            // clip into a field that did not (see `paste_answer_dispatch`). The
            // record is taken either way, so one request is answered once — and
            // a surplus answer, from a second read that raced the coalescing
            // gate open, finds the slot empty and is dropped.
            ShellUserEvent::ClipboardPaste(text) => {
                let asked_in = self.paste_session.take();
                if let Some(window) = self.window.clone()
                    && let Some(event) =
                        paste_answer_dispatch(asked_in, self.root.focus_epoch(), text)
                {
                    self.dispatch(&window, event);
                }
            }
            // The render thread lost its surface (split path): re-create it here
            // on the main thread (where winit yields the window handle), hand a
            // fresh surface across, and repaint. Rare path — correctness over
            // elegance.
            ShellUserEvent::RenderRecreateSurface => {
                if let Some(window) = self.window.clone() {
                    let size = window.inner_size();
                    self.executor.recreate_surface(
                        &window,
                        SurfaceSize {
                            width: size.width.max(1),
                            height: size.height.max(1),
                            scale: window.scale_factor(),
                        },
                    );
                    // The host's view hierarchy went with the lost surface:
                    // replay `Create` + `Update` for every live slot on the next
                    // drain, which the redraw below drives.
                    self.platform_views.on_surface_recreated();
                    window.request_redraw();
                }
            }
            // The render thread hit a fatal init error: stash it and stop the
            // loop, mirroring the inline path's `resumed` fatal handling.
            ShellUserEvent::RenderFatal(err) => {
                self.fatal = Some(err);
                event_loop.exit();
            }
            // The devtools UI-thread hop: answer every queued request here, on
            // the thread that owns the tree. Injected events go through
            // `DevtoolsUi::dispatch` → this shell's own `dispatch`, i.e. the
            // identical path a real winit event takes.
            #[cfg(feature = "devtools")]
            ShellUserEvent::Devtools => frust_shell_common::devtools::pump(self),
        }
    }

    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        // The window is created once and reused; the surface, by contrast, is
        // (re)created here every time we resume — `suspended()` tears it down,
        // mirroring Android's surfaceDestroyed/surfaceCreated so the §8.1
        // machine stays exercised on desktop too.
        if self.window.is_none() {
            // Title/size/hidden from the app's `DesktopConfig`, then through the
            // extension's pre-create hook (`window_attributes`) — the only
            // chance a per-OS shell gets at attributes winit refuses to change
            // after creation (Wayland `app_id`, X11 icon).
            let attrs = window_attributes(&self.config, &mut self.extensions);
            match event_loop.create_window(attrs) {
                Ok(window) => {
                    self.adapter = Some(Adapter::with_event_loop_proxy(
                        event_loop,
                        &window,
                        self.accesskit_proxy.clone(),
                    ));
                    // Post-create, pre-show: an extension attaches its native
                    // menu to the live handle and retains the window here (the
                    // one hook that receives it — see `crate::extensions`).
                    // Before `set_visible` so a menu bar is in place the first
                    // time the window is drawn, and after the adapter for the
                    // same reason the window is created hidden at all: the
                    // accesskit adapter must exist before the window is ever
                    // shown (`Adapter::with_event_loop_proxy`'s contract).
                    let window = Arc::new(window);
                    self.extensions.on_window_created(&window);
                    window.set_visible(true);
                    self.window = Some(window);
                }
                Err(err) => {
                    self.fatal =
                        Some(anyhow::Error::from(err).context("frust: failed to create window"));
                    event_loop.exit();
                    return;
                }
            }
        }

        let window = self
            .window
            .clone()
            .expect("window was just created or already present");

        // Bring the surface online if it is not already (a redundant `resumed`
        // is a no-op). Where the renderer lives (UI thread inline, render thread
        // in the split) decides where the pipeline-cache load/persist and the
        // adapter/device/renderer startup spans are recorded — the executor owns
        // that. Inline surface-creation failure is fatal here; a split failure is
        // reported back through the proxy (`RenderFatal`).
        if !self.executor.has_surface() {
            let size = window.inner_size();
            let surface_size = SurfaceSize {
                width: size.width.max(1),
                height: size.height.max(1),
                scale: window.scale_factor(),
            };
            if let Err(err) = self.executor.ensure_surface(&window, surface_size) {
                self.fatal = Some(err);
                event_loop.exit();
                return;
            }
            // A surface just came online, so any hosted native view the previous
            // one carried is gone (`suspended` told the host to drop them all):
            // queue the live-slot replay before the first paint after the
            // resume, whose ingest would otherwise emit a bare `Update` for a
            // view the host no longer has. A no-op on the first bring-up, where
            // there are no live slots yet.
            self.platform_views.on_surface_recreated();
        }

        // Seed the theme once, before the first rebuild: read the window's
        // reported light/dark preference into the M3 baseline, then push it to
        // the render root and the reactive context (`apply_theme` also requests
        // the redraw that drives the first frame). Live changes arrive later via
        // `WindowEvent::ThemeChanged`.
        if !self.theme_seeded {
            self.theme.brightness = brightness_from_winit(window.theme());
            self.theme_seeded = true;
            self.apply_theme(&window);
        } else {
            window.request_redraw();
        }

        // Seed the app-facing window-shape context beside the theme, before the
        // first frame the redraw above drives, so a `Component::build` calling
        // `use_context::<WindowMetrics>()` in the very first rebuild resolves a
        // real value rather than `None`. Self-guarded, so a redundant `resumed`
        // (or one after a suspend/resume at unchanged dimensions) publishes
        // nothing. Live changes arrive via `WindowEvent::Resized`.
        let physical = window.inner_size();
        self.push_window_metrics((physical.width, physical.height), window.scale_factor());
    }

    fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
        // Hosted native views go before the surface they were composited with,
        // while the window is still intact for the host to detach them from. The
        // matching replay is queued in `resumed`, which is the only way back.
        self.platform_views.suspend(&mut self.extensions);
        // Drop the surface on suspend: rare on macOS, but keeps the
        // NoSurface path exercised on desktop and matches Android's lifecycle. In
        // the split path this is a barriered `SurfaceDestroyed` — the shell
        // blocks until the render thread has released its surface resources.
        self.executor.destroy_surface();
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        // Drain any UI-thread local tasks that became runnable while dispatching
        // this batch of events, before the loop parks on `Wait`. Cheap no-op
        // when the queue is empty; a task that writes a signal here re-dirties a
        // scope and fires the waker, which re-arms the loop rather than parking.
        self.runtime.pump_local();

        // Animation pacing (frame-gate pacing): a paced-only decorative loop
        // scheduled its follow-up redraw for a future instant rather than the
        // next vsync. Park the loop on `WaitUntil(deadline)` so it wakes then;
        // once the deadline passes, request the redraw and revert to `Wait`.
        // With nothing pending, defensively return to `Wait` too, so no stale
        // `WaitUntil` can ever survive a turn (the busy-spin bug).
        // Any other redraw source (input, a signal wake, a resize) still wakes
        // the loop immediately regardless of this timer — pacing only bounds the
        // cosmetic loop's own cadence. The decision itself lives in the pure,
        // winit-free `paced_wake` module (see its docs) — this applies its
        // result wholesale (field, redraw, control flow are one value, so the
        // field can never be updated without also deciding the control flow).
        let decision = paced_wake_action(self.paced_wake, Instant::now());
        self.paced_wake = decision.paced_wake;
        if decision.request_redraw
            && let Some(window) = self.window.as_ref()
        {
            window.request_redraw();
        }
        apply_control_flow(event_loop, decision.control_flow);
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        event: WindowEvent,
    ) {
        let Some(window) = self.window.clone() else {
            return;
        };

        // Every `WindowEvent` must reach the accesskit adapter (its documented
        // `process_event` contract): it derives root-window
        // bounds/focus state from `Moved`/`Resized`/`Focused` regardless of
        // what the match below does with the same event.
        if let Some(adapter) = self.adapter.as_mut() {
            adapter.process_event(&window, &event);
        }

        match event {
            // The extension decides whether a close request ends the app: the
            // default (and the whole zero-config preview) is the unconditional
            // exit this arm always was, while a macOS shell may hide its
            // retained window instead and keep the loop alive. The
            // pipeline-cache persistence path is unaffected either way — it
            // hangs off the frame executor's drop once `run_app` returns, not
            // off this event.
            WindowEvent::CloseRequested => match self.extensions.on_close_requested() {
                CloseAction::Exit => {
                    // The window is about to be destroyed: let the host tear its
                    // hosted views out of a hierarchy that still exists, rather
                    // than leaving them to be dropped with it.
                    self.platform_views.suspend(&mut self.extensions);
                    event_loop.exit();
                }
                // Not a teardown — a macOS shell is only hiding its retained
                // window, and the hosted views hide with it. Removing them here
                // would strand the host with nothing to restore on reopen, since
                // no surface is re-created on that path to replay them.
                CloseAction::KeepRunning => {}
            },

            WindowEvent::Resized(size) => {
                // A resize with no live surface is dropped by the machine
                // (inline) or by the render thread's phase gate (split).
                self.executor.resize_surface(SurfaceSize {
                    width: size.width,
                    height: size.height,
                    scale: window.scale_factor(),
                });
                // Republish the app-facing window shape (new logical size, and
                // the derived portrait/landscape orientation with it). Reads the
                // event's own `size` rather than `inner_size()` — this IS the
                // authoritative new size, and it is also what winit delivers
                // after a `ScaleFactorChanged`, which is why that needs no arm
                // of its own. Self-guarded, so a resize that reports unchanged
                // dimensions publishes nothing.
                self.push_window_metrics((size.width, size.height), window.scale_factor());
                window.request_redraw();
            }

            // Live dark-mode toggle: flip the theme's brightness and re-push it
            // to both delivery paths (`apply_theme` requests the repaint). The
            // next paint resolves the dark scheme through `PaintCtx::theme_as`
            // and the next rebuild sees the new `use_context::<Theme>()` value.
            //
            // Override-wins rule: while an app-forced theme
            // override is active, this platform change must not flip
            // brightness — `effective_brightness_for_platform_change` passes
            // the current brightness through unchanged in that case. A seeded
            // *default* is deliberately not pinned that way: `self.theme` still
            // IS that base (`base_theme` seeded it and nothing replaced it), so
            // flipping its brightness in place re-derives light/dark from the
            // design system's own theme.
            WindowEvent::ThemeChanged(winit_theme) => {
                follow_platform_brightness(
                    &mut self.theme,
                    self.theme_override_active,
                    brightness_from_winit(Some(winit_theme)),
                );
                self.apply_theme(&window);
            }

            // Track the cursor in logical space and dispatch a `Move`. We
            // dispatch on every move (not just while a button is down) so hover
            // handling can land later without a shell change; a widget that only
            // cares about drags simply ignores moves with no capture.
            WindowEvent::CursorMoved { position, .. } => {
                let scale = window.scale_factor();
                self.cursor = physical_to_logical(position.x, position.y, scale);
                self.dispatch(
                    &window,
                    InputEvent::Pointer(PointerEvent {
                        phase: PointerPhase::Move,
                        position: self.cursor,
                        button: PointerButton::Primary,
                    }),
                );
            }

            // Primary (left) and secondary (right) buttons; Middle/Back/Forward
            // are ignored until those gestures are specced (`map_mouse_button`).
            // The press/release position is the last `CursorMoved` position
            // (winit carries none on the event). A Secondary press that arrives
            // while a gesture is captured is dropped, and its release follows
            // whatever happened to its press — see
            // `mouse_button_should_dispatch` for both invariants.
            WindowEvent::MouseInput { state, button, .. } => {
                let phase = match state {
                    ElementState::Pressed => PointerPhase::Down,
                    ElementState::Released => PointerPhase::Up,
                };
                if let Some(mapped_button) = map_mouse_button(button)
                    && mouse_button_should_dispatch(
                        mapped_button,
                        phase,
                        self.root.is_pointer_captured(),
                        &mut self.secondary_down_delivered,
                    )
                {
                    self.dispatch(
                        &window,
                        InputEvent::Pointer(PointerEvent {
                            phase,
                            position: self.cursor,
                            button: mapped_button,
                        }),
                    );
                }
            }

            // ctrl (Linux/Windows) / ⌘ (macOS) held turns a wheel tick into a
            // desktop zoom gesture instead of a scroll — see
            // `wheel_zoom_chord_held`/`map_wheel_scale_delta`. The wheel's own
            // gesture bracket (`phase`, discarded on the plain-scroll arm
            // above a moment ago but read here) becomes the `Scale` event's
            // phase via `map_gesture_phase`; the focal point is the last
            // known cursor position, exactly like the plain scroll's.
            WindowEvent::MouseWheel { delta, phase, .. } => {
                if wheel_zoom_chord_held(self.modifiers, cfg!(target_os = "macos")) {
                    let scale_delta = map_wheel_scale_delta(delta, window.scale_factor());
                    self.dispatch(
                        &window,
                        InputEvent::Scale(ScaleEvent {
                            phase: map_gesture_phase(phase),
                            scale_delta,
                            focal: self.cursor,
                            // Neither a notch wheel nor a precision trackpad's
                            // `MouseWheel` delta carries a rate — only
                            // winit's `PinchGesture`/a touch recognizer would.
                            velocity: 0.0,
                        }),
                    );
                } else {
                    let scroll = map_scroll_delta(delta, window.scale_factor());
                    self.dispatch(
                        &window,
                        InputEvent::Scroll {
                            position: self.cursor,
                            delta: scroll,
                        },
                    );
                }
            }

            // macOS/iOS-only two-finger trackpad pinch (see winit's
            // `PinchGesture` docs). Winit never emits this variant on
            // Linux/Windows at this winit pin, so a trackpad pinch there has
            // no desktop `Scale` source yet — only the ctrl/⌘+wheel mapping
            // above (a `docs/LIMITATIONS.md` row to add, not yet recorded).
            // `delta` is already the multiplicative increment winit reports
            // (positive magnifies), so `scale_delta = 1.0 + delta` turns it
            // into the same "multiply the running scale" contract the wheel
            // mapping above produces.
            WindowEvent::PinchGesture { delta, phase, .. } => {
                self.dispatch(
                    &window,
                    InputEvent::Scale(ScaleEvent {
                        phase: map_gesture_phase(phase),
                        scale_delta: 1.0 + delta,
                        focal: self.cursor,
                        // winit's `PinchGesture` carries no velocity either.
                        velocity: 0.0,
                    }),
                );
            }

            // winit delivers `ModifiersChanged` *before* the `KeyboardInput`
            // that relies on it, so tracking it here keeps `self.modifiers`
            // current by the time a key event is mapped.
            WindowEvent::ModifiersChanged(modifiers) => {
                self.modifiers = map_modifiers(modifiers.state());
            }

            // Not repeat-filtered — `repeat` passes through to the framework
            // event so a widget can decide whether to honor
            // auto-repeat (e.g. held Backspace). Dropped entirely (`None`) on
            // key-up, an unmapped named key, or a composing-suppressed
            // character (see `map_key_event`'s dedupe rule).
            WindowEvent::KeyboardInput { event, .. } => {
                if let Some(key_event) = map_key_event(
                    &event.logical_key,
                    event.text.as_deref(),
                    event.state,
                    event.repeat,
                    self.modifiers,
                    self.compose.is_composing(),
                ) {
                    self.dispatch(&window, InputEvent::Key(key_event));
                }
            }

            // The compose latch both maps the winit variant and updates its own
            // dedupe state in one pass (`ComposeLatch::observe`).
            WindowEvent::Ime(ime) => {
                let mapped = self.compose.observe(&ime);
                self.dispatch(&window, InputEvent::Ime(mapped));
            }

            WindowEvent::RedrawRequested => {
                // Drain any UI-thread local tasks queued since the last turn
                // before rebuilding, so their signal writes are visible to this
                // frame. Cheap no-op when the queue is empty.
                self.runtime.pump_local();

                // Drain the per-OS extension's own once-per-frame queue beside
                // the polls below — a native menu's activations, pushed into
                // `frust_reactive::push_menu_event`. Top of frame, so an
                // activation drained here is visible to *this* frame's rebuild
                // rather than the next one; a no-op for `NoExtensions`.
                self.extensions.pump();

                // Poll the app-facing theme override slot once
                // per frame, before rebuild — mirrors the mobile shells'
                // frame-callback poll. `Some(Some(theme))` is a new forced
                // theme; `Some(None)` is a `clear_app_theme` reverting to the
                // platform-derived default; `None` means nothing changed.
                //
                // Reverting an override lands on the base this shell seeded
                // itself from — the design-system default when one was
                // supplied, else the built-in fallback — with brightness
                // re-derived from the window's current preference rather than
                // inherited from the cleared override; that whole ladder lives
                // in `theme_after_override_poll` so this arm and its unit tests
                // share one implementation. Both inputs stay lazy: an
                // unchanged poll pays neither the default-slot read nor the
                // window appearance query.
                if let Some((theme, override_active)) =
                    theme_after_override_poll(self.theme_override.poll(), default_theme, || {
                        brightness_from_winit(window.theme())
                    })
                {
                    self.theme = theme;
                    self.theme_override_active = override_active;
                    self.apply_theme(&window);
                }

                // Poll the app-facing pending-font registry once per
                // frame, beside the theme poll above. `drain_into` applies any
                // late-registered fonts to `text_ctx` (clearing the shape cache
                // internally) and returns whether anything registered. On a
                // late drain, force the relayout `register_fonts` documents by
                // re-pushing the currently-active theme through `set_theme`
                // (the same LAYOUT|PAINT contract a theme swap uses — no new
                // core API), so text laid out before the drain re-shapes against
                // the new faces this frame. When nothing is pending this is one
                // cheap `Mutex` check returning an empty `Vec` (no allocation).
                if self.font_registry.drain_into(&mut self.text_ctx) {
                    self.root.set_theme(Box::new(self.theme.clone()));
                }

                // Rebuild the view tree every frame (build is cheap by
                // construction). A real dirty-tracking loop would skip
                // this when state is unchanged; the on-demand `Wait` control
                // flow already keeps us from free-running.
                //
                // The rebuild runs under the reactive runtime's root `Owner`
                // (so signals created during it are root-owned) and inside the
                // `TrackedScope` (so every signal read subscribes this frame —
                // a later write dirties the scope and wakes the loop). Fields
                // are borrowed disjointly so the tracking closure captures only
                // what the rebuild needs, not all of `self`.
                let rebuild_start = Instant::now();
                let runtime = self.runtime;
                let scope = &self.scope;
                let root = &mut self.root;
                let build = &mut self.build;
                let state = &mut self.state;
                let _flags = runtime.with_owner(|| scope.track(|| root.rebuild(build, state)));
                let rebuild_dur = rebuild_start.elapsed();
                // Perf instrumentation: the app's first-ever rebuild,
                // recorded once. Inline records it here; in the split path the
                // render thread owns the startup line, so this is a no-op there
                // (it records the milestone when the first scene arrives).
                self.executor.record_first_rebuild();
                // A rebuild can change which widget is focused / what it
                // publishes without an intervening event (e.g. state-driven
                // focus), so re-sync the platform IME here too.
                self.sync_ime(&window);

                // HiDPI: lay out in logical pixels, then scale
                // the whole scene by the device pixel ratio so glyph outlines
                // are re-rasterised sharp at physical resolution.
                let physical = window.inner_size();
                let scale = window.scale_factor();
                let logical = Size::new(
                    physical.width as f64 / scale,
                    physical.height as f64 / scale,
                );
                let text_ctx: &mut dyn Any = &mut self.text_ctx;
                let layout_start = Instant::now();
                self.root.layout_with_text(logical, text_ctx);
                let layout_dur = layout_start.elapsed();

                // Push a fresh semantics tree to the accesskit adapter if it may
                // have changed since the last push (the dirty gate —
                // `RenderRoot::semantics_if_changed`); post-layout so bounds are
                // valid. A no-op (`update_if_active` never runs the closure)
                // while no AT client has activated the adapter.
                if let Some(adapter) = self.adapter.as_mut()
                    && let Some(update) = self.root.semantics_if_changed(self.semantics_seen)
                {
                    self.semantics_seen = self.root.semantics_generation();
                    adapter.update_if_active(|| build_tree_update(&update, scale));
                }

                self.scene.reset();
                // Sample the shell-owned monotonic clock once per frame and hand
                // it to paint; every animating widget differences it against its
                // own stored time (the mobile shells swap this single expression for a
                // platform vsync timestamp instead).
                let frame_time = FrameTime::from_nanos(self.epoch.elapsed().as_nanos() as u64);
                // Push the render side's presented-frame count so a widget
                // measuring FPS reports the presented rate, not its paint cadence.
                // A pure observation — `set_presented_frames` dirties
                // nothing, so it neither forces a relayout nor (as the setter's
                // contract notes) would ever feed a frame gate.
                self.root
                    .set_presented_frames(self.executor.presented_frames());
                let paint_start = Instant::now();
                let paint_outcome = {
                    let mut builder = SceneBuilder::new(&mut self.scene);
                    builder.push_transform(Affine::scale(scale));
                    let outcome = self.root.paint(&mut builder, frame_time);
                    builder.pop_transform();
                    outcome
                };
                let paint_dur = paint_start.elapsed();

                // Platform views: ingest the pass that just painted — retire the
                // slots whose widgets were torn down, then diff this pass's
                // published frames into commands. Immediately after `paint` and
                // never earlier: `RenderRoot::platform_view_frames` reflects only
                // the most recent paint. Outside the paint span above, so the
                // diff is not charged to paint time. The returned "anything
                // changed" flag is deliberately not consulted — the drain below
                // runs unconditionally because a backlog can also come from a
                // surface-recreate replay that no ingest produced.
                self.platform_views.after_paint(&mut self.root);

                // Animation driver (spec v1 seam): if paint advanced animation
                // state (e.g. a scroll fling) it asks for another frame here.
                // `ControlFlow::Wait` would otherwise idle with no pending input,
                // so we keep frames coming with an explicit redraw request until
                // the animation reaches rest and stops signalling.
                //
                // Animation pacing (frame-gate pacing): when the request is a
                // paced-only decorative loop (`needs_frame_paced_only` — a
                // shimmer/pulse/spinner with no concurrent transition), schedule
                // the follow-up redraw a `cosmetic_loop_rate` interval out rather
                // than every vsync. The desktop shell has no skip gate, so it
                // paces via a delayed wake (`about_to_wait` parks on
                // `WaitUntil`). A `Transition` request (or the pacing kill
                // switch) keeps the immediate every-frame path. `needs_frame ==
                // false` (a settled loop) must clear any stale prior
                // `paced_wake` too, not just leave it assigned only inside a
                // `needs_frame` arm — `next_paced_wake` is driven every frame
                // (not just the `needs_frame` ones) precisely so its settle
                // path covers that case: it clears the field AND returns the
                // loop to `Wait`, never leaving a stale `WaitUntil` behind (the
                // busy-spin bug). The cap/fold arithmetic is
                // computed only inside the branch that schedules (in
                // `next_paced_wake`), so a settling frame never runs it; the
                // rate is kept finite by `CosmeticLoopRate`'s NaN-safe clamp so
                // that division can't panic. The decision bundles the field,
                // the redraw, and the control flow into one value, so the field
                // can never be updated without also deciding the control flow.
                //
                // Per-request pacing interval (A2): `paint_outcome.paced_interval`
                // is this same paint's MIN-aggregated per-request interval (a
                // ~500ms caret blink against a 30Hz shimmer cap) — fed straight
                // into `next_paced_wake` exactly as `needs_frame_paced_only` is
                // above, never stored in a struct field. Unlike the mobile
                // shells (whose gate decides *before* paint runs, so they must
                // latch the previous paint's interval into a field for the next
                // tick's decision — see `frust-shell-android`'s
                // `last_paced_interval`), desktop's decision runs synchronously
                // right after `RenderRoot::paint` returns, so this frame's own
                // outcome is always the freshest possible input: no persisted
                // value can ever go stale, and an interval change between
                // paints (a loop's cadence request changing) is re-derived from
                // scratch on every call rather than carried forward.
                // `next_paced_wake` folds it against the theme's cap with the
                // same `max(cap, requested)` semantics as
                // `FramePacing::effective_interval` — the cap is a ceiling, a
                // slower per-request interval widens the cadence, never
                // tightens it.
                let decision = next_paced_wake(
                    paint_outcome.needs_frame,
                    paint_outcome.needs_frame_paced_only,
                    self.anim_pacing,
                    Instant::now(),
                    self.theme.motion.cosmetic_loop_rate.hz(),
                    paint_outcome.paced_interval,
                );
                self.paced_wake = decision.paced_wake;
                if decision.request_redraw {
                    window.request_redraw();
                }
                apply_control_flow(event_loop, decision.control_flow);

                // A tracked signal written *during* this frame (e.g. a local
                // task pumped above, or a write racing in from a background
                // thread) already re-dirtied the scope after `track` cleared it.
                // The waker's clean→dirty edge fired inside `track`, so no user
                // event will arrive for it — request the follow-up frame here,
                // mirroring the `needs_frame` animation path above.
                if self.scope.is_dirty() {
                    window.request_redraw();
                }

                // Hand the finished frame to the executor. In the single-thread
                // fallback this runs encode→acquire→submit inline (clearing to
                // the live theme's surface color); in the split
                // path it moves the scene across the depth-1 latest-wins channel
                // and the render thread runs the tail, recording its own
                // `RenderSpans` folded with these `UiSpans` via
                // `FramePasses::from_split` (the single perf emitter). Either way
                // a render failure is log-and-continue, not fatal — one bad frame
                // must not kill the app (see `fatal` for the persistent case).
                let ui_spans = UiSpans {
                    rebuild: rebuild_dur,
                    layout: layout_dur,
                    paint: paint_dur,
                    skipped: false,
                };
                let base_color = self.theme.scheme().surface;
                let size = SurfaceSize {
                    width: physical.width,
                    height: physical.height,
                    scale,
                };
                self.executor.submit_frame(
                    &window,
                    &mut self.scene,
                    base_color,
                    ui_spans,
                    frame_time,
                    size,
                );

                // Hand the platform-view batch to the per-OS host, on this
                // thread, right after the scene is submitted. One call site
                // covers both executors: `FrameExecutor::submit_frame` is the
                // single entry for the inline and split paths alike
                // (`crate::render`), so there is no second place a frame leaves
                // the UI thread from. The batch describes the scene just
                // submitted, so a hosted view leads the content it is pinned to
                // by at most one frame — the present-sync gate that would close
                // that gap needs a presented-frame *id* this crate's executor
                // does not publish (see `crate::platform_view`'s timing
                // section). Logical points, not physical px: `scale` rides along
                // for a host that needs to convert.
                self.platform_views
                    .drain(&mut self.extensions, &window, scale);
            }

            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ClipboardAccess, ClipboardError, ClipboardFailure, ClipboardRequest, ClipboardWarnings,
        ComposeLatch, DesktopConfig, DesktopExtensions, ElementState, Ime, ImeSync, LogicalSize,
        MouseScrollDelta, NoExtensions, PasteText, ShellUserEvent, Tree, TreeId,
        WHEEL_SCALE_RATE_PER_LINE, WindowKnobSource, WinitCursorIcon, WinitKey, WinitNamedKey,
        WinitTheme, apply_window_size, base_theme, brightness_change_to_notify,
        brightness_from_winit, build_tree_update, clipboard_loop, clipboard_warning,
        cursor_change_to_apply, default_theme, finish, follow_platform_brightness, ime_purpose_for,
        map_gesture_phase, map_key_event, map_modifiers, map_mouse_button, map_named_key,
        map_scroll_delta, map_wheel_scale_delta, mouse_button_should_dispatch,
        parse_window_maximized, parse_window_size, paste_answer_dispatch, paste_input_event,
        physical_to_logical, resolved_window_knob, theme_after_override_poll,
        wheel_zoom_chord_held, window_attributes, winit_cursor_for,
    };
    use frust_core::SemanticsUpdate;
    use frust_core::accesskit::{
        Affine as AccessKitAffine, Node, NodeId, Rect as AccessKitRect, Role,
    };
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;
    // `InputEvent` is deliberately absent: the event-dispatch section further
    // down already imports it from `super`, and this module is one scope.
    use frust_core::event::{
        CursorIcon, EditCommand, ImeContentType, ImeEvent, Key, KeyEvent, Modifiers, NamedKey,
        PointerButton, ScalePhase, ScrollDelta,
    };
    use frust_theme::{Brightness, DesignLanguage, Theme};
    use kurbo::Point;
    use winit::dpi::PhysicalPosition;
    use winit::event::MouseButton;
    use winit::event::TouchPhase;
    use winit::keyboard::ModifiersState;
    use winit::window::{ImePurpose, WindowAttributes};

    // --- clipboard worker plumbing ---

    /// Test double for [`ClipboardAccess`] — the worker loop's seam onto the
    /// host clipboard, so the plumbing can be driven with no window, no event
    /// loop and no real desktop session (`Fake<Trait>`, per
    /// `docs/CODE_STANDARDS.md`'s naming table).
    #[derive(Default)]
    struct FakeClipboard {
        /// What a read answers: text, or the failure kind to fail with.
        read: Option<Result<String, ClipboardFailure>>,
        /// Every text written, in order.
        written: Vec<String>,
        /// How many reads were attempted.
        reads: usize,
    }

    impl FakeClipboard {
        fn answering(read: Result<String, ClipboardFailure>) -> Self {
            Self {
                read: Some(read),
                ..Self::default()
            }
        }
    }

    impl ClipboardAccess for FakeClipboard {
        fn read(&mut self) -> Result<String, ClipboardError> {
            self.reads += 1;
            match self.read.clone() {
                Some(Ok(text)) => Ok(text),
                Some(Err(kind)) => Err(ClipboardError::new(kind, "fake host failure")),
                None => Err(ClipboardError::new(
                    ClipboardFailure::Unanswered,
                    "fake host with nothing set",
                )),
            }
        }

        fn write(&mut self, text: &str) -> Result<(), ClipboardError> {
            self.written.push(text.to_string());
            Ok(())
        }
    }

    /// Run [`clipboard_loop`] over `requests` and collect every answer it
    /// posts. The sender is dropped before the loop starts, so the loop drains
    /// the queue and returns rather than blocking — the same exit a dropped
    /// `ShellHandler` produces in the shipped path.
    fn run_clipboard_loop(
        requests: Vec<ClipboardRequest>,
        access: &mut FakeClipboard,
        read_in_flight: &AtomicBool,
    ) -> Vec<ShellUserEvent> {
        let (tx, rx) = std::sync::mpsc::channel();
        for request in requests {
            tx.send(request).expect("the receiver is still alive");
        }
        drop(tx);

        let mut answers = Vec::new();
        clipboard_loop(
            &rx,
            access,
            &mut |event| answers.push(event),
            read_in_flight,
        );
        answers
    }

    /// A [`ClipboardAccess`] whose read panics the way a platform backend can,
    /// instead of returning an `Err` — the one case [`ReadGate`] exists for.
    struct PanickingClipboard;

    impl ClipboardAccess for PanickingClipboard {
        fn read(&mut self) -> Result<String, ClipboardError> {
            panic!("the platform clipboard backend panicked");
        }

        fn write(&mut self, _text: &str) -> Result<(), ClipboardError> {
            Ok(())
        }
    }

    #[test]
    fn a_panicking_read_still_reopens_the_coalescing_gate() {
        // Seeded `true` the way `request_clipboard_read` leaves it before the
        // request goes out. Before `ReadGate`, a panic out of the backend left
        // the flag stuck `true` for the rest of the run: `request_clipboard_read`
        // then took its coalescing branch every time, returning WITHOUT ever
        // attempting the channel send whose failure is what reports a dead
        // worker — so paste died silently, with no warning and no recovery.
        let read_in_flight = AtomicBool::new(true);

        // The panic is the point of the test, so keep its backtrace out of the
        // suite's output.
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let (tx, rx) = std::sync::mpsc::channel();
            tx.send(ClipboardRequest::Read)
                .expect("the receiver is still alive");
            drop(tx);
            clipboard_loop(&rx, &mut PanickingClipboard, &mut |_| {}, &read_in_flight);
        }));
        std::panic::set_hook(hook);

        assert!(
            unwound.is_err(),
            "the backend panic must propagate and end the worker, not be swallowed",
        );
        assert!(
            !read_in_flight.load(Ordering::Acquire),
            "the coalescing gate must re-open on an unwind, so the next paste request \
             reaches send_clipboard_request and its failing send reports the dead worker",
        );
    }

    #[test]
    fn a_successful_clipboard_read_answers_exactly_one_paste() {
        let mut access = FakeClipboard::answering(Ok("copied text".to_string()));
        // Seeded `true` the way `request_clipboard_read` leaves it before the
        // request goes out.
        let read_in_flight = AtomicBool::new(true);

        let answers =
            run_clipboard_loop(vec![ClipboardRequest::Read], &mut access, &read_in_flight);

        assert_eq!(answers.len(), 1, "one read, one answer: {answers:?}");
        let text = match answers.into_iter().next() {
            Some(ShellUserEvent::ClipboardPaste(text)) => text,
            other => panic!("expected a ClipboardPaste answer, got {other:?}"),
        };
        // …and that answer becomes exactly one top-level `EditCommand::Paste`.
        match paste_input_event(text) {
            InputEvent::EditCommand(EditCommand::Paste(pasted)) => {
                assert_eq!(pasted, "copied text");
            }
            other => panic!("expected an EditCommand::Paste dispatch, got {other:?}"),
        }
        assert!(
            !read_in_flight.load(Ordering::Acquire),
            "the coalescing gate must re-open for the next paste"
        );
    }

    #[test]
    fn a_failed_clipboard_read_dispatches_nothing() {
        // Every failure kind a read can produce, including the host's
        // misleading "the clipboard is empty" (`Unanswered`) — the one the
        // measured X11 hang ends in after ~24 s. None of them may synthesize a
        // paste: an empty one would silently clear the selection the user meant
        // to replace.
        for kind in [
            ClipboardFailure::Unavailable,
            ClipboardFailure::Unanswered,
            ClipboardFailure::ReadFailed,
        ] {
            let mut access = FakeClipboard::answering(Err(kind));
            let read_in_flight = AtomicBool::new(true);

            let answers =
                run_clipboard_loop(vec![ClipboardRequest::Read], &mut access, &read_in_flight);

            assert!(answers.is_empty(), "{kind:?} dispatched {answers:?}");
            assert_eq!(access.reads, 1, "{kind:?} must still have tried once");
            assert!(
                !read_in_flight.load(Ordering::Acquire),
                "{kind:?} must re-open the coalescing gate, or pasting stops for the run"
            );
        }
    }

    #[test]
    fn a_clipboard_write_reaches_the_host_and_answers_nothing() {
        let mut access = FakeClipboard::default();
        let read_in_flight = AtomicBool::new(false);

        let answers = run_clipboard_loop(
            vec![ClipboardRequest::Write("copied".to_string())],
            &mut access,
            &read_in_flight,
        );

        assert!(answers.is_empty(), "a write is not an answer: {answers:?}");
        assert_eq!(access.written, vec!["copied".to_string()]);
        assert_eq!(access.reads, 0);
    }

    #[test]
    fn clipboard_shutdown_abandons_what_was_queued_behind_it() {
        // The teardown handshake stops at `Shutdown` so `run_desktop`'s bounded
        // wait cannot be starved by work that arrived after it asked the worker
        // to stop.
        let mut access = FakeClipboard::answering(Ok("late".to_string()));
        let read_in_flight = AtomicBool::new(false);

        let answers = run_clipboard_loop(
            vec![ClipboardRequest::Shutdown, ClipboardRequest::Read],
            &mut access,
            &read_in_flight,
        );

        assert!(answers.is_empty(), "{answers:?}");
        assert_eq!(
            access.reads, 0,
            "the read queued behind Shutdown never runs"
        );
    }

    #[test]
    fn clipboard_warnings_fire_once_per_kind() {
        let mut warnings = ClipboardWarnings::default();

        assert!(warnings.first_time(ClipboardFailure::Unanswered));
        assert!(!warnings.first_time(ClipboardFailure::Unanswered));
        // Kinds are independent: a host that can neither read nor write still
        // says both things once.
        assert!(warnings.first_time(ClipboardFailure::WriteFailed));
        assert!(!warnings.first_time(ClipboardFailure::WriteFailed));
        assert!(warnings.first_time(ClipboardFailure::Unavailable));
        assert!(warnings.first_time(ClipboardFailure::ReadFailed));
    }

    #[test]
    fn the_unanswered_warning_refuses_the_hosts_empty_clipboard_claim() {
        // `arboard` returns `ContentNotAvailable` both for an empty clipboard
        // and for a selection owner that never answered; the measured X11 case
        // is the latter, after ~24 s. The line must not repeat the host's "or
        // the clipboard is empty" as if it were the truth, and must carry the
        // wait that makes a hung owner visible in a log.
        let line = clipboard_warning(
            &ClipboardError::new(ClipboardFailure::Unanswered, "the host reported no text"),
            Duration::from_millis(24_005),
        );

        assert!(line.contains("24005 ms"), "{line}");
        assert!(line.contains("never answered"), "{line}");
        assert!(line.contains("dropped"), "{line}");
    }

    #[test]
    fn a_paste_answer_never_logs_the_clipboard_text() {
        // The user event is `Debug`-formatted wholesale by anything logging a
        // loop turn, and clipboard text is user data — a password manager's
        // paste being the motivating case. Matches `EditCommand`'s own
        // redacting `Debug` in `frust-core`.
        let rendered = format!(
            "{:?}",
            ShellUserEvent::ClipboardPaste(PasteText("hunter2".to_string()))
        );

        assert!(!rendered.contains("hunter2"), "{rendered}");
        assert!(rendered.contains("redacted"), "{rendered}");
    }

    // --- binding a late paste answer to the focus session that asked ---
    //
    // The host read is asynchronous and its wait belongs to another process, so
    // the answer arrives on a later loop turn — by which time focus may have
    // moved. `EditCommand::Paste` carries text and no identity, so focus
    // routing alone would hand it to whatever field holds focus at delivery.
    //
    // These two drive a real `RenderRoot`, and move the focus session the way
    // the user does — a press the field answers with a focus claim of its own —
    // rather than by writing a counter, so they keep their meaning if the
    // session mechanism is reimplemented. They are a matched pair on purpose: a
    // guard that dropped every answer would pass the second one alone.
    //
    // What they do NOT reach is the wiring on either side of
    // `paste_answer_dispatch`: that `ShellHandler::request_clipboard_read`
    // records `RenderRoot::focus_epoch` and not `focus_ime_generation`, and that
    // `user_event`'s `ClipboardPaste` arm takes the record rather than copying
    // it and compares it against a freshly read `focus_epoch`. Both sites live
    // on a handler owning an `EventLoopProxy`, which cannot exist without an
    // event loop, so no unit test can construct one — the same wall
    // `clipboard_loop` meets, and the reason it takes its collaborators
    // generically. Those two sites are pinned by prose,
    // not by a test: swapping the counter at the request site would leave both
    // tests below green.

    /// A focusable stand-in for a text field: takes the focus session on a
    /// press inside itself, and records every paste it is handed.
    struct PasteField {
        /// The texts this field received, in order — the proof of where a paste
        /// actually landed.
        pasted: Rc<RefCell<Vec<String>>>,
    }

    impl Widget for PasteField {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(Size::new(100.0, 30.0))
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            match event {
                InputEvent::Pointer(p) if p.phase == PointerPhase::Down => {
                    ctx.request_focus();
                    EventResult::Handled
                }
                InputEvent::EditCommand(EditCommand::Paste(text)) => {
                    self.pasted.borrow_mut().push(text.clone());
                    EventResult::Handled
                }
                _ => EventResult::Ignored,
            }
        }
    }

    /// Two stacked fields: a press hit-tests, a paste follows the focus chain.
    struct PasteFields {
        first: frust_core::widget::ChildPod,
        second: frust_core::widget::ChildPod,
    }

    impl Widget for PasteFields {
        fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            self.first.layout_child(ctx, bc);
            self.first.set_origin(Point::ZERO);
            self.second.layout_child(ctx, bc);
            self.second.set_origin(Point::new(0.0, 30.0));
            bc.max()
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            if event.is_focus_routed() {
                for pod in [&mut self.first, &mut self.second] {
                    if pod.is_focused() {
                        return pod.event_child(ctx, event);
                    }
                }
                return EventResult::Ignored;
            }
            let position = event.position();
            let blurs = matches!(
                event,
                InputEvent::Pointer(p) if p.phase == PointerPhase::Down
            );
            let mut result = EventResult::Ignored;
            let mut hit = false;
            for pod in [&mut self.first, &mut self.second] {
                if !hit && pod.contains(position) {
                    hit = true;
                    result = pod.event_child(ctx, event);
                } else if blurs {
                    // A press landing elsewhere blurs the chain, exactly as
                    // `frust-widgets`' routers do.
                    pod.set_focused(false);
                }
            }
            result
        }
    }

    /// The fixture's view. It carries the two record handles so each test can
    /// read what its field received without reaching into the built tree.
    #[derive(Clone)]
    struct PasteFieldsView {
        first: Rc<RefCell<Vec<String>>>,
        second: Rc<RefCell<Vec<String>>>,
    }

    impl View<()> for PasteFieldsView {
        type Element = PasteFields;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> PasteFields {
            PasteFields {
                first: frust_core::widget::ChildPod::new(Box::new(PasteField {
                    pasted: self.first.clone(),
                })),
                second: frust_core::widget::ChildPod::new(Box::new(PasteField {
                    pasted: self.second.clone(),
                })),
            }
        }
        fn rebuild(
            &self,
            _prev: &Self,
            _element: &mut PasteFields,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            ChangeFlags::NONE
        }
    }

    /// Which of the fixture's two fields.
    #[derive(Clone, Copy)]
    enum PasteTarget {
        First,
        Second,
    }

    /// A laid-out `RenderRoot` over the two fields, plus their paste records.
    struct PasteHarness {
        root: RenderRoot<(), PasteFieldsView>,
        state: (),
        first: Rc<RefCell<Vec<String>>>,
        second: Rc<RefCell<Vec<String>>>,
    }

    impl PasteHarness {
        fn new() -> Self {
            let mut root: RenderRoot<(), PasteFieldsView> = RenderRoot::new();
            let mut state = ();
            let view = PasteFieldsView {
                first: Rc::new(RefCell::new(Vec::new())),
                second: Rc::new(RefCell::new(Vec::new())),
            };
            let (first, second) = (view.first.clone(), view.second.clone());
            root.rebuild(&mut move |_: &mut ()| view.clone(), &mut state);
            root.layout(Size::new(100.0, 60.0));
            PasteHarness {
                root,
                state,
                first,
                second,
            }
        }

        /// Press a field the way a user does — inside its bounds — which is
        /// what makes it claim the focus session.
        fn press(&mut self, target: PasteTarget) {
            let y = match target {
                PasteTarget::First => 15.0,
                PasteTarget::Second => 45.0,
            };
            let press = InputEvent::Pointer(PointerEvent {
                phase: PointerPhase::Down,
                position: Point::new(50.0, y),
                button: PointerButton::Primary,
            });
            self.root.event(&mut self.state, &press);
        }

        fn dispatch(&mut self, event: &InputEvent) {
            self.root.event(&mut self.state, event);
        }

        /// What each field has been handed so far.
        fn pasted(&self) -> (Vec<String>, Vec<String>) {
            (self.first.borrow().clone(), self.second.borrow().clone())
        }
    }

    #[test]
    fn a_paste_answer_still_lands_when_the_focus_session_never_moved() {
        // The control, and the half that keeps the other half honest: the
        // ordinary paste, where the answer comes back into the same session
        // that asked and must be delivered in full.
        let mut harness = PasteHarness::new();
        harness.press(PasteTarget::First);
        // What `request_clipboard_read` records at the moment the tree asks.
        let asked_in = Some(harness.root.focus_epoch());

        // …and what `user_event` decides when the worker answers.
        let dispatch = paste_answer_dispatch(
            asked_in,
            harness.root.focus_epoch(),
            PasteText("copied text".to_string()),
        )
        .expect("an answer arriving in the session that asked must still dispatch");
        harness.dispatch(&dispatch);

        let (first, second) = harness.pasted();
        assert_eq!(
            first,
            vec!["copied text".to_string()],
            "exactly one paste, with the text the worker read, into the field that asked"
        );
        assert!(second.is_empty(), "{second:?}");
    }

    #[test]
    fn a_paste_answer_is_withheld_once_the_focus_session_has_moved_on() {
        let mut harness = PasteHarness::new();
        harness.press(PasteTarget::First);
        let asked_in = Some(harness.root.focus_epoch());

        // The user moves on while the read is still outstanding. Nothing about
        // the request is replayed — only the tree's focus session moves, and it
        // moves through an honoured claim, the way it does in a running app.
        harness.press(PasteTarget::Second);
        assert_ne!(
            Some(harness.root.focus_epoch()),
            asked_in,
            "fixture precondition: an honoured focus claim moves the session"
        );

        assert!(
            paste_answer_dispatch(
                asked_in,
                harness.root.focus_epoch(),
                PasteText("copied text".to_string()),
            )
            .is_none(),
            "an answer whose session is gone must not become a dispatch"
        );
        let (first, second) = harness.pasted();
        assert!(
            first.is_empty() && second.is_empty(),
            "nothing may be pasted at all: {first:?} {second:?}"
        );

        // What makes the assertion above mean something: the very same answer,
        // dispatched with no session check, does land — in the field the user
        // moved to, which never asked for it. The tree would not have dropped
        // this paste on its own, so the withholding above is the guard's doing
        // and nothing else's.
        harness.dispatch(&paste_input_event(PasteText("copied text".to_string())));
        let (first, second) = harness.pasted();
        assert!(
            first.is_empty(),
            "the field that asked cannot be reached once focus has left it: {first:?}"
        );
        assert_eq!(
            second,
            vec!["copied text".to_string()],
            "unguarded, the clip is typed into the field that never asked"
        );
    }

    // --- brightness_from_winit ---

    #[test]
    fn brightness_from_winit_maps_dark_light_and_defaults() {
        assert_eq!(
            brightness_from_winit(Some(WinitTheme::Dark)),
            Brightness::Dark
        );
        assert_eq!(
            brightness_from_winit(Some(WinitTheme::Light)),
            Brightness::Light
        );
        // No reported preference falls back to Light.
        assert_eq!(brightness_from_winit(None), Brightness::Light);
    }

    // --- provide_context replacement (the app-code theme delivery path) ---

    #[test]
    fn re_providing_theme_context_lets_a_live_flip_win() {
        // The desktop shell re-`provide_context`s the theme under the root owner
        // on every `ThemeChanged`. This proves reactive_graph 0.2's replacement
        // semantics: a second provide of the same type under one owner wins for
        // subsequent `use_context` reads — so a live dark-mode flip is observed
        // (no `RwSignal<Theme>` fallback needed; see the task's note).
        use frust_reactive::{Owner, provide_context, use_context};

        let owner = Owner::new();
        let resolved = owner.with(|| {
            let mut light = Theme::neutral();
            light.brightness = Brightness::Light;
            provide_context(light);

            // A live flip: re-provide a dark theme under the same owner. Same
            // baseline, opposite brightness — the brightness is what the
            // read-back below discriminates on.
            let mut dark = Theme::neutral();
            dark.brightness = Brightness::Dark;
            provide_context(dark);

            use_context::<Theme>()
        });
        assert_eq!(resolved.map(|t| t.brightness), Some(Brightness::Dark));
    }

    #[test]
    fn physical_to_logical_divides_by_scale() {
        // A 2× HiDPI display: a physical (200, 100) cursor is logical (100, 50).
        assert_eq!(
            physical_to_logical(200.0, 100.0, 2.0),
            Point::new(100.0, 50.0)
        );
    }

    #[test]
    fn physical_to_logical_is_identity_at_unit_scale() {
        // A non-HiDPI display: physical and logical coincide.
        assert_eq!(physical_to_logical(37.0, 12.0, 1.0), Point::new(37.0, 12.0));
    }

    // --- map_mouse_button ---

    #[test]
    fn map_mouse_button_maps_left_to_primary() {
        assert_eq!(
            map_mouse_button(MouseButton::Left),
            Some(PointerButton::Primary)
        );
    }

    #[test]
    fn map_mouse_button_maps_right_to_secondary() {
        assert_eq!(
            map_mouse_button(MouseButton::Right),
            Some(PointerButton::Secondary)
        );
    }

    #[test]
    fn map_mouse_button_drops_middle_back_and_forward() {
        // `PointerButton` already models `Middle`, but nothing dispatches it
        // yet — this shell forwards only what v1 specced.
        assert_eq!(map_mouse_button(MouseButton::Middle), None);
        assert_eq!(map_mouse_button(MouseButton::Back), None);
        assert_eq!(map_mouse_button(MouseButton::Forward), None);
    }

    // --- mouse_button_should_dispatch ---

    /// One secondary press/release through the gate, against a caller-owned
    /// latch — the shape `WindowEvent::MouseInput` calls it in.
    fn secondary(phase: PointerPhase, captured: bool, latch: &mut bool) -> bool {
        mouse_button_should_dispatch(PointerButton::Secondary, phase, captured, latch)
    }

    #[test]
    fn an_uncaptured_secondary_press_and_its_release_both_dispatch() {
        let mut latch = false;
        assert!(secondary(PointerPhase::Down, false, &mut latch));
        assert!(secondary(PointerPhase::Up, false, &mut latch));
        // The latch is spent by the release it paired.
        assert!(!latch);
    }

    #[test]
    fn a_secondary_press_is_dropped_while_captured_and_so_is_its_release() {
        // A right-click mid-drag must not disturb the Primary capture it can
        // never have opened — and dropping the press means dropping the
        // release too, or the tree sees an `Up` with no `Down`.
        let mut latch = false;
        assert!(!secondary(PointerPhase::Down, true, &mut latch));
        assert!(!secondary(PointerPhase::Up, true, &mut latch));
        assert!(!secondary(PointerPhase::Up, false, &mut latch));
    }

    #[test]
    fn a_delivered_secondary_press_gets_its_release_even_if_a_capture_opened() {
        // The pairing invariant, and the wedge this gate exists to prevent: the
        // press was delivered while nothing was captured, something captured in
        // between (the widget it opened, or an unrelated one), and the release
        // must still land — otherwise the capture never closes.
        let mut latch = false;
        assert!(secondary(PointerPhase::Down, false, &mut latch));
        assert!(secondary(PointerPhase::Up, true, &mut latch));
        assert!(!latch);
    }

    #[test]
    fn a_secondary_release_without_a_delivered_press_never_dispatches() {
        // A release arriving with a cold latch (a press consumed by a native
        // menu, or one that landed before the window was focused) is not the
        // second half of anything.
        let mut latch = false;
        assert!(!secondary(PointerPhase::Up, false, &mut latch));
        assert!(!secondary(PointerPhase::Up, true, &mut latch));
    }

    #[test]
    fn a_second_secondary_press_re_arms_the_latch_rather_than_stacking() {
        // Two presses in a row (a release lost to the platform) leave the latch
        // describing the *last* press, so exactly one release is ever paired.
        let mut latch = false;
        assert!(secondary(PointerPhase::Down, false, &mut latch));
        assert!(!secondary(PointerPhase::Down, true, &mut latch));
        assert!(!secondary(PointerPhase::Up, false, &mut latch));
    }

    #[test]
    fn primary_always_dispatches_captured_or_not_and_leaves_the_latch_alone() {
        // Primary is the button a capture belongs to, so its own `Down`/`Up`
        // must never be the one this gate drops — and a Primary gesture must
        // not disturb a secondary press waiting for its release.
        let mut latch = true;
        for captured in [false, true] {
            for phase in [PointerPhase::Down, PointerPhase::Up] {
                assert!(mouse_button_should_dispatch(
                    PointerButton::Primary,
                    phase,
                    captured,
                    &mut latch
                ));
            }
        }
        assert!(latch);
    }

    // --- map_scroll_delta ---

    #[test]
    fn map_scroll_delta_negates_wheel_lines() {
        // winit's positive y moves the content down (revealing what is above);
        // frust's scrollables add the delta to an offset that grows to reveal
        // later content, so the sign flips at this boundary.
        assert_eq!(
            map_scroll_delta(MouseScrollDelta::LineDelta(0.0, 1.0), 1.0),
            ScrollDelta::Lines(0.0, -1.0)
        );
        assert_eq!(
            map_scroll_delta(MouseScrollDelta::LineDelta(2.0, -3.0), 1.0),
            ScrollDelta::Lines(-2.0, 3.0)
        );
    }

    #[test]
    fn map_scroll_delta_negates_and_scales_pixel_deltas() {
        // A 2× HiDPI display: a physical (20, 60) trackpad delta is logical
        // (10, 30), negated onto frust's convention.
        assert_eq!(
            map_scroll_delta(
                MouseScrollDelta::PixelDelta(PhysicalPosition::new(20.0, 60.0)),
                2.0
            ),
            ScrollDelta::Pixels(-10.0, -30.0)
        );
    }

    // --- map_wheel_scale_delta / wheel_zoom_chord_held / map_gesture_phase ---

    #[test]
    fn map_wheel_scale_delta_wheel_up_zooms_in() {
        // Unlike `map_scroll_delta`, the sign is NOT flipped: winit's raw
        // positive `y` (the wheel-up gesture) must map directly to
        // `scale_delta > 1.0`.
        let zoom_in = map_wheel_scale_delta(MouseScrollDelta::LineDelta(0.0, 1.0), 1.0);
        assert!(zoom_in > 1.0, "wheel up must zoom in, got {zoom_in}");
        assert_eq!(zoom_in, (WHEEL_SCALE_RATE_PER_LINE).exp());
    }

    #[test]
    fn map_wheel_scale_delta_wheel_down_zooms_out() {
        let zoom_out = map_wheel_scale_delta(MouseScrollDelta::LineDelta(0.0, -1.0), 1.0);
        assert!(zoom_out < 1.0, "wheel down must zoom out, got {zoom_out}");
        assert_eq!(zoom_out, (-WHEEL_SCALE_RATE_PER_LINE).exp());
    }

    #[test]
    fn map_wheel_scale_delta_is_a_no_op_at_zero_lines() {
        assert_eq!(
            map_wheel_scale_delta(MouseScrollDelta::LineDelta(0.0, 0.0), 1.0),
            1.0
        );
    }

    #[test]
    fn map_wheel_scale_delta_scales_pixel_deltas_by_the_line_height() {
        // A 2x HiDPI display: a physical 80px vertical delta is logical 40px,
        // which is exactly one `WHEEL_LINE_PX` (40.0) — one line-equivalent.
        let one_line = map_wheel_scale_delta(
            MouseScrollDelta::PixelDelta(PhysicalPosition::new(0.0, 80.0)),
            2.0,
        );
        assert_eq!(one_line, WHEEL_SCALE_RATE_PER_LINE.exp());
    }

    #[test]
    fn wheel_zoom_chord_held_gates_on_meta_for_macos_and_ctrl_elsewhere() {
        let ctrl_only = Modifiers {
            ctrl: true,
            ..Modifiers::default()
        };
        let meta_only = Modifiers {
            meta: true,
            ..Modifiers::default()
        };
        // macOS: ⌘ (meta) holds the chord, ctrl alone does not.
        assert!(wheel_zoom_chord_held(meta_only, true));
        assert!(!wheel_zoom_chord_held(ctrl_only, true));
        // Linux/Windows: ctrl holds the chord, meta (Super) alone does not —
        // Super+wheel is left for the host's own window-management shortcuts.
        assert!(wheel_zoom_chord_held(ctrl_only, false));
        assert!(!wheel_zoom_chord_held(meta_only, false));
        // Neither modifier held zooms nothing, on either OS.
        assert!(!wheel_zoom_chord_held(Modifiers::default(), true));
        assert!(!wheel_zoom_chord_held(Modifiers::default(), false));
    }

    #[test]
    fn map_gesture_phase_brackets_started_moved_ended() {
        assert_eq!(map_gesture_phase(TouchPhase::Started), ScalePhase::Begin);
        assert_eq!(map_gesture_phase(TouchPhase::Moved), ScalePhase::Update);
        assert_eq!(map_gesture_phase(TouchPhase::Ended), ScalePhase::End);
        assert_eq!(map_gesture_phase(TouchPhase::Cancelled), ScalePhase::End);
    }

    #[test]
    fn finish_propagates_fatal_error_with_context() {
        let err = anyhow::anyhow!("boom").context("frust: failed to create window");
        let result = finish(Some(err));

        let err = result.expect_err("a stashed fatal error must surface as Err");
        assert_eq!(
            err.to_string(),
            "frust: failed to create window",
            "the outermost context string must be preserved"
        );
        assert_eq!(
            err.chain().last().unwrap().to_string(),
            "boom",
            "the underlying cause must still be reachable via the error chain"
        );
    }

    #[test]
    fn finish_is_ok_on_the_happy_path() {
        assert!(finish(None).is_ok());
    }

    // --- map_named_key ---

    #[test]
    fn map_named_key_covers_every_editing_named_key() {
        assert_eq!(map_named_key(WinitNamedKey::Enter), Some(NamedKey::Enter));
        assert_eq!(
            map_named_key(WinitNamedKey::Backspace),
            Some(NamedKey::Backspace)
        );
        assert_eq!(map_named_key(WinitNamedKey::Delete), Some(NamedKey::Delete));
        assert_eq!(
            map_named_key(WinitNamedKey::ArrowLeft),
            Some(NamedKey::ArrowLeft)
        );
        assert_eq!(
            map_named_key(WinitNamedKey::ArrowRight),
            Some(NamedKey::ArrowRight)
        );
        assert_eq!(
            map_named_key(WinitNamedKey::ArrowUp),
            Some(NamedKey::ArrowUp)
        );
        assert_eq!(
            map_named_key(WinitNamedKey::ArrowDown),
            Some(NamedKey::ArrowDown)
        );
        assert_eq!(map_named_key(WinitNamedKey::Home), Some(NamedKey::Home));
        assert_eq!(map_named_key(WinitNamedKey::End), Some(NamedKey::End));
        assert_eq!(map_named_key(WinitNamedKey::Escape), Some(NamedKey::Escape));
        assert_eq!(map_named_key(WinitNamedKey::Tab), Some(NamedKey::Tab));
        // The dedicated hardware clipboard keys.
        assert_eq!(map_named_key(WinitNamedKey::Copy), Some(NamedKey::Copy));
        assert_eq!(map_named_key(WinitNamedKey::Cut), Some(NamedKey::Cut));
        assert_eq!(map_named_key(WinitNamedKey::Paste), Some(NamedKey::Paste));
        assert_eq!(map_named_key(WinitNamedKey::Insert), Some(NamedKey::Insert));
    }

    #[test]
    fn map_named_key_is_none_for_unmapped_named_keys() {
        // No editing semantics for these — they must not be misreported.
        assert_eq!(map_named_key(WinitNamedKey::F1), None);
        assert_eq!(map_named_key(WinitNamedKey::Alt), None);
        assert_eq!(map_named_key(WinitNamedKey::CapsLock), None);
    }

    // --- map_modifiers ---

    #[test]
    fn map_modifiers_translates_each_flag_independently() {
        assert_eq!(
            map_modifiers(ModifiersState::SHIFT),
            Modifiers {
                shift: true,
                ctrl: false,
                alt: false,
                meta: false,
            }
        );
        assert_eq!(
            map_modifiers(ModifiersState::CONTROL | ModifiersState::SUPER),
            Modifiers {
                shift: false,
                ctrl: true,
                alt: false,
                meta: true,
            }
        );
        assert_eq!(map_modifiers(ModifiersState::empty()), Modifiers::default());
    }

    // --- map_key_event ---

    fn mods() -> Modifiers {
        Modifiers {
            shift: true,
            ..Modifiers::default()
        }
    }

    #[test]
    fn map_key_event_maps_a_named_key() {
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::Backspace),
            None,
            ElementState::Pressed,
            false,
            mods(),
            false,
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Named(NamedKey::Backspace),
                modifiers: mods(),
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_maps_resolved_text_as_character() {
        let event = map_key_event(
            &WinitKey::Character("a".into()),
            Some("a"),
            ElementState::Pressed,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Character("a".to_string()),
                modifiers: Modifiers::default(),
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_falls_back_to_the_logical_key_when_ctrl_withholds_text() {
        // Winit's `KeyEvent.text` is documented not populated on every
        // backend while Ctrl is held (an unmodified `Ctrl+C`); the logical
        // `Character` key still carries the unmodified letter, so the chord
        // must still reach the widget rather than being dropped.
        let event = map_key_event(
            &WinitKey::Character("c".into()),
            None,
            ElementState::Pressed,
            false,
            Modifiers {
                ctrl: true,
                ..Modifiers::default()
            },
            false,
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Character("c".to_string()),
                modifiers: Modifiers {
                    ctrl: true,
                    ..Modifiers::default()
                },
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_falls_back_to_the_logical_key_when_meta_withholds_text() {
        // The same fallback applies to `meta` (Cmd on macOS) — `Cmd+C`.
        let event = map_key_event(
            &WinitKey::Character("c".into()),
            None,
            ElementState::Pressed,
            false,
            Modifiers {
                meta: true,
                ..Modifiers::default()
            },
            false,
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Character("c".to_string()),
                modifiers: Modifiers {
                    meta: true,
                    ..Modifiers::default()
                },
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_drops_a_textless_character_with_no_ctrl_or_meta() {
        // The fallback is scoped to the documented ctrl/meta case — a
        // textless `Character` key with neither modifier held stays dropped,
        // exactly as before this fallback existed.
        let event = map_key_event(
            &WinitKey::Character("c".into()),
            None,
            ElementState::Pressed,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(event, None);
    }

    #[test]
    fn map_key_event_ctrl_fallback_still_drops_while_composing() {
        // The composing dedupe rule applies to the fallback path too.
        let event = map_key_event(
            &WinitKey::Character("c".into()),
            None,
            ElementState::Pressed,
            false,
            Modifiers {
                ctrl: true,
                ..Modifiers::default()
            },
            true, // composing
        );
        assert_eq!(event, None);
    }

    #[test]
    fn map_key_event_passes_repeat_through_unfiltered() {
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::ArrowLeft),
            None,
            ElementState::Pressed,
            true,
            Modifiers::default(),
            false,
        );
        assert!(event.expect("named key maps").repeat);
    }

    #[test]
    fn map_key_event_is_none_on_release() {
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::Enter),
            None,
            ElementState::Released,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(event, None);
    }

    #[test]
    fn map_key_event_drops_character_while_composing() {
        // The dedupe rule: a Preedit-active composition suppresses
        // KeyboardInput-derived Character events (Ime::Commit is authoritative).
        let event = map_key_event(
            &WinitKey::Character("a".into()),
            Some("a"),
            ElementState::Pressed,
            false,
            Modifiers::default(),
            true, // composing
        );
        assert_eq!(event, None);
    }

    #[test]
    fn map_key_event_still_maps_named_keys_while_composing() {
        // Only Character events are deduped; named editing keys pass through.
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::Escape),
            None,
            ElementState::Pressed,
            false,
            Modifiers::default(),
            true, // composing
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Named(NamedKey::Escape),
                modifiers: Modifiers::default(),
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_maps_space_to_a_character() {
        // winit models the spacebar as `Named(Space)` carrying a `" "` text
        // payload, never as `Character(" ")` — it must still reach a text widget
        // as the character it types.
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::Space),
            Some(" "),
            ElementState::Pressed,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Character(" ".to_string()),
                modifiers: Modifiers::default(),
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_maps_space_without_a_text_payload() {
        // A platform that reports no resolved text for the spacebar still types
        // a space.
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::Space),
            None,
            ElementState::Pressed,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(
            event,
            Some(KeyEvent {
                key: Key::Character(" ".to_string()),
                modifiers: Modifiers::default(),
                repeat: false,
            })
        );
    }

    #[test]
    fn map_key_event_drops_space_while_composing() {
        // Space takes the character path, so it takes the character dedupe rule
        // with it: `Ime::Commit` is authoritative mid-composition.
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::Space),
            Some(" "),
            ElementState::Pressed,
            false,
            Modifiers::default(),
            true, // composing
        );
        assert_eq!(event, None);
    }

    #[test]
    fn map_key_event_is_none_for_unmapped_named_key_with_no_text() {
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::F1),
            None,
            ElementState::Pressed,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(event, None);
    }

    #[test]
    fn map_key_event_is_none_for_unmapped_named_key_carrying_text() {
        // The character carve-out is Space's alone: any other named key with no
        // editing semantics stays dropped, text payload or not.
        let event = map_key_event(
            &WinitKey::Named(WinitNamedKey::F1),
            Some("\u{f704}"),
            ElementState::Pressed,
            false,
            Modifiers::default(),
            false,
        );
        assert_eq!(event, None);
    }

    // --- ComposeLatch / Ime mapping ---

    #[test]
    fn compose_latch_opens_on_nonempty_preedit() {
        let mut latch = ComposeLatch::default();
        assert!(!latch.is_composing());
        let mapped = latch.observe(&Ime::Preedit("n".to_string(), Some((0, 1))));
        assert!(latch.is_composing());
        assert_eq!(
            mapped,
            ImeEvent::Compose {
                text: "n".to_string(),
                cursor: Some((0, 1)),
            }
        );
    }

    #[test]
    fn compose_latch_closes_on_empty_preedit_preceding_commit() {
        let mut latch = ComposeLatch::default();
        latch.observe(&Ime::Preedit("n".to_string(), Some((0, 1))));
        assert!(latch.is_composing());

        let mapped = latch.observe(&Ime::Preedit(String::new(), None));
        assert!(!latch.is_composing());
        assert_eq!(
            mapped,
            ImeEvent::Compose {
                text: String::new(),
                cursor: None,
            }
        );
    }

    #[test]
    fn compose_latch_closes_on_commit() {
        let mut latch = ComposeLatch::default();
        latch.observe(&Ime::Preedit("n".to_string(), Some((0, 1))));
        let mapped = latch.observe(&Ime::Commit("\u{306a}".to_string()));
        assert!(!latch.is_composing());
        assert_eq!(mapped, ImeEvent::Commit("\u{306a}".to_string()));
    }

    #[test]
    fn compose_latch_closes_on_enabled_and_disabled() {
        let mut latch = ComposeLatch::default();
        latch.observe(&Ime::Preedit("n".to_string(), Some((0, 1))));

        let mapped = latch.observe(&Ime::Disabled);
        assert!(!latch.is_composing());
        assert_eq!(mapped, ImeEvent::Disabled);

        latch.observe(&Ime::Preedit("n".to_string(), Some((0, 1))));
        let mapped = latch.observe(&Ime::Enabled);
        assert!(!latch.is_composing());
        assert_eq!(mapped, ImeEvent::Enabled);
    }

    // --- ime_purpose_for ---
    //
    // Pins the desktop shell's (deliberately thin) response to the
    // content-type hint: this is the honest "winit offers almost nothing"
    // outcome the task anticipated, recorded here so a later reader finds a
    // considered decision rather than a silently missed field. See
    // `ime_purpose_for`'s doc comment for why `Password` and `Terminal` are
    // the only variants that map to anything but `Normal`, and why even the
    // `Password` mapping only reaches Wayland.

    #[test]
    fn ime_purpose_maps_password_to_the_winit_password_purpose() {
        assert_eq!(
            ime_purpose_for(ImeContentType::Password),
            ImePurpose::Password
        );
    }

    #[test]
    fn ime_purpose_maps_terminal_to_the_winit_terminal_purpose() {
        assert_eq!(
            ime_purpose_for(ImeContentType::Terminal),
            ImePurpose::Terminal
        );
    }

    #[test]
    fn ime_purpose_has_no_distinct_mapping_for_normal_or_no_suggestions() {
        // `ImePurpose` has no "suppress suggestions" variant, so `NoSuggestions`
        // falls back to `Normal` just like `Normal` itself — only the secret
        // and terminal content types change the winit call.
        assert_eq!(ime_purpose_for(ImeContentType::Normal), ImePurpose::Normal);
        assert_eq!(
            ime_purpose_for(ImeContentType::NoSuggestions),
            ImePurpose::Normal
        );
    }

    /// Pins [`ImeSync`]'s default so a fresh shell starts believing it has
    /// already told winit `ImePurpose::Normal` — matching winit's own
    /// documented default, so the first real `Password` field is what
    /// triggers the first `set_ime_purpose` call, not startup.
    #[test]
    fn ime_sync_defaults_to_the_normal_purpose() {
        assert_eq!(ImeSync::default().purpose, ImePurpose::Normal);
    }

    // --- cursor: framework request -> winit shape, and the change gate ---
    //
    // The mapping is exhaustive over the framework's own vocabulary and the gate
    // is what keeps `Window::set_cursor` off the per-mouse-motion path; both are
    // pure, so neither needs a live window.

    #[test]
    fn every_framework_cursor_maps_to_its_winit_counterpart() {
        for (ours, theirs) in [
            (CursorIcon::Default, WinitCursorIcon::Default),
            (CursorIcon::Pointer, WinitCursorIcon::Pointer),
            (CursorIcon::Text, WinitCursorIcon::Text),
            (CursorIcon::Grab, WinitCursorIcon::Grab),
            (CursorIcon::Grabbing, WinitCursorIcon::Grabbing),
            (CursorIcon::ColResize, WinitCursorIcon::ColResize),
            (CursorIcon::RowResize, WinitCursorIcon::RowResize),
            (CursorIcon::NotAllowed, WinitCursorIcon::NotAllowed),
        ] {
            assert_eq!(
                winit_cursor_for(ours),
                theirs,
                "{ours:?} must reach the platform as {theirs:?}"
            );
        }
    }

    #[test]
    fn the_cursor_is_pushed_to_winit_only_on_a_change() {
        // A resolved cursor that has not moved says nothing to the platform — the
        // resolution re-runs on every pointer `Move`, so this gate is what stops a
        // platform call per mouse motion.
        assert_eq!(
            cursor_change_to_apply(CursorIcon::Default, CursorIcon::Default),
            None,
            "an unmoved cursor issues no winit call"
        );
        assert_eq!(
            cursor_change_to_apply(CursorIcon::Pointer, CursorIcon::Pointer),
            None
        );

        // Both directions of a real change fire, including the return to Default —
        // a widget releasing its request must actually restore the arrow.
        assert_eq!(
            cursor_change_to_apply(CursorIcon::Default, CursorIcon::Pointer),
            Some(WinitCursorIcon::Pointer)
        );
        assert_eq!(
            cursor_change_to_apply(CursorIcon::Pointer, CursorIcon::Default),
            Some(WinitCursorIcon::Default),
            "dropping a request restores the platform arrow"
        );
    }

    // --- build_tree_update ---
    //
    // Pure-function coverage of the `SemanticsUpdate` -> `accesskit::TreeUpdate`
    // assembly; no winit event loop or live adapter needed.

    #[test]
    fn build_tree_update_assembles_nodes_tree_and_focus() {
        let root_id = NodeId(1);
        let child_id = NodeId(2);
        let mut root_node = Node::new(Role::Window);
        root_node.set_children(vec![child_id]);
        let child_node = Node::new(Role::Button);

        let update = SemanticsUpdate {
            nodes: vec![(root_id, root_node), (child_id, child_node)],
            root: root_id,
            focus: Some(child_id),
        };

        let tree_update = build_tree_update(&update, 1.0);
        assert_eq!(tree_update.nodes.len(), 2);
        assert_eq!(tree_update.tree, Some(Tree::new(root_id)));
        assert_eq!(tree_update.tree_id, TreeId::ROOT);
        assert_eq!(tree_update.focus, child_id);
    }

    #[test]
    fn build_tree_update_defaults_focus_to_root_when_nothing_focused() {
        let root_id = NodeId(1);
        let update = SemanticsUpdate {
            nodes: vec![(root_id, Node::new(Role::Window))],
            root: root_id,
            focus: None,
        };

        let tree_update = build_tree_update(&update, 1.0);
        // SemanticsUpdate::focus_id() defaults to root — accesskit's `focus`
        // field is non-optional and must always name some target.
        assert_eq!(tree_update.focus, root_id);
    }

    // --- build_tree_update: HiDPI root transform ---
    //
    // `RenderRoot::semantics` reports bounds in LOGICAL pixels; AccessKit
    // expects PHYSICAL pixels (see `build_tree_update`'s doc). These pin the
    // scale-to-transform stamp: identity/no-op at 1.0 (the Linux/X11
    // default), `Affine::scale(2.0)` on the root only at 2.0, with child
    // bounds left untouched (they inherit the root's transform via
    // accesskit's ancestor-chain coordinate-space rule instead of being
    // rescaled directly).

    #[test]
    fn build_tree_update_at_scale_one_stamps_no_transform() {
        let root_id = NodeId(1);
        let update = SemanticsUpdate {
            nodes: vec![(root_id, Node::new(Role::Window))],
            root: root_id,
            focus: None,
        };

        let tree_update = build_tree_update(&update, 1.0);
        let (_, root_node) = &tree_update.nodes[0];
        // accesskit's own guidance: `None` rather than an explicit identity
        // transform for a node that doesn't need one — either reading is a
        // no-op, but this pins which one `build_tree_update` produces.
        assert!(
            root_node.transform().is_none(),
            "scale 1.0 must not stamp a transform onto the root"
        );
    }

    #[test]
    fn build_tree_update_at_scale_two_stamps_root_transform_only() {
        let root_id = NodeId(1);
        let child_id = NodeId(2);
        let mut root_node = Node::new(Role::Window);
        root_node.set_children(vec![child_id]);
        let mut child_node = Node::new(Role::Button);
        let child_bounds = AccessKitRect::new(1.0, 2.0, 3.0, 4.0);
        child_node.set_bounds(child_bounds);

        let update = SemanticsUpdate {
            nodes: vec![(root_id, root_node), (child_id, child_node)],
            root: root_id,
            focus: None,
        };

        let tree_update = build_tree_update(&update, 2.0);

        let (found_root_id, found_root_node) = &tree_update.nodes[0];
        assert_eq!(*found_root_id, root_id);
        assert_eq!(
            found_root_node.transform(),
            Some(&AccessKitAffine::scale(2.0)),
            "scale 2.0 must stamp Affine::scale(2.0) onto the root"
        );

        let (found_child_id, found_child_node) = &tree_update.nodes[1];
        assert_eq!(*found_child_id, child_id);
        assert!(
            found_child_node.transform().is_none(),
            "only the root gets a transform — children inherit it through the \
             ancestor chain rather than being rescaled directly"
        );
        // The child's own bounds stay in logical pixels — unrescaled by
        // `build_tree_update` — because they're relative to the root's
        // transform, not the tree's untransformed container.
        assert_eq!(found_child_node.bounds(), Some(child_bounds));
    }

    // --- the default-theme precedence ladder (seed / appearance / override) ---
    //
    // Every assertion below drives the SAME ladder helpers (`base_theme`,
    // `reverted_theme` via `theme_after_override_poll`,
    // `follow_platform_brightness`) the production seed (`run_desktop`'s
    // `theme:` field), appearance (`WindowEvent::ThemeChanged`) and
    // override-poll (`RedrawRequested`) arms call. That sharing is the whole
    // point: a test that recomputed the ladder in its own body would stay green
    // if one of those arms regressed to an unconditional `Theme::neutral()`.
    //
    // What it does NOT cover: how a production arm *composes* those helpers —
    // `base_theme(default_theme())` at the seed site, versus a
    // default-discarding `base_theme(None)`. Both type-check and both drive the
    // same helper, so no assertion here can tell them apart.
    // `crates/frust/tests/theme_ladder_conformance.rs` pins that other half
    // instead: that each arm still calls these helpers, that the seed site
    // still passes `default_theme()` into `base_theme`, and that the two mobile
    // shells' helper copies stay identical to the ones exercised here.

    /// A stand-in for the base theme a design-system plugin seeds through
    /// `set_default_theme`.
    ///
    /// Deliberately **not** `Theme::neutral()`: the ladder's whole point is
    /// that a seeded base displaces the shell's built-in floor, so every
    /// assertion below that spells `assert_ne!(.., Theme::neutral())` — or
    /// reads a seeded value back — needs a theme the floor cannot be confused
    /// with. The visible edit is the design-language tag, the one field a
    /// third-party design system is expected to claim (`DesignLanguage` is
    /// `#[non_exhaustive]` with exactly this `Custom` variant for it); every
    /// token stays the neutral baseline's, so no catalog is named here.
    fn seeded_design_system_theme() -> Theme {
        Theme::builder(Theme::neutral())
            .design_language(DesignLanguage::Custom("test-design-system"))
            .build()
    }

    #[test]
    fn an_unseeded_shell_starts_on_the_builtin_fallback_at_the_platform_brightness() {
        // Behavior 1. Nothing seeded: the seed site lands on the shell's own
        // built-in, design-language-free floor...
        let mut theme = base_theme(None);
        assert_eq!(theme, Theme::neutral());

        // ...and the platform's first appearance report drives brightness
        // (`resumed`'s seed, then every `ThemeChanged`), so the fallback's own
        // starting brightness never leaks onto a dark-preference platform.
        follow_platform_brightness(&mut theme, false, brightness_from_winit(None));
        assert_eq!(theme, Theme::neutral().with_brightness(Brightness::Light));
        follow_platform_brightness(
            &mut theme,
            false,
            brightness_from_winit(Some(WinitTheme::Dark)),
        );
        assert_eq!(theme, Theme::neutral().with_brightness(Brightness::Dark));
    }

    #[test]
    fn a_seeded_default_is_the_base_and_still_follows_platform_brightness() {
        // Behavior 2. A design system's `set_default_theme` supplies the base...
        let seeded = seeded_design_system_theme();
        let mut theme = base_theme(Some(seeded.clone()));
        assert_eq!(theme, seeded);
        // ...in place of the built-in floor, not layered over it.
        assert_ne!(theme, Theme::neutral());

        // ...and unlike an app-forced override it does NOT pin brightness: the
        // appearance arm keeps flipping the seeded base in place, both ways.
        follow_platform_brightness(
            &mut theme,
            false,
            brightness_from_winit(Some(WinitTheme::Dark)),
        );
        assert_eq!(theme, seeded.clone().with_brightness(Brightness::Dark));
        follow_platform_brightness(
            &mut theme,
            false,
            brightness_from_winit(Some(WinitTheme::Light)),
        );
        assert_eq!(theme, seeded.with_brightness(Brightness::Light));
    }

    #[test]
    fn an_app_theme_override_beats_a_seeded_default_and_pins_brightness() {
        // Behavior 3. The override poll's `Some(Some(theme))` arm takes the
        // forced theme wholesale. The suppliers panic rather than answer, which
        // proves more than an inequality could: the arm cannot even observe the
        // seeded default or the platform brightness, so no seeded value and no
        // platform preference can influence what an override resolves to.
        let forced = Theme::neutral().with_brightness(Brightness::Light);
        let decided = theme_after_override_poll(
            Some(Some(forced.clone())),
            || panic!("an active override must not consult the seeded default"),
            || panic!("an active override must not consult the platform brightness"),
        );
        assert_eq!(decided, Some((forced, true)));

        // ...and it keeps winning against a *later* live platform flip
        // (`ThemeChanged`'s override-wins rule), exactly where the seeded
        // default of the test above followed the platform instead. The
        // distinction that must survive here is brightness, not identity:
        // `Light` forced against a `Dark` platform report.
        let mut active = Theme::neutral().with_brightness(Brightness::Light);
        follow_platform_brightness(&mut active, true, Brightness::Dark);
        assert_eq!(active.brightness, Brightness::Light);
    }

    #[test]
    fn clearing_an_override_reverts_to_the_seeded_default_not_the_builtin() {
        // Behavior 4. The `Some(None)` arm with a design system's default
        // seeded: the revert lands on THAT base at the window's current
        // brightness — not on the built-in fallback, and not on the cleared
        // override's pinned brightness.
        let seeded = seeded_design_system_theme();
        let decided = theme_after_override_poll(
            Some(None),
            || Some(seeded.clone()),
            || brightness_from_winit(Some(WinitTheme::Dark)),
        );
        assert_eq!(
            decided,
            Some((seeded.with_brightness(Brightness::Dark), false))
        );
        // Spelled out, since this is the arm the ladder exists for: a seeded
        // shell must NOT revert to the built-in fallback.
        assert_ne!(
            decided.map(|(theme, _)| theme),
            Some(Theme::neutral().with_brightness(Brightness::Dark))
        );
    }

    #[test]
    fn clearing_an_override_with_nothing_seeded_reverts_to_the_builtin() {
        // Behavior 5. The same arm with an empty slot: the built-in fallback at
        // the platform's brightness.
        let decided = theme_after_override_poll(
            Some(None),
            || None,
            || brightness_from_winit(Some(WinitTheme::Dark)),
        );
        assert_eq!(
            decided,
            Some((Theme::neutral().with_brightness(Brightness::Dark), false))
        );
    }

    #[test]
    fn a_poll_reporting_no_change_leaves_the_active_theme_alone() {
        // The `None` arm: no `set_app_theme`/`clear_app_theme` since the last
        // frame, so the shell must not touch its theme — and must pay neither
        // the process-global slot read nor the window appearance query, both of
        // which run on every frame if this arm ever stops being lazy.
        let decided = theme_after_override_poll(
            None,
            || panic!("an unchanged poll must not read the process-global default slot"),
            || panic!("an unchanged poll must not query the window's appearance"),
        );
        assert_eq!(decided, None);
    }

    #[test]
    fn a_seeded_default_reaches_both_ladder_sites_through_the_process_global_slot() {
        // The wiring the argument-taking helpers above cannot check: what the
        // production sites actually pass is `frust_shell_common::default_theme`,
        // so a plugin's `set_default_theme` really does reach both the seed and
        // the revert.
        //
        // `theme_default` deliberately exposes no reset (a shell needs the same
        // seeded base again when `clear_app_theme` reverts an override, so the
        // slot is non-destructive), which is why this must remain the ONLY test in this
        // binary that writes it — `the_default_slot_has_exactly_one_test_writer`
        // pins that. Asserting the pristine state first turns a future second
        // writer into a loud failure here instead of a silent order dependency
        // in whichever test happens to run after it.
        assert_eq!(
            default_theme(),
            None,
            "another test in this binary seeded the process-global default slot first — \
             the slot has no reset, so tests that read it cannot be order-independent"
        );

        let seeded = seeded_design_system_theme();
        frust_shell_common::set_default_theme(seeded.clone());

        // The same composition the seed site (`run_desktop`'s `theme:` field)
        // performs — re-typed here, not shared with it, so this asserts only
        // that the composition resolves the seeded default, never that the
        // production site still spells it this way. That second half is
        // `theme_ladder_conformance.rs`'s
        // `every_shell_seeds_base_theme_from_the_default_slot` source scan.
        assert_eq!(base_theme(default_theme()), seeded);
        // ...and the revert arm, reading that same slot through the same
        // supplier the production arm passes.
        assert_eq!(
            theme_after_override_poll(Some(None), default_theme, || Brightness::Dark),
            Some((seeded.with_brightness(Brightness::Dark), false))
        );
    }

    #[test]
    fn the_default_slot_has_exactly_one_test_writer() {
        // Pins the uniqueness the test above depends on. A plain substring scan
        // of this very file (the `print_free_cores.rs`/`surface_mode_conformance.rs`
        // idiom — this repo has no lint-plugin tooling), not a parser: every
        // real call sits on its own statement line and comment-only lines (every
        // doc mention of the seam) are stripped. The needle is assembled from
        // two pieces so this line is not itself a hit.
        let needle = concat!("set_default_theme", "(");
        let writers = include_str!("app_handler.rs")
            .lines()
            .filter(|line| !line.trim_start().starts_with("//"))
            .filter(|line| line.contains(needle))
            .count();
        assert_eq!(
            writers, 1,
            "the process-global default-theme slot has no reset, so exactly one test in this \
             binary may write it (found {writers}); serialize them behind a lock the way \
             `frust-shell-common::theme_override`'s own tests do, or fold the new assertion \
             into the existing writer"
        );
    }

    // --- Event dispatch runs under the reactive root Owner -------------------
    //
    // Every shell wrapped its per-frame *rebuild* in
    // `ReactiveRuntime::with_owner` but left *event dispatch* unwrapped, so a
    // press/key/IME handler ran with `Owner::current() == None` and every
    // `use_context::<T>()` inside it resolved to `None` — including for the
    // `Theme`/`WindowMetrics` the shell itself provides. `Owner::with` restores
    // the previous owner on return, so nothing carried over from the rebuild.
    //
    // These drive `event_under_owner` (the production helper `dispatch` calls)
    // against a real `RenderRoot`, and pin the pre-fix shape as the negative
    // control — the `app_tree.rs` root-owner pair's idiom.

    use std::cell::RefCell;
    use std::rc::Rc;

    use std::sync::Arc;

    use frust_core::event::{EventCtx, EventResult, PointerEvent, PointerPhase};
    use frust_core::layout::BoxConstraints;
    use frust_core::view::BuildCtx;
    use frust_core::widget::{LayoutCtx, PaintCtx, Widget};
    use frust_core::{ChangeFlags, PaintScene, RenderRoot, View};
    use frust_reactive::{FrameWaker, ReactiveRuntime, RwSignal, TrackedScope, use_context};
    use kurbo::Size;
    use reactive_graph::owner::expect_context;
    use reactive_graph::traits::{Get, Set};

    use super::{InputEvent, event_under_owner, provide_context};

    /// The context value the shell provides under the root owner (a stand-in
    /// for the real `Theme`/`WindowMetrics` deliveries) and a handler reads back.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    struct ProbeCtx(u32);

    /// What one event pass observed, recorded by [`ProbeWidget::event`].
    #[derive(Debug, Default)]
    struct Observed {
        /// `use_context::<ProbeCtx>()` — the non-panicking form, and the only
        /// one app code can reach (the `frust` facade re-exports `use_context`
        /// but no `expect_context`).
        used: Option<u32>,
        /// The panic message `reactive_graph::expect_context` produced, or
        /// `None` if it returned normally.
        expect_panic: Option<String>,
    }

    /// Recording sink shared with the widget's handler.
    type Seen = Rc<RefCell<Observed>>;

    /// A leaf widget whose `event` handler does what an app's `.on_press`
    /// closure would: read a context, and read a signal.
    struct ProbeWidget {
        seen: Seen,
        /// Read with `.get()` from inside the handler — the read that must NOT
        /// register a dependency for the frame's rebuild scope.
        handler_signal: RwSignal<u32>,
    }

    impl Widget for ProbeWidget {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(Size::new(40.0, 20.0))
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, _ctx: &mut EventCtx, _event: &InputEvent) -> EventResult {
            let used = use_context::<ProbeCtx>().map(|c| c.0);
            let expect_panic =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(expect_context::<ProbeCtx>))
                    .err()
                    .map(|payload| match payload.downcast::<String>() {
                        Ok(msg) => *msg,
                        Err(_) => "<non-string panic payload>".to_string(),
                    });
            let _ = self.handler_signal.get();
            *self.seen.borrow_mut() = Observed { used, expect_panic };
            EventResult::Handled
        }
    }

    struct ProbeView {
        seen: Seen,
        handler_signal: RwSignal<u32>,
    }

    impl View<()> for ProbeView {
        type Element = ProbeWidget;
        fn build(&self, _ctx: &mut BuildCtx<'_>) -> ProbeWidget {
            ProbeWidget {
                seen: self.seen.clone(),
                handler_signal: self.handler_signal,
            }
        }
        fn rebuild(
            &self,
            _prev: &Self,
            element: &mut ProbeWidget,
            _ctx: &mut BuildCtx<'_>,
        ) -> ChangeFlags {
            element.seen = self.seen.clone();
            ChangeFlags::NONE
        }
    }

    /// One primary-button press at the widget's centre.
    fn press() -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase: PointerPhase::Down,
            position: kurbo::Point::new(20.0, 10.0),
            button: PointerButton::Primary,
        })
    }

    /// Build the shell-shaped fixture: the runtime, a root-provided context, a
    /// laid-out `RenderRoot` over `ProbeView`, and the frame `TrackedScope`
    /// (already tracking `view_signal` through one rebuild, exactly as
    /// `RedrawRequested` leaves it).
    #[expect(
        clippy::type_complexity,
        reason = "test fixture tuple, read once below"
    )]
    fn fixture() -> (
        &'static ReactiveRuntime,
        RenderRoot<(), ProbeView>,
        Seen,
        TrackedScope,
        RwSignal<u32>,
        RwSignal<u32>,
    ) {
        let waker: FrameWaker = Arc::new(|| {});
        let runtime = ReactiveRuntime::init(waker);
        runtime.with_owner(|| provide_context(ProbeCtx(7)));

        let (view_signal, handler_signal) =
            runtime.with_owner(|| (RwSignal::new(0u32), RwSignal::new(0u32)));
        let seen: Seen = Rc::new(RefCell::new(Observed::default()));

        let mut root: RenderRoot<(), ProbeView> = RenderRoot::new();
        let scope = TrackedScope::new();
        let seen_for_logic = seen.clone();
        let mut build = move |_state: &mut ()| {
            // A view read, the way a real `build`/`Component::build` reads
            // state — this is the subscription the frame loop depends on.
            let _ = view_signal.get();
            ProbeView {
                seen: seen_for_logic.clone(),
                handler_signal,
            }
        };
        // The production rebuild wrap, verbatim.
        runtime.with_owner(|| scope.track(|| root.rebuild(&mut build, &mut ())));
        root.layout(Size::new(100.0, 100.0));

        (runtime, root, seen, scope, view_signal, handler_signal)
    }

    /// The negative control, and the bug as it shipped: dispatching the event
    /// pass with no ambient owner (the pre-fix `self.root.event(...)` shape)
    /// resolves every context to `None`, and the panicking form panics.
    #[test]
    fn event_pass_without_the_owner_wrap_sees_no_context() {
        let (_runtime, mut root, seen, _scope, _view_signal, _handler_signal) = fixture();

        // `expect_context`'s panic is caught inside the handler; mute the
        // default hook so its backtrace line doesn't pollute the test output.
        let hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let outcome = root.event(&mut (), &press());
        std::panic::set_hook(hook);

        assert!(outcome.handled, "the probe widget consumed the press");
        let seen = seen.borrow();
        assert_eq!(
            seen.used, None,
            "pre-fix: an unwrapped event pass has no current Owner, so \
             use_context resolves None even for a context the shell provided"
        );
        // The panicking form's message, as actually observed on this path:
        //
        //   Location { file: ".../core/src/ops/function.rs", line: 250, column: 5 }
        //   expected context of type
        //   "frust_shell_desktop::app_handler::tests::ProbeCtx" to be present
        //
        // (the `Location` names core's `FnOnce::call_once` shim because
        // `expect_context` is handed to `catch_unwind` as a function item, so
        // its `#[track_caller]` resolves there) — only the message tail is
        // pinned below, since the prefix is a std implementation detail.
        let panic_msg = seen
            .expect_panic
            .as_deref()
            .expect("pre-fix: expect_context must panic with no ambient Owner");
        assert!(
            panic_msg.ends_with("to be present") && panic_msg.contains("expected context of type"),
            "unexpected panic message: {panic_msg}"
        );
    }

    /// The fix: the same press delivered through `event_under_owner` resolves
    /// the shell-provided context.
    #[test]
    fn event_pass_under_the_owner_wrap_resolves_root_context() {
        let (runtime, mut root, seen, _scope, _view_signal, _handler_signal) = fixture();

        let outcome = event_under_owner(runtime, &mut root, &mut (), &press());

        assert!(outcome.handled, "the probe widget consumed the press");
        let seen = seen.borrow();
        assert_eq!(
            seen.used,
            Some(7),
            "a handler must resolve a context the shell provided under the root \
             owner"
        );
        assert_eq!(
            seen.expect_panic, None,
            "the panicking form must no longer panic from an event handler"
        );
    }

    /// The cost side of the wrap: it installs an `Owner`, never a
    /// `TrackedScope`. A signal read inside a handler must not become a
    /// dependency of the frame's rebuild scope (a rebuild storm), and the
    /// dependencies the rebuild recorded must survive the event pass intact.
    #[test]
    fn event_pass_neither_adds_nor_drops_rebuild_dependencies() {
        let (runtime, mut root, _seen, scope, view_signal, handler_signal) = fixture();

        assert!(
            !scope.is_dirty(),
            "fixture precondition: the rebuild scope is clean"
        );

        event_under_owner(runtime, &mut root, &mut (), &press());
        assert!(
            !scope.is_dirty(),
            "the event pass itself must not dirty the frame scope"
        );

        // (1) No new dependency: the handler read `handler_signal`, but it did
        // so with no observer installed, so a later write schedules nothing.
        handler_signal.set(1);
        assert!(
            !scope.is_dirty(),
            "a signal read only inside an event handler must not subscribe the \
             frame scope — that would schedule a rebuild the pre-fix shell never \
             scheduled (a rebuild storm)"
        );

        // (2) No dropped dependency: the rebuild's own subscription still
        // stands. `TrackedScope::track` clears recorded sources on entry, so
        // this is what would break if the event pass were wrapped in `track`.
        view_signal.set(1);
        assert!(
            scope.is_dirty(),
            "the rebuild's tracked read must still wake the frame loop after an \
             event pass"
        );
    }

    // --- the desktop config / extension seam ---
    //
    // What is reachable without a live event loop: the config→attributes→hook
    // composition (`window_attributes`) and the brightness change gate. The
    // three hooks whose call sites need a real window or a running loop
    // (`on_event_loop_builder` in `run_desktop_with`, `on_window_created` and
    // `pump`/`on_close_requested` inside the winit callbacks) are documented at
    // their call sites instead — winit exposes no way to construct an
    // `ActiveEventLoop` or a `Window` outside `run_app`.

    /// A recording extension: proves the production attribute path really runs
    /// the hook (and runs it *last*, so a per-OS shell can override what the
    /// core assembled).
    #[derive(Debug, Default)]
    struct SpyExtensions {
        attributes_calls: usize,
        override_title: Option<&'static str>,
    }

    impl DesktopExtensions for SpyExtensions {
        fn on_window_attributes(&mut self, attributes: WindowAttributes) -> WindowAttributes {
            self.attributes_calls += 1;
            match self.override_title {
                Some(title) => attributes.with_title(title),
                None => attributes,
            }
        }
    }

    #[test]
    fn window_attributes_default_to_the_historical_preview_window() {
        // The `WINDOW_TITLE` const this shell used to hardcode now arrives via
        // the default config, so the zero-config preview is unchanged.
        let attributes = window_attributes(&DesktopConfig::default(), &mut NoExtensions);
        assert_eq!(attributes.title, "Frust");
        assert_eq!(attributes.inner_size, Some(super::INITIAL_SIZE.into()));
        assert!(
            !attributes.visible,
            "the window must be created hidden — the accessibility adapter is \
             constructed before it is shown"
        );
    }

    #[test]
    fn window_attributes_take_the_title_from_the_config() {
        let config = DesktopConfig::new().with_app_name("Huddle");
        let attributes = window_attributes(&config, &mut NoExtensions);
        assert_eq!(attributes.title, "Huddle");
    }

    #[test]
    fn window_attributes_run_the_extension_hook_last() {
        let mut extensions = SpyExtensions {
            override_title: Some("overridden"),
            ..SpyExtensions::default()
        };
        let config = DesktopConfig::new().with_app_name("Huddle");
        let attributes = window_attributes(&config, &mut extensions);

        assert_eq!(extensions.attributes_calls, 1);
        assert_eq!(
            attributes.title, "overridden",
            "the hook sees the core's attributes and its result wins — the only \
             chance a per-OS shell gets at pre-create-only attributes"
        );
    }

    // --- the FRUST_WINDOW_SIZE / FRUST_WINDOW_MAXIMIZED measurement knobs ---
    //
    // The parsers take explicit `Option<&str>` rather than touching the
    // process environment (the `render_thread_kill_switch`/`frame_gate`
    // precedent) — env-var tests that mutated `std::env` would race every
    // other test in this binary sharing the same process.

    #[test]
    fn parse_window_size_valid() {
        assert_eq!(
            parse_window_size(Some("2560x1440")),
            LogicalSize::new(2560, 1440)
        );
        // Surrounding whitespace on the whole value is trimmed, matching
        // every other `FRUST_*` string knob's parser.
        assert_eq!(
            parse_window_size(Some("  1280x720  ")),
            LogicalSize::new(1280, 720)
        );
        // The smallest legal value: both components at least 1.
        assert_eq!(parse_window_size(Some("1x1")), LogicalSize::new(1, 1));
    }

    #[test]
    fn parse_window_size_missing_falls_back_silently() {
        assert_eq!(parse_window_size(None), super::INITIAL_SIZE);
        assert_eq!(parse_window_size(Some("")), super::INITIAL_SIZE);
        assert_eq!(parse_window_size(Some("   ")), super::INITIAL_SIZE);
    }

    #[test]
    fn parse_window_size_zero_component_falls_back() {
        assert_eq!(parse_window_size(Some("0x600")), super::INITIAL_SIZE);
        assert_eq!(parse_window_size(Some("800x0")), super::INITIAL_SIZE);
        assert_eq!(parse_window_size(Some("0x0")), super::INITIAL_SIZE);
    }

    #[test]
    fn parse_window_size_invalid_falls_back() {
        for invalid in [
            "800",                      // no separator
            "800x",                     // missing height
            "x600",                     // missing width
            "800x600x400",              // extra separator
            "800X600",                  // wrong case separator
            "800.5x600",                // not an integer
            "-800x600",                 // signed
            "800 x 600",                // inner whitespace around the separator
            "eightx600",                // non-digit
            "800xsix",                  // non-digit
            "99999999999999999999x600", // overflows u32
        ] {
            assert_eq!(
                parse_window_size(Some(invalid)),
                super::INITIAL_SIZE,
                "expected {invalid:?} to fall back to the default size"
            );
        }
    }

    #[test]
    fn parse_window_maximized_recognises_one_and_true() {
        assert!(parse_window_maximized(Some("1")));
        assert!(parse_window_maximized(Some("true")));
        assert!(parse_window_maximized(Some("TRUE")));
        assert!(parse_window_maximized(Some("  True  ")));
    }

    #[test]
    fn parse_window_maximized_defaults_to_false() {
        assert!(!parse_window_maximized(None));
        assert!(!parse_window_maximized(Some("")));
        assert!(!parse_window_maximized(Some("0")));
        assert!(!parse_window_maximized(Some("yes")));
        assert!(!parse_window_maximized(Some("2")));
    }

    #[test]
    fn resolved_window_knob_runtime_wins_over_compile_time() {
        assert_eq!(
            resolved_window_knob(Some("800x600"), Some("2560x1440".to_string())),
            (Some("2560x1440".to_string()), WindowKnobSource::Env)
        );
    }

    #[test]
    fn resolved_window_knob_empty_runtime_falls_through_to_compile_time() {
        assert_eq!(
            resolved_window_knob(Some("800x600"), Some(String::new())),
            (Some("800x600".to_string()), WindowKnobSource::Define)
        );
    }

    #[test]
    fn resolved_window_knob_neither_set_is_default() {
        assert_eq!(
            resolved_window_knob(None, None),
            (None, WindowKnobSource::Default)
        );
    }

    #[test]
    fn apply_window_size_sets_inner_size_and_leaves_maximized_off_by_default() {
        let attributes = apply_window_size(
            WindowAttributes::default(),
            LogicalSize::new(1280, 720),
            false,
        );
        assert_eq!(
            attributes.inner_size,
            Some(LogicalSize::new(1280, 720).into())
        );
        assert!(!attributes.maximized);
    }

    #[test]
    fn apply_window_size_sets_maximized_when_requested() {
        let attributes = apply_window_size(WindowAttributes::default(), super::INITIAL_SIZE, true);
        assert!(
            attributes.maximized,
            "FRUST_WINDOW_MAXIMIZED=1 must set WindowAttributes::maximized — the size is still \
             applied (documented), but the OS ignores it for a window maximized at creation"
        );
    }

    // --- the theme-brightness hook's change gate ---

    #[test]
    fn the_first_resolved_brightness_is_always_reported() {
        // Nothing reported yet (`resumed`'s seed): the extension learns the
        // starting brightness rather than having to wait for a flip.
        assert_eq!(
            brightness_change_to_notify(None, Brightness::Light),
            Some(Brightness::Light)
        );
    }

    #[test]
    fn an_unchanged_brightness_reports_nothing() {
        // `apply_theme` also runs for theme re-pushes that move no brightness
        // (an override swapping one dark theme for another), and the hook's
        // contract is "actually changed".
        assert_eq!(
            brightness_change_to_notify(Some(Brightness::Dark), Brightness::Dark),
            None
        );
    }

    #[test]
    fn a_changed_brightness_is_reported() {
        assert_eq!(
            brightness_change_to_notify(Some(Brightness::Light), Brightness::Dark),
            Some(Brightness::Dark)
        );
        assert_eq!(
            brightness_change_to_notify(Some(Brightness::Dark), Brightness::Light),
            Some(Brightness::Light)
        );
    }
}