guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
pub mod animation;
mod app_state;
pub mod backdrop;
mod blur;
pub mod clock;
pub mod compositor;
mod deferred;
pub(crate) mod finite;
pub mod heap;
mod image_decode;
pub mod image_metadata;
mod ingress;
mod jobs;
pub mod keyboard;
pub mod layout;
pub mod outputs;
pub mod pivot;
pub mod reactive;
mod region;
pub mod render_stats;
mod secret;
pub mod session_lock;
pub mod shape;
pub mod surface;
mod surface_manager;
#[cfg(feature = "testing")]
pub mod testing;
pub mod transform;
pub mod tree;
pub mod widget_ref;
pub mod widgets;

// These modules are public for advanced use cases
pub mod platform;
pub mod renderer;

// Re-export macros
pub use guido_macros::{SignalFields, component};
pub use secret::Secret;

use std::sync::Arc;

use layout::Constraints;
use platform::create_wayland_app;
use reactive::owner::with_owner;
use reactive::{OwnerId, take_clipboard_change, take_cursor_change};
use renderer::{GpuSlot, Renderer, flatten_root_into};
use surface::{SurfaceCommand, SurfaceConfig, SurfaceId, drain_surface_commands};
use surface_manager::{ManagedSurface, SurfaceManager};
use widgets::Widget;
use widgets::font::FontFamily;

// Calloop imports for event-driven main loop (via smithay-client-toolkit re-exports)
use smithay_client_toolkit::reexports::calloop::EventLoop;
use smithay_client_toolkit::reexports::calloop::channel as calloop_channel;
use smithay_client_toolkit::reexports::calloop::ping::make_ping;
use smithay_client_toolkit::reexports::calloop_wayland_source::WaylandSource;

/// Set the application-wide default font family.
///
/// This should be called before creating any widgets. Widgets created after this
/// call will use the specified font family as their default.
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// set_default_font_family(FontFamily::name("Inter"));
/// ```
pub fn set_default_font_family(family: FontFamily) {
    with_app_state(|app| app.default_font_family.set(family));
}

/// Get the current application-wide default font family.
pub fn default_font_family() -> FontFamily {
    with_app_state(|app| app.default_font_family.get())
}

/// Load custom font data into the application.
///
/// The font bytes will be loaded into all internal FontSystem instances,
/// making the font available for use via `FontFamily::name`.
///
/// This should be called before creating any widgets or surfaces — and
/// before *each* [`App::run`], not once for the process: the fonts belong to
/// the `App` that loaded them and are forgotten with it, so a program that
/// restarts in a loop loads them again on every turn. Loading the same bytes
/// twice within one run registers them once.
///
/// # Example
///
/// ```ignore
/// // not compiled: `include_bytes!` needs a font file at the reader's own path,
/// // and the point of the sample is that the bytes are embedded at compile time.
/// const NERD_FONT: &[u8] = include_bytes!("../assets/MyFont.ttf");
/// guido::load_font(NERD_FONT.to_vec());
/// ```
pub fn load_font(data: Vec<u8>) {
    if with_app_state(|app| app.fonts_consumed.get()) {
        log::warn!(
            "load_font() called after FontSystem initialization — \
             this font will not be available. Call load_font() before App::run()."
        );
    }
    let mut hasher = std::hash::BuildHasher::build_hasher(&rustc_hash::FxBuildHasher);
    std::hash::Hasher::write(&mut hasher, &data);
    let hash = std::hash::Hasher::finish(&hasher);
    with_app_state(|app| {
        // Idempotent: an app that reloads its config re-registers the same
        // fonts on every run, and without this each run would keep a copy.
        if app.custom_font_hashes.borrow_mut().insert(hash) {
            app.custom_fonts.borrow_mut().push(Arc::new(data));
        }
    });
}

/// How many bytes of image texture the renderer keeps before it evicts, unless
/// the application says otherwise: 100 MB, Flutter's `ImageCache` default.
pub const DEFAULT_IMAGE_CACHE_BUDGET: usize = 100 << 20;

/// Set how many bytes of image texture the renderer may keep.
///
/// An image costs its width × height × 4 bytes, and one small enough to share
/// an atlas page costs its place there, a texel of gutter on every side
/// included. The pages themselves, 4 MB each, are not counted: one goes once
/// eviction has emptied it. Under the budget nothing is
/// evicted; over it, the least recently drawn go first — but never one drawn
/// within the last second, so the images a frame keeps drawing stay even when
/// they alone are over the budget. The default is [`DEFAULT_IMAGE_CACHE_BUDGET`].
///
/// # Example
///
/// ```no_run
/// # use guido::prelude::*;
/// set_image_cache_budget(32 << 20);
/// ```
pub fn set_image_cache_budget(bytes: usize) {
    with_app_state(|app| app.image_cache_budget.set(Some(bytes)));
}

/// The bytes of image texture the renderer may keep, as set by
/// [`set_image_cache_budget`] or the default.
pub(crate) fn image_cache_budget() -> usize {
    with_app_state(|app| app.image_cache_budget.get()).unwrap_or(DEFAULT_IMAGE_CACHE_BUDGET)
}

/// Get all registered custom font data (for loading into FontSystems).
///
/// Returns cloned `Arc` pointers so every FontSystem (measurer, renderer)
/// receives the same set of fonts.
pub(crate) fn get_registered_fonts() -> Vec<Arc<Vec<u8>>> {
    with_app_state(|app| {
        app.fonts_consumed.set(true);
        app.custom_fonts.borrow().clone()
    })
}

/// The reason the application's main loop exited.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExitReason {
    /// Normal exit: `quit_app()`, or the last surface closing.
    Quit,
    /// Restart requested (e.g. config change). The caller should re-create `App` and run again.
    Restart,
    /// The platform layer failed (no Wayland session, compositor without
    /// layer-shell support, connection lost, no GPU to draw a surface with).
    /// Previously these ordinary environmental conditions aborted the process
    /// with a panic.
    Error(platform::PlatformError),
}

/// Request a clean application restart.
///
/// The current `App::run()` loop will exit and return `ExitReason::Restart`.
/// Call this from any thread — it uses an atomic + ping to wake the event loop.
pub fn restart_app() {
    jobs::set_exit_request(jobs::ExitRequest::Restart);
}

/// Request a clean application quit.
///
/// The current `App::run()` loop will exit and return `ExitReason::Quit`.
pub fn quit_app() {
    jobs::set_exit_request(jobs::ExitRequest::Quit);
}

/// Everything an application needs, and nothing it does not.
///
/// Writing a *widget* or a *layout* rather than an application is a different
/// job with a different vocabulary — the tree, the two contexts, the
/// constraints. That lives in [`widget_prelude`], and is not re-exported here.
///
/// What an application needs includes every name it has to *write* to call the
/// methods exported here: [`StateStyle`](crate::widgets::StateStyle) is here,
/// so [`RippleConfig`](crate::widgets::RippleConfig) is too, because it is the
/// only way to spell the argument to `StateStyle::ripple_config`, and a caller
/// who can reach a method but cannot name what it takes has half of one.
///
/// Having to write it is the line, and three neighbours fall the far side of
/// it. A type the exported methods merely *hold*: `StateStyle`'s fields name `BackgroundOverride` and
/// `BorderOverride`, but `background`, `lighter`, `darker` and `border` take a
/// colour and a number and build them. A type only a `#[doc(hidden)]` method
/// takes: `StateWhen` is what [`Stateful`](crate::widgets::Stateful) hands
/// `push_state_style`, the hook `when_hovered` and its siblings are written
/// on, and every method a caller is shown takes a closure. And a bound rather
/// than a type — `child` takes `impl IntoChild<M>`, which an argument
/// satisfies without ever naming it, so nothing here follows from that
/// signature either way.
pub mod prelude {
    pub use crate::animation::{
        Animate, Animated, IntoAnimated, Keyframes, Repeat, SpringConfig, TimingFunction,
        Transition, TransitionConfig,
    };
    pub use crate::backdrop::{BackdropBlur, BackdropSources};
    pub use crate::compositor::{CompositorEffects, compositor_effects};
    pub use crate::keyboard::keyboard_modifiers;
    pub use crate::layout::{
        Axis, CrossAlignment, Flex, Length, MainAlignment, Size, ZStack, at_least, at_most, fill,
        fraction,
    };
    pub use crate::outputs::{OutputId, OutputInfo, outputs, surface_output};
    pub use crate::pivot::{HorizontalAnchor, Pivot, VerticalAnchor};
    pub use crate::platform::{Anchor, KeyboardInteractivity, Layer};
    pub use crate::reactive::{
        Callback, CursorIcon, IntoSignal, IntoVal, Memo, Password, RwSignal, Service, Signal,
        TimerHandle, Trigger, WriteSignal, create_derived, create_effect, create_memo,
        create_password, create_service, create_signal, create_stored, create_task, create_trigger,
        current_owner, expect_context, has_context, on_cleanup, provide_context,
        provide_signal_context, set_interval, set_timeout, use_context, with_context,
    };
    pub use crate::renderer::{Shadow, measure_text};
    pub use crate::session_lock::{
        LockState, lock_session, lock_state, session_locked, unlock_session,
    };
    pub use crate::surface::{
        ExclusiveZone, Margin, PopupAnchor, PopupConfig, PopupGravity, PopupHandle, SurfaceConfig,
        SurfaceExtent, SurfaceHandle, SurfaceId, content, spawn_popup, spawn_surface,
        surface_handle,
    };
    pub use crate::transform::{Scale, Translate};
    pub use crate::widget_ref::{WidgetRef, create_widget_ref};
    pub use crate::widgets::{
        AnyWidget, Border, Color, Container, ContentFit, Control, CornerRadii, Corners, Event,
        EventResponse, FontFamily, FontWeight, GradientDirection, Image, ImageSource, IntoChildren,
        IntoClickHandler, Key, LineHeight, LinearGradient, Modifiers, MouseButton, Overflow,
        Padding, PasswordInput, Point, PointerKind, Rect, RippleConfig, Scroll, ScrollSource,
        ScrollbarVisibility, Selection, StateStyle, Stateful, Text, TextAlign, TextInput,
        TextOverflow, TextShadow, TextStroke, TextStyle, Widget, container, image, keyed,
        password_input, text, text_input,
    };
    pub use crate::{
        App, ExitReason, Secret, SignalFields, component, default_font_family, load_font, quit_app,
        restart_app, set_default_font_family, set_image_cache_budget,
    };
}

/// What a widget or a layout written outside the crate needs, on top of
/// [`prelude`].
///
/// The two are meant to be imported together:
///
/// ```no_run
/// use guido::prelude::*;
/// use guido::widget_prelude::*;
/// ```
///
/// [`Widget`] has two required methods — `layout` and
/// `paint`; [`Layout`](crate::layout::Layout) has one. Everything else here is
/// what those signatures name.
///
/// Neither pass asks the widget to scope its own reads: the framework calls
/// both through one entry point each and opens the scope there, so a signal
/// read while laying out or drawing belongs to the widget that read it.
/// [`with_signal_tracking`](crate::reactive::with_signal_tracking) is still
/// exported, for a widget that wants a *narrower* attribution than its own
/// pass — a dynamic-children segment, which is what `JobType::Reconcile`
/// names.
pub mod widget_prelude {
    pub use crate::clock::{EventInstant, FrameInstant};
    pub use crate::layout::{Constraints, IntoF32, Layout};
    pub use crate::reactive::{JobType, with_signal_tracking};
    pub use crate::renderer::{PaintContext, RenderNode};
    /// The composed matrix. An application says `translate`, `rotate` and
    /// `scale`; a widget written outside the crate positions what it paints,
    /// and for that it needs the thing those three compose into.
    pub use crate::transform::Transform;
    pub use crate::tree::{LayoutCtx, LayoutPass, Tree, WidgetId};
    /// What [`PaintContext::paint_child`](crate::renderer::PaintContext::paint_child)
    /// is given. A widget with the ordinary children of an ordinary box passes
    /// `&ChildPaintOptions::default()`; the fields are for a parent that
    /// scrolls, clips or orders them.
    pub use crate::widgets::paint_children::{ChildPaintOptions, paint_children};
    pub use crate::widgets::{LayoutHints, Widget};
}

use crate::app_state::with_app_state;
use crate::{
    jobs::{get_exit_request, init_wakeup, process_jobs, take_wake_request},
    tree::{DamageRegion, Tree, WidgetId},
};

/// A surface definition that stores configuration and widget factory.
#[allow(clippy::type_complexity)]
struct SurfaceDefinition {
    id: SurfaceId,
    config: SurfaceConfig,
    widget_fn: Box<dyn FnOnce() -> Box<dyn Widget>>,
}

/// Close one surface synchronously: dismissal signal, widget-tree
/// teardown, GPU surface, Wayland objects. The managed surface drops
/// FIRST — its wgpu `Surface<'static>` borrows the wl_surface through
/// erased raw pointers, so the GPU surface must die before the Wayland
/// surface it points at.
fn close_surface_now<P: Platform>(
    id: SurfaceId,
    surface_manager: &mut SurfaceManager,
    wayland_state: &mut P,
    tree: &mut Tree,
) {
    surface::mark_popup_dismissed(id);
    if let Some(managed) = surface_manager.remove(id) {
        // Unregister the widget tree and its signal subscribers before the
        // drop disposes the reactive owner
        surface_manager::teardown_widget_subtree(tree, managed.widget_id);
    }
    wayland_state.destroy_surface(id);
}

/// Resolve the reservation policy against what the surface is anchored to and
/// how big it is, and send the protocol value if the compositor does not
/// already have it.
///
/// Called whenever something a reservation can follow has moved — the size,
/// the margin, the anchor, a measure — for every policy: `published` is what
/// keeps a constant from being sent again, rather than each caller deciding
/// which policies are worth resolving.
///
/// The size is the one just *asked* for, not the one the compositor last told us
/// about: `set_surface_size` only sends a request, and `WaylandSurfaceState`
/// learns the new size a round trip later, in `configure`. Resolving against
/// that reserves for the size the surface is leaving — a bar going from 32 to 48
/// keeps reserving 32.
///
/// A `Fixed` axis is therefore authoritative here. A `Content` one has no number
/// yet, so it falls back to `measured` if the caller has one and to the live
/// size otherwise, the measure pass re-resolving once it does. And the axis an
/// `Auto` reservation follows is always one we own — `follow_axis` gives up on
/// an axis anchored to both edges, the only kind the compositor sizes — so the
/// value we asked for is the value that will take effect.
fn publish_exclusive_zone<S: Surface>(
    surface: &mut S,
    config: &SurfaceConfig,
    measured: Option<(u32, u32)>,
    published: &mut Option<i32>,
) {
    // A content axis waiting to be measured has no size to reserve for, and the
    // confirmed one is the wrong answer rather than an old one: a surface
    // declared `width(content()).anchor(TOP | LEFT | RIGHT)` is stretched, so
    // 1920 is what the compositor imposed on an axis that was not ours. Re-anchor
    // it into a side dock and that number becomes a reservation for the whole
    // screen, pushing every other window off it, until the measure lands.
    //
    // So it waits for the measure, which publishes whenever it runs — but only
    // `Auto` waits, because only `Auto` reads a size. `Fixed`, `None` and
    // `Ignore` are constants with nothing to wait for.
    if config.exclusive_zone == surface::ExclusiveZone::Auto
        && measured.is_none()
        && surface::needs_content_measure(config)
    {
        return;
    }

    let known = measured.or_else(|| surface.configured_size());
    let width = surface::requested_extent(config.width, known.map(|(w, _)| w));
    let height = surface::requested_extent(config.height, known.map(|(_, h)| h));
    let zone = config
        .exclusive_zone
        .resolve(config.anchor, config.margin, width, height);
    if *published != Some(zone) {
        surface.set_exclusive_zone(zone);
        *published = Some(zone);
    }
}

/// Process dynamic surface commands (create, close, property changes).
/// Returns false when the last surface closed and the app quits with it.
fn process_surface_commands<P: Platform>(
    surface_manager: &mut SurfaceManager,
    wayland_state: &mut P,
    tree: &mut Tree,
    quit_on_last_surface: bool,
) -> bool {
    let mut closed_surface = false;
    for cmd in drain_surface_commands() {
        match cmd {
            SurfaceCommand::Create {
                id,
                config,
                widget_fn,
            } => {
                log::info!("Creating dynamic surface {:?}", id);

                // Create Wayland surface
                wayland_state.create_surface(id, &config);

                // Create the widget inside an owner scope so that signals/effects
                // created in the factory are properly owned.
                let (widget, owner_id) = with_owner(widget_fn);
                let managed = ManagedSurface::new(id, config, widget, owner_id, tree);
                surface_manager.add(managed);
            }
            SurfaceCommand::Close(id) => {
                log::info!("Closing dynamic surface {:?}", id);
                // Popup chains tear down children-first: destroying a popup
                // that still has a live child raises not_the_topmost_popup
                // and the compositor kills the connection.
                for child in wayland_state.popup_descendants_bottom_up(id) {
                    close_surface_now(child, surface_manager, wayland_state, tree);
                }
                close_surface_now(id, surface_manager, wayland_state, tree);
                closed_surface = true;
            }
            SurfaceCommand::SetLayer { id, layer } => {
                with_surface(wayland_state, id, |s| s.set_layer(layer));
            }
            SurfaceCommand::SetKeyboardInteractivity { id, mode } => {
                with_surface(wayland_state, id, |s| s.set_keyboard_interactivity(mode));
            }
            SurfaceCommand::SetAnchor { id, anchor } => {
                let asked = reconfigure(id, surface_manager, wayland_state, |managed, surface| {
                    managed.config.anchor = anchor;
                    surface.set_anchor(anchor);
                    // The size goes with it: which axes are the compositor's
                    // follows from the anchor, so a bar re-anchored to one edge
                    // has to stop asking for zero on the axis it now owns.
                    send_size(managed, surface)
                });
                if let Some((true, root)) = asked {
                    jobs::request_job(root, jobs::JobRequest::Layout);
                }
            }
            SurfaceCommand::SetSize { id, width, height } => {
                let asked = reconfigure(id, surface_manager, wayland_state, |managed, surface| {
                    managed.config.width = width;
                    managed.config.height = height;
                    // Here every value is one the caller just named, so anything
                    // the anchor discards is worth saying.
                    surface::warn_size_request_on_stretched_axis(id, &managed.config);
                    send_size(managed, surface)
                });
                if let Some((true, root)) = asked {
                    jobs::request_job(root, jobs::JobRequest::Layout);
                }
            }
            SurfaceCommand::SetExclusiveZone { id, zone } => {
                // Recorded through `reconfigure` like the rest, which publishes
                // the reservation after the change.
                let asked = reconfigure(id, surface_manager, wayland_state, |managed, _| {
                    managed.config.exclusive_zone = zone;
                    // Like its three sisters. Declaring `Auto` on a content
                    // surface leaves the publish waiting for a measure, so
                    // without asking for a layout the measure pass never runs on
                    // a settled UI and the reservation is never sent at all.
                    (
                        surface::needs_content_measure(&managed.config),
                        managed.widget_id,
                    )
                });
                if let Some((true, root)) = asked {
                    jobs::request_job(root, jobs::JobRequest::Layout);
                }
            }
            SurfaceCommand::SetMargin { id, margin } => {
                let asked = reconfigure(id, surface_manager, wayland_state, |managed, surface| {
                    managed.config.margin = margin;
                    surface.set_margin(margin);
                    // Like its three sisters. An `Auto` reservation is the margin
                    // *plus* the extent, so moving the margin moves it — and on a
                    // content axis the publish declines to guess and waits for a
                    // measure. Without asking for one, nothing lays anything out,
                    // the measure pass never runs, and the reservation keeps the
                    // old margin for as long as the surface lives.
                    (
                        surface::needs_content_measure(&managed.config),
                        managed.widget_id,
                    )
                });
                if let Some((true, root)) = asked {
                    jobs::request_job(root, jobs::JobRequest::Layout);
                }
            }
            SurfaceCommand::SetInputRegion { id, rects } => {
                // The base, not a separate opinion: a frame that publishes a
                // declared region reads this, so what a handle says survives
                // the next declaration instead of being overwritten by it.
                let mut declaring = false;
                if let Some(managed) = surface_manager.get_mut(id) {
                    managed.input_base = rects.clone();
                    declaring = managed.input_region.is_some();
                }

                if declaring {
                    // The tree has already spoken, and the answer is composed
                    // from both. Applying the base alone here would drop the
                    // declarations for a frame, so the frame that composes them
                    // is asked for instead.
                    if let Some(managed) = surface_manager.get(id) {
                        jobs::request_job(managed.widget_id, jobs::JobRequest::Paint);
                    }
                } else {
                    with_surface(wayland_state, id, |s| s.set_input_region(rects.as_deref()));
                }
            }
            SurfaceCommand::CreatePopup {
                id,
                parent,
                config,
                widget_fn,
            } => {
                log::info!("Creating popup {:?} anchored to {:?}", id, parent);

                // Build the widget tree FIRST: auto-height popups size to
                // their content, so the content must exist to be measured
                // before the xdg_positioner is created.
                let (widget, owner_id) = with_owner(widget_fn);
                let surface_config = SurfaceConfig::new()
                    .width(config.width)
                    .height(config.height.unwrap_or(1))
                    .background_color(config.background_color);
                let managed = ManagedSurface::new(id, surface_config, widget, owner_id, tree);

                let height = config.height.unwrap_or_else(|| {
                    measure_popup_height(tree, managed.widget_id, config.width, parent)
                });

                // A new grab must nest under the current grab holder:
                // xdg-shell forbids a grabbing popup whose parent chain
                // does not include the popup currently holding the grab
                // (the compositor kills the connection with
                // not_the_topmost_popup). Destroy conflicting grab chains
                // before creating, children first.
                if config.grab {
                    for stale in wayland_state.conflicting_grab_popups(parent) {
                        log::info!("Closing popup {:?} before new grab popup {:?}", stale, id);
                        close_surface_now(stale, surface_manager, wayland_state, tree);
                    }
                }

                if wayland_state.create_popup(id, parent, &config, (config.width, height)) {
                    surface_manager.add(managed);
                } else {
                    // Creation failed (no xdg_wm_base, parent gone): drop the
                    // widget tree and report the popup as dismissed.
                    drop(managed);
                    surface::mark_popup_dismissed(id);
                }
            }
        }
    }
    !(closed_surface && quit_on_last_surface && surface_manager.is_empty())
}

/// Measure a popup's natural content height at the given width.
fn measure_popup_height(tree: &mut Tree, root: WidgetId, width: u32, parent: SurfaceId) -> u32 {
    measure_natural_size(tree, root, Some(width), None, parent).1
}

/// Measure a widget tree's natural size. `fixed_w`/`fixed_h` pin an axis;
/// `None` measures it loose, capped at the surface's output size (minus a
/// margin) so a runaway or `fill()` content can't request an absurd
/// surface. Runs as a measure: animation TARGETS, not
/// in-flight values, so the result is animation-invariant.
fn measure_natural_size(
    tree: &mut Tree,
    root: WidgetId,
    fixed_w: Option<u32>,
    fixed_h: Option<u32>,
    surface: SurfaceId,
) -> (u32, u32) {
    let output_size = outputs::surface_output(surface)
        .and_then(|oid| {
            outputs::current_outputs()
                .into_iter()
                .find(|o| o.id == oid)
                .and_then(|o| o.logical_size)
        })
        .or_else(|| {
            outputs::current_outputs()
                .into_iter()
                .find_map(|o| o.logical_size)
        });
    let cap = |v: i32| (v as f32 - 64.0).max(100.0);
    let (cap_w, cap_h) = match output_size {
        Some((w, h)) => (cap(w), cap(h)),
        None => (800.0, 800.0),
    };

    let (min_w, max_w) = match fixed_w {
        Some(w) => (w as f32, w as f32),
        None => (0.0, cap_w),
    };
    let (min_h, max_h) = match fixed_h {
        Some(h) => (h as f32, h as f32),
        None => (0.0, cap_h),
    };

    let constraints = Constraints::new(min_w, min_h, max_w, max_h);
    let measured = tree
        .measure_widget(root, constraints)
        .unwrap_or(layout::Size::new(100.0, 100.0));

    let w = fixed_w.unwrap_or_else(|| (measured.width.ceil() as u32).max(1));
    let h = fixed_h.unwrap_or_else(|| (measured.height.ceil() as u32).max(1));
    (w, h)
}

/// Walk the render tree after painting and cache each node's output.
///
/// The third phase of a frame, after [`renderer::flatten_root_into`] and in
/// that order: flatten writes `cached_flatten` onto the nodes, and this walk
/// is what makes them reusable next frame. Public for the same reason flatten
/// is — a frame can be driven without a compositor, and the paint cache only
/// exists across frames, so a test that never runs this one never reaches it.
/// The loop calls it per child of the surface root, never on the root itself.
///
/// Caching is an `Rc::clone` of the node already sitting in the frame's
/// render tree — O(1) per node instead of the previous deep subtree clone.
///
/// Returns whether the subtree is partial (this node or any descendant had
/// children culled by cull_rect). Partial-ness propagates UP: an ancestor
/// whose subtree embeds an incomplete paint must not be cached either, or a
/// later cache reuse would permanently hide the culled grandchildren. It
/// invalidates as well as refuses — see the body.
///
/// Also clears needs_paint flags and the per-frame `repainted` marker for
/// freshly painted widgets (skipping already-clean subtrees entirely).
pub fn cache_paint_results(tree: &mut Tree, node: &std::rc::Rc<renderer::RenderNode>) -> bool {
    if !node.repainted.get() {
        // Reused from cache: its subtree is by construction complete and its
        // cache entries are already valid — nothing to do below it.
        return false;
    }

    let mut subtree_partial = node.partial;
    for child in &node.children {
        subtree_partial |= cache_paint_results(tree, child);
    }

    let widget_id = WidgetId::from_u64(node.id);
    if tree.contains(widget_id) {
        if subtree_partial {
            // Partial subtree — this paint cannot be cached, and neither can
            // the one before it stay: the widget painted this frame, and it
            // painted something else. Keeping the last complete entry as a
            // stand-in for "how it looks when nothing is culled" is how a
            // scrolled list came back at the top — culling starts the moment
            // it scrolls, so the newest complete entry is the list at rest,
            // and `reuse_cached` serves it whole the next time some other
            // widget asks for a frame.
            tree.clear_cached_paint(widget_id);
        } else {
            // Complete paint — safe to cache for future reuse.
            tree.cache_paint(widget_id, std::rc::Rc::clone(node));
        }
        tree.clear_needs_paint(widget_id);
    }
    // Mark as cached/clean for the flattener and future walks. The cache
    // entry shares this Cell, so reused nodes come out with the flag
    // already cleared.
    node.repainted.set(false);

    subtree_partial
}

/// Deliver this surface's queued input to the widget tree.
///
/// Handlers read signals for their current value, not to subscribe — a click
/// wants the value at click time — so the whole dispatch is a snapshot zone.
///
/// Jobs the handlers push (hover and pressed state changes, clicks) land in
/// the inbox, and distributing them here is what keeps hover from lagging a
/// frame behind the pointer: the drain later in this same frame picks them up.
///
/// `closing` is asked before each event. Once it says yes — a handler asked
/// for this surface to close — the rest of the batch is dropped, leave and
/// focus-out included: the widgets go with the surface on the next command
/// pass, and an action taken in between is one taken by a dialog the user has
/// already dismissed (#675). GTK drops events for a surface it has unmapped in
/// the same way; it lets a crossing through because GDK keeps crossing state
/// per seat, which nothing here does.
fn dispatch_events(
    events: &[(std::time::Instant, widgets::Event)],
    root: WidgetId,
    tree: &mut Tree,
    active_roots: &rustc_hash::FxHashSet<WidgetId>,
    closing: impl Fn() -> bool,
) {
    for (at, event) in events {
        if closing() {
            break;
        }
        if matches!(event, widgets::Event::MouseEnter { .. }) {
            reactive::cursor::resend_cursor();
        }
        // Declared per event, not per pass: they are delivered one at a time
        // and each has its own moment.
        tree.set_event_instant(Some(*at));
        reactive::diagnostics::snapshot_zone(|| {
            let response = tree.dispatch(root, event);

            // The dispatch just asked every widget under the point, and the
            // innermost one that declares a cursor said so last — unless it
            // was a press or release inside a chord, which asked only the
            // press route (#625).
            if event.coords().is_some() && tree.asked_under_the_point() {
                reactive::cursor::point_at(tree.cursor_under_the_point());
            }

            // A press nobody claimed is a press on nothing, and the keyboard
            // goes with it. This is the only place that can tell: a widget is
            // handed the presses that miss it, but never learns whether one of
            // them turned out to be somebody else's.
            //
            // Two ways to be somebody's. A widget consumed it, which is what
            // `Handled` says. Or the focus itself claims it — the box drawn
            // around a focused field is that field to the eye — which is a
            // different sentence and arrives on its own channel, because
            // saying it with `Handled` also silenced every ancestor (#308).
            if matches!(event, widgets::Event::MouseDown { .. })
                && response != Some(widgets::EventResponse::Handled)
                && !tree.focus_claimed_the_press()
            {
                reactive::focus::release_focus_under(root);
            }
        });
    }
    tree.set_event_instant(None);

    jobs::distribute_jobs(tree, active_roots);
}

/// Push anything the widgets changed back out to the compositor: the
/// clipboard after a copy, the primary selection after a select-to-copy, the
/// cursor shape after a hover.
///
/// Called once per iteration from the loop, not per surface. What it carries
/// belongs to the seat rather than to any one surface, and running it inside
/// the per-surface pass meant it only ran when a surface had a frame to give
/// it: an application with no surface yet — one that spawns its bars from an
/// event, a lock screen before its lock is granted — could copy or set a
/// cursor and have it sit in the queue with no pass coming to drain it. The
/// loop's pre-block check reads that queue and would have called it a lost
/// wakeup, which it is not: the producer woke the loop, and the loop had
/// nowhere to put the work.
fn sync_platform_state<P: Platform>(wayland_state: &mut P) {
    if let Some(text) = take_clipboard_change() {
        wayland_state.set_clipboard(text);
    }
    if let Some(text) = reactive::take_primary_change() {
        wayland_state.set_primary(text);
    }
    if let Some(cursor) = take_cursor_change() {
        wayland_state.set_cursor(cursor);
    }
    for (kind, token) in reactive::clipboard::take_paste_requests() {
        wayland_state.read_selection(kind, token);
    }
}

/// Run every job this surface owns, in the one order that works.
///
/// 1. Unregister — remove dead widgets first
/// 2. Animation — advance animated values so layout and paint see current
///    ones, not last frame's. May push Layout/Paint follow-ups.
/// 3. Reconcile — create and remove dynamic children. May push Layout.
/// 4. Layout — needs the advanced animations and the reconciled children
/// 5. Paint — needs the final positions
///
/// Animations run here rather than at end-of-frame because a hover that
/// retargets an animation must reach paint in the same frame; deferring it
/// left every animated value one frame stale.
///
/// The drain is surface-owned: `distribute_jobs` already resolved ownership,
/// so this returns only jobs belonging to this surface's subtree. That gives
/// the pacing gate and the queue the same granularity — a gated surface's
/// animation continuations sit untouched in its own queue until its frame
/// callback fires, whatever the other surfaces do meanwhile.
fn run_jobs(
    root: WidgetId,
    tree: &mut Tree,
    layout_roots: &mut Vec<WidgetId>,
    active_roots: &rustc_hash::FxHashSet<WidgetId>,
) {
    let jobs = jobs::drain_surface_jobs(root);
    process_jobs(&jobs, tree, layout_roots);
    jobs::recycle_job_buffer(jobs);

    // Follow-ups from the animation advances and the reconciliation land in
    // the inbox, so they need distributing before they can be drained.
    jobs::distribute_jobs(tree, active_roots);
    let followup = jobs::drain_surface_non_animation_jobs(root);
    if !followup.is_empty() {
        process_jobs(&followup, tree, layout_roots);
    }
    jobs::recycle_job_buffer(followup);
}

/// What this surface tells us about itself, read once at the top of a frame.
///
/// Copying it frees the borrow on `wayland_state`, which the phases below
/// need mutably — and nothing the compositor sends can change it before this
/// frame ends anyway.
struct Frame {
    /// What arrived for this surface, each with when it happened.
    events: Vec<(std::time::Instant, widgets::Event)>,
    scale_factor: f32,
    width: u32,
    height: u32,
    /// Whether a callback is in flight, and whether the surface still
    /// repaints in full.
    pacing: surface::FramePacing,
}

/// Whether this frame would only queue behind one the compositor has not shown.
///
/// The two that open the gate anyway are a resize and a scale change: both
/// have something to tell the compositor that cannot wait for a callback. A
/// surface with nothing on screen yet needs no third: it has committed
/// nothing, so no callback is in flight to wait on.
///
/// A function rather than the condition inline, because it is the one decision
/// in the frame path that can be taken from a `Frame` and a `Geometry` alone,
/// and so the one a test could reach first.
fn paced_out(frame: &Frame, geometry: &Geometry) -> bool {
    frame.pacing.callback_pending() && !geometry.needs_resize && !geometry.scale_changed
}

/// What the frame path asks of whatever is showing one surface.
///
/// Every request a frame makes of a compositor, and nothing that is not about
/// this surface: no id parameter, because a handle already knows which one it
/// is. `supports_blur_region` is the one that is not here — a capability
/// belongs to the connection, not to a window — and it lives on [`Platform`].
///
/// Two required methods. `open_frame` has no default because a surface that
/// cannot say what a frame is has nothing to show, and `pacing` has none
/// because there is no honest guess at it: a surface believed to be waiting on
/// the compositor never draws, and one believed never to be holds the loop
/// awake on work that cannot run. Every other request defaults
/// to doing nothing and knowing nothing, which is the honest answer for a surface
/// that does not have that protocol. So a second implementation writes down
/// what it wants to watch and stays silent about the rest.
///
/// What that cannot catch is a method added here and forgotten in the Wayland
/// implementation: it would silently do nothing against a real compositor
/// rather than fail to build. The defaults are for a surface that *cannot* do
/// the thing, never for one that has not been taught to.
pub(crate) trait Surface {
    /// The facts a frame is built from, or `None` if this surface has no size
    /// to draw at yet. Takes the queued input with it, so calling it twice for
    /// one frame loses events.
    fn open_frame(&mut self) -> Option<Frame>;

    /// Where this surface stands with its frame callbacks — what
    /// [`open_frame`](Self::open_frame) reads its gate from, asked without
    /// opening one. The loop reads it to decide how long it may sleep.
    fn pacing(&self) -> surface::FramePacing;

    /// The size the compositor has confirmed, if it has confirmed one.
    ///
    /// Not the size that was *requested*: `WaylandSurfaceState` is created
    /// holding that, which for a content axis is the 1px placeholder — so
    /// reading it unconditionally would report a number nobody agreed on as
    /// though it were live, and make `requested_extent`'s "no size yet" branch
    /// unreachable while the case it describes was still happening.
    fn configured_size(&self) -> Option<(u32, u32)> {
        None
    }

    /// The scale to build this surface's buffer at now: 1 until the compositor
    /// sends one, which is what `wl_surface.preferred_buffer_scale` defines a
    /// surface's scale to be before its first event. A scale that arrives
    /// later is a change like any other, and the target is resized to it.
    fn scale_factor(&self) -> f32 {
        1.0
    }

    /// The width an auto-width popup should be measured against.
    fn popup_auto_width(&self) -> Option<u32> {
        None
    }

    /// Tell the compositor an auto-height popup's content changed height.
    fn reposition_popup_if_changed(&mut self, new_height: u32) {
        let _ = new_height;
    }

    /// Ask for a size. A request: the answer arrives as a configure.
    fn set_size(&mut self, width: u32, height: u32) {
        let _ = (width, height);
    }

    /// Publish the screen space this surface reserves.
    fn set_exclusive_zone(&mut self, zone: i32) {
        let _ = zone;
    }

    /// Declare the logical size the buffer about to be attached stands for.
    ///
    /// Only a surface with a `wp_viewport` has one to declare; the rest scale
    /// their buffer with `wl_surface.set_buffer_scale`, which takes an integer
    /// and so cannot say 1.5 at all. Called from
    /// [`resolve_geometry`] — beside the resize, from the same numbers, so the
    /// destination and the buffer it describes cannot be resolved apart.
    fn set_viewport_destination(&mut self, width: u32, height: u32) {
        let _ = (width, height);
    }

    /// Run `f` and let its requests reach the compositor as one commit, so a
    /// group of them never shows an intermediate surface on the way.
    fn batch_layer_requests<F: FnOnce(&mut Self)>(&mut self, f: F) {
        f(self);
    }

    /// Whether this surface has a blur region published that would have to be
    /// withdrawn.
    fn has_published_blur(&self) -> bool {
        false
    }

    /// Whether the last published region was dropped and owes republishing.
    fn take_blur_resync(&mut self) -> bool {
        false
    }

    /// Publish the region to blur behind this surface.
    fn sync_blur_region(&mut self, rects: Vec<region::RegionRect>, commit: bool) {
        let _ = (rects, commit);
    }

    /// Publish where input reaches this surface: the area it takes, and the
    /// declarations the frame made about it.
    fn sync_input_region(&mut self, request: &region::InputRegionRequest, commit: bool) {
        let _ = (request, commit);
    }

    /// Ask to be told when this surface's last frame has been shown.
    fn request_frame_callback(&mut self) {}

    /// Report damaged buffer pixels, in buffer coordinates. Why it has to
    /// happen before presenting is on the implementation.
    fn damage(&mut self, x: i32, y: i32, width: i32, height: i32) {
        let _ = (x, y, width, height);
    }

    /// Record that the callback asked for is now committed — what
    /// [`pacing`](Self::pacing) answers from next. No default, for the same
    /// reason as that one's.
    fn mark_frame_callback_pending(&mut self);

    /// Move this surface between the compositor's layers.
    fn set_layer(&mut self, layer: platform::Layer) {
        let _ = layer;
    }

    /// Re-anchor it, which also decides which axes the compositor owns.
    fn set_anchor(&mut self, anchor: platform::Anchor) {
        let _ = anchor;
    }

    /// Hold it off the edges it is anchored to.
    fn set_margin(&mut self, margin: surface::Margin) {
        let _ = margin;
    }

    /// Restrict where input reaches it. `None` is the whole surface.
    fn set_input_region(&mut self, rects: Option<&[widgets::Rect]>) {
        let _ = rects;
    }

    /// How much of the keyboard this surface wants.
    fn set_keyboard_interactivity(&mut self, mode: platform::KeyboardInteractivity) {
        let _ = mode;
    }
}

/// The order a popup tree must be destroyed in: every descendant of `root`,
/// deepest and newest first.
///
/// `edges` is the whole live popup forest as `(popup, its parent)` pairs, in
/// any order; only the ones reachable from `root` come back, and `root` itself
/// does not — the caller destroys that after, or is a surface rather than a
/// popup.
///
/// **What the protocol requires** is that a popup outlive none of its children:
/// `xdg_popup.destroy` on one that is not the topmost raises
/// `not_the_topmost_popup` and the compositor drops the connection, and
/// xdg-shell defines that for a chain — *"Nested popups must be destroyed in
/// the reverse order they were created in, e.g. the only popup you are allowed
/// to destroy at all times is the topmost one."* Between two popups on the same
/// parent it says nothing, and this does not pretend otherwise.
///
/// **What is chosen** is that siblings come back newest first, and the way both
/// are had at once is a sort rather than a walk. A [`SurfaceId`] is a counter
/// that only goes up, so descending id puts every child before its parent for
/// free — a popup cannot be created on a parent that does not exist — and
/// orders siblings by age on the same pass. The reason to decide it at all is
/// that the alternative was three answers: a frontier reversed, a recursion,
/// and a hash iteration, disagreeing on the case the protocol leaves open, with
/// no way to tell which a compositor had been given.
///
/// Callers may depend on the order, and both `Platform` implementations do —
/// that is the point of it being here rather than in either of them.
/// topmost first.
///
/// `edges` is the whole live popup forest as `(popup, its parent)` pairs, in
/// any order; only the ones reachable from `root` come back, and `root` itself
/// does not — the caller destroys that after, or is a surface rather than a
/// popup.
///
/// **The order is decided, not incidental.** xdg-shell keeps live popups in a
/// stack and `xdg_popup.destroy` must take the topmost one; taking any other
/// raises `not_the_topmost_popup`, and the compositor drops the connection. The
/// stack is creation order, and a [`SurfaceId`] is a counter that only goes up,
/// so **descending id is the stack** — which is why this sorts rather than
/// walks. Depth needs no separate rule: a popup cannot be created on a parent
/// that does not exist, so a child's id always exceeds its parent's and comes
/// out first for free.
///
/// Callers may depend on that order, and the two `Platform` implementations do:
/// it is the same sequence on both, where a tree walk left it to whatever order
/// the surfaces happened to be stored in. Siblings were the visible half of
/// that — a frontier reversed, a recursion and a hash iteration are three
/// answers — but the old walks could also emit a popup while a *newer* sibling
/// was still live, which is the error above rather than a matter of taste.
pub(crate) fn descendants_bottom_up(
    root: SurfaceId,
    edges: impl Iterator<Item = (SurfaceId, SurfaceId)>,
) -> Vec<SurfaceId> {
    let edges: Vec<(SurfaceId, SurfaceId)> = edges.collect();
    let mut out: Vec<SurfaceId> = Vec::new();
    let mut frontier = vec![root];

    while let Some(current) = frontier.pop() {
        for (popup, parent) in &edges {
            if *parent == current {
                out.push(*popup);
                frontier.push(*popup);
            }
        }
    }

    out.sort_unstable_by_key(|id| std::cmp::Reverse(id.raw()));
    out
}

/// The grabbing popups a new grab under `new_parent` cannot coexist with, in
/// teardown order.
///
/// xdg-shell allows one grab chain at a time and requires a new grab to nest
/// under the current holder: *"The parent of a grabbing popup must either be an
/// xdg_toplevel surface or another xdg_popup with an explicit grab."* So a grab
/// requested anywhere else means the live chain comes down first, and it comes
/// down in [`descendants_bottom_up`]'s order like any other — these are the same
/// `xdg_popup.destroy` requests, and the same `not_the_topmost_popup` waiting
/// behind them.
///
/// `popups` is the live popup forest as `(popup, its parent, whether it holds a
/// grab)`. Anything on `new_parent`'s own ancestry is spared, that being exactly
/// the chain a new grab is allowed to nest under.
pub(crate) fn conflicting_grabs(
    new_parent: SurfaceId,
    popups: impl Iterator<Item = (SurfaceId, SurfaceId, bool)>,
) -> Vec<SurfaceId> {
    let popups: Vec<(SurfaceId, SurfaceId, bool)> = popups.collect();

    // What a new grab under `new_parent` may legally nest on.
    let mut ancestors = vec![new_parent];
    let mut current = new_parent;
    while let Some((_, parent, _)) = popups.iter().find(|(popup, _, _)| *popup == current) {
        ancestors.push(*parent);
        current = *parent;
    }

    let mut out: Vec<SurfaceId> = Vec::new();
    for (popup, _, holds_grab) in &popups {
        if *holds_grab && !ancestors.contains(popup) {
            out.push(*popup);
            out.extend(descendants_bottom_up(
                *popup,
                popups.iter().map(|(popup, parent, _)| (*popup, *parent)),
            ));
        }
    }

    // One sort for the whole answer rather than per chain: the rule that orders
    // a chain orders two of them against each other just as well, and the
    // alternative was concatenating chains in whatever order they were stored.
    out.sort_unstable_by_key(|id| std::cmp::Reverse(id.raw()));
    out.dedup();
    out
}

#[cfg(test)]
mod teardown_order {
    use super::{conflicting_grabs, descendants_bottom_up};
    use crate::surface::SurfaceId;

    /// Ids in the order they would have been created.
    fn ids(n: usize) -> Vec<SurfaceId> {
        (0..n).map(|_| SurfaceId::next()).collect()
    }

    #[test]
    fn a_chain_comes_back_deepest_first() {
        let s = ids(4);
        let edges = vec![(s[1], s[0]), (s[2], s[1]), (s[3], s[2])];
        assert_eq!(
            descendants_bottom_up(s[0], edges.into_iter()),
            vec![s[3], s[2], s[1]]
        );
    }

    /// The case the walks disagreed on: two popups on one parent, one of them
    /// carrying a chain of its own. The newest goes first even though it is the
    /// shallowest, because it is the one on top of the stack.
    #[test]
    fn siblings_come_back_newest_first() {
        let s = ids(4);
        // s[0] ── s[1] ── s[2]
        //     └── s[3]
        let edges = vec![(s[1], s[0]), (s[2], s[1]), (s[3], s[0])];
        assert_eq!(
            descendants_bottom_up(s[0], edges.into_iter()),
            vec![s[3], s[2], s[1]]
        );
    }

    /// Edges arrive in whatever order the surfaces happen to be stored in, and
    /// the answer may not depend on it — which is the whole point of sorting
    /// rather than walking.
    #[test]
    fn the_order_the_edges_arrive_in_does_not_matter() {
        let s = ids(4);
        let edges = [(s[1], s[0]), (s[2], s[1]), (s[3], s[0])];
        let want = vec![s[3], s[2], s[1]];

        let mut shuffled = edges;
        shuffled.reverse();
        assert_eq!(descendants_bottom_up(s[0], shuffled.into_iter()), want);
        assert_eq!(
            descendants_bottom_up(s[0], [edges[1], edges[2], edges[0]].into_iter()),
            want
        );
    }

    /// Another surface's popups are not this surface's to destroy.
    #[test]
    fn only_what_hangs_from_the_root_comes_back() {
        let s = ids(4);
        let edges = vec![(s[1], s[0]), (s[3], s[2])];
        assert_eq!(descendants_bottom_up(s[0], edges.into_iter()), vec![s[1]]);
    }

    /// A grab chain spares its own ancestry and takes everything else, in the
    /// order everything else comes down in.
    #[test]
    fn a_new_grab_takes_the_chain_it_cannot_nest_under() {
        let s = ids(4);
        // bar s[0] ── menu s[1] (grab) ── submenu s[2] (grab)
        let popups = vec![(s[1], s[0], true), (s[2], s[1], true)];
        assert_eq!(
            conflicting_grabs(s[0], popups.clone().into_iter()),
            vec![s[2], s[1]],
            "a grab on the bar itself cannot nest under the menu"
        );
        assert_eq!(
            conflicting_grabs(s[2], popups.into_iter()),
            Vec::new(),
            "a grab under the current holder nests, and takes nothing down"
        );
    }

    /// Two chains are ordered against each other by the same rule that orders
    /// one, rather than by which was looked at first.
    #[test]
    fn two_grab_chains_come_down_newest_first() {
        let s = ids(5);
        // s[0] ── s[1] (grab) ── s[2] (grab)
        // s[3] ── s[4] (grab)
        let popups = vec![(s[1], s[0], true), (s[2], s[1], true), (s[4], s[3], true)];
        let mut reversed = popups.clone();
        reversed.reverse();
        let want = vec![s[4], s[2], s[1]];
        assert_eq!(conflicting_grabs(s[3], popups.into_iter()), want);
        assert_eq!(conflicting_grabs(s[3], reversed.into_iter()), want);
    }

    /// A popup without a grab is nobody's conflict, and neither are its
    /// children — only a grab chain has to go.
    #[test]
    fn a_popup_holding_no_grab_is_left_alone() {
        let s = ids(3);
        let popups = vec![(s[1], s[0], false), (s[2], s[1], false)];
        assert_eq!(conflicting_grabs(s[0], popups.into_iter()), Vec::new());
    }

    #[test]
    fn a_surface_with_no_popups_has_nothing_to_tear_down() {
        let s = ids(2);
        let edges = vec![(s[1], s[0])];
        assert!(descendants_bottom_up(s[1], edges.into_iter()).is_empty());
    }
}

/// Whatever the application is running on.
///
/// The thin half: it hands out surfaces and answers for the things that belong
/// to the connection rather than to any one window. `WaylandState` is one
/// implementation; a recorder that keeps what it was asked is the other.
pub(crate) trait Platform {
    /// One surface, borrowed for as long as the caller needs it.
    ///
    /// A handle rather than an id on every method, because a Wayland surface is
    /// its own state *and* the connection's — `sync_blur_region` needs the
    /// effect manager, `set_size` needs the layer surface — so what a caller
    /// holds has to be able to reach both.
    type Surface<'a>: Surface
    where
        Self: 'a;

    fn surface(&mut self, id: SurfaceId) -> Option<Self::Surface<'_>>;

    /// Whether backdrop blur regions can be published at all. A capability of
    /// the connection, which is why it is here and not on a surface.
    fn supports_blur_region(&self) -> bool {
        false
    }

    /// Bring a surface into being. It has no size until a configure arrives.
    fn create_surface(&mut self, id: SurfaceId, config: &SurfaceConfig) {
        let _ = (id, config);
    }

    /// Bring a popup into being, anchored to another surface. `false` where
    /// popups are unavailable or the parent cannot host one.
    fn create_popup(
        &mut self,
        id: SurfaceId,
        parent: SurfaceId,
        config: &surface::PopupConfig,
        size: (u32, u32),
    ) -> bool {
        let _ = (id, parent, config, size);
        false
    }

    /// Take a surface away.
    fn destroy_surface(&mut self, id: SurfaceId) {
        let _ = id;
    }

    /// Popups holding a grab that a new one under `parent` would conflict with,
    /// which have to be dismissed before it opens.
    fn conflicting_grab_popups(&self, parent: SurfaceId) -> Vec<SurfaceId> {
        let _ = parent;
        Vec::new()
    }

    /// A popup's descendants, in the order [`descendants_bottom_up`] decides.
    fn popup_descendants_bottom_up(&self, root: SurfaceId) -> Vec<SurfaceId> {
        let _ = root;
        Vec::new()
    }

    /// Ask to lock the session. `false` where the protocol is unavailable.
    fn start_session_lock(&mut self) -> bool {
        false
    }

    /// Give one output its lock surface. `false` without an active lock.
    fn create_lock_surface(&mut self, id: SurfaceId, output: outputs::OutputId) -> bool {
        let _ = (id, output);
        false
    }

    /// What the lock has said since this was last asked.
    fn take_lock_events(&mut self) -> Vec<platform::LockEvent> {
        Vec::new()
    }

    /// Release the session.
    fn unlock_session(&mut self) {}

    /// Hand the seat what the widgets changed this iteration.
    fn set_clipboard(&mut self, text: String) {
        let _ = text;
    }

    fn set_primary(&mut self, text: String) {
        let _ = text;
    }

    fn set_cursor(&mut self, cursor: reactive::CursorIcon) {
        let _ = cursor;
    }

    /// Read a selection for the pastes waiting on `token`, and answer them
    /// with `reactive::clipboard::answer_paste` — now or when the read lands.
    /// Required, because a platform that forgot it would leave every paste
    /// unanswered.
    fn read_selection(&mut self, kind: reactive::SelectionKind, token: u64);

    /// Send everything this iteration queued. `false` means the connection is
    /// gone and the application is over.
    fn flush(&self) -> bool {
        true
    }

    /// Where this surface's frames should land, once it has a size.
    ///
    /// The one place the two implementations genuinely differ rather than one
    /// recording what the other sends: a compositor hands out a swapchain tied
    /// to a real window, and a driver with no compositor allocates a texture.
    /// `None` where the surface is not ready to be given one.
    fn create_render_target(
        &self,
        id: SurfaceId,
        gpu: &renderer::GpuContext,
        size: (u32, u32),
    ) -> Option<renderer::RenderTarget> {
        let _ = (id, gpu, size);
        None
    }
}

/// One Wayland surface, and the connection it needs to speak.
///
/// A pair rather than a borrow of `WaylandSurfaceState`, because half of what a
/// surface does reaches past itself: the blur region wants the effect manager,
/// a layer request wants the layer surface *and* the queue. Both live on the
/// state, so the handle carries the state and the name of one surface in it.
pub(crate) struct WaylandSurface<'a> {
    state: &'a mut platform::WaylandState,
    id: SurfaceId,
}

impl Surface for WaylandSurface<'_> {
    fn open_frame(&mut self) -> Option<Frame> {
        let surface = self.state.get_surface_mut(self.id)?;
        if !surface.configured {
            return None;
        }
        // Taken before the caller's GPU check, not after: a surface still
        // building its GPU state drops this frame *and* the input queued for
        // it. Holding the input instead would deliver a burst of stale events —
        // a pointer position from several frames ago among them — on the first
        // frame that renders.
        let events = surface.take_events();
        Some(Frame {
            events,
            scale_factor: surface.scale_factor,
            width: surface.width,
            height: surface.height,
            pacing: surface.pacing,
        })
    }

    fn pacing(&self) -> surface::FramePacing {
        self.state
            .get_surface(self.id)
            .map(|s| s.pacing)
            .unwrap_or_default()
    }

    fn configured_size(&self) -> Option<(u32, u32)> {
        self.state
            .get_surface(self.id)
            .filter(|s| s.configured)
            .map(|s| (s.width, s.height))
    }

    fn scale_factor(&self) -> f32 {
        self.state
            .get_surface(self.id)
            .map_or(1.0, |surface| surface.scale_factor)
    }

    fn popup_auto_width(&self) -> Option<u32> {
        self.state.popup_auto_width(self.id)
    }

    fn reposition_popup_if_changed(&mut self, new_height: u32) {
        self.state.reposition_popup_if_changed(self.id, new_height)
    }

    fn set_size(&mut self, width: u32, height: u32) {
        self.state.set_surface_size(self.id, width, height)
    }

    fn set_exclusive_zone(&mut self, zone: i32) {
        self.state.set_surface_exclusive_zone(self.id, zone)
    }

    fn set_viewport_destination(&mut self, width: u32, height: u32) {
        self.state.set_viewport_destination(self.id, width, height)
    }

    fn batch_layer_requests<F: FnOnce(&mut Self)>(&mut self, f: F) {
        let id = self.id;
        // The batching is the state's — one commit for the group — and what the
        // closure is handed back is this surface, so nothing inside it can
        // reach another one.
        let batch = self.state.open_layer_batch(id);
        f(self);
        self.state.close_layer_batch(batch);
    }

    fn has_published_blur(&self) -> bool {
        self.state.has_published_blur(self.id)
    }

    fn take_blur_resync(&mut self) -> bool {
        self.state.take_blur_resync(self.id)
    }

    fn sync_blur_region(&mut self, rects: Vec<region::RegionRect>, commit: bool) {
        self.state.sync_blur_region(self.id, rects, commit)
    }

    fn sync_input_region(&mut self, request: &region::InputRegionRequest, commit: bool) {
        self.state.sync_input_region(self.id, request, commit)
    }

    fn request_frame_callback(&mut self) {
        self.state.request_frame_callback(self.id)
    }

    fn damage(&mut self, x: i32, y: i32, width: i32, height: i32) {
        self.state.damage_surface(self.id, x, y, width, height)
    }

    fn mark_frame_callback_pending(&mut self) {
        self.state.mark_frame_callback_pending(self.id)
    }

    fn set_layer(&mut self, layer: platform::Layer) {
        self.state.set_surface_layer(self.id, layer)
    }

    fn set_anchor(&mut self, anchor: platform::Anchor) {
        self.state.set_surface_anchor(self.id, anchor)
    }

    fn set_margin(&mut self, margin: surface::Margin) {
        self.state.set_surface_margin(self.id, margin)
    }

    fn set_input_region(&mut self, rects: Option<&[widgets::Rect]>) {
        self.state.set_surface_input_region(self.id, rects)
    }

    fn set_keyboard_interactivity(&mut self, mode: platform::KeyboardInteractivity) {
        self.state.set_surface_keyboard_interactivity(self.id, mode)
    }
}

impl Platform for platform::WaylandState {
    type Surface<'a> = WaylandSurface<'a>;

    fn surface(&mut self, id: SurfaceId) -> Option<WaylandSurface<'_>> {
        self.get_surface(id)?;
        Some(WaylandSurface { state: self, id })
    }

    fn supports_blur_region(&self) -> bool {
        self.supports_blur_region()
    }

    fn create_surface(&mut self, id: SurfaceId, config: &SurfaceConfig) {
        self.create_surface_with_id(id, config)
    }

    fn create_popup(
        &mut self,
        id: SurfaceId,
        parent: SurfaceId,
        config: &surface::PopupConfig,
        size: (u32, u32),
    ) -> bool {
        self.create_popup_surface_with_id(id, parent, config, size)
    }

    fn destroy_surface(&mut self, id: SurfaceId) {
        self.destroy_surface(id)
    }

    fn conflicting_grab_popups(&self, parent: SurfaceId) -> Vec<SurfaceId> {
        self.conflicting_grab_popups(parent)
    }

    fn popup_descendants_bottom_up(&self, root: SurfaceId) -> Vec<SurfaceId> {
        self.popup_descendants_bottom_up(root)
    }

    fn start_session_lock(&mut self) -> bool {
        self.start_session_lock()
    }

    fn create_lock_surface(&mut self, id: SurfaceId, output: outputs::OutputId) -> bool {
        self.create_lock_surface_with_id(id, output)
    }

    fn take_lock_events(&mut self) -> Vec<platform::LockEvent> {
        self.take_lock_events()
    }

    fn unlock_session(&mut self) {
        self.unlock_session()
    }

    fn set_clipboard(&mut self, text: String) {
        self.set_clipboard(text)
    }

    fn set_primary(&mut self, text: String) {
        self.set_primary(text)
    }

    fn set_cursor(&mut self, cursor: reactive::CursorIcon) {
        self.set_cursor(cursor)
    }

    fn read_selection(&mut self, kind: reactive::SelectionKind, token: u64) {
        self.read_selection(kind, token)
    }

    fn flush(&self) -> bool {
        if let Err(e) = self.connection.flush() {
            log::error!("Wayland connection flush failed: {e}");
            return false;
        }
        true
    }

    fn create_render_target(
        &self,
        id: SurfaceId,
        gpu: &renderer::GpuContext,
        size: (u32, u32),
    ) -> Option<renderer::RenderTarget> {
        let wl_surface = &self.get_surface(id)?.wl_surface;
        let window = platform::WaylandWindowWrapper::new(&self.connection, wl_surface);
        Some(renderer::RenderTarget::Swapchain(
            gpu.create_surface(window, size.0, size.1),
        ))
    }
}

/// The physical size, and what about it changed since the last frame.
struct Geometry {
    physical_width: u32,
    physical_height: u32,
    needs_resize: bool,
    scale_changed: bool,
    /// The logical size this frame owes its viewport, or `None` when the one
    /// the compositor holds is still right. Resolved beside the buffer and
    /// sent beside the commit — see [`resolve_geometry`].
    declare_destination: Option<(u32, u32)>,
}

/// Read the surface's state and take its queued input, or give up on this
/// frame: an unconfigured surface has no size to render at, and one whose GPU
/// state has not been built yet gets it on the next iteration.
fn open_frame<P: Platform>(ctx: &mut FrameContext<P>) -> Option<Frame> {
    // The host answers for the compositor; the GPU readiness is ours, and a
    // surface still building its swapchain has nowhere to draw.
    let frame = ctx.wayland_state.surface(ctx.id)?.open_frame()?;
    ctx.surface.is_gpu_ready().then_some(frame)
}

/// Resolve the physical size, bring the swapchain in line with it, and work
/// out what that buffer will have to be declared as.
///
/// Runs after input rather than with the rest of the snapshot: dispatching
/// events cannot change the surface size, but resizing the swapchain before
/// the widgets have been told anything would reorder the frame for no gain.
///
/// The buffer and the viewport destination are **resolved together**, from one
/// frame's numbers, because a compositor reading the buffer through a
/// destination it does not match shows the surface at the wrong size — and,
/// where a source rectangle is in play, is handed `wp_viewport: error 2` and
/// drops the client. Resolved here; *sent* by `paint_and_present`, beside the
/// damage and the frame callback, because that is where this file keeps the
/// requests that have to ride the buffer's own commit. Sending it from here
/// would leave it pending across a `batch_layer_requests` group — which a
/// content-sized surface opens in `layout_pass`, in between — and that group's
/// commit would latch the new destination over the previous frame's buffer.
fn resolve_geometry<P: Platform>(ctx: &mut FrameContext<P>, frame: &Frame) -> Geometry {
    let id = ctx.id;
    let surface = &mut *ctx.surface;
    let (physical_width, physical_height) =
        surface::buffer_size((frame.width, frame.height), frame.scale_factor);

    let wgpu_surface = surface.wgpu_surface.as_mut().unwrap();
    let needs_resize =
        wgpu_surface.width() != physical_width || wgpu_surface.height() != physical_height;
    let scale_changed = frame.scale_factor != surface.previous_scale_factor;

    if needs_resize {
        log::info!(
            "Resizing surface {:?} to {}x{} (physical), scale {}",
            id,
            physical_width,
            physical_height,
            frame.scale_factor
        );
        wgpu_surface.resize(physical_width, physical_height);
    }

    if scale_changed {
        log::info!(
            "Surface {:?} scale factor changed: {} -> {}",
            id,
            surface.previous_scale_factor,
            frame.scale_factor
        );
        surface.previous_scale_factor = frame.scale_factor;
    }

    // Driven by the logical size and not by the resize: 2560x32 at 1.5 and
    // 3840x48 at 1.0 are the same buffer, and only one of them is 2560x32.
    // Compared here rather than in a platform for the reason the input region
    // is — a frame that has nothing new to declare declares nothing, once, for
    // every surface there is.
    let destination = (frame.width, frame.height);
    let declare_destination =
        (surface.viewport_destination != Some(destination)).then_some(destination);

    Geometry {
        physical_width,
        physical_height,
        needs_resize,
        scale_changed,
        declare_destination,
    }
}

/// Bring the tree's geometry up to date, and let a content-sized surface
/// tell the compositor how big it wants to be.
///
/// Partial layout is the normal path: only the subtrees that marked
/// themselves re-run, from their relayout boundaries. A full layout from the
/// root happens only on a resize, because that is the one change no widget
/// can have noticed on its own.
fn layout_pass<P: Platform>(
    ctx: &mut FrameContext<P>,
    frame: &Frame,
    geometry: &Geometry,
    has_pending_layouts: bool,
    layout_roots: &mut Vec<WidgetId>,
) {
    let id = ctx.id;
    let surface = &mut *ctx.surface;
    let wayland_state = &mut *ctx.wayland_state;
    let renderer = &mut *ctx.renderer;
    let tree = &mut *ctx.tree;

    // Update renderer for this surface
    renderer.set_screen_size(
        geometry.physical_width as f32,
        geometry.physical_height as f32,
    );
    renderer.set_scale_factor(frame.scale_factor);

    // Re-layout using partial layout from boundaries when available
    let constraints = Constraints::new(0.0, 0.0, frame.width as f32, frame.height as f32);
    if !layout_roots.is_empty() {
        // Partial layout: only update dirty subtrees starting from boundaries
        let mut roots = Vec::new();
        std::mem::swap(&mut roots, layout_roots);
        for root_id in &roots {
            // Use cached constraints for boundaries, or fall back to parent constraints
            let cached = tree
                .last_layout_constraints(*root_id)
                .unwrap_or(constraints);
            tree.layout_widget(*root_id, cached);
        }
        // Paint invalidation is per widget, not per subtree: every widget
        // that actually ran its layout marked itself (and its ancestors)
        // inside Tree::cache_layout, and Tree::set_origin damaged what
        // moved. Marking the whole subtree here instead would repaint
        // every descendant of the layout root — which in a
        // content-sized tree is the whole surface — and throw away the
        // paint and flatten caches the layout pass just earned.
    } else if geometry.needs_resize {
        // Full layout from root only when explicitly needed (first frame, resize, etc.)
        tree.layout_widget(surface.widget_id, constraints);
        tree.mark_subtree_needs_paint(surface.widget_id);
    }
    // If neither condition is true, skip layout entirely - nothing is dirty

    // Auto-height popups follow their content: when this surface had
    // layout activity, re-measure the natural height and ask the
    // compositor to reposition if it changed (submenus expanding, lists
    // growing). The measure pass runs under different constraints, so
    // the real layout is restored right after.
    if has_pending_layouts
        && let Some(popup_width) = wayland_state.surface(id).and_then(|s| s.popup_auto_width())
    {
        let natural = measure_popup_height(tree, surface.widget_id, popup_width, id);
        tree.layout_widget(surface.widget_id, constraints);
        with_surface(wayland_state, id, |s| {
            s.reposition_popup_if_changed(natural)
        });
    } else if (has_pending_layouts || frame.pacing.forced())
        && surface::needs_content_measure(&surface.config)
    {
        // Initialization included: a freshly spawned surface reaches
        // its first frames through the full-layout path, not
        // layout_roots — without measuring here a single-toast spawn
        // would stay at its 1px initial size until the NEXT content
        // change.
        // Content-sized layer surface (toast stacks, OSDs): measure
        // the natural size and follow it — the layer counterpart of
        // the popup reposition above. Without this a content-sized
        // surface is stuck at its initial size: the real layout
        // clamps to the surface, so a measured rect can never exceed
        // it. The measure reads animation TARGETS, so an animated
        // growth resizes once and the animation plays inside.
        let (fixed_w, fixed_h) =
            surface::measure_pins(&surface.config, (frame.width, frame.height));
        let (nw, nh) = measure_natural_size(tree, surface.widget_id, fixed_w, fixed_h, id);
        tree.layout_widget(surface.widget_id, constraints);
        // Compared as they will be *asked for*, not as they were measured. On an
        // axis the compositor owns both sides are zero, so a `content()` width
        // under `LEFT | RIGHT` cannot make this true for ever by measuring 300
        // against a screen's 1920 — which it did, resizing, resyncing,
        // committing and logging once a frame for the whole life of the surface.
        let asking = surface::honour_owned_axes(surface.config.anchor, nw, nh);
        let resizing =
            asking != surface::honour_owned_axes(surface.config.anchor, frame.width, frame.height);
        // The resize is conditional; the publish is not. This is the only place
        // the measurement is known, and the reservation may be waiting on it even
        // when the size did not move — `publish_exclusive_zone` declines to
        // resolve `Auto` against an unmeasured content axis, so a re-anchoring
        // that measures back to the number it already had would otherwise leave
        // the reservation deferred for ever.
        {
            // One commit, like every other pair of these. A content surface whose
            // content animates resizes on frame after frame, and two commits a
            // frame show the compositor the new size against the old reservation
            // in between.
            let config = &surface.config;
            let published = &mut surface.exclusive_zone;
            if let Some(mut handle) = wayland_state.surface(id) {
                handle.batch_layer_requests(|surface| {
                    if resizing {
                        // Through the same rule as every other resize: a measured
                        // number on an axis the compositor owns hands back an axis
                        // that is not ours, and a full-width bar would then stay at
                        // whatever the screen was when it was measured.
                        let (ask_w, ask_h) = asking;
                        surface.set_size(ask_w, ask_h);
                    }
                    // An `Auto` reservation follows an automatic resize too, and this
                    // is the one caller that knows the measured size before the
                    // compositor does — so it passes it rather than letting the
                    // helper look it up.
                    publish_exclusive_zone(surface, config, Some((nw, nh)), published);
                });
            }
        }
    }

    // Where every ref'd widget is drawn now: after layout, and on a frame
    // that only scrolled or animated a transform, which moves it all the same.
    widget_ref::update_widget_refs(tree);

    // A `WidgetRef::focus()` from application code lands here: after layout, so
    // a handle attached this very frame has resolved to a widget, and before
    // `paint_and_present`, so the frame that resolves it is the frame that
    // draws the caret. Applying it after the render pass instead reads
    // tidier — one call per iteration rather than one per surface — and costs
    // an autofocused field a frame of looking unfocused.
    //
    // Staying parked is this one's resting state, unlike the queues in
    // `deferred`: a request for a widget that does not exist yet is the
    // ordinary shape of `focus()` from a startup effect, and it waits as many
    // frames as it takes. Which is also why it does not matter that a surface
    // must exist for this to run — without one there is no tree to resolve
    // against.
    reactive::focus::apply_pending_focus(tree);
}

/// Send the size the surface is currently asking for, and report whether the
/// content-measure pass has to run before that answer is right.
///
/// Shared by the two commands that can change it — a resize, and a re-anchoring
/// that changes which axes are ours — so the anchor and the size cannot end up
/// describing different surfaces.
///
/// An axis crossing from the compositor's side to ours has to be given a number:
/// layer-shell makes zero on an axis not anchored to opposite edges a protocol
/// error, so a re-anchored bar that says nothing is disconnected at its next
/// commit. The number is the config's, **default included** — a bar written
/// `height(32).anchor(TOP | LEFT | RIGHT)` never names a width, so re-anchoring
/// it to `TOP | LEFT` asks for [`SurfaceConfig::default`]'s 400 rather than the
/// screen width it was stretched to. Handing back the size it happens to have
/// instead would read better there and worse where it counts: it would also
/// override a width the app *did* name and had ignored while stretched. An app
/// re-anchoring to an axis it cares about sets the size for it.
///
/// It does not warn. A re-anchoring names no sizes, so warning from here fired
/// on every anchor change for an axis that was stretched before and still is —
/// the noise
/// [`warn_content_on_stretched_axis`](surface::warn_content_on_stretched_axis)
/// was split off to avoid. The caller that was handed a size says so.
fn send_size<S: Surface>(managed: &ManagedSurface, surface: &mut S) -> (bool, WidgetId) {
    let live = surface.configured_size();
    let (ask_w, ask_h, needs_measure) = surface::resize_request(&managed.config, live);
    surface.set_size(ask_w, ask_h);
    (needs_measure, managed.widget_id)
}

/// Apply a change to a surface, then re-publish what follows from it.
///
/// Every property a reservation can follow — the anchor, the size, the margin,
/// the policy itself — goes through here, so the publish happens in one place
/// and a fifth trigger cannot be added to three of the four. Forgetting exactly
/// that is how a re-anchored dock went on reserving a bar's height at the top of
/// the screen.
///
/// The change records on the config *and* sends the protocol request, because
/// the two must not drift: the content-sizing pass reads the config every frame.
fn reconfigure<P: Platform, R>(
    id: SurfaceId,
    surface_manager: &mut SurfaceManager,
    platform: &mut P,
    change: impl FnOnce(&mut ManagedSurface, &mut P::Surface<'_>) -> R,
) -> Option<R> {
    let managed = surface_manager.get_mut(id)?;
    let mut handle = platform.surface(id)?;
    let mut result = None;
    // One commit for the group. A re-anchoring sends the anchor, the size and
    // the reservation, and each request committing on its own would show the
    // compositor two intermediate surfaces on the way.
    handle.batch_layer_requests(|surface| {
        result = Some(change(managed, surface));
        publish_exclusive_zone(surface, &managed.config, None, &mut managed.exclusive_zone);
    });
    result
}

/// Paint, flatten, hand the frame to the GPU, and re-arm the pacing gate.
///
/// The order at the end is not free-form: the frame callback and the damage
/// are both requested BEFORE presenting, because presenting is what commits
/// the surface. Anything set afterwards would ride an empty second commit
/// the compositor cannot use.
fn paint_and_present<P: Platform>(ctx: &mut FrameContext<P>, frame: &Frame, geometry: &Geometry) {
    let id = ctx.id;
    let surface = &mut *ctx.surface;
    let wayland_state = &mut *ctx.wayland_state;
    let renderer = &mut *ctx.renderer;
    let tree = &mut *ctx.tree;

    // Force full repaint on resize, scale change, or during initialization
    if frame.pacing.forced() || geometry.needs_resize || geometry.scale_changed {
        tree.mark_subtree_needs_paint(surface.widget_id);
    }

    // Skip frame if nothing needs paint
    if !tree.needs_paint(surface.widget_id) {
        // Only when one is owed. The retained command buffer still holds the
        // last frame, which is what is on screen — so it is also the right
        // region, and rebuilding it from those commands is right but not free:
        // an idle surface would walk a whole frame's worth of them, every frame,
        // to arrive at the region it published already. The one thing that can
        // change while nothing paints is the compositor's blur capability, which
        // drops its regions, and that says so.
        if let Some(mut handle) = wayland_state.surface(id)
            && handle.take_blur_resync()
        {
            let blur_rects = blur::regions_from_commands(
                &surface.flattened_commands,
                surface.flatten_scratch.clip_chains(),
            );
            handle.sync_blur_region(blur_rects, true);
        }
        render_stats::record_frame_skipped();
        render_stats::end_frame(&DamageRegion::None);
        return;
    }

    // Clear and reuse the root node (preserves capacity)
    surface.root_node.clear();
    surface.root_node.bounds =
        widgets::Rect::new(0.0, 0.0, frame.width as f32, frame.height as f32);

    time_phase!(render_stats::Phase::Paint, {
        tree.paint_widget(
            surface.widget_id,
            &mut surface.root_node,
            frame.scale_factor,
        );
    });

    // Flatten tree into reused buffers
    let carried;
    time_phase!(render_stats::Phase::Flatten, {
        carried = flatten_root_into(
            &surface.root_node,
            &mut surface.flattened_commands,
            &mut surface.command_layers,
            &mut surface.flatten_scratch,
        );
    });

    // The compositor blur region is read off the frame that was just built, so
    // it cannot disagree with what is on screen — see `blur`. Set before
    // present() so it rides the buffer commit: region and content change
    // together.
    // Asked before the scan, not after: without the protocol there is nothing
    // to publish, and walking the frame's commands to find out would be a
    // per-frame cost on the compositors that can do the least with it.
    //
    // And on the compositors that *can*, only for a frame that asks. The flatten
    // counted them on its way past, so the scan is skipped for the surfaces —
    // almost all of them — with no compositor blur in the frame at all. The one
    // frame that has to be walked without carrying one is the frame that stops:
    // it owes the compositor the empty region that withdraws the last one.
    if wayland_state.supports_blur_region()
        && let Some(mut handle) = wayland_state.surface(id)
        && (carried.compositor_blur || handle.has_published_blur())
    {
        let blur_rects = blur::regions_from_commands(
            &surface.flattened_commands,
            surface.flatten_scratch.clip_chains(),
        );
        handle.sync_blur_region(blur_rects, false);
    }

    // And the other region read off the same frame, on the same commit. The
    // rule for whether to publish at all is here rather than in a platform:
    // a surface whose tree has never declared anything about input is left
    // alone, so what a config or a handle asked for stays; one that has
    // declared publishes when the answer changes and not otherwise. The one
    // frame that must be published while carrying nothing is the frame that
    // stops declaring, which owes the compositor its base back.
    if carried.input_region || surface.input_region.is_some() {
        let request = region::InputRegionRequest {
            base: region::base_rects(
                surface.input_base.as_deref(),
                frame.width as f32,
                frame.height as f32,
            ),
            ops: region::input_ops_from_commands(
                &surface.flattened_commands,
                surface.flatten_scratch.clip_chains(),
            ),
        };
        if surface.input_region.as_ref() != Some(&request)
            && let Some(mut handle) = wayland_state.surface(id)
        {
            handle.sync_input_region(&request, false);
            // Remembered while the tree is still declaring. The frame that
            // stops declaring publishes the base once and then forgets, so a
            // surface whose declaration resolves to nothing this frame — fully
            // clipped, scrolled away — does not re-send the same region on
            // every frame after it.
            surface.input_region = carried.input_region.then_some(request);
        }
    }

    // The logical size the buffer about to be attached stands for, on that
    // buffer's own commit: a destination latched against any other buffer is
    // the surface drawn at the wrong size. `resolve_geometry` decided it; this
    // is the first place after it that nothing else can commit the surface,
    // and the memo is written here rather than there so a frame that never
    // reached this line has not recorded a declaration it did not make.
    if let Some((width, height)) = geometry.declare_destination {
        surface.viewport_destination = Some((width, height));
        with_surface(wayland_state, id, |s| {
            s.set_viewport_destination(width, height)
        });
    }

    // Here, above `present`, because both of these have to ride its commit —
    // why is on the two methods. Previously the callback was requested exactly
    // once at startup and never again, and the only pacing was the event loop
    // blocking inside the Fifo swapchain.
    with_surface(wayland_state, id, |s| s.request_frame_callback());

    let damage = tree.take_damage(surface.widget_id);
    match damage {
        DamageRegion::None => {
            // Shouldn't happen since we're rendering, but report full damage to be safe
            with_surface(wayland_state, id, |s| {
                s.damage(
                    0,
                    0,
                    geometry.physical_width as i32,
                    geometry.physical_height as i32,
                )
            });
        }
        DamageRegion::Partial(rect) => {
            let scale = frame.scale_factor;
            with_surface(wayland_state, id, |s| {
                s.damage(
                    (rect.x * scale) as i32,
                    (rect.y * scale) as i32,
                    (rect.width * scale).ceil() as i32,
                    (rect.height * scale).ceil() as i32,
                )
            });
        }
        DamageRegion::Full => {
            with_surface(wayland_state, id, |s| {
                s.damage(
                    0,
                    0,
                    geometry.physical_width as i32,
                    geometry.physical_height as i32,
                )
            });
        }
    }

    let presented;
    time_phase!(render_stats::Phase::GpuRender, {
        presented = renderer.render(
            surface.wgpu_surface.as_mut().unwrap(),
            &renderer::FlatFrame {
                commands: &surface.flattened_commands,
                layers: &surface.command_layers,
                clips: surface.flatten_scratch.clip_chains(),
            },
            surface.config.background_color,
        );
    });

    if !presented {
        // Nothing reached the screen (lost/outdated swapchain — common
        // right after a resize). Keep all dirty flags so the content is
        // repainted next frame instead of staying stale, restore full
        // damage, and request that frame.
        tree.set_full_damage(surface.widget_id);
        jobs::wake_loop();
        return;
    }

    // Cache paint results AFTER flatten so cached_flatten data is preserved.
    // This enables incremental flatten for paint-cached nodes on subsequent
    // frames. The surface root itself is never cache-reused (it always
    // repaints), so only its children are cached.
    time_phase!(render_stats::Phase::CachePaintResults, {
        for child in &surface.root_node.children {
            cache_paint_results(tree, child);
        }
        tree.clear_needs_paint(surface.widget_id);
    });

    // Track render stats (when compiled with --features render-stats)
    render_stats::record_frame_painted();
    render_stats::end_frame(&damage);

    with_surface(wayland_state, id, |s| s.mark_frame_callback_pending());
}

/// The borrows a frame needs from start to finish, in one place.
///
/// They are distinct objects in the caller, so bundling them costs nothing —
/// and it spares every phase below the parameter list that had already grown
/// past what anyone reads. Each phase reborrows what it uses, so its body
/// reads as if it still owned the arguments.
struct FrameContext<'a, P: Platform> {
    id: SurfaceId,
    surface: &'a mut surface_manager::ManagedSurface,
    wayland_state: &'a mut P,
    renderer: &'a mut Renderer,
    tree: &'a mut Tree,
}

/// What the loop knows about waiting work when it decides how long to sleep.
struct Pending {
    /// A surface has nothing on screen yet, so it must not wait for input to
    /// arrive before drawing.
    force_render: bool,
    /// Jobs queued by the previous frame that the next one could run —
    /// animation continuations, mostly. Not a surface's that is waiting on its
    /// frame callback: the callback is what wakes the loop for those.
    jobs: bool,
    /// A wake request that landed *after* this iteration consumed the flag.
    /// Blocking on one already set would suppress every later ping, so it
    /// counts as pending work rather than as a reason to sleep — see
    /// [`jobs::wake_request_pending`].
    wake_requested: bool,
    /// When the next scheduled thing is due, if anything is scheduled.
    deadline: Option<std::time::Instant>,
}

/// The earliest moment the loop has to wake with nothing else to do: a
/// scheduled job, a timer, or the device outliving the last surface.
fn wake_deadline(gpu: &GpuSlot) -> Option<std::time::Instant> {
    [
        jobs::next_deadline(),
        reactive::timer::next_deadline(),
        gpu.release_at(),
    ]
    .into_iter()
    .flatten()
    .min()
}

/// How long this iteration may sleep before it has to look again.
///
/// `None` blocks until the compositor or a ping. Nothing queued can be stranded
/// by that: work and its wakeup are one gesture — see `deferred` and the
/// ingress channel.
///
/// Waiting work polls at frame rate instead, and it outranks a deadline: the
/// deadline is the longer sleep of the two, and the queued job would sit
/// through it.
///
/// A deadline alone sleeps exactly that long. A caret blinks twice a second, so
/// this wakes once, where treating a schedule as pending work would spin at 60
/// fps to repaint nothing 113 frames out of 114.
///
/// `now` is passed rather than read so the decision can be asked about.
fn wait_for(pending: &Pending, now: std::time::Instant) -> Option<std::time::Duration> {
    if pending.jobs || pending.force_render || pending.wake_requested {
        return Some(std::time::Duration::from_millis(16));
    }
    pending
        .deadline
        .map(|deadline| deadline.saturating_duration_since(now))
}

/// How long the loop may sleep now, from everything it knows about waiting
/// work.
///
/// Gathered here rather than in `App::run` so that there is one gathering:
/// the loop blocks for what this answers, and
/// [`Headless::next_wait`](testing::Headless::next_wait) reports it, so a test
/// asks the question the loop asks. `wake_requested` is the caller's because
/// the flag is process-wide, and a test binary running several applications
/// at once shares it — see [`Pending::wake_requested`].
fn loop_timeout<P: Platform>(
    platform: &mut P,
    surfaces: &SurfaceManager,
    gpu: &GpuSlot,
    wake_requested: bool,
    now: std::time::Instant,
) -> Option<std::time::Duration> {
    let mut force_render = false;
    let mut waiting = smallvec::SmallVec::<[WidgetId; 4]>::new();
    for id in surfaces.ids() {
        let Some(pacing) = platform.surface(id).map(|s| s.pacing()) else {
            continue;
        };
        force_render |= pacing.forced();
        if pacing.callback_pending()
            && let Some(surface) = surfaces.get(id)
        {
            waiting.push(surface.widget_id);
        }
    }
    let pending = Pending {
        force_render,
        jobs: jobs::has_runnable_jobs(|root| waiting.contains(&root)),
        wake_requested,
        deadline: wake_deadline(gpu),
    };
    wait_for(&pending, now)
}

/// Whether a close is queued for this surface, or for a popup it hangs from:
/// closing a popup takes its descendants down with it.
///
/// Asked before every event, so the common answers are the cheap ones: with
/// nothing queued the list is empty and allocates nothing, and the surface's
/// own close is found before any popup tree is walked.
fn close_requested<P: Platform>(platform: &P, id: SurfaceId) -> bool {
    let closing = surface::closes_requested();
    closing.contains(&id)
        || closing
            .into_iter()
            .any(|root| platform.popup_descendants_bottom_up(root).contains(&id))
}

/// Ask one surface for something, if it is still there.
///
/// Nine call sites want exactly this, and none has anything to say about a
/// surface that vanished between the frame opening and the request being made —
/// so the lookup is here rather than spelled out at each of them.
fn with_surface<P: Platform>(platform: &mut P, id: SurfaceId, f: impl FnOnce(&mut P::Surface<'_>)) {
    if let Some(mut surface) = platform.surface(id) {
        f(&mut surface);
    }
}

/// One surface, one frame, in the order the phases have to run.
fn render_surface<P: Platform>(
    ctx: &mut FrameContext<P>,
    layout_roots: &mut Vec<WidgetId>,
    woken: bool,
    active_roots: &rustc_hash::FxHashSet<WidgetId>,
    at: std::time::Instant,
) {
    let Some(frame) = open_frame(ctx) else {
        return;
    };

    let root = ctx.surface.widget_id;
    let (id, platform) = (ctx.id, &*ctx.wayland_state);
    dispatch_events(&frame.events, root, ctx.tree, active_roots, move || {
        close_requested(platform, id)
    });

    let geometry = resolve_geometry(ctx, &frame);

    // This returns BEFORE draining jobs, and that is the whole point:
    // animation continuations have to stay queued. Advancing them on every
    // loop iteration would re-ping the wakeup each time and spin the loop
    // flat out between frame callbacks. Input was dispatched above, so it is
    // never delayed by the gate; initialisation and resizes bypass it.
    if paced_out(&frame, &geometry) {
        render_stats::record_frame_skipped();
        return;
    }

    // What time it is, for this whole frame. Declared once here because a
    // frame is these three passes: the animations advance, layout measures what
    // they produced, paint draws it. Asking the clock inside each of them made
    // one frame several instants, and made the middle of an animation something
    // no test could ask about — only sleep towards.
    //
    // Handed in rather than read, and sampled once per iteration rather than
    // once per surface: two bars drawn in the same pass are the same moment,
    // and a driver that wants to say when a frame happened has somewhere to
    // say it.
    ctx.tree.set_frame_instant(Some(at));

    run_jobs(root, ctx.tree, layout_roots, active_roots);

    // Nothing moved and nothing is starting up: there is no frame to draw.
    let has_pending_layouts = !layout_roots.is_empty();
    if !(frame.pacing.forced()
        || woken
        || has_pending_layouts
        || geometry.needs_resize
        || geometry.scale_changed
        || ctx.tree.needs_paint(root))
    {
        ctx.tree.set_frame_instant(None);
        return;
    }

    layout_pass(ctx, &frame, &geometry, has_pending_layouts, layout_roots);
    paint_and_present(ctx, &frame, &geometry);
    // The frame is over, and so is its instant. Leaving it set would let a
    // later call read a time that has nothing to do with it, silently — the
    // failure a stale clock always has.
    ctx.tree.set_frame_instant(None);
}

/// The application: the loop, its surfaces and the reactive state they run on.
///
/// One at a time per process. A new one may start once the previous one is
/// dropped, and starts clean: dropping an `App` retires what it left behind,
/// the writes its background services queued included. Two at once in one
/// process would share that process-wide state, and are not supported.
pub struct App {
    /// Surface definitions added via add_surface()
    surface_definitions: Vec<SurfaceDefinition>,
    /// The layout tree for widget storage (owned by App)
    tree: Tree,
    /// Layout roots that need re-layout, keyed by surface root so one
    /// surface's render pass never lays out another surface's subtrees
    /// (each inner Vec is deduped — typically 1–3 entries per frame)
    layout_roots: rustc_hash::FxHashMap<WidgetId, Vec<WidgetId>>,
    /// Root owner for the reactive graph. When disposed, cascades cleanup
    /// through all signals, effects, and cleanup callbacks.
    root_owner_id: Option<OwnerId>,
    /// Whether closing the last surface ends [`run`](Self::run).
    quit_on_last_surface: bool,
}

impl App {
    pub fn new() -> Self {
        Self {
            surface_definitions: Vec::new(),
            tree: Tree::new(),
            layout_roots: rustc_hash::FxHashMap::default(),
            root_owner_id: None,
            quit_on_last_surface: true,
        }
    }

    /// Set the application-wide default font family.
    ///
    /// This sets the default font family that will be used by all text widgets
    /// that don't explicitly specify a font family.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let config = SurfaceConfig::new();
    /// # let view = || text("hi");
    /// App::new()
    ///     .default_font_family(FontFamily::name("Inter"))
    ///     .run(|app| {
    ///         app.add_surface(config, view);
    ///     });
    /// ```
    pub fn default_font_family(self, family: FontFamily) -> Self {
        set_default_font_family(family);
        self
    }

    /// Set how many bytes of image texture the renderer may keep before it
    /// evicts; see [`set_image_cache_budget`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let config = SurfaceConfig::new();
    /// # let view = || text("hi");
    /// App::new()
    ///     .image_cache_budget(32 << 20)
    ///     .run(|app| {
    ///         app.add_surface(config, view);
    ///     });
    /// ```
    pub fn image_cache_budget(self, bytes: usize) -> Self {
        set_image_cache_budget(bytes);
        self
    }

    /// Whether closing the last surface ends the application. On by default.
    ///
    /// Off, the application idles when its last surface closes — by its
    /// handle, by the compositor, or with its monitor — as one that has not
    /// spawned any yet does, until
    /// [`spawn_surface`](crate::surface::spawn_surface) brings one back. It
    /// then ends through [`quit_app`] or a lost connection. For a resident
    /// program that only sometimes has something to show, such as a polkit
    /// agent.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// App::new().quit_on_last_surface(false).run(|_app| {
    ///     // No `add_surface`: surfaces are spawned when something asks.
    /// });
    /// ```
    pub fn quit_on_last_surface(mut self, quit: bool) -> Self {
        self.quit_on_last_surface = quit;
        self
    }

    /// Add a surface to the application.
    ///
    /// This method allows creating multiple layer shell surfaces within a single app.
    /// Each surface has its own widget tree but all surfaces share the same reactive
    /// signals and app state.
    ///
    /// The widget factory closure creates the root widget for the surface.
    ///
    /// Returns a `SurfaceId` that can be used to get a `SurfaceHandle` later via
    /// `surface_handle()` to modify surface properties.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// App::new().run(|app| {
    ///     let bar_id = app.add_surface(
    ///         SurfaceConfig::new()
    ///             .height(32)
    ///             .anchor(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT)
    ///             .layer(Layer::Top)
    ///             .namespace("status-bar"),
    ///         || text("bar"),
    ///     );
    /// });
    /// ```
    pub fn add_surface<W, F>(&mut self, config: SurfaceConfig, widget_fn: F) -> SurfaceId
    where
        W: Widget + 'static,
        F: FnOnce() -> W + 'static,
    {
        let id = SurfaceId::next();
        self.surface_definitions.push(SurfaceDefinition {
            id,
            config,
            widget_fn: Box::new(move || Box::new(widget_fn())),
        });
        id
    }

    /// Run the application with a setup closure.
    ///
    /// The setup closure runs inside a root owner scope — all signals, effects,
    /// and other reactive primitives created within it are automatically cleaned
    /// up when the `App` is dropped. Use `app.add_surface()` inside the closure
    /// to define surfaces.
    ///
    /// An application with no surfaces is not an error: it idles until
    /// [`spawn_surface`](crate::surface::spawn_surface) gives it one. Unless
    /// [`quit_on_last_surface`](Self::quit_on_last_surface) says otherwise,
    /// closing the last surface returns [`ExitReason::Quit`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let config = SurfaceConfig::new();
    /// # let build_ui = |c: RwSignal<i32>| text(move || c.get().to_string());
    /// App::new().run(|app| {
    ///     let count = create_signal(0);
    ///     app.add_surface(config, move || build_ui(count));
    /// });
    /// ```
    pub fn run(mut self, setup: impl FnOnce(&mut Self)) -> ExitReason {
        // The loop is created before the connection because the keyboard is
        // built during the first dispatch, and it needs the loop handle to arm
        // its key-repeat timer.
        let mut event_loop: EventLoop<platform::WaylandState> =
            EventLoop::try_new().expect("Failed to create event loop");
        let loop_handle = event_loop.handle();

        // Both wakeup mechanisms are installed before anything can reach
        // them, which means before `setup` runs: an app's very first act is
        // often a `create_task` that writes a signal, and the compositor
        // starts talking during `create_wayland_app`'s roundtrips and the
        // configure loop. A producer that finds neither a channel nor a ping
        // handle has nowhere to put its wakeup.
        // Create ping mechanism for wakeup on signal changes
        let (ping, ping_source) = make_ping().expect("Failed to create ping");
        init_wakeup(ping);

        // Insert ping source - this wakes the loop when signals change
        loop_handle
            .insert_source(ping_source, |_, _, _| {
                // Ping received - a signal was updated, frame will be rendered
            })
            .expect("Failed to insert ping source");

        // Cross-thread ingress channel: background threads send messages
        // here instead of hand-rolling wakeups. calloop guarantees a send
        // wakes the next dispatch — see the ingress module.
        let (ingress_tx, ingress_channel) = calloop_channel::channel();
        ingress::install_ingress(ingress_tx);
        loop_handle
            .insert_source(ingress_channel, |event, _, _| {
                if let calloop_channel::Event::Msg(message) = event {
                    match message {
                        // Doorbell only: the write payloads live in the
                        // reactive write queue, drained at the flush point
                        // later this same iteration.
                        ingress::IngressMessage::BgWritesQueued => {}
                        ingress::IngressMessage::SelectionRead { token, content } => {
                            reactive::clipboard::answer_paste(token, content)
                        }
                    }
                }
            })
            .expect("Failed to insert ingress channel");

        // Create root owner scope — all signals/effects created in setup are owned
        self.root_owner_id = Some(reactive::create_root_owner());
        setup(&mut self);

        if self.surface_definitions.is_empty() {
            // Not an error: outputs-driven apps start with zero surfaces and
            // spawn one per monitor from an effect once the compositor
            // reports its outputs. An app that never spawns anything will
            // just idle in the event loop.
            log::info!(
                "No static surfaces defined; waiting for dynamic surfaces \
                 (spawn_surface, e.g. from an outputs() effect)"
            );
        }

        let (connection, mut event_queue, mut wayland_state) =
            match create_wayland_app(loop_handle.clone()) {
                Ok(app) => app,
                Err(e) => {
                    log::error!("Cannot start: {e}");
                    return ExitReason::Error(e);
                }
            };

        // Create surfaces from add_surface() calls
        for def in &self.surface_definitions {
            wayland_state.create_surface_with_id(def.id, &def.config);
        }

        // Wait for all surfaces to configure
        while !wayland_state.all_surfaces_configured() {
            if let Err(e) = event_queue.blocking_dispatch(&mut wayland_state) {
                log::error!("Wayland dispatch failed during configure: {e}");
                return ExitReason::Error(platform::PlatformError::ConnectionLost);
            }
        }

        let mut gpu = GpuSlot::lazy();

        // Create surface manager and runtime entries for each surface
        let mut surface_manager = SurfaceManager::new();
        let mut renderer: Option<Renderer> = None;

        // Create entries for surfaces added via add_surface(). The widget and
        // nothing else: a target and a first layout are what `iterate` gives
        // any surface that has not got one, and a surface built here is built
        // by the same lines as one spawned at runtime.
        //
        // That is not tidiness. The first layout seeds every enter animation,
        // and the frame that advances them is the first iteration's — so a
        // layout out here would be seeded before `Renderer::new`, before the
        // Wayland source is even inserted, and an enter would have travelled
        // the whole of start-up before its first frame. Every one of these is
        // still forced — see `FramePacing::forced` — so `wait_for` returns a
        // 16ms timeout and the first iteration is immediate.
        for def in self.surface_definitions.drain(..) {
            // Create the widget inside an owner scope so that signals/effects
            // created in the factory (e.g. create_memo) are properly owned.
            let (widget, owner_id) = with_owner(|| (def.widget_fn)());
            surface_manager.add(ManagedSurface::new(
                def.id,
                def.config,
                widget,
                owner_id,
                &mut self.tree,
            ));
        }

        // Insert Wayland source - this handles all Wayland protocol events
        WaylandSource::new(connection.clone(), event_queue)
            .insert(loop_handle.clone())
            .expect("Failed to insert Wayland source");

        // Main loop - event-driven, blocks until Wayland event or signal update
        loop {
            // Anything whose deadline has arrived becomes ordinary pending
            // work. Here and not in `loop_timeout`, which a test asks too, on
            // a clock it does not hold.
            jobs::promote_due_jobs();
            let timeout = loop_timeout(
                &mut wayland_state,
                &surface_manager,
                &gpu,
                jobs::wake_request_pending(),
                std::time::Instant::now(),
            );

            if let Err(e) = event_loop.dispatch(timeout, &mut wayland_state) {
                // The connection died (compositor exited, protocol error).
                // Exit cleanly instead of panicking the process.
                log::error!("Event loop dispatch failed: {e}");
                return ExitReason::Error(platform::PlatformError::ConnectionLost);
            }

            let ctx = LoopContext {
                wayland_state: &mut wayland_state,
                surface_manager: &mut surface_manager,
                gpu: &mut gpu,
                renderer: &mut renderer,
                quit_on_last_surface: self.quit_on_last_surface,
            };
            if let Some(reason) = iterate(ctx, &mut self.tree, &mut self.layout_roots, None) {
                return reason;
            }

            // The running commentary is the driver's to ask for. A frame
            // accumulates and says nothing; this is the one loop that wants
            // the once-a-second dump on stderr, and a harness stepping
            // `iterate` itself keeps its counters.
            render_stats::report_if_due();
        }
    }
}

/// Every handle one iteration needs, in one place.
struct LoopContext<'a, P: Platform> {
    wayland_state: &'a mut P,
    surface_manager: &'a mut SurfaceManager,
    gpu: &'a mut GpuSlot,
    renderer: &'a mut Option<Renderer>,
    quit_on_last_surface: bool,
}

/// Everything one iteration does once it has finished waiting.
///
/// Split from the waiting because the waiting is calloop's and this is
/// guido's: a driver that wants to step the application forward wants this
/// half and not the other. `run` calls it after every dispatch; #264 step 5
/// is where something else does.
///
/// `frame_at` names the moment every surface drawn this pass is drawn at — and
/// every surface *born* in it, whose first layout seeds the animations this
/// pass then advances. `None` takes it where those two meet: after the session
/// lock and the surface commands, before `init_pending_gpu`. Sampling it any
/// earlier would date the frame from before work that has nothing to do with
/// it; any later and a birth would fall outside the frame that draws it, which
/// is #392. On the one iteration that builds a renderer, `Renderer::new` falls
/// inside — once per process, against a surface that has no frame yet anyway.
///
/// `Some` ends the loop with that reason.
fn iterate<P: Platform>(
    ctx: LoopContext<'_, P>,
    tree: &mut Tree,
    layout_roots: &mut rustc_hash::FxHashMap<WidgetId, Vec<WidgetId>>,
    frame_at: Option<std::time::Instant>,
) -> Option<ExitReason> {
    let LoopContext {
        gpu,
        wayland_state,
        surface_manager,
        renderer,
        quit_on_last_surface,
    } = ctx;
    // Reset ping coalescing first: the first wake_loop from here on sends a
    // fresh ping, so the next dispatch cannot block on work queued during
    // this iteration.
    jobs::mark_loop_awake();

    // Check for programmatic exit/restart requests
    match get_exit_request() {
        jobs::ExitRequest::Quit => return Some(ExitReason::Quit),
        jobs::ExitRequest::Restart => return Some(ExitReason::Restart),
        jobs::ExitRequest::Running => {}
    }

    // Drive the session-lock state machine (lock/unlock requests,
    // grant/denial events, per-output lock surfaces)
    session_lock::process_session_lock(surface_manager, wayland_state, tree, gpu);

    // Run deferred owner disposals (public dispose_owner). Safe
    // here: no user closure is on the stack.
    reactive::owner::flush_pending_disposals();

    // What the renderer said about image textures last pass, and which images
    // let go of their decodes — settled here, where a signal may be written.
    // Before the background writes are flushed below: a raster the worker
    // delivered since is newer than the renderer's report that it had none,
    // and its write has to land last.
    image_decode::settle_image_events();

    // Process dynamic surface commands
    if !process_surface_commands(surface_manager, wayland_state, tree, quit_on_last_surface) {
        return Some(ExitReason::Quit);
    }

    // One instant for every surface this pass draws, and for every surface it
    // gives birth to: a surface created here is laid out here and drawn here,
    // and the enter animations that layout seeds are advanced by that draw. A
    // birth outside the frame's moment is an enter that has already travelled
    // when its first frame arrives. A driver that named an instant is obeyed.
    let frame_at = frame_at.unwrap_or_else(std::time::Instant::now);

    // Nothing has been left to draw on for long enough: the device goes, and
    // the renderer with it, since it holds the device too.
    if surface_manager.is_empty() && gpu.release_if_idle(frame_at) {
        *renderer = None;
    }

    // Initialize GPU for any pending surfaces (newly created dynamic surfaces)
    if !surface_manager.is_empty() {
        let Some(gpu_context) = gpu.get() else {
            return Some(ExitReason::Error(platform::PlatformError::NoGpu));
        };
        surface_manager.init_pending_gpu(gpu_context, wayland_state, tree, frame_at);
    }

    // Lazily create the shared renderer once the first surface has a
    // GPU state (apps may start with zero surfaces and spawn them
    // dynamically, e.g. one bar per output).
    if renderer.is_none()
        && let Some(wgpu_surface) = surface_manager.first_gpu_surface()
    {
        *renderer = Some(Renderer::new(
            wgpu_surface.device().clone(),
            wgpu_surface.queue().clone(),
            wgpu_surface.format(),
        ));
    }

    // Timers due by this pass's moment, on the pass's own clock, so a driver
    // that names the moment names which fire. Before the surfaces draw, so
    // what a callback writes is in this frame.
    reactive::timer::run_due_timers(frame_at);

    // Pastes whose text has arrived, handed to whoever asked before the
    // surfaces draw, so a field shows what it was given in this frame.
    reactive::clipboard::deliver_pastes(tree);

    // Flush background-thread signal writes once per frame (queued via WriteSignal).
    // Must run before take_wake_request() so that signal changes from bg writes
    // are processed into jobs before we check the wake request.
    reactive::flush_bg_writes();

    // Take the wake request once for all surfaces (not per-surface)
    let woken = take_wake_request();

    // Render each surface (no renderer yet means no surface has a
    // GPU state — nothing can be rendered this iteration)
    if let Some(renderer) = renderer.as_mut() {
        let surface_ids: Vec<SurfaceId> = surface_manager.ids().collect();

        // Live surface roots: the ownership domain for job
        // scheduling. Computed after surface commands/session-lock
        // processing so closed surfaces are already gone.
        let active_roots: rustc_hash::FxHashSet<WidgetId> = surface_ids
            .iter()
            .filter_map(|sid| surface_manager.get(*sid).map(|s| s.widget_id))
            .collect();

        // Resolve job ownership, then run the orphan lane: jobs
        // whose widget has no live surface (deferred Unregister
        // cleanup from closed surfaces, mostly) must not wait for
        // a render pass that will never come.
        jobs::distribute_jobs(tree, &active_roots);
        let orphans = jobs::drain_orphan_jobs();
        if !orphans.is_empty() {
            let mut scratch_layout_roots = Vec::new();
            process_jobs(&orphans, tree, &mut scratch_layout_roots);
        }
        jobs::recycle_job_buffer(orphans);

        // Drop layout roots of surfaces that no longer exist.
        layout_roots.retain(|root, _| active_roots.contains(root));

        for id in surface_ids {
            let Some(surface) = surface_manager.get_mut(id) else {
                continue;
            };
            let layout_roots = layout_roots.entry(surface.widget_id).or_default();
            let mut ctx = FrameContext {
                id,
                surface,
                wayland_state,
                renderer,
                tree,
            };
            render_surface(&mut ctx, layout_roots, woken, &active_roots, frame_at);
        }
    }

    // Hand the seat what the widgets changed — after the render
    // pass, so a copy or a cursor set by this iteration's event
    // handling still goes out in this iteration, and outside it, so
    // it goes out whether or not any surface had a frame to draw.
    sync_platform_state(wayland_state);

    // Everything this iteration queued goes out at once.
    if !wayland_state.flush() {
        return Some(ExitReason::Error(platform::PlatformError::ConnectionLost));
    }
    None
}

/// Everything an application leaves on **its own thread**, forgotten, so the
/// next one there starts clean: the widgets, the reactive arena, the job
/// queues.
///
/// Written once because it is read twice. `App` is the obvious caller;
/// [`Headless`](testing::Headless) is the other, and a list hand-copied into it
/// would go stale at the first cell added here — which is the failure
/// `restart_tests` already records once, where the reset was a hand-written
/// list of calls and the font was the line somebody missed.
///
/// What is deliberately *not* here is the state that belongs to the process
/// rather than the thread: the wake flag and the ping in [`jobs`], the ingress
/// sender, the background-write queue and its epoch. `App` clears those below,
/// because a program has one; `Headless` must not, because a test binary runs
/// several of them at once and clearing them reaches into somebody else's
/// application.
pub(crate) fn reset_thread_state(tree: &mut Tree) {
    // The tree BEFORE the queues. Dropping widgets triggers
    // ChildrenSource::drop() which pushes Unregister jobs; reset the queues
    // first and those late jobs survive into the next application and destroy
    // its widgets, which reuse the same ids.
    tree.clear();
    reactive::reset_reactive();
    app_state::reset();
}

impl Drop for App {
    fn drop(&mut self) {
        // Dispose the root owner first — cascades cleanup through the entire
        // reactive graph (signals, effects, cleanup callbacks).
        if let Some(root_id) = self.root_owner_id {
            reactive::dispose_owner_now(root_id);
        }

        reset_thread_state(&mut self.tree);

        // And the process-wide half, which only a program that owns the process
        // may clear. Retiring the background writes is what stops the next
        // application receiving the ones this one's services queued.
        jobs::reset_wakeup();
        ingress::reset_ingress();
        reactive::reset_bg_writes();
    }
}

impl Default for App {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod restart_tests {
    use super::*;
    use crate::jobs::{JobRequest, has_pending_jobs, request_job};
    use crate::reactive::clipboard::take_paste_requests;
    use crate::reactive::owner::create_root_owner;
    use crate::reactive::{
        clipboard_copy, clipboard_paste, create_signal, flush_bg_writes, take_clipboard_change,
    };
    use crate::surface::drain_surface_commands;
    use crate::widget_ref::create_widget_ref;

    #[test]
    fn widget_drop_can_read_global_focus_and_the_next_app_starts_clean() {
        use std::cell::Cell;
        use std::rc::Rc;

        struct ReadsFocusOnDrop {
            inner: Box<dyn Widget>,
            drops: Rc<Cell<usize>>,
        }

        impl Widget for ReadsFocusOnDrop {
            fn layout(
                &mut self,
                ctx: &mut crate::tree::LayoutCtx,
                constraints: crate::layout::Constraints,
            ) -> crate::layout::Size {
                self.inner.layout(ctx, constraints)
            }

            fn paint(&self, ctx: &mut crate::renderer::PaintContext) {
                self.inner.paint(ctx);
            }
        }

        impl Drop for ReadsFocusOnDrop {
            fn drop(&mut self) {
                assert_eq!(crate::reactive::focus::focused_widget(), None);
                assert!(crate::reactive::focus::focus_path().is_empty());
                self.drops.set(self.drops.get() + 1);
            }
        }

        let _wakeup = crate::jobs::wakeup_test_lock();
        let drops = Rc::new(Cell::new(0));
        for expected_drops in 1..=2 {
            let mut app = App::new();
            app.root_owner_id = Some(create_root_owner());
            assert_eq!(crate::reactive::focus::focused_widget(), None);
            let widget = app.tree.register(Box::new(ReadsFocusOnDrop {
                inner: Box::new(crate::widgets::container()),
                drops: drops.clone(),
            }));
            crate::reactive::focus::request_focus(&app.tree, widget);
            assert_eq!(crate::reactive::focus::focused_widget(), Some(widget));

            drop(app);

            assert_eq!(drops.get(), expected_drops);
            assert!(!has_pending_jobs());
        }
    }

    /// The font the last `App` declared is state of the last `App`. It was the
    /// one cell `App::drop` never reset, and nothing noticed because the reset
    /// was a hand-written list of calls rather than a value.
    #[test]
    fn a_second_app_does_not_inherit_the_font_the_first_one_declared() {
        let first = App::new().default_font_family(FontFamily::name("Inter"));
        assert_eq!(
            default_font_family(),
            FontFamily::name("Inter"),
            "the declaration reaches the widgets that will read it"
        );
        drop(first);

        let _next = App::new();

        assert_eq!(
            default_font_family(),
            FontFamily::SansSerif,
            "an App that declares no font gets the default, not the last App's"
        );
    }

    /// Font *data* goes the same way as the family, which is a change: the
    /// bytes used to outlive every `App` on the thread, so a restarting
    /// program that loaded its font once above the loop kept it. It reloads
    /// it each run now — `load_font` says so, and the hash beside it is what
    /// makes reloading the same bytes cost nothing.
    #[test]
    fn a_second_app_does_not_inherit_the_fonts_the_first_one_loaded() {
        let first = App::new();
        load_font(vec![11u8; 64]);
        assert_eq!(
            get_registered_fonts().len(),
            1,
            "the App under test has a font to forget"
        );
        drop(first);

        let _next = App::new();

        assert!(
            get_registered_fonts().is_empty(),
            "the next App would draw in a font it was never given"
        );
    }

    #[test]
    fn writers_from_the_first_app_cannot_change_the_second_apps_signals() {
        let first = App::new();
        let stale_set = create_signal(1u32).writer();
        let stale_update = create_signal(2u32).writer();
        let stale_set_always = create_signal(3u32).writer();
        let stale_update_always = create_signal(4u32).writer();
        drop(first);

        let _next = App::new();
        let set_target = create_signal(10u32);
        let update_target = create_signal(20u32);
        let set_always_target = create_signal(30u32);
        let update_always_target = create_signal(40u32);

        stale_set.set(11);
        stale_update.update(|value| *value = 21);
        stale_set_always.set_always(31);
        stale_update_always.update_always(|value| *value = 41);

        assert_eq!(set_target.get_untracked(), 10);
        assert_eq!(update_target.get_untracked(), 20);
        assert_eq!(set_always_target.get_untracked(), 30);
        assert_eq!(update_always_target.get_untracked(), 40);

        update_always_target
            .writer()
            .update_always(|value| *value = 41);
        assert_eq!(update_always_target.get_untracked(), 41);
    }

    #[test]
    fn background_writers_from_the_first_app_cannot_change_the_second_apps_signals() {
        let first = App::new();
        let stale_set = create_signal(1u32).writer();
        let stale_update = create_signal(2u32).writer();
        let stale_set_always = create_signal(3u32).writer();
        let stale_update_always = create_signal(4u32).writer();
        std::thread::spawn(move || {
            stale_set.set(11);
            stale_update.update(|value| *value = 21);
            stale_set_always.set_always(31);
            stale_update_always.update_always(|value| *value = 41);
        })
        .join()
        .unwrap();

        drop(first);
        let _next = App::new();
        let set_target = create_signal(10u32);
        let update_target = create_signal(20u32);
        let set_always_target = create_signal(30u32);
        let update_always_target = create_signal(40u32);
        flush_bg_writes();

        assert_eq!(set_target.get_untracked(), 10);
        assert_eq!(update_target.get_untracked(), 20);
        assert_eq!(set_always_target.get_untracked(), 30);
        assert_eq!(update_always_target.get_untracked(), 40);
    }

    #[test]
    fn late_background_writers_cannot_change_the_second_apps_signals() {
        let first = App::new();
        let stale_set = create_signal(1u32).writer();
        let stale_update = create_signal(2u32).writer();
        let stale_set_always = create_signal(3u32).writer();
        let stale_update_always = create_signal(4u32).writer();
        drop(first);

        let _next = App::new();
        let set_target = create_signal(10u32);
        let update_target = create_signal(20u32);
        let set_always_target = create_signal(30u32);
        let update_always_target = create_signal(40u32);
        std::thread::spawn(move || {
            stale_set.set(11);
            stale_update.update(|value| *value = 21);
            stale_set_always.set_always(31);
            stale_update_always.update_always(|value| *value = 41);
        })
        .join()
        .unwrap();
        flush_bg_writes();

        assert_eq!(set_target.get_untracked(), 10);
        assert_eq!(update_target.get_untracked(), 20);
        assert_eq!(set_always_target.get_untracked(), 30);
        assert_eq!(update_always_target.get_untracked(), 40);
    }

    /// A `WriteSignal` is one handle an `App` can leave behind; the
    /// `RwSignal` it came from is another, and reads its id the same way.
    #[test]
    fn signals_from_the_first_app_cannot_reach_the_second_apps_signals() {
        let first = App::new();
        let stale = create_signal(1u32);
        drop(first);

        let _next = App::new();
        let target = create_signal(10u32);

        stale.set(11);

        assert_eq!(target.get_untracked(), 10);
        assert!(stale.try_get_untracked().is_none());
    }

    /// The order inside the reset, which is the one thing about it the
    /// compiler cannot check.
    ///
    /// A queued surface command carries a widget factory, and what that
    /// factory captured is dropped with it — a `ChildrenSource` among them,
    /// whose own `Drop` asks for an Unregister job
    /// (`src/widgets/children.rs`). So the queue holding the command has to
    /// be emptied *before* the job queue, and a value that queues from its
    /// `Drop` is what says so: reorder those two lines in
    /// `app_state::reset` and this goes red.
    #[test]
    fn a_job_queued_while_the_app_is_being_forgotten_is_forgotten_too() {
        let _wakeup = crate::jobs::wakeup_test_lock();
        struct QueuesOnDrop(WidgetId);
        impl Drop for QueuesOnDrop {
            fn drop(&mut self) {
                request_job(self.0, JobRequest::Unregister);
            }
        }

        create_root_owner();
        let mut app = App::new();
        let widget = app
            .tree
            .register(Box::new(crate::widgets::container()) as Box<dyn Widget>);

        let late = QueuesOnDrop(widget);
        crate::surface::spawn_surface(crate::surface::SurfaceConfig::new(), move || {
            let _captured = &late;
            crate::widgets::container()
        });

        drop(app);

        assert!(
            !has_pending_jobs(),
            "a command dropped by the reset queued a job the reset had already emptied"
        );
    }

    /// Everything the application queues for the loop dies with the `App` that
    /// queued it: the next one starts on an empty outbox, not on work aimed at
    /// a tree that no longer exists.
    #[test]
    fn nothing_the_last_app_queued_survives_its_drop() {
        let _wakeup = crate::jobs::wakeup_test_lock();
        create_root_owner();
        let mut app = App::new();

        let widget = app
            .tree
            .register(Box::new(crate::widgets::container()) as Box<dyn Widget>);
        request_job(widget, JobRequest::Paint);
        crate::surface::spawn_surface(crate::surface::SurfaceConfig::new(), || {
            crate::widgets::container()
        });
        clipboard_copy("a secret");
        clipboard_paste(|_| {});
        create_widget_ref().focus();
        crate::session_lock::unlock_session();

        assert!(has_pending_jobs(), "the App under test has work to forget");

        drop(app);

        assert!(!has_pending_jobs(), "a job is still aimed at the old tree");
        assert!(
            drain_surface_commands().is_empty(),
            "the loop would open a surface the old App asked for"
        );
        assert_eq!(
            take_clipboard_change(),
            None,
            "the next App would offer the last one's copy"
        );
        assert!(
            take_paste_requests().is_empty(),
            "the next App would read for a paste the last one asked for"
        );
        with_app_state(|app| {
            assert!(
                app.pending_focus.borrow().is_none(),
                "a focus request outlived the widget it named"
            );
            assert!(
                app.lock_request.is_empty(),
                "the next App would answer a lock question it was never asked"
            );
        });
    }
}

#[cfg(test)]
mod exclusive_zone_resync_tests {
    use super::*;
    use crate::platform::Anchor;
    use crate::surface::{ExclusiveZone, Margin, SurfaceExtent};

    /// The reservation has to follow the size that was just *requested*. The
    /// compositor only tells us the new size a round trip later, so resolving
    /// against what it last said reserves for the size the surface is leaving.
    #[test]
    fn a_fixed_axis_resolves_against_the_requested_size() {
        // A bar that was 32 tall and has just asked for 48.
        let live_height = Some(32);
        let height = surface::requested_extent(SurfaceExtent::Fixed(48), live_height);
        assert_eq!(height, 48, "the request wins over the stale configure");

        let zone = ExclusiveZone::Auto.resolve(Anchor::TOP, Margin::default(), 800, height);
        assert_eq!(zone, 48);
    }

    /// A content axis has no number of its own yet — `initial()` is 1px, which
    /// must never be what a running surface asks for.
    #[test]
    fn a_content_axis_holds_the_live_size_until_it_is_measured() {
        assert_eq!(
            surface::requested_extent(SurfaceExtent::Content, Some(240)),
            240
        );
        // Before the first configure there is nothing better to say, and the
        // placeholder is what creation asks for too — the content-measure pass
        // runs on a surface's first frames regardless, so this is a size it is
        // on its way out of rather than one it can be stuck at. What must not
        // happen is reporting the placeholder as though the compositor had
        // agreed to it, which is why `live` is the *configured* size.
        assert_eq!(
            surface::requested_extent(SurfaceExtent::Content, None),
            SurfaceExtent::Content.initial()
        );
        assert_eq!(
            surface::requested_extent(SurfaceExtent::Content, Some(1)),
            1,
            "and once configured at 1px, 1px is the honest answer"
        );
    }

    /// The anchor is what an `Auto` reservation reads to decide which axis it
    /// follows and which edge's margin counts, so a bar becoming a side dock has
    /// to reserve on the other axis. It used to keep reserving its old one:
    /// `SetAnchor` was the one command that recorded nothing on the config.
    #[test]
    fn a_reservation_follows_the_anchor_it_was_given() {
        let margin = Margin::default();

        // A 800x32 bar at the top reserves its height.
        let bar = ExclusiveZone::Auto.resolve(Anchor::TOP, margin, 800, 32);
        assert_eq!(bar, 32);

        // The same surface, re-anchored as a 48-wide dock on the left, has to
        // reserve its width instead.
        let dock = ExclusiveZone::Auto.resolve(Anchor::LEFT, margin, 48, 600);
        assert_eq!(dock, 48);
        assert_ne!(dock, bar, "the axis genuinely changes with the anchor");
    }

    /// Handing an axis back to `content()` at runtime must not ask for 1px, and
    /// must ask for a layout — nothing else brings the content-measure pass
    /// round for a surface whose widgets did not change.
    #[test]
    fn handing_an_axis_to_content_keeps_the_size_and_asks_for_a_measure() {
        let live = Some((300u32, 40u32));
        let anchored = |w: SurfaceExtent, h: SurfaceExtent| SurfaceConfig {
            anchor: Anchor::TOP,
            width: w,
            height: h,
            ..SurfaceConfig::new()
        };

        let (w, h, measure) =
            surface::resize_request(&anchored(SurfaceExtent::Content, 40.into()), live);
        assert_eq!((w, h), (300, 40), "no 1px collapse");
        assert!(measure, "the measure pass has to be woken");

        let (w, h, measure) = surface::resize_request(&anchored(200.into(), 60.into()), live);
        assert_eq!((w, h), (200, 60));
        assert!(!measure, "two fixed axes need no measure");
    }

    /// A `content()` axis the compositor owns is measured and then thrown away.
    /// Asking for the measure anyway re-lays out the whole subtree on every
    /// resize and every re-anchoring, to produce a number nothing can use.
    #[test]
    fn a_stretched_content_axis_asks_for_no_measure() {
        let live = Some((1920u32, 32u32));
        let bar = |anchor: Anchor| SurfaceConfig {
            anchor,
            width: SurfaceExtent::Content,
            height: 32.into(),
            ..SurfaceConfig::new()
        };

        let stretched = bar(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT);
        let (_, _, measure) = surface::resize_request(&stretched, live);
        assert!(!measure, "the width is the compositor's either way");
        assert!(
            !surface::needs_content_measure(&stretched),
            "and the frame loop's measure pass asks the same question, or it \
             re-measures a discarded axis on every frame that lays anything out"
        );

        let ours = bar(Anchor::TOP | Anchor::LEFT);
        let (_, _, measure) = surface::resize_request(&ours, live);
        assert!(
            measure,
            "anchored to one edge it is ours, and has to be measured"
        );
        assert!(surface::needs_content_measure(&ours));
    }

    /// And until it *is* measured there is nothing to reserve for. The confirmed
    /// size of a stretched axis is the compositor's, not a measurement: a bar
    /// declared `width(content()).anchor(TOP | LEFT | RIGHT)` is confirmed at the
    /// screen's 1920, and re-anchoring it into a side dock turns that into a
    /// reservation for the whole screen — every other window pushed off it — for
    /// the frame between the command and the measure.
    #[test]
    fn a_reservation_waits_for_the_measure_rather_than_guessing() {
        // A left dock: anchored to one horizontal edge and both vertical ones, so
        // the height is the compositor's and the reservation follows the width.
        let dock = SurfaceConfig {
            anchor: Anchor::LEFT | Anchor::TOP | Anchor::BOTTOM,
            width: SurfaceExtent::Content,
            height: 32.into(),
            exclusive_zone: surface::ExclusiveZone::Auto,
            ..SurfaceConfig::new()
        };

        // What the stretched anchor left behind, and what the content is worth.
        let stale = 1920;
        let measured = 240;

        assert!(
            surface::needs_content_measure(&dock),
            "the width is ours now, so it is waiting on a measure"
        );
        assert_eq!(
            dock.exclusive_zone
                .resolve(dock.anchor, dock.margin, measured, 32),
            240,
            "the measure is what it reserves for"
        );
        assert_eq!(
            dock.exclusive_zone
                .resolve(dock.anchor, dock.margin, stale, 32),
            1920,
            "and the confirmed size is the whole screen, which is why publishing \
             from it has to wait"
        );
    }

    /// Only `Auto` waits, because only `Auto` reads a size. The other three are
    /// constants: deferring one would hold `set_exclusive_zone(Fixed(40))` on a
    /// surface with a `content()` axis until something happened to measure it,
    /// for a number that needs no measure.
    #[test]
    fn only_a_reservation_that_reads_a_size_waits_for_one() {
        let toast = |zone| SurfaceConfig {
            anchor: Anchor::LEFT | Anchor::TOP | Anchor::BOTTOM,
            width: SurfaceExtent::Content,
            height: SurfaceExtent::Content,
            exclusive_zone: zone,
            ..SurfaceConfig::new()
        };

        assert!(
            surface::needs_content_measure(&toast(surface::ExclusiveZone::Auto)),
            "the premise: this is the surface whose measure is pending"
        );

        // Whatever size these are handed, they answer the same thing — so there
        // is nothing for them to wait for.
        for zone in [
            surface::ExclusiveZone::Fixed(40),
            surface::ExclusiveZone::None,
            surface::ExclusiveZone::Ignore,
        ] {
            let config = toast(zone);
            let unmeasured = zone.resolve(config.anchor, config.margin, 1, 1);
            let measured = zone.resolve(config.anchor, config.margin, 240, 60);
            assert_eq!(
                unmeasured, measured,
                "{zone:?} does not depend on the size, so deferring it only loses it"
            );
        }
    }

    /// Which axes are the compositor's follows from the anchor, and layer-shell
    /// is strict about it: omitting a dimension *without* opposite-edge
    /// anchoring is a protocol error, so a bar re-anchored to one edge has to
    /// stop asking for zero on the axis it now owns — at the next commit, which
    /// is every frame, the compositor would close the connection.
    #[test]
    fn the_size_asked_for_follows_the_anchor() {
        let bar = |anchor: Anchor| SurfaceConfig {
            anchor,
            width: 800.into(),
            height: 32.into(),
            ..SurfaceConfig::new()
        };
        let live = Some((1920u32, 32u32));

        let stretched =
            surface::resize_request(&bar(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT), live);
        assert_eq!(
            (stretched.0, stretched.1),
            (0, 32),
            "anchored to both horizontal edges, the width is the compositor's"
        );

        let pinned = surface::resize_request(&bar(Anchor::TOP | Anchor::LEFT), live);
        assert_eq!(
            (pinned.0, pinned.1),
            (800, 32),
            "anchored to one, it is ours again and must be sent"
        );

        let dock = surface::resize_request(&bar(Anchor::LEFT | Anchor::TOP | Anchor::BOTTOM), live);
        assert_eq!(
            (dock.0, dock.1),
            (800, 0),
            "and the other axis, the other way"
        );
    }
}

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

    /// An app that reloads its config calls load_font again on every run.
    /// Without dedup each run kept another copy of the same bytes.
    #[test]
    fn loading_the_same_font_twice_registers_it_once() {
        let font = vec![7u8; 64];
        super::load_font(font.clone());
        let after_first = with_app_state(|app| app.custom_fonts.borrow().len());
        super::load_font(font);
        let after_second = with_app_state(|app| app.custom_fonts.borrow().len());
        assert_eq!(after_first, after_second);

        super::load_font(vec![9u8; 64]);
        assert_eq!(
            with_app_state(|app| app.custom_fonts.borrow().len()),
            after_second + 1,
            "a different font must still register"
        );
    }
}

#[cfg(test)]
mod dispatch_declares_the_moment {
    use super::*;
    use crate::layout::Size;
    use crate::tree::LayoutCtx;
    use crate::widgets::widget::{Event, EventResponse};

    /// A widget that records what time the tree said it was when it was handed
    /// an event.
    struct Spy(std::rc::Rc<std::cell::Cell<Option<crate::clock::EventInstant>>>);

    impl widgets::Widget for Spy {
        fn layout(
            &mut self,
            _ctx: &mut LayoutCtx,
            constraints: crate::layout::Constraints,
        ) -> Size {
            Size::new(constraints.max_width, constraints.max_height)
        }

        fn paint(&self, _ctx: &mut crate::renderer::PaintContext) {}

        fn event(&mut self, tree: &mut Tree, _id: WidgetId, _event: &Event) -> EventResponse {
            self.0.set(Some(tree.event_instant()));
            EventResponse::Handled
        }
    }

    /// The queue carries each event's moment and `dispatch_events` is what puts
    /// it where a widget can read it. Without that one line every widget falls
    /// back to the clock, which is what they all did before this existed — and
    /// the tests of the widgets themselves cannot tell, because they declare
    /// the instant by hand.
    ///
    /// So this one does not: it goes through the dispatcher, as the loop does.
    #[test]
    fn a_widget_is_told_when_the_event_it_is_handed_happened() {
        let seen = std::rc::Rc::new(std::cell::Cell::new(None));
        let mut tree = Tree::new();
        let root = tree.register(Box::new(Spy(seen.clone())));
        tree.set_origin(root, 0.0, 0.0);

        // An hour ago: no clock this process could read would answer with it,
        // so the widget can only have got it from the event.
        let happened = std::time::Instant::now() - std::time::Duration::from_secs(3600);
        let happened_on_the_event_clock = crate::clock::EventInstant::from(happened);
        let events = [(happened, Event::mouse_move(10.0, 10.0))];

        dispatch_events(&events, root, &mut tree, &Default::default(), || false);

        assert_eq!(
            seen.get(),
            Some(happened_on_the_event_clock),
            "the widget has to be told the moment the queue carried, not the \
             moment the dispatch ran"
        );
        // And once the dispatch is over the moment is gone: what a later
        // reader gets is the clock, not the last event's time.
        let after = tree.event_instant();
        assert!(
            after > happened_on_the_event_clock,
            "the moment has to be cleared when the dispatch ends, got {after:?} \
             for an event from an hour ago"
        );
    }
}

/// Where a press stops being the focused field's business.
///
/// Focus used to leave only with the whole surface: `Event::FocusOut` comes
/// from `wl_keyboard.leave` and nothing else, so a press that landed anywhere
/// else in the same surface left the caret blinking in a field the user had
/// walked away from. The dispatcher is the only place that can see the
/// difference, because it is the only place that learns whether *anything*
/// claimed the press.
#[cfg(test)]
mod a_press_nothing_claimed_takes_the_focus_with_it {
    use super::*;
    use crate::layout::{Constraints, Flex};
    use crate::reactive::create_signal;
    use crate::reactive::owner::create_root_owner;
    use crate::widget_ref::{WidgetRef, create_widget_ref, update_widget_refs};
    use crate::widgets::state_layer::Stateful;
    use crate::widgets::widget::{Event, MouseButton};
    use crate::widgets::{Widget, container, text_input};

    /// A surface: one root, laid out at 200x100, driven through the dispatcher
    /// the loop drives. Two of them share a `Tree`, because the application
    /// holds every surface's root in one.
    struct Screen {
        tree: Tree,
        root: WidgetId,
    }

    impl Screen {
        fn new(widget: impl Widget + 'static) -> Self {
            let mut tree = Tree::new();
            let root = Self::lay_out(&mut tree, widget);
            Self { tree, root }
        }

        /// A second surface beside the first, in the tree they share.
        fn add(&mut self, widget: impl Widget + 'static) -> WidgetId {
            Self::lay_out(&mut self.tree, widget)
        }

        fn lay_out(tree: &mut Tree, widget: impl Widget + 'static) -> WidgetId {
            let root = tree.register(Box::new(widget));
            tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
            tree.set_origin(root, 0.0, 0.0);
            tree.layout_widget(root, Constraints::new(0.0, 0.0, 200.0, 100.0));
            // The handles resolve once their widgets have been laid out, which
            // is the order the loop runs them in.
            update_widget_refs(tree);
            root
        }

        /// A left press on this screen's own surface.
        fn press(&mut self, x: f32, y: f32) {
            let root = self.root;
            self.press_button(root, x, y, MouseButton::Left);
        }

        /// A press and its release, which is the gesture a click is made of:
        /// `on_click` fires on the release and only if the press was seen.
        fn click(&mut self, x: f32, y: f32) {
            self.press(x, y);
            let root = self.root;
            let events = [(
                std::time::Instant::now(),
                Event::mouse_up(x, y, MouseButton::Left),
            )];
            dispatch_events(&events, root, &mut self.tree, &Default::default(), || false);
        }

        fn press_button(&mut self, root: WidgetId, x: f32, y: f32, button: MouseButton) {
            let events = [(std::time::Instant::now(), Event::mouse_down(x, y, button))];
            dispatch_events(&events, root, &mut self.tree, &Default::default(), || false);
        }
    }

    /// A handle for the field, in a fresh owner: the ref and the signal behind
    /// it are made before the tree that will come to hold them.
    fn a_field() -> WidgetRef {
        create_root_owner();
        create_widget_ref()
    }

    /// A field on a surface with nothing else on it, with the keyboard already
    /// in it. The press that put it there is the same in four of the tests
    /// below, and it is the half of the rule that already worked.
    fn a_focused_field() -> (Screen, WidgetRef) {
        let field = a_field();
        let mut screen = Screen::new(
            container()
                .width(200.0)
                .height(100.0)
                .child(text_input(create_signal(String::new())).widget_ref(field)),
        );

        screen.press(100.0, 8.0);
        assert!(field.is_focused(), "a press inside the field focuses it");
        (screen, field)
    }

    /// The press that lands on the background is claimed by nobody, and there
    /// is nothing left for the focus to belong to.
    #[test]
    fn a_press_on_the_background_takes_the_keyboard_off_the_field() {
        let (mut screen, field) = a_focused_field();

        screen.press(100.0, 80.0);
        assert!(
            !field.is_focused(),
            "a press on the background is a press on nothing, and takes the \
             keyboard with it"
        );
    }

    /// The press the field itself claimed. Nothing to do with the rule, and
    /// everything to do with it not firing on the gesture that grants focus.
    #[test]
    fn a_press_inside_the_field_keeps_it() {
        let (mut screen, field) = a_focused_field();

        screen.press(40.0, 8.0);
        assert!(
            field.is_focused(),
            "a second press inside the field moves the caret, it does not \
             surrender the keyboard"
        );
    }

    /// `TextInput` takes the focus on a middle press as readily as a left one
    /// (the primary-selection paste), so a middle press has to be able to take
    /// it away.
    #[test]
    fn a_middle_press_on_the_background_takes_the_keyboard_too() {
        let (mut screen, field) = a_focused_field();
        let root = screen.root;

        screen.press_button(root, 100.0, 80.0, MouseButton::Middle);
        assert!(
            !field.is_focused(),
            "the button that can take the focus can give it back"
        );
    }

    /// The arms that grant focus are guarded on left and middle, so a right
    /// press inside the field falls past all of them. Read as "nobody claimed
    /// it" that is a press on nothing — and it landed on the caret.
    #[test]
    fn a_right_press_inside_the_field_keeps_it() {
        let (mut screen, field) = a_focused_field();
        let root = screen.root;

        screen.press_button(root, 100.0, 8.0, MouseButton::Right);
        assert!(
            field.is_focused(),
            "a press inside the field is the field's, whatever the button"
        );
    }

    /// The other half of the box's claim: it holds presses because it holds
    /// *this* focus, not because it once declared it would light up for one.
    /// Without the second half every `when_focused` box in an application
    /// swallows every press inside it.
    #[test]
    fn a_when_focused_box_holding_no_focus_claims_nothing() {
        let field = a_field();
        let mut screen = Screen::new(
            container()
                .width(200.0)
                .height(100.0)
                .layout(Flex::column())
                .child(
                    container()
                        .padding(8.0)
                        .when_focused(|s| s.border(2.0, crate::widgets::Color::WHITE))
                        .child(text_input(create_signal(String::new())).widget_ref(field)),
                )
                .child(
                    container()
                        .width(200.0)
                        .height(40.0)
                        .when_focused(|s| s.border(2.0, crate::widgets::Color::WHITE)),
                ),
        );

        screen.press(100.0, 12.0);
        assert!(field.is_focused(), "the press reached the field");

        screen.press(100.0, 50.0);
        assert!(
            !field.is_focused(),
            "a box that declares when_focused while the focus is elsewhere has              claimed nothing, and the press is still a press on nothing"
        );
    }

    /// Focus is one signal for the whole application while one `Tree` holds
    /// every surface's root. A press on the bar must not blur the field on the
    /// popup: the focus path ends at the root that owns it, and that is not
    /// this one.
    #[test]
    fn a_press_in_one_surface_does_not_blur_a_field_focused_in_another() {
        let (mut screen, field) = a_focused_field();
        let other = screen.add(container().width(200.0).height(100.0));

        screen.press_button(other, 100.0, 80.0, MouseButton::Left);
        assert!(
            field.is_focused(),
            "a press on another surface says nothing about where this one's \
             keyboard is"
        );
    }

    /// The box drawn around a field is the field, as far as the user is
    /// concerned: it lights up when the focus is inside it, and clicking its
    /// padding is clicking the thing it draws.
    #[test]
    fn a_press_on_the_padding_of_a_when_focused_box_keeps_it() {
        let field = a_field();
        let mut screen = Screen::new(
            container().width(200.0).height(100.0).child(
                container()
                    .padding(8.0)
                    .when_focused(|s| s.border(2.0, crate::widgets::Color::WHITE))
                    .child(text_input(create_signal(String::new())).widget_ref(field)),
            ),
        );

        screen.press(100.0, 12.0);
        assert!(field.is_focused(), "the press reached the field");

        screen.press(4.0, 4.0);
        assert!(
            field.is_focused(),
            "the padding of the box that lights up for this focus belongs to it"
        );
    }

    /// Keeping the keyboard and consuming the press are two different
    /// sentences, and the box that keeps the focus says only the first.
    ///
    /// A clickable row wrapping a decorated field: pressing the box's padding
    /// is pressing the field as far as the focus goes, and pressing the row as
    /// far as the row goes. Answering with `Handled` said both at once, so the
    /// row never saw the press and its `on_click` never fired — and which of
    /// the two happened depended on where the keyboard was.
    #[test]
    fn a_box_that_keeps_the_focus_does_not_swallow_the_press() {
        let field = a_field();
        let clicks = std::rc::Rc::new(std::cell::Cell::new(0u32));
        let counted = std::rc::Rc::clone(&clicks);
        let mut screen = Screen::new(
            container()
                .width(200.0)
                .height(100.0)
                .on_click(move || counted.set(counted.get() + 1))
                .child(
                    container()
                        .padding(8.0)
                        .when_focused(|s| s.border(2.0, crate::widgets::Color::WHITE))
                        .child(text_input(create_signal(String::new())).widget_ref(field)),
                ),
        );

        // Released, because a press left down leaves the field dragging a
        // selection and the next release is the field's by right.
        screen.click(100.0, 12.0);
        assert!(field.is_focused(), "the press reached the field");
        assert_eq!(
            clicks.get(),
            0,
            "which the field claimed, so the row did not"
        );

        screen.click(4.0, 4.0);
        assert!(
            field.is_focused(),
            "the padding of the box that lights up for this focus belongs to it"
        );
        assert_eq!(
            clicks.get(),
            1,
            "and the row around it is still a row that can be clicked"
        );
    }

    /// The claim belongs to the press that earned it and to no other.
    ///
    /// It is one field on the tree, and what makes it mean "this press" rather
    /// than "some press once" is that `dispatch_events` clears it going into
    /// every event. Without that line the first press on a focused box latches
    /// it, and nothing blurs a field again for the life of the process — the
    /// whole of #206 undone, silently, by a flag nobody reset.
    #[test]
    fn a_claim_does_not_outlive_the_press_that_made_it() {
        let field = a_field();
        let mut screen = Screen::new(
            container().width(200.0).height(100.0).child(
                container()
                    .padding(8.0)
                    .when_focused(|s| s.border(2.0, crate::widgets::Color::WHITE))
                    .child(text_input(create_signal(String::new())).widget_ref(field)),
            ),
        );

        screen.press(100.0, 12.0);
        assert!(field.is_focused(), "the press reached the field");

        screen.press(4.0, 4.0);
        assert!(field.is_focused(), "the box's padding claims this one");

        screen.press(100.0, 80.0);
        assert!(
            !field.is_focused(),
            "the claim belonged to the press before it, not to this one"
        );
    }

    /// The box is asked where the press landed, and it is asked in its own
    /// coordinates.
    ///
    /// The box sits 50 down the surface and at zero inside its own parent, so
    /// the two answers cannot be confused for one another: its surface rows are
    /// 50 to 90, its parent-relative rows are 0 to 40, and the press below is
    /// in the first and not the second. Only the walk knows the difference —
    /// by the time the event reaches the box the point has been rebased through
    /// every ancestor. Resolving this from outside, against the bounds the tree
    /// stores, tests the press against a rectangle somewhere else entirely.
    #[test]
    fn a_box_offset_from_the_surface_is_asked_in_its_own_coordinates() {
        let field = a_field();
        let mut screen = Screen::new(
            container()
                .width(200.0)
                .height(100.0)
                .layout(Flex::column())
                .child(container().width(200.0).height(50.0))
                .child(
                    container().layout(Flex::column()).child(
                        container()
                            .width(200.0)
                            .height(40.0)
                            .padding(8.0)
                            .when_focused(|s| s.border(2.0, crate::widgets::Color::WHITE))
                            .child(text_input(create_signal(String::new())).widget_ref(field)),
                    ),
                ),
        );

        screen.press(100.0, 65.0);
        assert!(field.is_focused(), "the press reached the field");

        // The bottom padding of the box: inside it on the surface, outside the
        // rectangle the tree stores for it.
        screen.press(100.0, 85.0);
        assert!(
            field.is_focused(),
            "the padding of the box belongs to it wherever the box happens to be"
        );
    }

    /// The field itself keeps the focus on a press it does not otherwise claim,
    /// and that must not silence an ancestor either.
    ///
    /// A right press inside a focused field falls past every arm that grants
    /// focus, so the field has to say the press is its own. Saying it with
    /// `Handled` meant a row wrapping the field never got its context menu —
    /// and got one when the field was not focused. The same conflation as the
    /// box, one widget over.
    #[test]
    fn a_field_keeping_its_own_focus_does_not_swallow_the_press() {
        let field = a_field();
        let menus = std::rc::Rc::new(std::cell::Cell::new(0u32));
        let counted = std::rc::Rc::clone(&menus);
        let mut screen = Screen::new(
            container()
                .width(200.0)
                .height(100.0)
                .on_right_click(move || counted.set(counted.get() + 1))
                .child(text_input(create_signal(String::new())).widget_ref(field)),
        );

        screen.press(100.0, 8.0);
        assert!(field.is_focused(), "the press reached the field");

        let root = screen.root;
        screen.press_button(root, 100.0, 8.0, MouseButton::Right);
        assert!(
            field.is_focused(),
            "a press inside the field is the field's, whatever the button"
        );
        assert_eq!(
            menus.get(),
            1,
            "and the row around it still opens its context menu"
        );
    }

    /// A toolbar button acting on the field, spelled the way every button is
    /// spelled: it has an `on_click`, so it claims the press, so the press is
    /// not a press on nothing.
    #[test]
    fn a_press_a_button_claimed_keeps_it() {
        let field = a_field();
        let mut screen = Screen::new(
            container()
                .width(200.0)
                .height(100.0)
                .layout(Flex::column())
                .child(text_input(create_signal(String::new())).widget_ref(field))
                .child(container().width(200.0).height(40.0).on_click(|| {})),
        );

        screen.press(100.0, 8.0);
        assert!(field.is_focused(), "the press reached the field");

        screen.press(100.0, 40.0);
        assert!(
            field.is_focused(),
            "a widget that claimed the press said the press was its own; the \
             focus is not up for grabs"
        );
    }
}

/// A frame is a description of what the compositor said, and the pacing gate is
/// a decision taken from that description. Neither needs a compositor to exist,
/// and until the Wayland types came out of the frame path neither could be
/// named here: `Frame` held a live `WlSurface`, and a test has no display to
/// get one from.
#[cfg(test)]
mod a_frame_is_a_description_not_a_connection {
    use super::*;

    /// A surface with a frame out, and its callback in flight or come back —
    /// reached the way a surface reaches it, through what it is told.
    fn pacing(callback_pending: bool) -> surface::FramePacing {
        let mut pacing = surface::FramePacing::default();
        pacing.committed();
        if !callback_pending {
            pacing.callback_done();
        }
        pacing
    }

    fn frame(callback_pending: bool) -> Frame {
        Frame {
            events: Vec::new(),
            scale_factor: 1.0,
            width: 200,
            height: 50,
            pacing: pacing(callback_pending),
        }
    }

    fn geometry(needs_resize: bool, scale_changed: bool) -> Geometry {
        Geometry {
            physical_width: 200,
            physical_height: 50,
            needs_resize,
            scale_changed,
            declare_destination: None,
        }
    }

    #[test]
    fn a_frame_can_be_described_without_a_display() {
        let f = frame(false);
        assert_eq!((f.width, f.height), (200, 50));
    }

    #[test]
    fn a_callback_still_in_flight_paces_a_frame_out() {
        assert!(paced_out(&frame(true), &geometry(false, false)));
    }

    /// Each on its own, because either alone has to open the gate.
    #[test]
    fn a_resize_and_a_scale_change_each_bypass_the_gate() {
        assert!(!paced_out(&frame(true), &geometry(true, false)));
        assert!(!paced_out(&frame(true), &geometry(false, true)));
    }

    #[test]
    fn no_callback_in_flight_paces_nothing_out() {
        assert!(!paced_out(&frame(false), &geometry(false, false)));
    }
}

/// What a missing GPU adapter means to a test: skip, unless
/// `GUIDO_GPU_REQUIRED` says a skip is a failure.
///
/// A test that needs an adapter and silently passes without one reports green
/// for the single reason that matters, so the job pointed at lavapipe sets that
/// variable and a skip becomes a failure there. Written once because the
/// variable's name and the message are the contract that job depends on.
#[cfg(test)]
fn or_skip<T>(made: Option<T>) -> Option<T> {
    match made {
        Some(made) => Some(made),
        None if std::env::var_os("GUIDO_GPU_REQUIRED").is_some() => {
            panic!("GUIDO_GPU_REQUIRED is set and no GPU adapter was found")
        }
        None => {
            eprintln!("no GPU adapter; skipping");
            None
        }
    }
}

/// A surface the manager owns, for the tests that need one rather than a
/// recorder alone — `send_size` reads its config, and a frame needs somewhere to
/// land.
///
/// The widget is the smallest there is: none of these lay anything out, it only
/// has to be registered so the tree can name it. The tree is the caller's
/// because [`ManagedSurface::new`] registers into it and some callers go on to
/// use it.
#[cfg(test)]
fn managed_surface(config: SurfaceConfig, tree: &mut Tree) -> ManagedSurface {
    let (widget, owner) = with_owner(|| Box::new(widgets::container()) as Box<dyn Widget>);
    ManagedSurface::new(SurfaceId::next(), config, widget, owner, tree)
}

/// The frame path asks a compositor for things, and this is the asking written
/// down. `WaylandState` is one answer to it; a recorder that keeps what it was
/// asked is another, and having two is the whole point — one implementation is
/// a rename, two is a seam.
#[cfg(test)]
mod a_second_host_can_answer_for_a_compositor {
    use super::*;
    use crate::platform::Anchor;
    use crate::surface::{ExclusiveZone, Margin, SurfaceConfig};

    /// Answers nothing and remembers what it was asked. Overrides `open_frame`
    /// and `pacing`, which are required, and the two methods these tests read;
    /// inherits the other sixteen, which is the point of the defaults.
    #[derive(Default)]
    struct Recorder {
        configured: Option<(u32, u32)>,
        exclusive_zones: Vec<i32>,
        sizes_asked: Vec<(u32, u32)>,
    }

    impl Surface for Recorder {
        fn open_frame(&mut self) -> Option<Frame> {
            None
        }

        fn pacing(&self) -> crate::surface::FramePacing {
            crate::surface::FramePacing::default()
        }

        fn mark_frame_callback_pending(&mut self) {}

        fn configured_size(&self) -> Option<(u32, u32)> {
            self.configured
        }

        fn set_exclusive_zone(&mut self, zone: i32) {
            self.exclusive_zones.push(zone);
        }

        fn set_size(&mut self, width: u32, height: u32) {
            self.sizes_asked.push((width, height));
        }
    }

    /// A surface the compositor has already sized. Every test here needs one or
    /// deliberately does not, and the distinction is easier to read as a name
    /// than as a struct-update literal.
    fn confirmed(width: u32, height: u32) -> Recorder {
        Recorder {
            configured: Some((width, height)),
            ..Default::default()
        }
    }

    fn bar() -> SurfaceConfig {
        SurfaceConfig::new()
            .height(32)
            .anchor(Anchor::TOP | Anchor::LEFT | Anchor::RIGHT)
            .exclusive_zone(ExclusiveZone::Auto)
    }

    /// The first thing anything has ever asserted about what a surface *asks
    /// the compositor for*, rather than about what it draws.
    #[test]
    fn a_bar_reserving_automatically_asks_for_the_height_it_declared() {
        let mut surface = confirmed(800, 32);
        publish_exclusive_zone(&mut surface, &bar(), None, &mut None);
        assert_eq!(surface.exclusive_zones, vec![32]);
    }

    /// The margin on the anchored edge is the compositor's to add, and the one
    /// facing away is the bar's: a bar held eight pixels off the top with eight
    /// below it asks for forty, and the compositor reserves forty-eight.
    #[test]
    fn only_the_margin_facing_away_from_the_anchor_is_asked_for() {
        let mut surface = confirmed(800, 32);
        publish_exclusive_zone(
            &mut surface,
            &bar().margin(Margin::from([8, 0, 0, 0])),
            None,
            &mut None,
        );
        assert_eq!(
            surface.exclusive_zones,
            vec![32],
            "the top margin is not ours to add"
        );

        let mut surface = confirmed(800, 32);
        publish_exclusive_zone(&mut surface, &bar().margin(Margin::all(8)), None, &mut None);
        assert_eq!(surface.exclusive_zones, vec![40], "the bottom margin is");
    }

    /// A dock down the left edge, as wide as whatever it holds. Its reservation
    /// follows the width, and the width is the one axis it owns — `TOP | BOTTOM`
    /// hands the height to the compositor, `LEFT` alone leaves the width to the
    /// surface.
    ///
    /// The anchor is what makes this a dock rather than a corner: `follow_axis`
    /// gives up on a surface pinned to one edge of each axis, so `TOP | LEFT`
    /// would reserve nothing whatever the width, and every assertion below would
    /// hold for the wrong reason.
    fn side_dock() -> SurfaceConfig {
        SurfaceConfig::new()
            .width(surface::content())
            .anchor(Anchor::LEFT | Anchor::TOP | Anchor::BOTTOM)
            .exclusive_zone(ExclusiveZone::Auto)
    }

    /// An unmeasured content axis publishes nothing and waits for the measure.
    /// This is the case the guard in `publish_exclusive_zone` exists for, and
    /// its comment says what 1920 would cost; here it is only the number the
    /// guard has to refuse.
    #[test]
    fn a_dock_whose_width_is_unmeasured_reserves_nothing_rather_than_the_whole_output() {
        let mut surface = confirmed(1920, 1080);
        publish_exclusive_zone(&mut surface, &side_dock(), None, &mut None);
        assert!(
            surface.exclusive_zones.is_empty(),
            "reserved {:?} against a width the compositor imposed",
            surface.exclusive_zones
        );
    }

    /// The deferral lasts until the measure lands, not for ever. The measured
    /// width is what is reserved, and it is not the confirmed one: the surface
    /// is still 1920 wide as far as the compositor knows.
    #[test]
    fn the_dock_reserves_the_measured_width_not_the_confirmed_one() {
        let mut surface = confirmed(1920, 1080);
        publish_exclusive_zone(&mut surface, &side_dock(), Some((240, 1080)), &mut None);
        assert_eq!(surface.exclusive_zones, vec![240]);
    }

    /// What a bar asks for: the height it declared, and whatever
    /// `surface::honour_owned_axes` leaves of the width, which for both
    /// horizontal edges is nothing.
    #[test]
    fn a_bar_asks_for_its_own_height_and_leaves_the_stretched_width_to_the_compositor() {
        let mut tree = Tree::new();
        let managed = managed_surface(bar(), &mut tree);
        let mut surface = confirmed(1920, 32);

        let (needs_measure, root) = send_size(&managed, &mut surface);

        assert_eq!(surface.sizes_asked, vec![(0, 32)]);
        assert!(!needs_measure, "two fixed axes have nothing to measure");
        assert_eq!(
            root, managed.widget_id,
            "and the layout job names this root"
        );
    }

    /// A `content()` axis has no number of its own, so it asks for the one the
    /// compositor confirmed — not the 1px placeholder, which is what it would
    /// fall back to if `send_size` stopped reading the live size.
    #[test]
    fn a_dock_asks_for_the_width_it_was_confirmed_at_rather_than_the_placeholder() {
        let mut tree = Tree::new();
        let managed = managed_surface(side_dock(), &mut tree);
        let mut surface = confirmed(240, 1080);

        let (needs_measure, _) = send_size(&managed, &mut surface);

        assert_eq!(surface.sizes_asked, vec![(240, 0)]);
        assert!(
            needs_measure,
            "and the width is still the surface's own, so it is still waiting on a measure"
        );
    }

    /// A constant on the same unmeasured surface goes out at once: the guard is
    /// `Auto`-only, and `publish_exclusive_zone` says what deferring one would
    /// cost.
    #[test]
    fn a_constant_reservation_on_an_unmeasured_dock_is_not_deferred() {
        let mut surface = Recorder::default();
        publish_exclusive_zone(
            &mut surface,
            &side_dock().exclusive_zone(48u32),
            None,
            &mut None,
        );
        assert_eq!(surface.exclusive_zones, vec![48]);
    }
}

/// How long an iteration is allowed to sleep is a decision, and it was four
/// conditions inline in `App::run` — reachable only by running a compositor.
#[cfg(test)]
mod what_the_loop_waits_for {
    use super::*;
    use std::time::{Duration, Instant};

    const FRAME: Duration = Duration::from_millis(16);

    /// An idle loop still holding a device it no longer needs wakes to let
    /// it go, rather than sleeping on it until something else comes along.
    #[test]
    fn a_device_waiting_to_go_is_a_deadline() {
        let Some(gpu) = crate::or_skip(renderer::GpuContext::try_new()) else {
            return;
        };
        let closed = Instant::now();
        let slot = GpuSlot::Lazy {
            gpu: Some(gpu),
            idle_since: Some(closed),
        };
        assert_eq!(wake_deadline(&slot), Some(closed + renderer::GPU_GRACE));
        assert_eq!(
            wake_deadline(&GpuSlot::lazy()),
            None,
            "nothing held, nothing to wake for"
        );
    }

    fn idle() -> Pending {
        Pending {
            force_render: false,
            jobs: false,
            wake_requested: false,
            deadline: None,
        }
    }

    /// Nothing queued and nothing scheduled: sleep until the compositor or a
    /// ping says otherwise. Anything else would spin.
    #[test]
    fn an_idle_loop_blocks() {
        assert_eq!(wait_for(&idle(), Instant::now()), None);
    }

    /// Each on its own, because any one of them means work is waiting and a
    /// block would strand it. `wake_requested` is the subtle one: it lands
    /// *after* the iteration consumed the flag, and blocking on it would
    /// suppress every later ping.
    #[test]
    fn any_pending_work_polls_at_frame_rate() {
        for pending in [
            Pending {
                jobs: true,
                ..idle()
            },
            Pending {
                force_render: true,
                ..idle()
            },
            Pending {
                wake_requested: true,
                ..idle()
            },
        ] {
            assert_eq!(wait_for(&pending, Instant::now()), Some(FRAME));
        }
    }

    /// A caret blinks twice a second. Sleeping exactly that long wakes once,
    /// where treating a schedule as pending work would repaint nothing 113
    /// frames out of 114.
    #[test]
    fn a_deadline_is_slept_to_exactly() {
        let now = Instant::now();
        let pending = Pending {
            deadline: Some(now + Duration::from_millis(500)),
            ..idle()
        };
        assert_eq!(wait_for(&pending, now), Some(Duration::from_millis(500)));
    }

    /// A deadline already gone is not a negative sleep.
    #[test]
    fn a_deadline_in_the_past_does_not_wait() {
        let now = Instant::now();
        let pending = Pending {
            deadline: Some(now - Duration::from_secs(1)),
            ..idle()
        };
        assert_eq!(wait_for(&pending, now), Some(Duration::ZERO));
    }

    /// Pending work outranks a deadline: the deadline would be the longer
    /// sleep, and the queued job would sit through it.
    #[test]
    fn pending_work_outranks_a_later_deadline() {
        let now = Instant::now();
        let pending = Pending {
            jobs: true,
            deadline: Some(now + Duration::from_secs(10)),
            ..idle()
        };
        assert_eq!(wait_for(&pending, now), Some(FRAME));
    }
}

/// The frame path, driven with nothing behind it.
///
/// What a test can reach from outside the crate is [`crate::testing::Headless`],
/// and `tests/headless_app.rs` uses it. This module keeps only what needs the
/// internals: `resolve_geometry`'s answer, which a driver deliberately does not
/// expose.
#[cfg(test)]
mod a_frame_lands_where_the_surface_points {
    use super::*;
    use crate::renderer::{GpuContext, RenderTarget};
    use crate::surface::SurfaceConfig;

    const W: u32 = 100;
    const H: u32 = 32;

    /// A surface with one frame's worth of facts and nothing else.
    struct OneSurface {
        width: u32,
        height: u32,
    }

    impl Surface for OneSurface {
        fn open_frame(&mut self) -> Option<Frame> {
            Some(Frame {
                events: Vec::new(),
                scale_factor: 1.0,
                width: self.width,
                height: self.height,
                pacing: crate::surface::FramePacing::default(),
            })
        }

        fn pacing(&self) -> crate::surface::FramePacing {
            crate::surface::FramePacing::default()
        }

        fn mark_frame_callback_pending(&mut self) {}
    }

    /// A surface nobody has told a scale is at 1, which is what
    /// `wl_surface.preferred_buffer_scale` defines it to be before its first
    /// event: the trait's own answer, for an implementation that keeps no scale.
    #[test]
    fn a_surface_nobody_has_told_a_scale_is_at_one() {
        let surface = OneSurface {
            width: W,
            height: H,
        };
        assert_eq!(surface.scale_factor(), 1.0);
    }

    struct OnePlatform(OneSurface);

    /// The handle, as the two real implementations spell it: a newtype over
    /// what it borrows, so the trait does not have to be implemented for
    /// references as well.
    struct OneHandle<'a>(&'a mut OneSurface);

    impl Surface for OneHandle<'_> {
        fn open_frame(&mut self) -> Option<Frame> {
            self.0.open_frame()
        }

        fn pacing(&self) -> crate::surface::FramePacing {
            self.0.pacing()
        }

        fn mark_frame_callback_pending(&mut self) {
            self.0.mark_frame_callback_pending()
        }
    }

    impl Platform for OnePlatform {
        type Surface<'a> = OneHandle<'a>;

        fn surface(&mut self, _id: SurfaceId) -> Option<OneHandle<'_>> {
            Some(OneHandle(&mut self.0))
        }

        fn read_selection(&mut self, _kind: reactive::SelectionKind, token: u64) {
            reactive::clipboard::answer_paste(token, None);
        }
    }

    /// A target smaller than its frame is made to fit, and then reports that it
    /// fits.
    ///
    /// The second half is the whole of it: a target that quietly declined would
    /// pass the first assertion of every frame and report a resize on all of
    /// them, repainting the entire tree for ever.
    #[test]
    fn a_target_the_wrong_size_is_resized_once_and_not_again() {
        let Some(gpu) = or_skip(GpuContext::try_new()) else {
            return;
        };

        let mut tree = Tree::new();
        let mut surface = managed_surface(SurfaceConfig::new(), &mut tree);
        surface.wgpu_surface = Some(RenderTarget::offscreen(&gpu, 8, 8));
        let mut renderer = Renderer::new(
            gpu.device.clone(),
            gpu.queue.clone(),
            wgpu::TextureFormat::Rgba8Unorm,
        );
        let mut platform = OnePlatform(OneSurface {
            width: W,
            height: H,
        });
        let id = surface.id;
        let mut ctx = FrameContext {
            id,
            surface: &mut surface,
            wayland_state: &mut platform,
            renderer: &mut renderer,
            tree: &mut tree,
        };
        let frame = ctx.wayland_state.surface(id).unwrap().open_frame().unwrap();

        let first = resolve_geometry(&mut ctx, &frame);
        assert!(first.needs_resize, "an 8x8 target for a 100x32 frame");
        assert_eq!(
            (
                ctx.surface.wgpu_surface.as_ref().unwrap().width(),
                ctx.surface.wgpu_surface.as_ref().unwrap().height()
            ),
            (W, H)
        );

        let again = resolve_geometry(&mut ctx, &frame);
        assert!(!again.needs_resize, "the target already fits");
    }
}

/// Who a read belongs to, when the widget that made it opened no scope of its
/// own.
#[cfg(test)]
mod a_layout_is_attributed_to_the_widget_that_ran_it {
    use super::*;
    use crate::layout::{Constraints, Size};
    use crate::reactive::create_signal;
    use crate::tree::LayoutCtx;

    /// A leaf written the way a third-party one is easiest to write: it reads
    /// a signal in `layout` and opens no tracking scope, because nothing made
    /// it.
    struct Plain(crate::reactive::Signal<f32>);

    impl widgets::Widget for Plain {
        fn layout(&mut self, _ctx: &mut LayoutCtx, _constraints: Constraints) -> Size {
            let extent = self.0.get();
            Size::new(extent, extent)
        }

        fn paint(&self, _ctx: &mut crate::renderer::PaintContext) {}
    }

    /// The read belongs to the leaf, so the write re-lays out the leaf. Without
    /// a scope around the call it belongs to the nearest ancestor that opened
    /// one — the container — which is laid out again with every child it has,
    /// "reactive, but imprecise, and silently so".
    #[test]
    fn a_leaf_that_opens_no_scope_is_still_the_one_marked() {
        let extent = create_signal(20.0f32);
        let mut tree = Tree::new();
        let root = tree.register(Box::new(
            widgets::container()
                .width(200.0)
                .child(Plain(extent.into())),
        ));
        tree.with_widget_mut(root, |w, id, t| w.register_children(t, id));
        tree.layout_widget(root, Constraints::new(0.0, 0.0, 400.0, 400.0));
        let leaf = tree.get_children(root)[0];

        extent.set(40.0);
        let roots = [root].into_iter().collect();
        jobs::distribute_jobs(&tree, &roots);
        let drained = jobs::drain_surface_jobs(root);
        let mut layout_roots = Vec::new();
        jobs::process_jobs(&drained, &mut tree, &mut layout_roots);
        jobs::recycle_job_buffer(drained);

        assert!(
            tree.needs_layout(leaf),
            "the widget that read the signal is the one that has to run again"
        );
    }
}