kui-core 0.1.0-alpha.45

kui contract: flat per-frame tree, clay-style flex layout, text stack, events as data, quad display list
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
//! The frame's back half: layout, then emission into the display list.
//!
//! `finish_frame` runs the passes; the rest are the passes — one node's
//! quads, the departed subtrees replayed as ghosts, position easing, the
//! `layout` events, the default focus ring — and the quad helpers they
//! share. Everything here reads the tree `builder` built and writes
//! `display`; the input side of the same frame is `dispatch`.

use super::*;

const SCROLLBAR_W: f32 = 4.0;
/// Thumb width while hovered or dragged.
const SCROLLBAR_ACTIVE_W: f32 = 6.0;
/// Grabbable gutter width (wider than the drawn thumb).
const SCROLLBAR_HIT_W: f32 = 10.0;
const SCROLLBAR_INSET: f32 = 2.0;
const SCROLLBAR_MIN: f32 = 24.0;
/// An `auto` bar (`ScrollbarMode::Auto`): how long it stays after the
/// scroll state last changed, then how long it takes to fade. Seconds of
/// the driver's clock.
const SCROLLBAR_HOLD: f64 = 1.0;
const SCROLLBAR_FADE: f64 = 0.25;
/// The default focus ring:
/// drawn this far outside the focused node, this thick, when focus is
/// keyboard-visible and the node styles nothing itself.
///
/// The *colour* is `theme.focus_ring`: the geometry is
/// still not a prop and still not negotiable, but a ring that cannot be
/// seen is not a focus indicator, and the pale blue that reads on a dark
/// page is invisible on a light one.
const FOCUS_RING_GAP: f32 = 2.0;
const FOCUS_RING_W: f32 = 2.0;

/// The disjoint borrows one box's paint needs, split off the core field by
/// field — a macro rather than a method so the tree, the stroke list and a
/// ghost's points can stay borrowed beside them.
macro_rules! painter {
    ($core:expr) => {
        Painter {
            display: &mut $core.display,
            text: &mut $core.text,
            edit: &mut $core.edit,
            cells: &mut $core.cells,
            atlas: &mut $core.atlas,
            session: &$core.session,
            path_tex: &mut $core.path_textures,
            frame_no: $core.frame_no,
        }
    };
}

impl Core {
    /// The scrollbar thumb's colour at rest and while hovered or dragged:
    /// the node's own where it declared one, else the theme's. A wash over
    /// whatever it sits on rather than a fill, which is why the theme's
    /// are two translucent colours and not one with an alpha applied.
    fn thumb_color(&self, bar: &crate::spec::Scrollbar, active: bool) -> Color {
        let t = self.theme();
        if active {
            bar.active_color.unwrap_or(t.scrollbar_active)
        } else {
            bar.color.unwrap_or(t.scrollbar)
        }
    }

    /// Node `i`'s hit region, for a node that tracks the pointer. Out of
    /// line: a box that takes no input — most of a frame — does not carry
    /// the context-menu walk, the slider's track or the shape in
    /// `emit_node`'s saved registers and stack frame.
    #[inline(never)]
    fn push_hit(
        &mut self,
        i: usize,
        rect: Rect,
        clip: Rect,
        drop: Option<crate::input::DropOwner>,
        hits: &mut Vec<HitRegion>,
    ) {
        let spec = &self.tree.specs[i];
        let parent = self.tree.parent[i];
        let parent_rect = if parent == NIL {
            Rect::new(0.0, 0.0, self.viewport.w, self.viewport.h)
        } else {
            let p = parent as usize;
            Rect::from_pos_size(self.tree.pos[p], self.tree.size[p])
        };
        // A disabled node keeps hover (a tooltip can say why) and loses
        // every interaction: it emits nothing and takes no focus.
        let live = !spec.disabled;
        // The menu this region opens is its own or an ancestor's; the
        // walk is skipped on a frame where no node offers one (T1).
        let context_menu = if self.tree.any_context_menu {
            self.enclosing_menu(i).map(|j| crate::input::MenuOwner {
                key: self.tree.keys[j],
                origin: self.tree.origins[j],
                tag: self.tree.specs[j]
                    .events()
                    .on_context_menu
                    .clone()
                    .expect("enclosing_menu returns a node that offers one"),
            })
        } else {
            None
        };
        // A slider that asked for its changes reads the pointer along
        // its content box (ADR 0034, decision 4); a disabled one, or a
        // range that is not one, reads nothing.
        let slider = match spec.events().on_change.as_ref() {
            Some(tag) if live && spec.access().role == Some(crate::access::Role::Slider) => {
                crate::slider::SliderRange::of(spec.access()).map(|range| {
                    Box::new(crate::slider::SliderTrack::new(
                        rect,
                        spec.layout.padding,
                        spec.layout.dir == crate::spec::Dir::Column,
                        range,
                        tag.clone(),
                    ))
                })
            }
            _ => None,
        };
        // The shape past the rect (ADR 0026): a stroke's pieces, a
        // fill's outline, a rounded box's corners; a plain box none.
        let shape = match self.tree.content[i] {
            NodeContent::Line(id) => {
                let (run, points) = self.lines.run(id);
                self.hit_shapes.segments(points, run.width)
            }
            NodeContent::Polygon(id) => {
                let draw = self.fragments.get(id);
                let mut pts = [Vec2::ZERO; crate::fragment::POLYGON_MAX_POINTS];
                for (k, p) in pts.iter_mut().enumerate() {
                    *p = Vec2::new(draw.params[k * 2] * rect.w, draw.params[k * 2 + 1] * rect.h);
                }
                self.hit_shapes.polygon(&pts)
            }
            NodeContent::Path(id) => {
                let (run, ops) = self.paths.run(id);
                let mut outline = Vec::new();
                // Hit by its fill when it may paint one: a `bg`, or one a
                // hover, a press or the focus brings (the shape is
                // decided before the pointer is, so by what is declared).
                // With a stroke too, by the stroke's own pieces as well,
                // or the outer half of a thick one is painted and not
                // hit (RG112).
                let s = &spec.style;
                let fill = run.stroke_w <= 0.0
                    || s.bg.is_visible()
                    || spec.interact.as_deref().is_some_and(|i| {
                        [i.hover_bg, i.pressed_bg, i.focus_bg]
                            .iter()
                            .any(|c| c.is_some_and(|c| c.is_visible()))
                    });
                if fill && run.stroke_w <= 0.0 {
                    crate::path::flatten(ops, &mut outline);
                } else {
                    crate::path::flatten_stroke(ops, &mut outline);
                }
                // A turned path is hit where it is drawn: the outline
                // turned about the box's centre, which is its pivot (ADR
                // 0041). The contour breaks are not points and stay.
                if let Some(angle) = run.angle.filter(|a| *a != 0.0) {
                    let c = Vec2::new(rect.w * 0.5, rect.h * 0.5);
                    for p in outline.iter_mut().filter(|p| !p.x.is_nan()) {
                        *p = crate::path::turned(*p, c, angle);
                    }
                }
                if fill {
                    self.hit_shapes.path(&outline, run.rule, run.stroke_w)
                } else {
                    // A stroke with no fill is hit as a line is, by the
                    // pieces it paints: a contour its `Z` closed runs
                    // back to its start, an open one does not, and the
                    // breaks are kept so no piece runs from one contour
                    // to the next.
                    self.hit_shapes.segments(&outline, run.stroke_w)
                }
            }
            _ if spec.style.radius != crate::display::SQUARE => {
                crate::input::HitShape::Rounded(spec.style.radius)
            }
            _ => crate::input::HitShape::Rect,
        };
        hits.push(HitRegion {
            key: self.tree.keys[i],
            origin: self.tree.origins[i],
            rect,
            clip,
            shape,
            payload: spec.events().on_click.clone().filter(|_| live),
            drag: spec.events().on_drag.clone().filter(|_| live),
            parent_rect,
            key_sink: spec.events().on_key.clone().filter(|_| live),
            key_up: spec.events().key_up,
            context_menu,
            drop,
            focusable: crate::access::focusable(&self.tree, i),
            edit_origin: None,
            select_scope: self.scope_of(i).filter(|_| live),
            window: spec.window,
            hover: spec.events().on_hover.clone(),
            group: spec.interact().hover_group,
            click_sound: spec.interact().click_sound.filter(|_| live),
            hover_sound: spec.interact().hover_sound,
            cursor: spec.cursor,
            slider,
        });
    }

    /// An editor's own hit region, whose origin is where its glyphs sit
    /// (shifted by what a field is scrolled). Out of line for the reason
    /// `push_hit` is.
    #[inline(never)]
    #[allow(clippy::too_many_arguments)]
    fn push_edit_hit(
        &mut self,
        i: usize,
        key: Key,
        rect: Rect,
        clip: Rect,
        scale: f32,
        drop: Option<crate::input::DropOwner>,
        hits: &mut Vec<HitRegion>,
    ) {
        let spec = &self.tree.specs[i];
        let pad = spec.layout.padding;
        let content_origin = Vec2::new(rect.x + pad.l, rect.y + pad.t);
        let inner_w = (rect.w - pad.x()).max(0.0);
        // A single-line field scrolls its own text (F41). Resolved
        // here, where the box is known, and read back by the hit
        // region and the access runs so all three agree on where the
        // glyphs are; the painter reads the same stored offset.
        let offset = {
            let sess = &mut *self.session.state();
            self.edit.line_offset(key, inner_w * scale, &mut sess.fonts)
        };
        hits.push(HitRegion {
            key,
            origin: self.tree.origins[i],
            rect,
            clip,
            // A field's corners round its hit too (ADR 0026).
            shape: if spec.style.radius != crate::display::SQUARE {
                crate::input::HitShape::Rounded(spec.style.radius)
            } else {
                crate::input::HitShape::Rect
            },
            payload: None,
            drag: None,
            parent_rect: rect,
            // Shifted by what the field is scrolled: a click lands on
            // the character under the pointer.
            edit_origin: Some(Vec2::new(
                content_origin.x - offset / scale,
                content_origin.y,
            )),
            // An editor is its own selection scope: a press in it
            // places a caret and drags a selection through the
            // editor's own path, not the scope's.
            select_scope: None,
            key_sink: None,
            key_up: false,
            context_menu: None,
            // A field inside a zone is the zone's: files dropped on
            // it land there.
            drop,
            focusable: !spec.disabled,
            window: None,
            hover: None,
            group: None,
            click_sound: None,
            hover_sound: None,
            // The editor's own node carries any override.
            cursor: spec.cursor,
            slider: None,
        });
    }

    /// The index in `regions` of the nearest scroll region around node
    /// `i` in the tree, [`NIL`] for none. Ancestors are emitted before
    /// their descendants — a float's layer comes after the one its
    /// declaring node is in — so the one around is already in the list.
    /// Off `emit_node`'s straight path: only a scroller pays for it.
    #[inline(never)]
    fn enclosing_scroll_region(&self, i: usize, regions: &[ScrollRegion]) -> u32 {
        let mut a = self.tree.parent[i];
        while a != NIL {
            if let Some(r) = regions.iter().rposition(|r| r.node == a) {
                return r as u32;
            }
            a = self.tree.parent[a as usize];
        }
        NIL
    }

    /// Emits one node's quads and registers its hit/scroll regions.
    fn emit_node(
        &mut self,
        i: usize,
        rect: Rect,
        paint: Paint,
        hits: &mut Vec<HitRegion>,
        scroll_regions: &mut Vec<ScrollRegion>,
    ) {
        let Paint { clip, scale, .. } = paint;
        // Behind a modal a node still draws, and stops taking input.
        let interactive = self.interactive(i);
        let spec = &self.tree.specs[i];
        let style = spec.style;
        // The zone this node's regions belong to — its own `on_drop` or
        // an ancestor's — by the context menu's walk (ADR 0031, decision
        // 2); skipped wholesale on a frame with no zone.
        let drop = if self.tree.any_drop && interactive {
            self.enclosing_drop(i).map(|j| crate::input::DropOwner {
                key: self.tree.keys[j],
                origin: self.tree.origins[j],
                tag: self.tree.specs[j]
                    .events()
                    .on_drop
                    .clone()
                    .expect("enclosing_drop returns a node that declares one"),
            })
        } else {
            None
        };
        // A stroke emits no hit region: it takes no input (ADR 0010,
        // decision 7).
        if spec.hover_tracked() && interactive {
            self.push_hit(i, rect, clip.rect, drop.clone(), hits);
        }
        let spec = &self.tree.specs[i];
        // An `on_scroll` node takes the wheel the way a container does —
        // one list, one paint-order rule (ADR 0029, decision 4).
        let handler = self.tree.any_scroll_handler && spec.events().on_scroll.is_some();
        if spec.layout.scroll_x || spec.layout.scroll_y || handler {
            // A container behind a modal keeps its scrollbar drawn and
            // refuses the wheel and the thumb.
            let (takes_x, takes_y) = if handler {
                let axes = spec.events().scroll_axes;
                (axes.takes(true), axes.takes(false))
            } else {
                (spec.layout.scroll_x, spec.layout.scroll_y)
            };
            scroll_regions.push(ScrollRegion {
                key: self.tree.keys[i],
                node: i as u32,
                rect,
                clip: clip.rect,
                inert: !interactive,
                handler,
                takes_x,
                takes_y,
                scrolls_x: spec.layout.scroll_x,
                scrolls_y: spec.layout.scroll_y,
                contain: spec.interact().overscroll == crate::spec::Overscroll::Contain,
                mods: if handler {
                    spec.events().scroll_mods.bits()
                } else {
                    0
                },
                parent: self.enclosing_scroll_region(i, scroll_regions),
            });
        }
        if let NodeContent::Edit(key) = self.tree.content[i]
            && interactive
        {
            self.push_edit_hit(i, key, rect, clip.rect, scale, drop, hits);
        }
        // The content, resolved to what the painter needs — a text node's
        // selection and its place, an editor's focus — then painted by the
        // one step a ghost also paints through.
        let leaf = match self.tree.content[i] {
            NodeContent::Text(tid) => {
                // The keys above it, nearest first, so a query by the
                // `line` row (or a wrapper) finds the runs inside it.
                let ancestry = self.text_ancestors(i);
                self.text.place(
                    self.tree.keys[i],
                    &ancestry,
                    tid,
                    self.tree.pos[i],
                    self.scope_of(i),
                    true,
                );
                Leaf::Text {
                    tid,
                    sel: self.sel_range(i, tid),
                }
            }
            NodeContent::Cells(cid) => Leaf::Cells {
                cid,
                at: self.cells_origin(i),
                // The window's selection, when it is in this very grid.
                sel: self
                    .cell_selection
                    .as_ref()
                    .filter(|s| s.node == self.tree.keys[i] && !s.is_empty()),
                tint: self.theme.selection,
            },
            NodeContent::Edit(key) => Leaf::Edit {
                key,
                focused: self.edit.focused() == Some(key),
                pad: self.tree.specs[i].layout.padding,
            },
            NodeContent::Image(id, opts) => Leaf::Image(id, opts),
            NodeContent::Fragment(id) => Leaf::Fragment(self.fragments.get(id)),
            NodeContent::Polygon(id) => Leaf::Polygon(self.fragments.get(id)),
            NodeContent::Line(id) => {
                let (run, points) = self.lines.run(id);
                Leaf::Line {
                    points,
                    width: run.width,
                    dash: run.dash,
                }
            }
            NodeContent::Path(id) => {
                let (run, ops) = self.paths.run(id);
                Leaf::Path {
                    ops,
                    rule: run.rule,
                    stroke_w: run.stroke_w,
                    dash: run.dash,
                    hash: run.hash,
                    angle: run.angle,
                    animating: run.animating,
                }
            }
            NodeContent::Container => Leaf::Container,
        };
        // A backdrop blur before anything the node paints — its shadow,
        // its background — so all of it lies over the blurred picture
        // (backlog F129). Cold, and looked for only on a frame that has one.
        if self.tree.any_backdrop_blur {
            let r = self.tree.specs[i].interact().backdrop_blur;
            if r > 0.0 {
                backdrop_quad(&mut self.display.quads, rect, &style, &paint, r);
            }
        }
        let first_quad = self.display.quads.len();
        painter!(self).paint_box(rect, &style, &paint, leaf);
        // A gradient over the background the box just painted. Out of
        // `emit_node` as the rules below are, and for the same reason.
        if self.tree.any_gradient
            && let Some(g) = &self.tree.specs[i].interact().gradient
            // A stroke and a fill paint no box for it to lie over.
            && !matches!(
                self.tree.content[i],
                NodeContent::Line(_) | NodeContent::Polygon(_) | NodeContent::Path(_)
            )
        {
            painter!(self).paint_gradient(g, rect, &style, &paint, first_quad);
        }
        // A table's grid rules, with its box and under its cells. Out of
        // `emit_node`: a rare path kept off its codegen (C48).
        if self.tree.any_table
            && let Some(c) = self.tree.specs[i].interact().rules
            && self.tree.specs[i].layout.is_table()
        {
            self.emit_rules(i, rect, c, &paint);
        }
    }

    /// The `rules` of table `i`, laid out by [`rule_lines`]
    /// from its in-flow children as layout reads them — a row is what
    /// `layout::is_table_row` says is one, so the grid is drawn over the
    /// rows its columns were laid across and not through a heading or a
    /// section beside them.
    #[cold]
    #[inline(never)]
    fn emit_rules(&mut self, i: usize, rect: Rect, color: Color, paint: &Paint) {
        let tree = &self.tree;
        let at = |j: u32| Rect::from_pos_size(tree.pos[j as usize], tree.size[j as usize]);
        let in_flow = |j: &u32| tree.specs[*j as usize].layout.float.is_none();
        let children: Vec<RuledChild> = tree
            .children(i as u32)
            .filter(in_flow)
            .map(|c| RuledChild {
                rect: at(c),
                cells: crate::layout::is_table_row(tree, c)
                    .then(|| tree.children(c).filter(in_flow).map(at).collect()),
            })
            .collect();
        let spec = &tree.specs[i];
        let lines = rule_lines(rect, spec.layout.padding, spec.interact().rule_w, &children);
        // The clip the table's children get: its own box when it clips or
        // scrolls, since the rows' places carry its scroll offset and the
        // rules drawn from them go wherever the rows do.
        let clip_id = if spec.layout.clips() {
            let radius = if tree.any_rounded_clip {
                spec.style.radius
            } else {
                crate::display::SQUARE
            };
            let clip = paint.clip.intersect(rect, radius);
            self.display.intern_clip(clip.scaled(paint.scale))
        } else {
            paint.clip_id
        };
        push_rules(&mut self.display, &lines, color, paint, clip_id);
    }

    /// [`Core::emit_rules`] for a departing table's ghost, node `i` of
    /// `g` drawn at `rect`, its children `offset` from where they were:
    /// the same rules from the children the ghost copied, under the same
    /// clip its children get, faded with it by `paint`.
    #[cold]
    #[inline(never)]
    fn emit_ghost_rules(
        &mut self,
        g: &Ghost,
        i: usize,
        rect: Rect,
        offset: Vec2,
        color: Color,
        paint: &Paint,
    ) {
        let at = |node: &crate::depart::GhostNode| {
            Rect::new(
                node.rect.x + offset.x,
                node.rect.y + offset.y,
                node.rect.w,
                node.rect.h,
            )
        };
        // The nodes are in preorder, so a grandchild's parent is the most
        // recent child. A departing `cells` grid, or a fragment whose draw
        // was gone, is a `Container` here — a `row` one straight under a
        // table would read as a row of no cells, where layout read it as
        // no row.
        let mut children: Vec<RuledChild> = Vec::new();
        let mut last = NIL;
        for (j, node) in g.nodes.iter().enumerate().skip(i + 1) {
            // Past the table's subtree: a node whose parent precedes it.
            if node.parent == NIL || (node.parent as usize) < i {
                break;
            }
            if node.spec.layout.float.is_some() {
                continue;
            }
            if node.parent as usize == i {
                let row = crate::layout::row_shaped(
                    &node.spec.layout,
                    matches!(node.content, GhostContent::Container),
                );
                children.push(RuledChild {
                    rect: at(node),
                    cells: row.then(Vec::new),
                });
                last = j as u32;
            } else if node.parent == last
                && let Some(cells) = children.last_mut().and_then(|c| c.cells.as_mut())
            {
                cells.push(at(node));
            }
        }
        let spec = &g.nodes[i].spec;
        let lines = rule_lines(rect, spec.layout.padding, spec.interact().rule_w, &children);
        let clip_id = if spec.layout.clips() {
            let clip = paint.clip.intersect(rect, spec.style.radius);
            self.display.intern_clip(clip.scaled(paint.scale))
        } else {
            paint.clip_id
        };
        push_rules(&mut self.display, &lines, color, paint, clip_id);
    }

    /// Runs layout and emission into `output()`, and installs this frame's
    /// hit and scroll regions for input handling. The last step of
    /// `Ui::finish`, which runs the extension fills, the devtools panel
    /// and the open menu first — and crate-private for that reason:
    /// a host that called this directly got a frame where
    /// `open_menu` drew nothing and `KUI_DEVTOOLS` did nothing, with no
    /// warning. A driver with a bare `Core` finishes through
    /// `Ui::wrap(core).finish()`.
    pub(crate) fn finish_frame(&mut self) {
        self.layout_frame();
        self.emit_frame();
        self.building = false;
        self.submenu_frame_end();
        // A focus the view moved, or a focused node the frame declared
        // `on_focus` on or dropped (backlog DX18).
        let mut out = std::mem::take(&mut self.pending);
        self.report_focus("program", &mut out);
        self.pending = out;
        self.snapshot_nodes();
        self.devtools_after_frame();
        self.trace_finish_frame();
        // Between frames the host is who talks to the core: a driver that
        // tagged the last nodes with an extension's origin by hand (rather
        // than through `fill`, which restores it) must not leave its
        // `set_tokens` landing in that extension's table (ADR 0027).
        self.origin = crate::tree::OriginId::HOST;
    }

    /// The frame's first half: layout, then everything that resolves
    /// against it before a quad is emitted — the caret and reveal nudges,
    /// the `layout` events and the diagnostics, the declared window set,
    /// the modal scope and the Tab step a view asked for.
    fn layout_frame(&mut self) {
        // Tolerate unclosed containers (an FFI caller may have bailed early).
        self.stack.truncate(1);
        self.counters.truncate(1);

        self.tree.host_area = self.dt_area;
        if !self.pending_scroll_labels.is_empty() {
            self.resolve_scroll_labels();
        }
        {
            let sess = &mut *self.session.state();
            let mut measure = Measure {
                text: &mut self.text,
                cells: &mut self.cells,
                fonts: &mut sess.fonts,
                edit: &mut self.edit,
                resources: &sess.resources,
            };
            layout::compute(
                &mut self.tree,
                &mut measure,
                &mut self.scroll,
                self.viewport,
                self.scale,
            );
        }
        self.scroll_caret_into_view();
        // An explicit `reveal` after the caret nudge: the app asked for
        // this one, so it wins the offset if both want to move it.
        self.apply_pending_reveal();
        // A container a view sliced its rows by (`scroll_geometry`) that
        // came out otherwise — taller, scrolled elsewhere — owes a frame
        // built against this layout, or the slice stays a frame behind
        // until the next event (`ScrollStore::resliced`).
        if self.scroll.take_resliced() {
            self.owe_frame("resliced");
        }
        if self.tree.any_slide {
            self.ease_positions();
        }
        // Positions are final: report the rects views asked about, and
        // look for the misconfigurations that would otherwise fail silently.
        if self.tree.any_layout {
            self.emit_layout_events();
        }
        self.diag
            .check(&self.tree, &self.text, &self.edit, self.frame_no);
        // Text set for a key nothing had declared yet was held for this
        // frame (backlog F25). What it declared has taken its seed; what
        // is left named an editor no view draws, so drop it and say so.
        // Drained whatever `diag.enabled` says, so the gate changes what
        // is reported and never what is retained.
        for seed in self.edit.take_unclaimed_seeds() {
            self.diag.raise(match seed {
                crate::edit::Unclaimed::Key(key) => crate::diag::edit_text_without_editor(key),
                crate::edit::Unclaimed::Label(label) => {
                    crate::diag::edit_text_without_editor_label(&label)
                }
            });
        }
        // The declared window set, diffed against the session's: a frame
        // that declared a new name queues its `Open` here.
        self.sync_windows();
        // The frame's modal scope, and the focus it moves: emission reads
        // it (everything outside is inert) and so does the Tab ring.
        self.modal = if self.tree.any_modal {
            self.modal_scope()
        } else {
            None
        };
        self.resolve_modal_focus();
        // Then the regions: a `focus_region` asked for during the build,
        // the region following a focus the build declared, and a region
        // that went away handing focus back (`docs/adr/0022`).
        self.resolve_regions();
        // The ring exists now: laid out, and scoped to the modal if there
        // is one, else to the region in effect. A step asked for during
        // the build lands here, so it wins over both the modal's own focus
        // move and a same-frame `set_focus`. Like a real Tab press, the
        // scroll it triggers shows on the next frame.
        if let Some(forward) = self.pending_focus_step.take() {
            self.focus_next(forward);
        }
    }

    /// Numbers the text nodes of the selection's scope in tree order and
    /// resolves the two ends against those ordinals. Run once per frame,
    /// after the scope map and before emission, because a run's range has
    /// to be known when the run is drawn and its *offset* cannot be —
    /// the runs after it have not been placed yet, and an end may be one
    /// of them.
    fn resolve_selection(&mut self) {
        self.sel_ords.clear();
        self.sel_ends = None;
        let Some(sel) = self.selection else { return };
        self.sel_ords.resize(self.tree.len(), u32::MAX);
        let (mut anchor, mut focus) = (None, None);
        // The built runs, in order, with the virtualised row each is in:
        // what an end whose own node is *not* built is placed against.
        let mut built: Vec<(u32, Option<u64>, usize)> = Vec::new();
        let mut ord = 0u32;
        for i in 0..self.tree.len() {
            if self.scopes.get(i).copied().flatten() != Some(sel.scope)
                || !matches!(self.tree.content[i], NodeContent::Text(_))
            {
                continue;
            }
            self.sel_ords[i] = ord;
            let key = self.tree.keys[i];
            let len = match self.tree.content[i] {
                NodeContent::Text(tid) => self.text.content_len(tid),
                _ => 0,
            };
            built.push((ord, self.rows.get(i).copied().flatten(), len));
            if key == sel.anchor.node {
                anchor = Some((ord, sel.anchor.byte));
            }
            if key == sel.focus.node {
                focus = Some((ord, sel.focus.byte));
            }
            ord += 1;
        }
        // An end this frame did not build is placed by its row's index in
        // the data: before everything built, after it, or at the boundary
        // it falls on. That is what lets the built middle paint while a
        // virtual list scrolls under a selection (ADR 0017, tier 3).
        let place = |end: &crate::select::Endpoint| -> Option<(u32, usize)> {
            let row = end.row?;
            let (start, last) = (built.first()?, built.last()?);
            // The row itself is built, on runs no end's key names: a Select
            // All's placeholder end (`select_all_in` puts it on the scope
            // with the row's index and `ROW_END`) after the list scrolled
            // that row into the built window. It lands in that row's own
            // runs — the end of its last one, or the byte into its first —
            // rather than at the boundary an unbuilt row would take.
            let mut in_row = built.iter().filter(|(_, r, _)| *r == Some(row));
            if let Some(first_run) = in_row.next() {
                return Some(if end.byte >= crate::select::ROW_END {
                    let last_run = in_row.next_back().unwrap_or(first_run);
                    (last_run.0, last_run.2)
                } else {
                    (first_run.0, end.byte.min(first_run.2))
                });
            }
            // Against the built runs that *carry* a row, not the first and
            // last of everything built: a scope can hold plain labels
            // beside virtual rows — a header, a footer — and a label says
            // nothing about where a row sits in the data. Comparing
            // against one puts an end below the list at the top of it.
            let hi = built.iter().rev().find_map(|(_, r, _)| *r)?;
            if crate::select::unbuilt_row_is_after(row, Some(hi)) {
                return Some((last.0, last.2));
            }
            // Below the first row, or inside the built range without being
            // built — a hole, which a contiguous virtual window does not
            // have. Either way the start is the nearest honest boundary.
            Some((start.0, 0))
        };
        let anchor = anchor.or_else(|| place(&sel.anchor));
        let focus = focus.or_else(|| place(&sel.focus));
        if let (Some(a), Some(f)) = (anchor, focus) {
            self.sel_ends = Some(crate::select::Ends::ordered(a, f));
        }
    }

    /// The bytes of node `i`'s text the selection covers, with the colour
    /// to paint under them. `None` on every node of every frame that has
    /// no selection.
    fn sel_range(&self, i: usize, tid: crate::tree::TextId) -> Option<((usize, usize), Color)> {
        let ends = self.sel_ends?;
        let ord = self.sel_ords.get(i).copied()?;
        if ord == u32::MAX {
            return None;
        }
        let range = ends.range_in(ord, self.text.content_len(tid))?;
        Some((range, self.theme().selection))
    }

    /// The innermost selection scope node `i` is inside, if any. Empty on
    /// every frame that declares no `selectable` at all, where the map is
    /// not even sized.
    #[inline]
    fn scope_of(&self, i: usize) -> Option<Key> {
        self.scopes.get(i).copied().flatten()
    }

    /// The keys above node `i`, nearest first, as many as a `TextPlace`
    /// remembers — what lets a query by a `line` row or a wrapper find
    /// the runs inside it.
    /// The keys above text node `i`, nearest first, as many as a place
    /// remembers; how many there are; and the depth of the nearest
    /// `role="none"` ancestor among them, which a query from above it
    /// does not reach. A `line` row further up than the
    /// place can remember raises `text-beyond-line`, once per text.
    fn text_ancestors(&mut self, i: usize) -> crate::text::Ancestry {
        use crate::access::Role;
        let mut ancestors = [Key::ROOT; crate::text::PLACE_ANCESTORS];
        let mut depth = 0;
        let mut none_at = None;
        let mut p = self.tree.parent[i];
        while p != NIL && depth < ancestors.len() {
            let j = p as usize;
            ancestors[depth] = self.tree.keys[j];
            if none_at.is_none() && self.tree.specs[j].access().role == Some(Role::None) {
                none_at = Some(depth);
            }
            depth += 1;
            p = self.tree.parent[j];
        }
        // Past the reach: a `line` row still above is one the text cannot
        // be found from, and the app should hear it.
        if p != NIL && self.tree.any_line {
            let mut q = p;
            while q != NIL {
                let j = q as usize;
                if self.tree.specs[j].access().role == Some(Role::Line) {
                    self.diag.raise(crate::diag::text_beyond_line(
                        self.tree.keys[i],
                        self.tree.keys[j],
                        crate::text::PLACE_ANCESTORS,
                    ));
                    break;
                }
                q = self.tree.parent[j];
            }
        }
        crate::text::Ancestry {
            keys: ancestors,
            depth,
            none_at,
        }
    }

    /// The frame's second half: the laid-out tree into the display list,
    /// in paint order — the in-flow layer, then one layer per floating
    /// subtree in the order they opened, each with the departed subtrees
    /// that were painted among it and its own chrome (scrollbars, the
    /// ring) at its end — and the hit and scroll regions the
    /// next input is tested against, in the same order.
    fn emit_frame(&mut self) {
        let scale = self.scale;
        let mut hits: Vec<HitRegion> = self.interaction.take_hit_buffer();
        self.hit_shapes = self.interaction.take_shape_buffer();
        let mut scroll_regions: Vec<ScrollRegion> = Vec::new();
        self.display.viewport = Size::new(self.viewport.w * scale, self.viewport.h * scale);
        self.display.scale = scale;
        self.display.time = self.anim.time().unwrap_or(0.0) as f32;

        // Read once each: what the frame declared, noted by `Tree::push`
        // (and by `configure_root`, whose spec replaces the root's).
        let any_clip = self.tree.any_clip;
        let any_rounded_clip = self.tree.any_rounded_clip;
        let any_opacity = self.tree.any_opacity;
        let any_float = self.tree.any_float;
        // Read once: every per-node selection check below is behind it.
        let any_selectable = self.tree.any_selectable;

        // inherited clip per node (logical): ancestors only, not the node
        // itself. Only materialized when something actually clips.
        // Index 0 is the clip that clips nothing, so an unclipped frame
        // interns once and every quad on it names entry zero. Seeded
        // rather than found, so `clip_of` has something to answer with
        // even on a frame that emitted no quad at all.
        let no_clip = self.display.intern_clip(Clip::NONE.scaled(scale));
        self.clips.clear();
        self.clip_ids.clear();
        if any_clip {
            self.clips.resize(self.tree.len(), Clip::NONE);
            self.clip_ids.resize(self.tree.len(), no_clip);
        }
        self.opacity.clear();
        if any_opacity {
            self.opacity.resize(self.tree.len(), 1.0);
        }
        self.float_root.clear();
        if any_float {
            self.float_root.resize(self.tree.len(), NIL);
        }
        // The innermost `selectable` above each node (ADR 0017). Parents
        // precede their children in the tree array, so one forward pass
        // inherits it; a node declaring `selectable` inside another scope
        // takes the text under it and is warned about, because two scopes
        // over one run would each think they own it.
        self.scopes.clear();
        self.rows.clear();
        if any_selectable {
            self.scopes.resize(self.tree.len(), None);
            self.rows.resize(self.tree.len(), None);
            // The rows a virtual list built, by node, so the walk below
            // can carry each one down to the text inside it.
            for &(node, index) in &self.tree.indexed {
                if let Some(slot) = self.rows.get_mut(node as usize) {
                    *slot = Some(index);
                }
            }
            for i in 0..self.tree.len() {
                let parent = self.tree.parent[i];
                // A floating subtree escapes the scope it floats out of,
                // the way it escapes the clip: a popover over a card is
                // not part of the card's paragraph, and a float is
                // emitted in a later pass than its tree position, which
                // would put its runs out of reading order anyway.
                let outer = if parent == NIL || self.tree.specs[i].layout.float.is_some() {
                    None
                } else {
                    self.scopes[parent as usize]
                };
                // An inner scope takes the text under it; the nesting
                // itself is reported by `diag`, over the finished tree.
                //
                // A `cells` grid is its own scope and never joins the one
                // around it: it selects in cells, and a selection that ran
                // from a paragraph into a terminal screen would be two
                // kinds of selection at once (ADR 0017, decision 4).
                let grid = matches!(self.tree.content[i], NodeContent::Cells(_));
                self.scopes[i] = if self.tree.specs[i].interact().selectable {
                    Some(self.tree.keys[i])
                } else if grid {
                    None
                } else {
                    outer
                };
                // A row's index reaches the text inside it: the node that
                // declared it keeps its own, everything under it inherits.
                if self.rows[i].is_none() && parent != NIL {
                    self.rows[i] = self.rows[parent as usize];
                }
            }
        }
        self.resolve_selection();

        // Exits: what the previous frame declared and this one does not is
        // copied out of the tree the previous frame left behind, and every
        // departing subtree still in flight is taken out for the passes,
        // which paint each one where its node was (see `depart`).
        if !self.prev_tree.is_empty() || !self.depart.is_empty() {
            self.collect_departures();
        }
        let mut replay = Replay::default();
        let mut took_ghosts = false;
        if !self.depart.is_empty()
            && let Some(now) = self.anim.time()
        {
            replay = self.depart.begin_replay(now);
            took_ghosts = true;
        }
        let any_ghost = !replay.is_empty();

        // Pass 1: clip/float propagation + in-flow emission (preorder =
        // paint order; parents precede children). `float_root[i]` is the
        // nearest layer-opening ancestor-or-self, `NIL` in flow: the layer
        // a node paints in (ADR 0023, decision 1). Every layer root goes
        // into `roots`, in tree order, for the stack to sort. A `line`,
        // `polygon` or `path` in its parent's box space floats without
        // opening a layer (`Tree::opens_layer`, F123): it is the parent's
        // content, painted at its place in the tree and held by the
        // parent's clip, as a child is.
        let mut roots: Vec<u32> = Vec::new();
        for i in 0..self.tree.len() {
            let parent = self.tree.parent[i];
            let floats_here = any_float && self.tree.opens_layer(i);
            if any_float {
                self.float_root[i] = if floats_here {
                    roots.push(i as u32);
                    i as u32
                } else if parent != NIL {
                    self.float_root[parent as usize]
                } else {
                    NIL
                };
            }
            let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
            // Opacity multiplies down the tree, floats included: a tooltip
            // inside a fading panel fades with it.
            let opacity = if !any_opacity {
                1.0
            } else {
                let inherited = if parent == NIL {
                    1.0
                } else {
                    self.opacity[parent as usize]
                };
                let o = inherited * self.tree.specs[i].style.opacity;
                self.opacity[i] = o;
                o
            };
            // A parent-anchored float that declared `clip` belongs to the
            // parent's content as a child does, so the parent's clip holds
            // it: a node on a `clip` canvas panned past the canvas's edge
            // is cut there (F90). Any other float (a tooltip, a menu, a
            // stroke anchored to the viewport) escapes. Only the clip is
            // the parent's: a declared float still paints in its own
            // layer. A stroke or polygon in its parent's box, which the
            // core gives the bit (F78, ADR 0010 decision 5), is not a
            // layer root at all (above), so it takes the parent's clip
            // here by the in-flow arm, as its graph's rows do.
            let drawn_in_parent = floats_here
                && parent != NIL
                && self.tree.specs[i]
                    .layout
                    .float
                    .is_some_and(|f| f.clipped_by_parent());
            let (clip, clip_id) = if !any_clip {
                (Clip::NONE, no_clip)
            } else {
                // Floating nodes escape ancestor clips.
                let (clip, id) = if parent == NIL || (floats_here && !drawn_in_parent) {
                    (Clip::NONE, no_clip)
                } else {
                    let p = parent as usize;
                    if self.tree.specs[p].layout.clips() {
                        // A clipper with a radius rounds what it clips, so
                        // the children of a rounded card stay inside its
                        // corners (see `display::Clip`).
                        let box_rect = Rect::from_pos_size(self.tree.pos[p], self.tree.size[p]);
                        let box_radius = if any_rounded_clip {
                            self.tree.specs[p].style.radius
                        } else {
                            crate::display::SQUARE
                        };
                        let clip = self.clips[p].intersect(box_rect, box_radius);
                        (clip, self.display.intern_clip(clip.scaled(scale)))
                    } else {
                        // The overwhelming case: the clip is the parent's,
                        // so the entry is too, and nothing is compared.
                        (self.clips[p], self.clip_ids[p])
                    }
                };
                self.clips[i] = clip;
                self.clip_ids[i] = id;
                (clip, id)
            };
            if any_float && self.float_root[i] != NIL {
                continue; // deferred to its layer, in the float pass
            }
            // A departing subtree painted just under this node last time
            // goes first, so it stays under it.
            if any_ghost && replay.may_precede(self.tree.keys[i]) {
                let key = self.tree.keys[i];
                replay.paint(At::UnderInFlow(key), |g, play| {
                    self.emit_ghost(g, play, scale)
                });
            }
            // Entirely clipped away: skip drawing and hit-testing.
            // Rect, not rounded: a node that survives only in a corner's
            // arc is drawn and clipped rather than culled.
            let visible = rect.intersect(&clip.rect);
            if visible.w <= 0.0 || visible.h <= 0.0 {
                // Culled — but a text run inside a selection scope keeps
                // its place in the order and its content reachable, so a
                // selection can run past the edge of a scroller (ADR
                // 0017, tier 2). Marked undrawn: no hit region, no
                // `text_hit`, nothing a pointer can find.
                //
                // Behind the frame's own flag, hoisted out of the loop:
                // a frame that declares no scope does not pay a lookup
                // per culled node to find that out (C15).
                if any_selectable
                    && let Some(scope) = self.scope_of(i)
                    && let NodeContent::Text(tid) = self.tree.content[i]
                {
                    let ancestry = self.text_ancestors(i);
                    self.text.place(
                        self.tree.keys[i],
                        &ancestry,
                        tid,
                        self.tree.pos[i],
                        Some(scope),
                        false,
                    );
                }
                continue;
            }
            let paint = Paint {
                clip,
                clip_id,
                scale,
                opacity,
            };
            self.emit_node(i, rect, paint, &mut hits, &mut scroll_regions);
        }

        if any_ghost {
            // The in-flow ghosts whose place is gone: the end of their
            // layer, still under its chrome and under every float.
            replay.paint(At::InFlowEnd, |g, play| self.emit_ghost(g, play, scale));
        }

        // The in-flow layer's chrome — its scrollers' bars and, if the
        // focused node is in flow, the ring — above its content and under
        // every float (ADR 0023, decision 2).
        let mut scrollbars: Vec<ScrollbarRegion> = Vec::new();
        let mut chrome_from = 0usize;
        self.emit_layer_chrome(
            NIL,
            &scroll_regions[chrome_from..],
            &mut scrollbars,
            hits.len(),
            scale,
        );
        chrome_from = scroll_regions.len();

        // Pass 2: the float layers, bottom to top in the order they opened
        // (ADR 0023, decision 3); each one's chrome at its end. Their hit
        // regions land in the same order, so `hit_at` reads the stack.
        if any_float {
            let order = self.stack_floats(&roots);
            for &r in &order {
                let root = r as usize;
                let root_key = self.tree.keys[root];
                if any_ghost && replay.may_precede(root_key) {
                    // A departed float that was under this one stays under
                    // it: a whole layer, painted before this layer starts.
                    replay.paint(At::UnderLayer(root_key), |g, play| {
                        self.emit_ghost(g, play, scale)
                    });
                }
                let end = self.tree.subtree_end(root);
                for i in root..end {
                    if self.float_root[i] != r {
                        continue; // a nested float: its own layer, later
                    }
                    if any_ghost && replay.may_precede(self.tree.keys[i]) {
                        let key = self.tree.keys[i];
                        replay.paint(At::UnderInLayer(key), |g, play| {
                            self.emit_ghost(g, play, scale)
                        });
                    }
                    let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
                    let clip = if any_clip { self.clips[i] } else { Clip::NONE };
                    let clip_id = if any_clip { self.clip_ids[i] } else { no_clip };
                    let opacity = if any_opacity { self.opacity[i] } else { 1.0 };
                    let visible = rect.intersect(&clip.rect);
                    if visible.w <= 0.0 || visible.h <= 0.0 {
                        continue;
                    }
                    let paint = Paint {
                        clip,
                        clip_id,
                        scale,
                        opacity,
                    };
                    self.emit_node(i, rect, paint, &mut hits, &mut scroll_regions);
                }
                if any_ghost {
                    replay.paint(At::LayerEnd(root_key), |g, play| {
                        self.emit_ghost(g, play, scale)
                    });
                }
                // A layer with no scroller and no ring to draw has no
                // chrome: the common float is a leaf, and ten thousand of
                // them (a `line` each) pay a call apiece otherwise (C29).
                if scroll_regions.len() > chrome_from || self.focus_visible {
                    self.emit_layer_chrome(
                        r,
                        &scroll_regions[chrome_from..],
                        &mut scrollbars,
                        hits.len(),
                        scale,
                    );
                    chrome_from = scroll_regions.len();
                }
            }
            self.check_layers_over_modal(&order);
        } else if !self.float_stack.is_empty() {
            // No floats this frame: every layer closed.
            self.float_stack.clear();
        }

        if any_ghost {
            // A ghost whose whole layer is gone: on top, the only place
            // left that is under nothing it was under.
            replay.paint(At::Top, |g, play| self.emit_ghost(g, play, scale));
        }
        if took_ghosts {
            self.depart.end_replay(replay);
        }

        // Rounded span backgrounds, joined into one shape with the ones
        // they meet now that every text is painted (backlog F101).
        let joins = self.text.take_joins();
        if !joins.is_empty() {
            let sess = &mut *self.session.state();
            let id = sess.resources.add_fragment(crate::fragment::JOIN);
            if let Some(source) = sess.resources.fragment(id).cloned() {
                crate::join::shape(&mut self.display, &joins, id, &source, scale);
            }
        }

        let shapes = std::mem::take(&mut self.hit_shapes);
        self.interaction.set_hits_shaped(hits, shapes);
        // A button held on a node this frame no longer declares has no one
        // to hear its release (backlog F105).
        let tree = &self.tree;
        self.interaction
            .drop_gone_buttons(|key| tree.index_of(key).is_some());
        // A new frame can move a hover-sound node under a still cursor.
        self.flush_sound_requests();
        // Against this window's mounts only (AR7): a popup or a second
        // window finishing a frame with no `<audio>` in it says nothing
        // about the main window's loop.
        let window = self.env.window.id;
        self.session.state().audio.reconcile(window);
        self.interaction.scroll_regions = scroll_regions;
        self.interaction.scrollbars = scrollbars;
        self.ime_rect = self.focused_caret_rect();
        self.note_sink_caret();
        self.atlas.end_frame();
        // The atlas refused a glyph for room this frame rather than drop
        // a slot the frame had already used (F99): the next frame starts
        // on an empty page and draws it, and has to come — an
        // input-driven app would keep the short frame until the next
        // event. A page that only grew is right as it is presented.
        if self.atlas.short() {
            self.owe_frame("atlas full");
        }
        // A long line's rows came out other than layout's once emission
        // shaped what shows (backlog RG70): the frame laid out on them is
        // owed, or an idle view keeps the estimate's box.
        if self.text.take_owed() {
            self.owe_frame("long line rows");
        }
    }

    /// The exit diff: every key the previous frame declared an `exit` on
    /// and this frame does not becomes a departing subtree, copied out of
    /// `prev_tree` — the frame that still had it — and handed to the store
    /// with the place it painted in, so its ghost keeps it.
    /// A ghost whose key came back is retired here too: the live node wins.
    ///
    /// Only two kinds of key are interesting (the previous frame's
    /// exit-declaring roots, and the roots already departing), and both are
    /// few, so the walk over *this* frame's keys — the part that scales
    /// with the frame — is one AND against a 64-bit membership mask per
    /// node, and a hash lookup only for the handful that collide with it.
    fn collect_departures(&mut self) {
        let Some(now) = self.anim.time() else {
            // No clock: every transition snaps, and an exit that snaps is
            // the plain disappearance it has always been.
            self.depart.clear();
            return;
        };
        // The steady state: the view declared the same nodes in the same
        // order, so nothing left and nothing came back. Two flat arrays of
        // u64 compared is cheaper than anything that looks at the keys one
        // at a time, and it is the case almost every frame is.
        if self.prev_tree.keys == self.tree.keys {
            return;
        }
        let mut watch: FxHashSet<Key> = FxHashSet::default();
        let mut mask = 0u64;
        for k in self.depart.keys() {
            watch.insert(k);
            mask |= 1u64 << (k.0 & 63);
        }
        let mut candidates: Vec<usize> = Vec::new();
        for i in 0..self.prev_tree.len() {
            if crate::depart::can_depart(&self.prev_tree.specs[i]) {
                candidates.push(i);
                // The node, and its parent: an exit plays only where the
                // parent is still declared (backlog DX19), so the diff has
                // to know about that key too.
                let p = self.prev_tree.parent[i];
                let keys = [
                    Some(self.prev_tree.keys[i]),
                    (p != NIL).then(|| self.prev_tree.keys[p as usize]),
                ];
                for k in keys.into_iter().flatten() {
                    watch.insert(k);
                    mask |= 1u64 << (k.0 & 63);
                }
            }
        }
        if watch.is_empty() {
            return;
        }
        let mut live: FxHashSet<Key> = FxHashSet::default();
        for &k in &self.tree.keys {
            if mask & (1u64 << (k.0 & 63)) != 0 && watch.contains(&k) {
                live.insert(k);
            }
        }
        self.depart.retire_returned(&live);
        // The frame's removal, whole, before any of it is copied: the roots
        // that actually left, in tree order so a departing subtree swallows
        // the exits nested inside it rather than drawing them a second time
        // on top, and how many nodes they come to together.
        let mut roots: Vec<usize> = Vec::new();
        let mut wanted = 0usize;
        let mut swallowed_until = 0usize;
        for i in candidates {
            if i < swallowed_until || live.contains(&self.prev_tree.keys[i]) {
                continue;
            }
            // Its parent went too, and the parent declared no exit that
            // would have carried it (it would have swallowed it above): the
            // node went with its ancestor, not on its own, and plays nothing
            // — a tab switched away does not fade out every column that
            // fades when it closes (backlog DX19). CSS removes the subtree;
            // React's `AnimatePresence` plays the exits of its direct
            // children only. This is that rule.
            let p = self.prev_tree.parent[i];
            if p != NIL && !live.contains(&self.prev_tree.keys[p as usize]) {
                continue;
            }
            swallowed_until = self.prev_tree.subtree_end(i);
            wanted += swallowed_until - i;
            roots.push(i);
        }
        if roots.is_empty() {
            return;
        }
        // ADR 0012, decisions 2 and 3: the removal animates whole or not at
        // all, and takes the room it needs from the oldest ghosts in flight
        // before it is refused. Refused means every node of it vanishes at
        // once — what a node with no `exit` does — and one warning for the
        // frame, keyed by its first departing root, says how much did.
        if !self.depart.admit(wanted) {
            self.diag.raise(Warning {
                code: crate::diag::EXIT_BUDGET,
                key: self.prev_tree.keys[roots[0]],
                message: format!(
                    "this frame removed {wanted} nodes declaring `exit` and the exit store \
                     holds {}, so none of that removal animated: every departing node \
                     vanished at once, as a node with no `exit` does; `exit` is per node, \
                     and a list that drops many rows at once wants it on the list, not on \
                     every row",
                    crate::depart::MAX_NODES
                ),
            });
            return;
        }
        // The previous frame's paint order, built on the first departure:
        // a frame with one is a frame that changed shape and paid for a
        // layout, and the frames that did not never get here.
        let mut order: Option<PaintOrder> = None;
        for &i in &roots {
            let place = order
                .get_or_insert_with(|| PaintOrder::of(&self.prev_tree, &self.tree))
                .place(&self.prev_tree, i, &self.float_stack);
            // The group opacity the root inherited from ancestors that are
            // now gone: a subtree already half-faded departs from there.
            let mut base = 1.0;
            let mut a = self.prev_tree.parent[i];
            while a != NIL {
                base *= self.prev_tree.specs[a as usize].style.opacity;
                a = self.prev_tree.parent[a as usize];
            }
            self.depart.depart(
                &self.prev_tree,
                i,
                now,
                base,
                place,
                &self.text,
                &self.lines,
                &self.fragments,
                &self.paths,
            );
        }
        // Named now, while a tree still has them (backlog F111).
        self.trace_departures(&roots);
    }

    /// One departing subtree's quads: frozen rects moved by however far
    /// its `exit` has got, outside every clip (its ancestors may be gone).
    /// A smaller `emit_node`: the parts a picture has (shadow, background,
    /// border, its content) and none of the parts a node has — no hit
    /// region, no scroll region, no access row.
    fn emit_ghost(&mut self, g: &Ghost, play: &Playback, scale: f32) {
        // Whole physical pixels, for the reason a slide's is: a ghost is
        // mostly text, and it moves for its whole life.
        let offset = play.offset.snapped(scale);
        self.ghost_opacity.clear();
        self.ghost_opacity.resize(g.nodes.len(), 1.0);
        self.ghost_clip.clear();
        self.ghost_clip.resize(g.nodes.len(), Clip::NONE);
        self.ghost_clip_ids.clear();
        self.ghost_clip_ids.resize(g.nodes.len(), NO_CLIP_ID);
        self.ghost_rect.clear();
        self.ghost_rect
            .resize(g.nodes.len(), Rect::new(0.0, 0.0, 0.0, 0.0));
        for (i, node) in g.nodes.iter().enumerate() {
            let mut rect = Rect::new(
                node.rect.x + offset.x,
                node.rect.y + offset.y,
                node.rect.w,
                node.rect.h,
            );
            let mut style = node.spec.style;
            let inherited = if node.parent == NIL {
                // The root carries the eased slots; an `exit` says nothing
                // about the subtree under it, which fades and moves with
                // its root and no more.
                if let Some(bg) = play.bg {
                    style.bg = bg;
                }
                if let Some(radius) = play.radius {
                    style.radius = radius;
                }
                if let Some((w, h)) = play.size {
                    // The root's own box only: the subtree inside it is a
                    // picture, and re-laying it out is the one thing a
                    // frozen ghost must not do.
                    rect.w = w.unwrap_or(rect.w);
                    rect.h = h.unwrap_or(rect.h);
                }
                style.opacity = play.opacity;
                play.base_opacity
            } else {
                self.ghost_opacity[node.parent as usize]
            };
            let opacity = (inherited * style.opacity).clamp(0.0, 1.0);
            self.ghost_opacity[i] = opacity;
            // The clip is the subtree's own: a scroll box or `clip` node
            // inside the picture still bounds what it held (the rows a
            // virtual list built past its edge stay past it), while the
            // ancestors outside the picture, which may be gone, clip
            // nothing. Same rule as the live pass, from the root down —
            // a parent-anchored float with `clip`, a stroke or polygon
            // included, is held by the parent's clip as a child is (F78,
            // F90; the ghost pass kept the old escape, RG26).
            let escapes = node
                .spec
                .layout
                .float
                .is_some_and(|f| !f.clipped_by_parent());
            let (clip, clip_id) = if node.parent == NIL || escapes {
                (Clip::NONE, NO_CLIP_ID)
            } else {
                let p = node.parent as usize;
                let inherited = self.ghost_clip[p];
                if g.nodes[p].spec.layout.clips() {
                    let clip =
                        inherited.intersect(self.ghost_rect[p], g.nodes[p].spec.style.radius);
                    (clip, self.display.intern_clip(clip.scaled(scale)))
                } else {
                    (inherited, self.ghost_clip_ids[p])
                }
            };
            self.ghost_clip[i] = clip;
            self.ghost_clip_ids[i] = clip_id;
            self.ghost_rect[i] = rect;
            let visible = rect.intersect(&clip.rect);
            if visible.w <= 0.0 || visible.h <= 0.0 {
                continue;
            }
            let leaf = match node.content {
                GhostContent::Container => Leaf::Container,
                // None once the shaped buffer has been evicted: a ghost
                // older than the text cache draws no text rather than
                // somebody else's. A departing subtree takes no input and
                // holds no selection; it records no place either.
                GhostContent::Text { cache_key, color } => {
                    match self.text.readd(cache_key, color) {
                        Some(tid) => Leaf::Text { tid, sel: None },
                        None => Leaf::Container,
                    }
                }
                // Never focused: the departing subtree gave the keyboard
                // up the frame it stopped being declared.
                GhostContent::Edit(key) => Leaf::Edit {
                    key,
                    focused: false,
                    pad: node.spec.layout.padding,
                },
                GhostContent::Image(id, opts) => Leaf::Image(id, opts),
                // The picture is frozen at departure — the parameters are
                // the ones the node last declared — while the box eases
                // and the group opacity fades it.
                GhostContent::Fragment(draw) => Leaf::Fragment(draw),
                GhostContent::Polygon(draw) => Leaf::Polygon(draw),
                // The points are the ghost's own copy; the colour is the
                // `bg` slot, which `play.bg` eases on the root.
                GhostContent::Line {
                    first,
                    len,
                    width,
                    dash,
                } => Leaf::Line {
                    points: &g.points[first as usize..(first + len) as usize],
                    width,
                    dash,
                },
                // The ops are the ghost's own copy, the hash the live
                // node's, so the masks are the slots it already had.
                GhostContent::Path {
                    first,
                    len,
                    rule,
                    stroke_w,
                    dash,
                    hash,
                    angle,
                } => Leaf::Path {
                    ops: &g.ops[first as usize..(first + len) as usize],
                    rule,
                    stroke_w,
                    dash,
                    hash,
                    angle,
                    animating: false,
                },
            };
            let paint = Paint {
                clip,
                clip_id,
                scale,
                opacity,
            };
            // A departing box blurs what is under it for as long as it
            // fades, as it did while it was declared.
            let blur = node.spec.interact().backdrop_blur;
            if blur > 0.0 {
                backdrop_quad(&mut self.display.quads, rect, &style, &paint, blur);
            }
            let first_quad = self.display.quads.len();
            painter!(self).paint_box(rect, &style, &paint, leaf);
            // A departing box keeps its gradient, from the slot it had.
            if let Some(grad) = &node.spec.interact().gradient
                && !matches!(
                    node.content,
                    GhostContent::Line { .. }
                        | GhostContent::Polygon(_)
                        | GhostContent::Path { .. }
                )
            {
                painter!(self).paint_gradient(grad, rect, &style, &paint, first_quad);
            }
            // A departing table keeps its grid for as long as it fades.
            if let Some(c) = node.spec.interact().rules
                && node.spec.layout.is_table()
            {
                self.emit_ghost_rules(g, i, rect, offset, c, &paint);
            }
        }
    }

    /// After layout: nodes that `slide` ease from last frame's position
    /// toward where layout put them, carrying their subtree along (hit
    /// regions come from the same positions, so input follows the motion).
    /// Nodes whose `enter` has an offset start that far away on first
    /// sight and ease in the same way; without `slide` that entrance is
    /// all their position ever eases. Preorder means a parent shifts before
    /// its children are visited, so nested sliders ease relative to an
    /// already-eased parent.
    fn ease_positions(&mut self) {
        for i in 0..self.tree.len() {
            let spec = &self.tree.specs[i];
            let Some(t) = spec.transition else {
                continue;
            };
            let enter = spec.anim().enter.filter(|e| e.offsets());
            if !spec.slide && enter.is_none() {
                continue;
            }
            let key = self.tree.keys[i];
            let target = self.tree.pos[i];
            let from = enter.map(|e| [target.x + e.dx, target.y + e.dy, 0.0, 0.0]);
            let v = self.anim.drive(
                key,
                Slot::Pos,
                from,
                [target.x, target.y, 0.0, 0.0],
                t,
                spec.slide,
            );
            // Whole physical pixels, so the text inside moves with its box
            // rather than wobbling in it (`Vec2::snapped`). Rounding here
            // and not at the end means the last frame lands exactly on the
            // layout position, as it did before.
            let d = Vec2::new(v[0] - target.x, v[1] - target.y).snapped(self.scale);
            if d.x == 0.0 && d.y == 0.0 {
                continue;
            }
            let end = self.tree.subtree_end(i);
            for p in &mut self.tree.pos[i..end] {
                p.x += d.x;
                p.y += d.y;
            }
        }
    }

    /// After layout: every `on_layout` node whose rect differs from the one
    /// last reported for its key — or that was not seen last frame — posts
    /// `{kind="layout", x, y, w, h, parent, scale, tag}`, pending like a
    /// `resize`.
    /// A frame that leaves a node where it was posts nothing, so a view
    /// that stores the rect in its model and redraws does not loop.
    fn emit_layout_events(&mut self) {
        let frame_no = self.frame_no;
        for i in 0..self.tree.len() {
            let Some(tag) = &self.tree.specs[i].events().on_layout else {
                continue;
            };
            let key = self.tree.keys[i];
            let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
            let changed = match self.layouts.get(&key) {
                Some((last, seen)) if *seen + 1 == frame_no => *last != rect,
                _ => true,
            };
            self.layouts.insert(key, (rect, frame_no));
            if !changed {
                continue;
            }
            let parent = self.tree.parent[i];
            let parent_rect = if parent == NIL {
                Rect::new(0.0, 0.0, self.viewport.w, self.viewport.h)
            } else {
                let p = parent as usize;
                Rect::from_pos_size(self.tree.pos[p], self.tree.size[p])
            };
            let rect_value = |r: Rect| {
                Value::map([
                    ("x", Value::Float(r.x as f64)),
                    ("y", Value::Float(r.y as f64)),
                    ("w", Value::Float(r.w as f64)),
                    ("h", Value::Float(r.h as f64)),
                ])
            };
            let payload = Value::map([
                ("kind", Value::str("layout")),
                ("x", Value::Float(rect.x as f64)),
                ("y", Value::Float(rect.y as f64)),
                ("w", Value::Float(rect.w as f64)),
                ("h", Value::Float(rect.h as f64)),
                ("parent", rect_value(parent_rect)),
                // Physical px per logical px at this node — the number a
                // view multiplies `w`/`h` by to know how many pixels to
                // render before `update_image` (ADR 0025, decision 5).
                // The frame's today; where a zoom would compose in.
                ("scale", Value::Float(self.scale as f64)),
            ]);
            self.pending
                .push(UiEvent::on(self.tree.origins[i], key, payload).tagged(Some(tag)));
        }
    }

    /// The chrome of one layer, after its content: the bars of every
    /// scroller the layer emitted (`regions`), then the ring if the focused
    /// node is in this layer. `layer` is the float
    /// root's index, or `NIL` for the in-flow layer; `above` is the hit
    /// list's length now, which is what a bar records so a press can tell
    /// a region under it from one in a layer over it.
    fn emit_layer_chrome(
        &mut self,
        layer: u32,
        regions: &[ScrollRegion],
        scrollbars: &mut Vec<ScrollbarRegion>,
        above: usize,
        scale: f32,
    ) {
        let cursor = self.interaction.cursor();
        let above = above as u32;
        for r in regions {
            let i = r.node as usize;
            // The node's own bar style, if it declared one: hidden means
            // no thumb and no track, and the wheel still works because the
            // scroll region is already pushed. A handler has no offset to
            // draw a bar for.
            let style = self.tree.specs[i].interact().scrollbar;
            if r.handler || style.mode == crate::spec::ScrollbarMode::Hidden {
                continue;
            }
            let rest_w = style.width.unwrap_or(SCROLLBAR_W);
            let active_w = rest_w + (SCROLLBAR_ACTIVE_W - SCROLLBAR_W);
            // The grabbable gutter: the stock one, or enough for a wide
            // thumb and its inset.
            let hit_w = SCROLLBAR_HIT_W.max(active_w + 2.0 * SCROLLBAR_INSET);
            let max = self.tree.scroll_max[i];
            let offset = self.scroll.drawn(r.key);
            let clip_id = self.clip_ids.get(i).copied().unwrap_or(NO_CLIP_ID);
            let mut opacity = self.opacity.get(i).copied().unwrap_or(1.0);
            // The tracks, before either bar: an `auto` bar is held while
            // the pointer is on either track, and the two tracks share the
            // one quiet clock.
            let track_y = Rect::new(
                r.rect.x + r.rect.w - hit_w,
                r.rect.y + SCROLLBAR_INSET,
                hit_w,
                r.rect.h - 2.0 * SCROLLBAR_INSET,
            );
            let track_x = Rect::new(
                r.rect.x + SCROLLBAR_INSET,
                r.rect.y + r.rect.h - hit_w,
                r.rect.w - 2.0 * SCROLLBAR_INSET,
                hit_w,
            );
            if style.mode == crate::spec::ScrollbarMode::Auto
                && let Some(now) = self.anim.time()
            {
                let held = self.interaction.is_scrollbar_dragging(r.key, ScrollAxis::Y)
                    || self.interaction.is_scrollbar_dragging(r.key, ScrollAxis::X)
                    || cursor.is_some_and(|p| {
                        (max.y > 0.0 && track_y.contains(p)) || (max.x > 0.0 && track_x.contains(p))
                    });
                let idle = self.scroll.bar_idle(r.key, now, held);
                let shown = if idle < SCROLLBAR_HOLD {
                    1.0
                } else {
                    (1.0 - (idle - SCROLLBAR_HOLD) / SCROLLBAR_FADE).max(0.0)
                };
                if shown <= 0.0 {
                    continue; // faded out: no thumb, and no track to press
                }
                // Something to settle: the hold running out, or the fade.
                // Not while held — that is input's to end, and a frame a
                // hover would ask for every 8 ms is the idle CPU C27 fought.
                if !held {
                    self.owe_frame("scrollbar fade");
                }
                opacity *= shown as f32;
            }
            for (axis, track) in [(ScrollAxis::Y, track_y), (ScrollAxis::X, track_x)] {
                let (max_a, offset_a) = match axis {
                    ScrollAxis::Y => (max.y, offset.y),
                    ScrollAxis::X => (max.x, offset.x),
                };
                if max_a <= 0.0 {
                    continue;
                }
                let active = self.interaction.is_scrollbar_dragging(r.key, axis)
                    || cursor.is_some_and(|p| track.contains(p));
                let w = if active { active_w } else { rest_w };
                let (thumb, bar_len) = thumb_along(axis, r.rect, track, max_a, offset_a, w);
                let mut bar =
                    scrollbar_quad(thumb, scale, clip_id, self.thumb_color(&style, active));
                bar.color.a *= opacity;
                self.display.quads.push(bar);
                scrollbars.push(ScrollbarRegion {
                    key: r.key,
                    axis,
                    thumb,
                    track,
                    bar_len,
                    max: max_a,
                    inert: r.inert,
                    above,
                });
            }
        }
        self.emit_focus_ring(layer, scale);
    }

    /// The layer node `i` paints in: its float root's index, `NIL` in flow
    /// — and `NIL` for every node of a frame that floats nothing, where the
    /// map is not even sized.
    #[inline]
    fn layer_of(&self, i: usize) -> u32 {
        self.float_root.get(i).copied().unwrap_or(NIL)
    }

    /// This frame's float layers in paint order, from `roots` (the float
    /// roots in tree order) and the stack the last frame left: a root the
    /// stack knows keeps its place, one it does not is appended, in tree
    /// order, and a root the frame no longer declares is dropped. Writes
    /// the stack back for the next frame.
    ///
    /// The steady state — the same roots as last frame — is one pass over
    /// the stack and no allocation beyond the order itself: each entry
    /// remembers its root's rank in tree order, so the check and the
    /// answer are the same read.
    fn stack_floats(&mut self, roots: &[u32]) -> Vec<u32> {
        let keys = &self.tree.keys;
        let parent = &self.tree.parent;
        let float_root = &self.float_root;
        // The float a root is in, or NIL for one in the flow.
        let outer_of = |root: u32| {
            let p = parent[root as usize];
            if p == NIL {
                NIL
            } else {
                float_root[p as usize]
            }
        };
        // Every nested float above the float it is in.
        let nested_above = |order: &[u32]| {
            order.iter().enumerate().all(|(pos, &r)| {
                let outer = outer_of(r);
                outer == NIL || order[..pos].contains(&outer)
            })
        };
        let stack = &mut self.float_stack;
        let steady = stack.len() == roots.len()
            && stack
                .iter()
                .all(|&(k, rank)| keys[roots[rank as usize] as usize] == k);
        // The steady order holds unless a root moved into a float under a
        // key the app keeps (`open_key`), which changes no rank: then the
        // rebuild below sorts it, as it does a root the stack is new to
        // (backlog RG151).
        let order: Vec<u32> = if steady {
            stack
                .iter()
                .map(|&(_, rank)| roots[rank as usize])
                .collect()
        } else {
            Vec::new()
        };
        let order = if steady && nested_above(&order) {
            order
        } else {
            // A float opened or closed: the ranks are found again, by key.
            let rank_of: FxHashMap<Key, u32> = roots
                .iter()
                .enumerate()
                .map(|(rank, &r)| (keys[r as usize], rank as u32))
                .collect();
            let mut placed = vec![false; roots.len()];
            let mut next: Vec<(Key, u32)> = Vec::with_capacity(roots.len());
            for &(k, _) in stack.iter() {
                if let Some(&rank) = rank_of.get(&k) {
                    placed[rank as usize] = true;
                    next.push((k, rank));
                }
            }
            for (rank, &r) in roots.iter().enumerate() {
                if !placed[rank] {
                    next.push((keys[r as usize], rank as u32));
                }
            }
            // A box that kept its key while it became a float is new here,
            // and a float it already held is not: the held one waits for
            // it and goes just above it, and what it holds in turn after
            // that — each in the order it had — so a nested float stays
            // over the float it is in and two held side by side keep
            // their order (backlog RG151).
            let rank_of_outer = |root: u32| {
                let outer = outer_of(root);
                if outer == NIL {
                    None
                } else {
                    rank_of.get(&keys[outer as usize]).copied()
                }
            };
            let mut out: Vec<(Key, u32)> = Vec::with_capacity(next.len());
            let mut out_has = vec![false; roots.len()];
            let mut waiting: Vec<(Key, u32)> = Vec::new();
            for e in next {
                match rank_of_outer(roots[e.1 as usize]) {
                    Some(outer) if !out_has[outer as usize] => waiting.push(e),
                    _ => {
                        out_has[e.1 as usize] = true;
                        out.push(e);
                        // What waited on it, and on those, in turn.
                        while let Some(i) = waiting.iter().position(|w| {
                            rank_of_outer(roots[w.1 as usize])
                                .is_none_or(|outer| out_has[outer as usize])
                        }) {
                            let w = waiting.remove(i);
                            out_has[w.1 as usize] = true;
                            out.push(w);
                        }
                    }
                }
            }
            debug_assert!(
                waiting.is_empty(),
                "a float inside a float this frame has no root"
            );
            *stack = out;
            stack
                .iter()
                .map(|&(_, rank)| roots[rank as usize])
                .collect()
        };
        // Said here so the placement above cannot drift.
        debug_assert!(nested_above(&order));
        order
    }

    /// The `modal-behind-content` check, for the stack: a float layer
    /// above the modal's whose root is outside the modal's scope is inert
    /// and drawn over the one surface that takes input, which is the same
    /// defect the in-flow check names. Only a layer
    /// with something in it that *would* take input is the defect — a
    /// control the user sees and cannot press. A picture over the dialog
    /// (a HUD, the devtools' inspector outline) is not, and is not named.
    fn check_layers_over_modal(&mut self, order: &[u32]) {
        let Some((start, end, modal_key)) = self.modal else {
            return;
        };
        let modal_layer = self.layer_of(start);
        if modal_layer == NIL {
            return; // `diag::check_modal` has this case
        }
        let Some(at) = order.iter().position(|&r| r == modal_layer) else {
            return;
        };
        let over = order[at + 1..].iter().any(|&r| {
            let root = r as usize;
            !(start..end).contains(&root)
                && (root..self.tree.subtree_end(root)).any(|i| {
                    self.float_root[i] == r
                        && (self.tree.specs[i].hover_tracked()
                            || crate::access::focusable(&self.tree, i))
                })
        });
        if over {
            self.diag.raise(crate::diag::modal_under_layer(modal_key));
        }
    }

    /// The default focus ring around the keyboard-visibly focused node, at
    /// the end of the layer the node is in — above every sibling that could
    /// touch it, under every layer over it — in the same display list
    /// every binding draws. Not for editors (the caret shows focus), key
    /// sinks (an app surface styles itself, through `is_focused` /
    /// `focus_visible`) or nodes declaring `focus_bg`.
    fn emit_focus_ring(&mut self, layer: u32, scale: f32) {
        if !self.focus_visible {
            return;
        }
        let Some(i) = self.focus_index() else {
            return;
        };
        if self.layer_of(i) != layer {
            return;
        }
        let spec = &self.tree.specs[i];
        let editor = matches!(self.tree.content[i], NodeContent::Edit(_))
            || spec
                .access()
                .role
                .is_some_and(crate::access::Role::is_editor);
        if editor
            || spec.events().on_key.is_some()
            || spec.interact().focus_bg.is_some()
            || spec.disabled
        {
            return;
        }
        let node = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
        let rect = Rect::new(
            node.x - FOCUS_RING_GAP,
            node.y - FOCUS_RING_GAP,
            node.w + 2.0 * FOCUS_RING_GAP,
            node.h + 2.0 * FOCUS_RING_GAP,
        );
        let clip = self.clips.get(i).copied().unwrap_or(Clip::NONE);
        // No entry means nothing clipped this frame, which is entry zero.
        let clip_id = self.clip_ids.get(i).copied().unwrap_or(NO_CLIP_ID);
        let visible = rect.intersect(&clip.rect);
        if visible.w <= 0.0 || visible.h <= 0.0 {
            return;
        }
        let mut ring = self.theme().focus_ring;
        ring.a *= self.opacity.get(i).copied().unwrap_or(1.0);
        self.display.quads.push(Quad {
            rect: rect.scaled(scale),
            color: Color::TRANSPARENT,
            border_color: ring,
            radius: spec.style.radius.map(|r| (r + FOCUS_RING_GAP) * scale),
            border_w: FOCUS_RING_W * scale,
            blur: 0.0,
            kind: QuadKind::Solid,
            clip: clip_id,
            uv: [0; 4],
        });
    }

    /// See the `ime_rect` field. None when nothing with a caret is
    /// focused: neither a stock editor nor a sink holding a `line` that
    /// declares one.
    pub fn ime_rect(&self) -> Option<Rect> {
        self.ime_rect
    }

    /// The stock editor `key`'s node and its caret rect in viewport
    /// coordinates, from the frame laid out: the editor's own caret
    /// (physical px inside its text box) placed at the node's content
    /// origin. The one place this arithmetic lives — the
    /// IME anchor and the scroll-into-view both read it. None when no
    /// node of this frame is that editor, or it has no caret.
    pub(crate) fn stock_caret_viewport_rect(&mut self, key: Key) -> Option<(usize, Rect)> {
        let i = (0..self.tree.len()).find(|&i| self.tree.content[i] == NodeContent::Edit(key))?;
        let caret = self.edit_with_fonts(|edit, fs| edit.caret_rect(key, fs))?;
        let pad = self.tree.specs[i].layout.padding;
        Some((
            i,
            Rect::new(
                self.tree.pos[i].x + pad.l + caret.x / self.scale,
                self.tree.pos[i].y + pad.t + caret.y / self.scale,
                caret.w / self.scale,
                caret.h / self.scale,
            ),
        ))
    }

    fn focused_caret_rect(&mut self) -> Option<Rect> {
        if let Some(key) = self.edit.focused() {
            return self.stock_caret_viewport_rect(key).map(|(_, r)| r);
        }
        // A custom editor (backlog C17): the focused node's subtree holds
        // the `line` rows it draws, and the one carrying `caret` says
        // where the caret is — a byte offset into that line's runs, which
        // is the question `caret_rect` answers. This runs after the text
        // pass, so the places it reads are this frame's.
        let (l, caret, _) = self.sink_caret_line()?;
        self.text.caret_at(self.tree.keys[l], caret as usize, false)
    }

    /// The `line` under the focused node that declares `caret`, the
    /// offset it declares, and whether it declares the caret
    /// `caret_solid` — a custom editor's caret, in the frame just built.
    /// None with a stock editor focused, or nothing declaring one.
    fn sink_caret_line(&self) -> Option<(usize, u32, bool)> {
        if !self.tree.any_line {
            return None;
        }
        // The editor whose caret this is: the focused sink, or the sink
        // enclosing a focused control inside it — the node keys and
        // commits already go to (`key_target`, `sink_event`). Read from
        // the focused node alone, focus on a pane button inside a custom
        // editor un-armed the blink clock and lost the IME its anchor
        // while the keys kept arriving (backlog AR29).
        let i = self.focus_index()?;
        let i = if self.tree.specs[i].events().on_key.is_some() {
            i
        } else {
            self.enclosing_sink(i)?
        };
        // The candidates are the editor's lines as the access tree reads
        // them — `role="none"` subtrees (a gutter) skipped, a line's own
        // subtree not descended into — and the *last* one declaring a
        // caret is the caret, as `custom_editor` reads it.
        let l = crate::access::lines_under(&self.tree, i)
            .into_iter()
            .rev()
            .find(|&l| self.tree.specs[l].access().caret.is_some())?;
        let access = self.tree.specs[l].access();
        Some((l, access.caret?, access.caret_solid))
    }

    /// Remembers this frame's custom-editor caret and bumps the stamp when
    /// it is not last frame's: the blink clock reads both.
    /// Whether it is solid is kept beside it, not in it: a caret going
    /// from bar to block has not moved, and the clock re-arms on the
    /// way back from `has_caret` alone.
    fn note_sink_caret(&mut self) {
        let (now, solid) = if self.edit.focused().is_some() {
            (None, false)
        } else {
            match self.sink_caret_line() {
                Some((l, offset, solid)) => (Some((self.tree.keys[l], offset)), solid),
                None => (None, false),
            }
        };
        if now != self.sink_caret {
            self.sink_caret = now;
            self.sink_caret_stamp += 1;
        }
        self.sink_caret_solid = solid;
    }

    // -- The caret's blink --------------------------------------------
    // The clock is the driver's (a frame twice a second is a decision
    // about the window, not the tree); what the core keeps is whether
    // there is a caret to blink, when it moved, and the phase the driver
    // last set — for the stock editor, which paints its own caret on the
    // phase, and for a custom one, which reads it (backlog C35).

    /// Whether there is a caret to blink: a focused stock editor's, or the
    /// `caret` a `line` under the focused custom editor declares — unless
    /// that line declares it `caret_solid`, which is a caret to anchor
    /// the IME and read to assistive technology but not one to blink. A
    /// driver arms its blink clock while this is true and leaves the
    /// caret solid otherwise.
    pub fn has_caret(&self) -> bool {
        self.edit.focused().is_some() || (self.sink_caret.is_some() && !self.sink_caret_solid)
    }

    /// Changes whenever the caret moved or focus changed — the stock
    /// editor's caret through typing or a click, a custom editor's
    /// through the `caret` row it declares — so a driver comparing it
    /// across frames re-arms the blink with the caret solid, the way a
    /// caret that just moved is never mid-blink.
    pub fn caret_stamp(&self) -> u64 {
        self.edit.caret_stamp().wrapping_add(self.sink_caret_stamp)
    }

    /// The blink phase, as the driver last set it: `true` draws the
    /// caret. The stock editor reads it itself; a custom editor reads it
    /// in `view` (`Ui::caret_visible`) and skips its caret node on the
    /// off phase, so the two blink in step — and a window without the
    /// keyboard, where the driver parks it hidden, shows neither.
    /// Headless it stays `true`.
    pub fn caret_visible(&self) -> bool {
        self.edit.blink_visible()
    }

    /// Sets the blink phase; the driver's, on its clock. A frame is the
    /// caller's to ask for.
    pub fn set_caret_visible(&mut self, visible: bool) {
        self.edit.set_blink_visible(visible);
    }
}

/// Combined measurer handed to the layout pass: static text through the
/// shape cache, editors through the edit store (sharing one FontSystem),
/// images through the resource registry.
struct Measure<'a> {
    text: &'a mut TextSystem,
    cells: &'a mut crate::cells::CellStore,
    fonts: &'a mut cosmic_text::FontSystem,
    edit: &'a mut EditStore,
    resources: &'a Resources,
}

impl TextMeasure for Measure<'_> {
    fn intrinsic(&mut self, id: crate::tree::TextId) -> Size {
        self.text.intrinsic(id)
    }

    fn wrapped(&mut self, id: crate::tree::TextId, max_w: f32) -> Size {
        self.text.wrapped(id, max_w, self.fonts)
    }

    fn min_content(&mut self, id: crate::tree::TextId) -> f32 {
        self.text.min_content(id)
    }

    fn edit_intrinsic(&mut self, key: Key) -> Size {
        self.edit.intrinsic(key, self.fonts)
    }

    fn edit_wrapped(&mut self, key: Key, max_w: f32) -> Size {
        self.edit.wrapped(key, max_w, self.fonts)
    }

    fn baseline(&mut self, id: crate::tree::TextId) -> f32 {
        self.text.baseline(id)
    }

    fn edit_baseline(&mut self, key: Key) -> f32 {
        self.edit.baseline(key)
    }

    fn cells_size(&mut self, id: crate::cells::CellsId) -> Size {
        self.cells.size(id, self.resources, self.fonts)
    }

    fn image_size(&mut self, id: crate::resources::ImageId) -> Size {
        self.resources
            .image(id)
            .map_or(Size::ZERO, |e| Size::new(e.width as f32, e.height as f32))
    }
}

/// What a node inherits at emission time: the frame's scale, the clip its
/// ancestors imposed (logical px), and the group opacity its own `opacity`
/// and every ancestor's multiply out to.
#[derive(Clone, Copy)]
/// What a box holds, resolved to what painting it needs: the live pass
/// resolves a text node's selection and an editor's focus from the frame,
/// a ghost resolves nothing (no selection, never focused, its text re-added
/// from the cache) — and both hand the result here.
enum Leaf<'a> {
    Container,
    Text {
        tid: crate::tree::TextId,
        sel: Option<((usize, usize), Color)>,
    },
    Cells {
        cid: crate::cells::CellsId,
        at: Vec2,
        sel: Option<&'a crate::select::CellSelection>,
        tint: Color,
    },
    Edit {
        key: Key,
        focused: bool,
        /// The box's padding: the text starts inside it.
        pad: crate::geom::Edges,
    },
    Image(crate::resources::ImageId, crate::resources::ImageOpts),
    Fragment(crate::fragment::Draw),
    /// A polygon's draw; the fill is the node's `bg`, put through the
    /// fragment quad's colour rather than a box under it.
    Polygon(crate::fragment::Draw),
    Line {
        points: &'a [Vec2],
        width: f32,
        /// What cuts the stroke into marks (backlog V2); None for solid.
        dash: Option<crate::line::Cut>,
    },
    /// A path's run; the fill is the node's `bg`, the stroke its border
    /// colour and width, each a mask quad from the atlas (ADR 0040).
    Path {
        ops: &'a [crate::path::PathOp],
        rule: crate::path::FillRule,
        stroke_w: f32,
        /// What cuts the stroke into marks, as a line's (backlog V2).
        dash: Option<crate::line::Cut>,
        hash: u64,
        /// The turn in radians of a path that declared one (ADR 0041).
        angle: Option<f32>,
        animating: bool,
    },
}

/// One box's paint: its shadow, its fill and border, its content, faded by
/// the group opacity — written once for the live node and the ghost, which
/// differ in what they *record* (hit regions, scroll regions, a text's
/// place) and not in what they draw. The two were the same hundred and
/// twenty lines until F41 had to be fixed in both.
struct Painter<'a> {
    display: &'a mut DisplayList,
    text: &'a mut TextSystem,
    edit: &'a mut EditStore,
    cells: &'a mut crate::cells::CellStore,
    atlas: &'a mut GlyphAtlas,
    session: &'a Session,
    /// The masks drawn from textures of their own (ADR 0040).
    path_tex: &'a mut crate::path::PathTextures,
    frame_no: u64,
}

impl Painter<'_> {
    /// Inlined into its two callers: a call per node with the borrows
    /// packed into a struct measured +2.5% on `frame_10k_rects`.
    /// What a leaf draws, and a shadow, are calls (`paint_leaf`,
    /// `shadow_quad`): inlined as well, they made every box pay for them.
    #[inline(always)]
    fn paint_box(
        &mut self,
        rect: Rect,
        style: &crate::spec::VisualStyle,
        paint: &Paint,
        leaf: Leaf<'_>,
    ) {
        let Paint {
            clip,
            clip_id,
            scale,
            opacity,
        } = *paint;
        let clip_px = clip.scaled(scale);
        let first_quad = self.display.quads.len();
        if style.shadow.is_visible() {
            self.display
                .quads
                .push(shadow_quad(style, rect, clip_id, scale));
        }
        // A stroke's `bg` is its colour, not a box to fill (ADR 0010,
        // decision 7), and a polygon's is its fill (ADR 0025, decision 6)
        // — for the ghost of one as much as for the live one.
        let is_line = matches!(
            leaf,
            Leaf::Line { .. } | Leaf::Polygon(_) | Leaf::Path { .. }
        );
        if !is_line
            && (style.bg.is_visible() || (style.border_w > 0.0 && style.border_color.is_visible()))
        {
            // Where layout put it, or on whole pixels when it asked
            // (`pixelSnap`), from the same numbers a text's backgrounds are.
            let px = rect.scaled(scale);
            self.display.quads.push(Quad {
                rect: if style.pixel_snap { px.on_pixels() } else { px },
                color: style.bg,
                border_color: style.border_color,
                radius: style.radius.map(|r| r * scale),
                border_w: style.border_w * scale,
                blur: 0.0,
                kind: QuadKind::Solid,
                clip: clip_id,
                uv: [0; 4],
            });
        }
        if !matches!(leaf, Leaf::Container) {
            // A picture or a fragment fills its box, so a border painted
            // under it with the background is covered: it moves to a ring
            // over the content, as it does over a gradient (backlog RG152).
            let covers = matches!(leaf, Leaf::Image(..) | Leaf::Fragment(..));
            let solid = self.display.quads.len().checked_sub(1);
            self.paint_leaf(rect, style, paint, clip_px, leaf);
            if covers && style.border_w > 0.0 && style.border_color.is_visible() {
                ring_over_content(&mut self.display.quads, solid);
            }
        }
        if opacity < 1.0 {
            fade(&mut self.display.quads[first_quad..], opacity);
        }
    }

    /// A box's `gradient` (ADR 0042): one `Image` quad over the box's
    /// rect from the gradient's slot in the atlas, put where it paints
    /// over the background and under everything else the box drew — its
    /// content, and its border, which moves to a ring of its own on top
    /// so the gradient does not cover the inside of it. `first_quad` is
    /// where the box's quads start. A gradient no page can hold draws
    /// nothing.
    #[cold]
    #[inline(never)]
    fn paint_gradient(
        &mut self,
        g: &crate::gradient::Gradient,
        rect: Rect,
        style: &crate::spec::VisualStyle,
        paint: &Paint,
        first_quad: usize,
    ) {
        if !g.is_drawable() {
            return;
        }
        let (w, h) = g.slot_size();
        let Some(slot) = self
            .atlas
            .get_or_insert_gradient(g.key(), w, h, || g.rasterize())
        else {
            return;
        };
        let quads = &mut self.display.quads;
        let px = rect.scaled(paint.scale);
        let image = Quad {
            rect: if style.pixel_snap { px.on_pixels() } else { px },
            // White is untinted; the group opacity rides its alpha.
            color: Color {
                a: paint.opacity.min(1.0),
                ..Color::WHITE
            },
            border_color: Color::TRANSPARENT,
            radius: style.radius.map(|r| r * paint.scale),
            border_w: 0.0,
            blur: 0.0,
            kind: QuadKind::Image,
            clip: paint.clip_id,
            // The raster inside its gutter (`Gradient::rasterize`).
            uv: [slot.x + 1, slot.y + 1, slot.w - 2, slot.h - 2],
        };
        // Where `paint_box` put the box's own solid, when it painted
        // one: after the shadow, before the content.
        let at = first_quad + usize::from(style.shadow.is_visible());
        let bordered = style.border_w > 0.0 && style.border_color.is_visible();
        if !style.bg.is_visible() && !bordered {
            // No background and no border: the gradient is the box.
            quads.insert(at, image);
            return;
        }
        // The border as a ring of its own, above the gradient; what is
        // left under it is the background alone. A picture's or a
        // fragment's border is a ring over the content already
        // (`ring_over_content`), and its solid has none left to give.
        let ring = (bordered && quads[at].border_w > 0.0).then(|| Quad {
            color: Color::TRANSPARENT,
            ..quads[at]
        });
        if style.bg.is_visible() {
            quads[at].border_w = 0.0;
            quads[at].border_color = Color::TRANSPARENT;
            quads.insert(at + 1, image);
        } else {
            quads[at] = image;
        }
        let over = at + 1 + usize::from(style.bg.is_visible());
        if let Some(ring) = ring {
            quads.insert(over, ring);
        }
    }

    /// What a leaf draws inside its box: text, cells, an editor, an
    /// image, a fragment, a polygon's fill or a stroke. Out of line, so the
    /// kinds a plain box never takes do not weigh on every node's
    /// `emit_node` — its saved registers and its stack frame.
    #[inline(never)]
    fn paint_leaf(
        &mut self,
        rect: Rect,
        style: &crate::spec::VisualStyle,
        paint: &Paint,
        clip_px: crate::display::Clip,
        leaf: Leaf<'_>,
    ) {
        let Paint { clip_id, scale, .. } = *paint;
        match leaf {
            Leaf::Container => {}
            Leaf::Text { tid, sel } => {
                let sess = &mut *self.session.state();
                self.text.emit(
                    tid,
                    Vec2::new(rect.x, rect.y),
                    Size::new(rect.w, rect.h),
                    clip_px,
                    clip_id,
                    &mut self.display.clips,
                    &sess.resources,
                    &mut sess.fonts,
                    self.atlas,
                    &mut self.display.quads,
                    sel,
                );
            }
            Leaf::Cells { cid, at, sel, tint } => {
                let sess = &mut *self.session.state();
                self.cells.emit(
                    cid,
                    at,
                    clip_px,
                    clip_id,
                    &sess.resources,
                    &mut sess.fonts,
                    self.text.raster_mut(),
                    self.atlas,
                    &mut self.display.quads,
                    sel.map(|s| (s, tint)),
                );
            }
            Leaf::Edit { key, focused, pad } => {
                let origin = Vec2::new(
                    crate::geom::snap_px((rect.x + pad.l) * scale),
                    crate::geom::snap_px((rect.y + pad.t) * scale),
                );
                // A field bounds its own text horizontally — it is what
                // makes scrolling one legible rather than a line running
                // out over its neighbours (F41). Horizontally only: the
                // ancestors own the vertical clip, and a descender or a
                // caret is not what a field is trying to cut off.
                // Narrowing the clip makes a new one, so it needs an entry
                // of its own; an editor that folds to its width — a
                // document, or a field with `wrap` (F44) — keeps the node's.
                let (edit_clip, edit_clip_id) = if self.edit.folds(key) {
                    (clip_px, clip_id)
                } else {
                    let narrowed = clip_px.intersect(
                        Rect::new(
                            origin.x,
                            clip_px.rect.y,
                            (rect.w - pad.x()).max(0.0) * scale,
                            clip_px.rect.h,
                        ),
                        crate::display::SQUARE,
                    );
                    (narrowed, self.display.intern_clip(narrowed))
                };
                let sess = &mut *self.session.state();
                self.edit.emit(
                    key,
                    origin,
                    focused,
                    edit_clip,
                    edit_clip_id,
                    &mut sess.fonts,
                    self.text,
                    self.atlas,
                    &mut self.display.quads,
                );
            }
            Leaf::Image(id, opts) => {
                let sess = self.session.state();
                if let Some(entry) = sess.resources.image(id) {
                    // Atlas-backed unless the entry says otherwise — or
                    // unless the atlas cannot take it after all, which
                    // used to draw nothing (ADR 0025, decision 2).
                    let slot =
                        match entry.backing {
                            crate::resources::ImageBacking::Atlas => self
                                .atlas
                                .get_or_insert_image(id, entry.width, entry.height, &entry.rgba),
                            crate::resources::ImageBacking::Texture => None,
                        };
                    let (kind, uv) = match slot {
                        Some(slot) => (QuadKind::Image, [slot.x, slot.y, slot.w, slot.h]),
                        None => (
                            QuadKind::Texture,
                            [self.display.textures.len() as u32, 0, 0, 0],
                        ),
                    };
                    let mut uv = uv;
                    let (rect, tex_uv) = fit_image(
                        opts.fit,
                        rect,
                        Size::new(entry.width as f32, entry.height as f32),
                        [0, 0, entry.width, entry.height],
                    );
                    if kind == QuadKind::Image {
                        // The crop, if any, applied inside the atlas slot.
                        uv = [uv[0] + tex_uv[0], uv[1] + tex_uv[1], tex_uv[2], tex_uv[3]];
                    } else {
                        self.display
                            .textures
                            .push(crate::display::TextureDraw { id, uv: tex_uv });
                        self.display
                            .texture_pixels
                            .push(crate::display::TexturePixels {
                                width: entry.width,
                                height: entry.height,
                                rev: entry.rev,
                                rgba: entry.rgba.clone(),
                            });
                    }
                    self.display.quads.push(Quad {
                        rect: rect.scaled(scale),
                        // White = untinted; radius rounds like a solid.
                        color: Color::WHITE,
                        border_color: Color::TRANSPARENT,
                        radius: style.radius.map(|r| r * scale),
                        // The sampling flag rides the slot an image never
                        // had a border in (decision 4).
                        border_w: match opts.sampling {
                            crate::resources::Sampling::Linear => 0.0,
                            crate::resources::Sampling::Nearest => 1.0,
                        },
                        blur: 0.0,
                        kind,
                        clip: clip_id,
                        uv,
                    });
                }
            }
            Leaf::Fragment(draw) => {
                // On whole pixels when the node asked (`pixelSnap`), as its
                // background is, so a stack of fragments meets seamlessly.
                let px = rect.scaled(scale);
                push_fragment(
                    self.display,
                    self.atlas,
                    &self.session.state().resources,
                    draw,
                    if style.pixel_snap { px.on_pixels() } else { px },
                    style.radius.map(|r| r * scale),
                    clip_id,
                    Color::WHITE,
                );
            }
            Leaf::Polygon(draw) => {
                if style.bg.is_visible() {
                    push_fragment(
                        self.display,
                        self.atlas,
                        &self.session.state().resources,
                        draw,
                        rect.scaled(scale),
                        crate::display::SQUARE,
                        clip_id,
                        style.bg,
                    );
                }
            }
            Leaf::Line {
                points,
                width,
                dash,
            } => {
                let origin = Vec2::new(rect.x, rect.y);
                let quads = &mut self.display.quads;
                // A pattern too fine to be one draws solid.
                let cut = dash.is_some_and(|d| {
                    push_marks(quads, origin, points, width, d, style.bg, clip_id, scale)
                });
                if !cut {
                    push_segments(quads, origin, points, width, style.bg, clip_id, scale);
                }
            }
            Leaf::Path {
                ops,
                rule,
                stroke_w,
                dash,
                hash,
                angle,
                animating,
            } => {
                let px = rect.scaled(scale);
                let mask = match angle {
                    // The mask covers the node's box at physical scale, a
                    // pixel over for the ramp, and is drawn on whole
                    // pixels with the box's fractional offset baked in at
                    // the nearest quarter — the bins a glyph is keyed on
                    // — so the quad never resamples it.
                    None => {
                        let bin_of = |f: f32| -> (f32, u8) {
                            let b = (f * 4.0).round() as u8;
                            if b >= 4 { (1.0, 0) } else { (0.0, b) }
                        };
                        let (fx, fy) = (px.x.floor(), px.y.floor());
                        let (cx, bx) = bin_of(px.x - fx);
                        let (cy, by) = bin_of(px.y - fy);
                        MaskAt {
                            at: Rect::new(
                                fx + cx,
                                fy + cy,
                                (px.w.ceil() + 1.0).max(1.0),
                                (px.h.ceil() + 1.0).max(1.0),
                            ),
                            bin: (bx, by),
                            off: Vec2::new(f32::from(bx) * 0.25, f32::from(by) * 0.25),
                            angle: 0.0,
                        }
                    }
                    // A turning path's box is the square about its pivot
                    // (ADR 0041): the mask is that square on an even
                    // number of pixels with the pivot at its centre, the
                    // centre on a whole pixel, so the quad turns about
                    // its own middle and, at no angle, is texel for texel.
                    Some(angle) => {
                        let side = 2.0 * (px.w * 0.5).ceil() + 2.0;
                        let (cx, cy) = ((px.x + px.w * 0.5).round(), (px.y + px.h * 0.5).round());
                        MaskAt {
                            at: Rect::new(cx - side * 0.5, cy - side * 0.5, side, side),
                            bin: crate::path::TURNED_BIN,
                            off: Vec2::new((side - px.w) * 0.5, (side - px.h) * 0.5),
                            angle,
                        }
                    }
                };
                if style.bg.is_visible() {
                    self.paint_mask(
                        ops,
                        hash,
                        scale,
                        mask,
                        crate::path::MaskPaint::Fill(rule),
                        style.bg,
                        clip_id,
                        animating,
                    );
                }
                if stroke_w > 0.0 && style.border_color.is_visible() {
                    self.paint_mask(
                        ops,
                        hash,
                        scale,
                        mask,
                        match dash {
                            Some(cut) => crate::path::MaskPaint::Dashed(
                                stroke_w * scale,
                                crate::line::Cut {
                                    lens: cut.lens.map(|l| l * scale),
                                    offset: cut.offset * scale,
                                },
                            ),
                            None => crate::path::MaskPaint::Stroke(stroke_w * scale),
                        },
                        style.border_color,
                        clip_id,
                        animating,
                    );
                }
            }
        }
    }

    /// One mask quad of a path: from the atlas when the mask fits it and
    /// the path is still, from a texture of its own otherwise (ADR 0040,
    /// decisions 6–8), turned by the quad when the path turns (ADR 0041).
    #[allow(clippy::too_many_arguments)]
    fn paint_mask(
        &mut self,
        ops: &[crate::path::PathOp],
        hash: u64,
        scale: f32,
        mask: MaskAt,
        paint: crate::path::MaskPaint,
        color: Color,
        clip_id: ClipId,
        animating: bool,
    ) {
        let MaskAt {
            at,
            bin,
            off,
            angle,
        } = mask;
        let (w, h) = (at.w as u32, at.h as u32);
        let key = crate::path::mask_key(hash, scale, bin, paint);
        let texels = u64::from(w) * u64::from(h);
        let slot = if animating || texels >= crate::path::MAX_ATLAS_MASK_TEXELS {
            None
        } else {
            self.atlas.get_or_insert_path(key, w, h, || {
                crate::path::rasterize_at(ops, scale, off, w, h, paint)
            })
        };
        let (kind, uv) = match slot {
            Some(slot) => (QuadKind::GlyphMask, [slot.x, slot.y, slot.w, slot.h]),
            None => {
                let tex =
                    self.path_tex
                        .get_or_make(key, w, h, self.frame_no, self.session.id(), || {
                            crate::path::rasterize_at(ops, scale, off, w, h, paint)
                        });
                let index = self.display.textures.len() as u32;
                self.display.textures.push(crate::display::TextureDraw {
                    id: tex.id,
                    uv: [0, 0, w, h],
                });
                self.display
                    .texture_pixels
                    .push(crate::display::TexturePixels {
                        width: w,
                        height: h,
                        rev: 0,
                        rgba: tex.rgba.clone(),
                    });
                (QuadKind::Texture, [index, 0, 0, 0])
            }
        };
        self.display.quads.push(Quad {
            rect: at,
            color,
            border_color: Color::TRANSPARENT,
            radius: crate::display::SQUARE,
            border_w: 0.0,
            // A mask has no blur; the slot carries its turn, in radians
            // about the quad's centre, 0 for none (ADR 0041, decision 4).
            blur: angle,
            kind,
            clip: clip_id,
            uv,
        });
    }
}

/// Where one path's masks go: the quad in physical px, on whole pixels;
/// the bin its masks are keyed under; where the node's box begins inside
/// the mask; and the quad's turn in radians.
#[derive(Clone, Copy)]
struct MaskAt {
    at: Rect,
    bin: (u8, u8),
    off: Vec2,
    angle: f32,
}

#[derive(Clone, Copy)]
struct Paint {
    clip: Clip,
    /// `clip`, scaled and interned: what the node's quads name.
    clip_id: ClipId,
    scale: f32,
    /// Multiplied into the alpha of every quad the node emits.
    opacity: f32,
}

/// As much of the previous frame's paint order as a departure needs to
/// keep its place (see `depart::Place`): the layer each node painted in,
/// and for the in-flow layer the next node at or after each index that
/// this frame still declares. Built once per frame that has a departure,
/// from the previous tree and the stack as that frame left it.
struct PaintOrder {
    /// The previous tree's float roots, by node: `NIL` in flow.
    float_root: Vec<u32>,
    /// By previous-tree index: the next live in-flow node at or after it;
    /// one past the end reads `NIL`.
    next_live: Vec<u32>,
    /// This frame's keys.
    live: FxHashSet<Key>,
    /// This frame's float roots, by key.
    roots: FxHashSet<Key>,
}

impl PaintOrder {
    fn of(prev: &Tree, tree: &Tree) -> Self {
        let n = prev.len();
        let live: FxHashSet<Key> = tree.keys.iter().copied().collect();
        let roots: FxHashSet<Key> = (0..tree.len())
            .filter(|&i| tree.opens_layer(i))
            .map(|i| tree.keys[i])
            .collect();
        let mut float_root = vec![NIL; n];
        for i in 0..n {
            let parent = prev.parent[i];
            // The live pass's rule (`Tree::opens_layer`): a stroke in its
            // parent's box painted in the parent's layer, so a departing
            // one keeps its place there.
            float_root[i] = if prev.opens_layer(i) {
                i as u32
            } else if parent != NIL {
                float_root[parent as usize]
            } else {
                NIL
            };
        }
        let mut next_live = vec![NIL; n + 1];
        for j in (0..n).rev() {
            next_live[j] = next_live[j + 1];
            if float_root[j] == NIL && live.contains(&prev.keys[j]) {
                next_live[j] = j as u32;
            }
        }
        Self {
            float_root,
            next_live,
            live,
            roots,
        }
    }

    /// The place the subtree rooted at `root` of the previous frame painted
    /// in: its layer, and what was painted right after it there that is
    /// still here. `stack` is the previous frame's float stack, bottom to
    /// top — where a departing float finds the layer that was over it.
    fn place(&self, prev: &Tree, root: usize, stack: &[(Key, u32)]) -> Place {
        let end = prev.subtree_end(root);
        let layer = self.float_root[root];
        if layer == NIL {
            let after = self.next_live[end];
            return Place::InFlow {
                before: (after != NIL).then(|| prev.keys[after as usize]),
            };
        }
        if layer as usize != root {
            // Inside a float: the next live node of the same layer, found
            // by a scan bounded by that layer's subtree — a departure is
            // rare and a float is small.
            let layer_end = prev.subtree_end(layer as usize);
            let before = (end..layer_end)
                .find(|&j| self.float_root[j] == layer && self.live.contains(&prev.keys[j]))
                .map(|j| prev.keys[j]);
            return Place::InLayer {
                layer: prev.keys[layer as usize],
                before,
            };
        }
        // A float root: under the first layer above it in the stack that
        // is still a float this frame.
        let key = prev.keys[root];
        let at = stack.iter().position(|&(k, _)| k == key);
        let before = at.and_then(|at| {
            stack[at + 1..]
                .iter()
                .map(|&(k, _)| k)
                .find(|k| self.roots.contains(k))
        });
        Place::Layer { before }
    }
}

/// One [`QuadKind::Segment`] per straight piece of a stroke: `points` are
/// relative to `origin` (the node's box, logical px) and `width` is
/// logical; everything on the quad is physical. The rect is the piece's
/// bounding box padded by half the width plus two logical px, so the
/// backend's edge ramp is never cut by the quad's own edge, and the
/// endpoints ride in `uv` (see [`Quad::segment_ends`]).
///
/// Kept out of line on purpose: inlined into `emit_node`,
/// whose size moves with every prop a hit region grows, the loop's carried
/// point lost its register to the stack once the drop-zone commit tipped
/// the allocator — a store and a reload on every segment, +10% on
/// `frame_1k_curves`. On its own the loop keeps every value in a register.
#[inline(never)]
fn push_segments(
    quads: &mut Vec<Quad>,
    origin: Vec2,
    points: &[Vec2],
    width: f32,
    color: Color,
    clip_id: ClipId,
    scale: f32,
) {
    let pad = crate::line::pad(width) * scale;
    let w = width.max(0.0) * scale;
    for pair in points.windows(2) {
        let a = Vec2::new(
            (origin.x + pair[0].x) * scale,
            (origin.y + pair[0].y) * scale,
        );
        let b = Vec2::new(
            (origin.x + pair[1].x) * scale,
            (origin.y + pair[1].y) * scale,
        );
        let (x0, x1) = (a.x.min(b.x) - pad, a.x.max(b.x) + pad);
        let (y0, y1) = (a.y.min(b.y) - pad, a.y.max(b.y) + pad);
        quads.push(Quad {
            rect: Rect::new(x0, y0, x1 - x0, y1 - y0),
            color,
            border_color: Color::TRANSPARENT,
            radius: crate::display::SQUARE,
            border_w: w,
            blur: 0.0,
            kind: QuadKind::Segment,
            clip: clip_id,
            uv: Quad::segment_uv([a.x, a.y, b.x, b.y]),
        });
    }
}

/// A dashed stroke's quads: one [`QuadKind::Segment`] per mark per
/// piece it lies on, as [`push_segments`] makes one per piece — a mark is
/// a short stroke, round caps and all, so a backend that draws a line
/// draws a dashed one (backlog V2). False, with nothing pushed, for a
/// pattern the caller draws solid: a mark and its gap under a physical
/// pixel together, or
/// more marks than [`crate::line::MAX_MARKS`].
///
/// Its own function, and never inlined, for the reason `push_segments`
/// is: nothing of the rare path belongs in `emit_node`.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn push_marks(
    quads: &mut Vec<Quad>,
    origin: Vec2,
    points: &[Vec2],
    width: f32,
    cut: crate::line::Cut,
    color: Color,
    clip_id: ClipId,
    scale: f32,
) -> bool {
    let pad = crate::line::pad(width) * scale;
    let w = width.max(0.0) * scale;
    cut.marks(points, 1.0 / scale, |from, to| {
        let a = Vec2::new((origin.x + from.x) * scale, (origin.y + from.y) * scale);
        let b = Vec2::new((origin.x + to.x) * scale, (origin.y + to.y) * scale);
        let (x0, x1) = (a.x.min(b.x) - pad, a.x.max(b.x) + pad);
        let (y0, y1) = (a.y.min(b.y) - pad, a.y.max(b.y) + pad);
        quads.push(Quad {
            rect: Rect::new(x0, y0, x1 - x0, y1 - y0),
            color,
            border_color: Color::TRANSPARENT,
            radius: crate::display::SQUARE,
            border_w: w,
            blur: 0.0,
            kind: QuadKind::Segment,
            clip: clip_id,
            uv: Quad::segment_uv([a.x, a.y, b.x, b.y]),
        });
    })
}

/// The drop shadow behind one node, in physical pixels. The quad is the
/// shadow's own shape — the node's rect moved by `dx`/`dy` and grown by
/// `spread` — inflated by `blur` on every side, because that is how far
/// the blurred edge reaches; the backend insets by `blur` again to find
/// the shape. Radii grow with the spread so a rounded box keeps its
/// silhouette instead of sprouting corners. Never inlined: in
/// `emit_node` its arithmetic took two more saved float registers for
/// every node, shadow or not.
#[inline(never)]
fn shadow_quad(style: &crate::spec::VisualStyle, rect: Rect, clip_id: ClipId, scale: f32) -> Quad {
    let sh = style.shadow;
    let blur = sh.blur.max(0.0);
    let shape = Rect::new(
        rect.x + sh.dx - sh.spread,
        rect.y + sh.dy - sh.spread,
        (rect.w + 2.0 * sh.spread).max(0.0),
        (rect.h + 2.0 * sh.spread).max(0.0),
    );
    let rect = if style.pixel_snap {
        // Snapped with its box, so it stays under it; the blur around it.
        let s = shape.scaled(scale).on_pixels();
        let b = blur * scale;
        Rect::new(s.x - b, s.y - b, s.w + 2.0 * b, s.h + 2.0 * b)
    } else {
        Rect::new(
            (shape.x - blur) * scale,
            (shape.y - blur) * scale,
            (shape.w + 2.0 * blur) * scale,
            (shape.h + 2.0 * blur) * scale,
        )
    };
    Quad {
        rect,
        color: sh.color,
        border_color: Color::TRANSPARENT,
        radius: style.radius.map(|r| (r + sh.spread).max(0.0) * scale),
        border_w: 0.0,
        blur: blur * scale,
        kind: QuadKind::Shadow,
        clip: clip_id,
        uv: [0; 4],
    }
}

/// A node's `backdrop_blur` (backlog F129): one [`QuadKind::Backdrop`]
/// over the box, rounded and clipped as its background is, `blur` the
/// radius in physical px and the group opacity in `color.a` — how much of
/// the blurred picture replaces the sharp one. Pushed before the node's
/// own quads, so it is not in the run their fade multiplies; it carries
/// the opacity itself.
#[cold]
#[inline(never)]
fn backdrop_quad(
    quads: &mut Vec<Quad>,
    rect: Rect,
    style: &crate::spec::VisualStyle,
    paint: &Paint,
    radius: f32,
) {
    let px = rect.scaled(paint.scale);
    if px.w <= 0.0 || px.h <= 0.0 || paint.opacity <= 0.0 {
        return;
    }
    quads.push(Quad {
        rect: if style.pixel_snap { px.on_pixels() } else { px },
        color: Color {
            r: 0.0,
            g: 0.0,
            b: 0.0,
            a: paint.opacity.min(1.0),
        },
        border_color: Color::TRANSPARENT,
        radius: style.radius.map(|r| r * paint.scale),
        border_w: 0.0,
        blur: radius * paint.scale,
        kind: QuadKind::Backdrop,
        clip: paint.clip_id,
        uv: [0; 4],
    });
}

/// Multiplies a group opacity into a run of quads. Alpha only: every quad
/// kind reads `color.a` as its coverage, so one multiply fades a
/// background, a border, a glyph and an image alike.
fn fade(quads: &mut [Quad], opacity: f32) {
    for q in quads {
        q.color.a *= opacity;
        q.border_color.a *= opacity;
    }
}

/// The thumb of a scrollbar along `axis`, inset from the far edge of the
/// scroller's `rect`, `w` thick, and its length along the track: the
/// track's share of the content that is visible, never shorter than
/// `SCROLLBAR_MIN`, placed by how far the content has scrolled. One
/// geometry for both bars — the Y bar and the X bar were the same thirty
/// lines with the axes swapped.
fn thumb_along(
    axis: ScrollAxis,
    rect: Rect,
    track: Rect,
    max: f32,
    offset: f32,
    w: f32,
) -> (Rect, f32) {
    let t = (offset / max).clamp(0.0, 1.0);
    match axis {
        ScrollAxis::Y => {
            let bar = (track.h * rect.h / (rect.h + max)).max(SCROLLBAR_MIN);
            let thumb = Rect::new(
                rect.x + rect.w - w - SCROLLBAR_INSET,
                track.y + t * (track.h - bar),
                w,
                bar,
            );
            (thumb, bar)
        }
        ScrollAxis::X => {
            let bar = (track.w * rect.w / (rect.w + max)).max(SCROLLBAR_MIN);
            let thumb = Rect::new(
                track.x + t * (track.w - bar),
                rect.y + rect.h - w - SCROLLBAR_INSET,
                bar,
                w,
            );
            (thumb, bar)
        }
    }
}

/// One in-flow child of a table as its rules read it: its box, and for a
/// row (`layout::is_table_row`) its in-flow cells' boxes.
struct RuledChild {
    rect: Rect,
    cells: Option<Vec<Rect>>,
}

/// The rules of a table at `rect` over its in-flow `children`, `rule_w` thick
/// (1 when not positive):
///
/// - across, one down the middle of each gap between two in-flow
///   children, the content box wide;
/// - down, one down the middle of each gap between the columns of the
///   row with the most cells, over each run of consecutive rows — from
///   the run's first row's top to its last row's bottom.
///
/// A child that is no row — a heading text beside the rows, a `column`
/// section wrapping a heading over a row — is laid out across the
/// table and has no cells, and is ruled as a row spanning every column,
/// the way a `colspan` cell of a ruled HTML table is: a rule above and
/// below it as between rows, and the column rules stop at its edges
/// instead of crossing it. A table with no row has no grid to rule.
fn rule_lines(
    rect: Rect,
    pad: crate::geom::Edges,
    rule_w: f32,
    children: &[RuledChild],
) -> Vec<Rect> {
    let w = if rule_w > 0.0 { rule_w } else { 1.0 };
    let Some(widest) = children
        .iter()
        .filter_map(|c| c.cells.as_ref())
        .max_by_key(|cells| cells.len())
    else {
        return Vec::new();
    };
    let mut lines: Vec<Rect> = Vec::new();
    for pair in children.windows(2) {
        let (a, b) = (pair[0].rect, pair[1].rect);
        let y = (a.y + a.h + b.y) / 2.0;
        let x = rect.x + pad.l;
        lines.push(Rect::new(x, y - w / 2.0, rect.w - pad.l - pad.r, w));
    }
    let mut run = 0usize;
    while run < children.len() {
        if children[run].cells.is_none() {
            run += 1;
            continue;
        }
        let mut end = run;
        while end + 1 < children.len() && children[end + 1].cells.is_some() {
            end += 1;
        }
        let (top, last) = (children[run].rect.y, children[end].rect);
        let bottom = last.y + last.h;
        for pair in widest.windows(2) {
            let x = (pair[0].x + pair[0].w + pair[1].x) / 2.0;
            lines.push(Rect::new(x - w / 2.0, top, w, bottom - top));
        }
        run = end + 1;
    }
    lines
}

/// Pushes a table's `lines` in `color`, faded by `paint`'s opacity, under
/// `clip_id`. On whole pixels, so a 1 px rule is one crisp pixel line at
/// any scale.
fn push_rules(
    display: &mut DisplayList,
    lines: &[Rect],
    color: Color,
    paint: &Paint,
    clip_id: ClipId,
) {
    let color = Color {
        a: color.a * paint.opacity,
        ..color
    };
    for line in lines {
        display.quads.push(Quad {
            rect: line.scaled(paint.scale).on_pixels(),
            color,
            border_color: Color::TRANSPARENT,
            radius: [0.0; 4],
            border_w: 0.0,
            blur: 0.0,
            kind: QuadKind::Solid,
            clip: clip_id,
            uv: [0; 4],
        });
    }
}

fn scrollbar_quad(bar: Rect, scale: f32, clip_id: ClipId, color: Color) -> Quad {
    Quad {
        rect: bar.scaled(scale),
        color,
        border_color: Color::TRANSPARENT,
        radius: [bar.w.min(bar.h) / 2.0 * scale; 4],
        border_w: 0.0,
        blur: 0.0,
        kind: QuadKind::Solid,
        clip: clip_id,
        uv: [0; 4],
    }
}

/// One `fragment` node's quad, live or ghost.
///
/// The handle is resolved first: a removed or foreign one draws nothing,
/// which is the documented fallback for every resource kind, and the
/// lookup is what records the `foreign-resource` warning. The quad carries
/// the node's own rect, radii and clip — a fragment rounds and clips like
/// a solid — and an opaque white `color`, whose alpha the group-opacity
/// pass then multiplies into; the shader reads that alpha and nothing else
/// of the colour, because a fragment returns its own.
#[allow(clippy::too_many_arguments)]
/// Resolves the `fit` row: the rect the pixels paint into (logical px)
/// and the texel rect of the image they come from. `fill` stretches the
/// whole image to the box; `contain` shrinks the painted rect to the
/// image's aspect, centred; `cover` keeps the box and crops the texels,
/// centred. A zero-sized image or box falls back to
/// `fill`, which paints nothing visible either way.
pub(crate) fn fit_image(
    fit: crate::resources::ImageFit,
    rect: Rect,
    image: Size,
    texels: [u32; 4],
) -> (Rect, [u32; 4]) {
    use crate::resources::ImageFit;
    if image.w <= 0.0 || image.h <= 0.0 || rect.w <= 0.0 || rect.h <= 0.0 {
        return (rect, texels);
    }
    let box_aspect = rect.w / rect.h;
    let image_aspect = image.w / image.h;
    match fit {
        ImageFit::Fill => (rect, texels),
        ImageFit::Contain => {
            let (w, h) = if image_aspect > box_aspect {
                (rect.w, rect.w / image_aspect)
            } else {
                (rect.h * image_aspect, rect.h)
            };
            (
                Rect::new(
                    rect.x + (rect.w - w) * 0.5,
                    rect.y + (rect.h - h) * 0.5,
                    w,
                    h,
                ),
                texels,
            )
        }
        ImageFit::Cover => {
            // Whole texels: a crop is a rect on the texture, and a
            // half-texel edge would sample the neighbour.
            let (w, h) = if image_aspect > box_aspect {
                ((image.h * box_aspect).round().max(1.0), image.h)
            } else {
                (image.w, (image.w / box_aspect).round().max(1.0))
            };
            let x = ((image.w - w) * 0.5).floor();
            let y = ((image.h - h) * 0.5).floor();
            (
                rect,
                [
                    texels[0] + x as u32,
                    texels[1] + y as u32,
                    w as u32,
                    h as u32,
                ],
            )
        }
    }
}

/// One fragment quad and its side entry: the draw, the source a backend
/// compiles, and the colour the function reads as `in.color` — white for
/// a `fragment`, the fill for a `polygon`.
///
/// A draw naming an `image` resolves it here, where the window's atlas
/// is: an atlas-backed image goes into the atlas as an `image` node's
/// would and the draw carries its slot; a texture-backed one takes an
/// entry of the texture side list — the same entry an `image` node of it
/// would — and the draw carries the index, so the backend binds that
/// texture for this one quad as it does for a texture quad. An image
/// handle that is not live draws nothing, the fallback every resource
/// kind has, and the lookup is what records a foreign one.
#[allow(clippy::too_many_arguments)]
fn push_fragment(
    display: &mut DisplayList,
    atlas: &mut GlyphAtlas,
    resources: &crate::resources::Resources,
    draw: crate::fragment::Draw,
    rect: Rect,
    radius: [f32; 4],
    clip_id: ClipId,
    color: Color,
) {
    let Some(source) = resources.fragment(draw.id) else {
        return;
    };
    let image = match draw.image {
        None => crate::display::FragmentImage::None,
        Some(id) => {
            let Some(entry) = resources.image(id) else {
                return;
            };
            let slot = match entry.backing {
                crate::resources::ImageBacking::Atlas => {
                    atlas.get_or_insert_image(id, entry.width, entry.height, &entry.rgba)
                }
                crate::resources::ImageBacking::Texture => None,
            };
            match slot {
                Some(slot) => {
                    crate::display::FragmentImage::Atlas([slot.x, slot.y, slot.w, slot.h])
                }
                None => {
                    let index = display.textures.len() as u32;
                    let uv = [0, 0, entry.width, entry.height];
                    display
                        .textures
                        .push(crate::display::TextureDraw { id, uv });
                    display.texture_pixels.push(crate::display::TexturePixels {
                        width: entry.width,
                        height: entry.height,
                        rev: entry.rev,
                        rgba: entry.rgba.clone(),
                    });
                    crate::display::FragmentImage::Texture { index, uv }
                }
            }
        }
    };
    let index = display.fragments.len() as u32;
    display.fragments.push(crate::display::FragmentDraw {
        id: draw.id,
        params: draw.params,
        image,
    });
    display.fragment_sources.push(source.clone());
    display.quads.push(Quad {
        rect,
        // White on a `fragment` — the function returns its own colour and
        // reads this as `in.color` if it wants one — and the fill on a
        // `polygon`; `a` is the fill's alpha times the group opacity, which
        // the fade pass multiplies in after the node's quads are pushed.
        color,
        border_color: Color::TRANSPARENT,
        radius,
        border_w: 0.0,
        blur: 0.0,
        kind: QuadKind::Fragment,
        clip: clip_id,
        uv: [index, 0, 0, 0],
    });
}

/// The box's own solid, at `solid`, gives its border to a ring pushed
/// after what the box drew over it, and keeps the background (backlog
/// RG152). Out of `paint_box`: a bordered picture is rare.
#[cold]
#[inline(never)]
fn ring_over_content(quads: &mut Vec<Quad>, solid: Option<usize>) {
    let Some(at) =
        solid.filter(|&at| quads[at].kind == QuadKind::Solid && quads[at].border_w > 0.0)
    else {
        return;
    };
    let ring = Quad {
        color: Color::TRANSPARENT,
        ..quads[at]
    };
    quads[at].border_w = 0.0;
    quads[at].border_color = Color::TRANSPARENT;
    quads.push(ring);
}