day-toolkit-appkit 0.6.1

Declarative app development API using native UI toolkits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! day-toolkit-appkit: the macos-appkit backend (DESIGN.md §9). objc2, pure Rust, no shim.
//!
//! `Handle = Retained<NSView>`. Containers are flipped `NSView`s (top-left origin, so Day's
//! frames apply directly and survive diffing). One custom target class (`DayTarget`) forwards
//! target/action + text-delegate callbacks into the Day event sink, node-id keyed (§8.3).

#![allow(unused_unsafe)]
#![cfg(target_os = "macos")]

mod controls;

mod applications;
mod nav_progress;

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

use linkme::distributed_slice;
use objc2::Message as _;
use objc2::rc::Retained;
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::{
    AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
};
use objc2_app_kit::NSAccessibility as _;
use objc2_app_kit::NSAppearanceCustomization as _;
use objc2_app_kit::NSDraggingInfo as _;
use objc2_app_kit::NSSplitViewDelegate;
use objc2_app_kit::NSTextContent as _;
use objc2_app_kit::NSUserInterfaceItemIdentification as _;
use objc2_app_kit::{
    NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
    NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
};
use objc2_app_kit::{
    NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
    NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
    NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
    NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
    NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
    NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
    NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
    NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
    NSWindowDelegate, NSWindowStyleMask,
};
use objc2_app_kit::{
    NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
    NSApplicationWillTerminateNotification,
};
use objc2_app_kit::{
    NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
};
use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
use objc2_core_foundation::CGAffineTransform;
use objc2_foundation::{
    NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
    NSNumber, NSObject, NSPoint, NSRect, NSSize, NSString,
};
use objc2_quartz_core::{
    CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
    kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
    kCAMediaTimingFunctionLinear,
};

use day_spec::ffi_guard;
use day_spec::present;
use day_spec::props::*;
use day_spec::sidetable::SideTable;
use day_spec::{
    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
    InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
    Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
    WindowOptions, kinds, props_of,
};

pub type Handle = Retained<NSView>;

/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
pub use toolbar::image_for as toolbar_image;

// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
mod dock;
mod documents;
mod frame;
mod picker;
mod status_item;
mod textarea;
mod toolbar;
mod transfer;
mod window_chrome;
use objc2_app_kit::NSDraggingSource;

pub mod ext;
pub use ext::*;

// ---------------------------------------------------------------------------
// Event plumbing: node-id keyed sink, thread-local (single UI thread)
// ---------------------------------------------------------------------------

/// The day-core event sink (node-id keyed).
type Sink = Rc<dyn Fn(NodeId, Event)>;

day_core::tls_group! {
    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
    /// The style each button currently carries, keyed by its view pointer.
    ///
    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
        RefCell::new(HashMap::new());
    /// Original template images, retained across tint changes and swept on view release.
    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
    /// buttons whose `state` `read_native` reports as `checked`.
    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());

    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
    /// (replay inserted but nothing ever removed).
    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
    static APP_LABELED: SideTable<()> = SideTable::new();
    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
    /// was realized as a template, and whether a tint is on it now. Template rendering is a
    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
    /// on release.
    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
    /// layer geometry and re-syncs it from the view, so a transform written into the layer
    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
    static TRANSFORMS: SideTable<Transform> = SideTable::new();
    /// Each view's frame as Day laid it out, before any translation, so a translation change can
    /// move the view without waiting for the next layout.
    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
    static PAN_NODES: SideTable<NodeId> = SideTable::new();
    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
    static KEY_NODES: SideTable<NodeId> = SideTable::new();
    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
    /// press, reports both directions, hears the arrows). Empty for every container that
    /// never asked, whose behavior is exactly as before.
    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();

    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
    static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
        RefCell::new(HashMap::new());

    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
        RefCell::new(std::collections::HashSet::new());
    /// Each nav page's pane, recorded at realize because `insert` sees only handles
    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();

    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
    /// A [`SideTable`]: the release sweep drops it with the view.
    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();

    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
    static SPLIT_PANES: SideTable<bool> = SideTable::new();

    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();

    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());

    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
    /// Entries leave only through `release_image`, which day-core calls when the app drops its
    /// last `Bitmap` handle.
    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
    /// via `day_spec::sidetable`.
    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();

    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());

    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
    static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
        const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
    static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
        const { std::cell::RefCell::new(None) };

    /// Live modal sheets keyed by request id (for programmatic dismissal).
    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
        RefCell::new(HashMap::new());
    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
        RefCell::new(HashMap::new());

    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
    // lifetime.
    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
        const { std::cell::RefCell::new(None) };
    /// The primary window's content view, for call sites without backend access that must
    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
        const { std::cell::RefCell::new(None) };

}

/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
pub fn emit(id: NodeId, ev: Event) {
    let sink = SINK.with(|s| s.borrow().clone());
    if let Some(sink) = sink {
        sink(id, ev);
    }
}

fn ptr_of(v: &NSView) -> usize {
    (v as *const NSView).cast::<()>() as usize
}

/// An image view's rendering (`IMAGE_MODES`).
#[derive(Clone, Copy)]
struct ImageMode {
    template: bool,
    tinted: bool,
}

impl ImageMode {
    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
    /// template color.
    fn renders_template(self) -> bool {
        self.template || self.tinted
    }
}

/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
///
/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
/// asset at half its real width.
struct AppKitBitmap {
    image: Retained<objc2_app_kit::NSImage>,
    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
    info: day_spec::BitmapInfo,
}

/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
/// `fit`.
///
/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
/// one that carries transparency through a PNG round-trip intact.
fn scaled_rep(
    image: &objc2_app_kit::NSImage,
    pixels: Size,
    scale: f64,
) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
    use objc2::AllocAnyThread as _;
    let w = (pixels.width * scale).round().max(1.0);
    let h = (pixels.height * scale).round().max(1.0);
    let rep = unsafe {
        objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
            objc2_app_kit::NSBitmapImageRep::alloc(),
            std::ptr::null_mut(),
            w as isize,
            h as isize,
            8,
            4,
            true,
            false,
            objc2_app_kit::NSDeviceRGBColorSpace,
            0,
            0,
        )
    }?;
    let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
    NSGraphicsContext::saveGraphicsState_class();
    objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
    unsafe {
        image.drawInRect_fromRect_operation_fraction(
            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
            NSRect::ZERO,
            objc2_app_kit::NSCompositingOperation::SourceOver,
            1.0,
        );
    }
    NSGraphicsContext::restoreGraphicsState_class();
    Some(rep)
}

/// Re-encode a decoded bitmap (docs/images.md).
///
/// A free function rather than the duty's body so each refusal reads as an early return instead
/// of another copy of the same emit.
fn encode_bitmap(
    id: day_spec::BitmapId,
    spec: &day_spec::EncodeSpec,
) -> Result<Vec<u8>, day_spec::ImageError> {
    use day_spec::ImageFormat as F;
    use objc2_app_kit::NSBitmapImageFileType as T;
    let file_type = match spec.format {
        F::Png => T::PNG,
        F::Jpeg => T::JPEG,
        F::Tiff => T::TIFF,
        F::Bmp => T::BMP,
        F::Gif => T::GIF,
        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
        // that everything decodable is also encodable.
        _ => return Err(day_spec::ImageError::Encode),
    };
    let held = BITMAPS.with(|m| {
        m.borrow()
            .get(&id.0)
            .map(|b| (b.rep.clone(), b.image.clone(), b.info))
    });
    let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
    let rep = rep.ok_or(day_spec::ImageError::Encode)?;

    // `fit` scales the longest side down first. A box larger than the original is ignored:
    // upscaling on an export path inflates the bytes without adding any detail.
    let rep = match spec.fit {
        Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
            let scale = (fit.width / info.pixels.width)
                .min(fit.height / info.pixels.height)
                .min(1.0);
            if scale < 1.0 {
                scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
            } else {
                rep
            }
        }
        _ => rep,
    };

    let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
        // AppKit's own compression-factor property; a lossless writer ignores it.
        Some(q) => {
            let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
            let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
            let value: &objc2::runtime::AnyObject = &number;
            NSDictionary::from_slices::<NSString>(&[key], &[value])
        }
        None => NSDictionary::new(),
    };
    let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
        .ok_or(day_spec::ImageError::Encode)?;
    Ok(data.to_vec())
}

/// Replay a display list into the current graphics context. The one painter both the on-screen
/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
/// (docs/canvas.md "Exporting").
fn paint_ops(ops: &[DrawOp]) {
    for op in ops {
        draw_op(op);
    }
}

/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
/// a PDF page) and `scale` its units per canvas point.
///
/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
    use objc2_core_graphics::CGContext;
    CGContext::save_g_state(Some(cg));
    CGContext::translate_ctm(Some(cg), 0.0, height);
    CGContext::scale_ctm(Some(cg), scale, -scale);
    let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
    NSGraphicsContext::saveGraphicsState_class();
    NSGraphicsContext::setCurrentContext(Some(&ns));
    paint_ops(ops);
    NSGraphicsContext::restoreGraphicsState_class();
    CGContext::restore_g_state(Some(cg));
}

/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point.
///
/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
/// color, shows on the display through the same color matching the live canvas gets, and writes
/// that profile into a PNG.
fn render_bitmap_image(
    ops: &[DrawOp],
    size: Size,
    scale: f64,
) -> Result<AppKitBitmap, day_spec::ExportError> {
    use objc2::AllocAnyThread as _;
    use objc2_core_graphics::{
        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
    };
    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
    let (pw, ph) = day_spec::export_pixels(size, scale);
    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
    let cg = unsafe {
        CGBitmapContextCreate(
            std::ptr::null_mut(),
            pw as usize,
            ph as usize,
            8,
            0,
            Some(&space),
            CGImageAlphaInfo::PremultipliedLast.0,
        )
    }
    .ok_or_else(|| {
        day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
    })?;
    // A new bitmap context starts zeroed, which is the transparent background.
    paint_flipped(&cg, ph as f64, scale, ops);
    let cg_image = CGBitmapContextCreateImage(Some(&cg))
        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
    let rep = unsafe {
        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
            objc2_app_kit::NSBitmapImageRep::alloc(),
            &cg_image,
        )
    };
    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
    // sharp at `scale`× — the same shape as a staged @2x asset.
    let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
    unsafe { rep.setSize(points) };
    let image =
        unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
    unsafe { image.addRepresentation(&rep) };
    Ok(AppKitBitmap {
        image,
        rep: Some(rep),
        info: day_spec::BitmapInfo {
            pixels: Size::new(pw as f64, ph as f64),
            scale,
            format: None,
            has_alpha: true,
        },
    })
}

/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
fn render_pdf_bytes(
    pages: &[day_spec::PdfPage],
    info: &day_spec::PdfInfo,
) -> Result<Vec<u8>, day_spec::ExportError> {
    use objc2_core_foundation::{
        CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
    };
    use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
    let media =
        |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
    let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
    let data = CFMutableData::new(None, 0)
        .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
    let consumer = CGDataConsumer::with_cf_data(Some(&data))
        .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;

    let mut keys: Vec<&CFString> = Vec::new();
    let mut values: Vec<CFRetained<CFString>> = Vec::new();
    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
    let (title_key, author_key) = unsafe {
        (
            objc2_core_graphics::kCGPDFContextTitle,
            objc2_core_graphics::kCGPDFContextAuthor,
        )
    };
    for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
        if let Some(value) = value {
            keys.push(key);
            values.push(CFString::from_str(value));
        }
    }
    let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
    let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);

    let first_box = media(first.size);
    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
    // auxiliary-info string keys to strings, which is the type those keys take.
    let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
        .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
    for page in pages {
        let page_box = media(page.size);
        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
        unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
        paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
        CGContext::end_page(Some(&pdf));
    }
    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
    CGPDFContextClose(Some(&pdf));
    drop(pdf);
    drop(consumer);
    Ok(data.to_vec())
}

thread_local! {
    /// Each realized list item's current props, by its view: a patch updates one part and the
    /// item is re-dressed from the whole (docs/list.md "List items").
    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
        std::cell::RefCell::new(std::collections::HashMap::new());
}

/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
/// draws it: a 16pt template image, the title in the system font with a smaller secondary
/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
/// them.
///
/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
/// its frame edge to edge, the words take every spare point and give way first, and the
/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
/// width had two equally weak claims, the words' column and the gap before the trailing parts,
/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
/// beside the title in one row and at the trailing edge in the next, and stayed put.
fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
    use objc2_app_kit::{
        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
    };
    let label = |text: &str, size: f64, secondary: bool| {
        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
        unsafe {
            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
            if secondary {
                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
            }
            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
        }
        tf
    };
    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
    const STRETCH: f32 = 1.0;
    const HOLD: f32 = 750.0;
    let stack = NSStackView::new(mtm);
    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
    stack.setAlignment(NSLayoutAttribute::CenterY);
    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
    stack.setSpacing(6.0);
    // A table row's breathing room above and below; the list gives the sides.
    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
        top: 4.0,
        left: 0.0,
        bottom: 4.0,
        right: 0.0,
    });
    let icon = unsafe { NSImageView::new(mtm) };
    unsafe {
        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
        icon.widthAnchor()
            .constraintEqualToConstant(16.0)
            .setActive(true);
        icon.heightAnchor()
            .constraintEqualToConstant(16.0)
            .setActive(true);
    }
    stack.addArrangedSubview(&icon);
    // The title and subtitle span the words' column (Width alignment), so the column's width is
    // theirs and nothing is left over inside it.
    let texts = NSStackView::new(mtm);
    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
    texts.setAlignment(NSLayoutAttribute::Width);
    texts.setSpacing(1.0);
    // Its height is its lines', centered in the row, not the row's height with the lines
    // floating somewhere inside it.
    texts.setHuggingPriority_forOrientation(
        HOLD,
        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
    );
    let title = label("", size, false);
    let subtitle = label("", small, true);
    // The words take the width and give way first, truncating, before the trailing parts.
    for line in [&title, &subtitle] {
        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
    }
    texts.addArrangedSubview(&title);
    texts.addArrangedSubview(&subtitle);
    stack.addArrangedSubview(&texts);
    let detail = label("", size, true);
    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
    stack.addArrangedSubview(&detail);
    let check = unsafe { NSImageView::new(mtm) };
    unsafe {
        check.setImage(
            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
                &NSString::from_str("checkmark"),
                None,
            )
            .as_deref(),
        );
        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
    }
    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
    stack.addArrangedSubview(&check);
    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
    dress_list_item(&view, p, mtm);
    view
}

/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
    use objc2_app_kit::{NSImageView, NSStackView};
    let Some(stack) = view.downcast_ref::<NSStackView>() else {
        return;
    };
    let parts = stack.arrangedSubviews();
    if parts.len() < 4 {
        return;
    }
    let icon = parts.objectAtIndex(0);
    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
        let image = p
            .icon
            .as_ref()
            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
        unsafe {
            iv.setImage(image.as_deref());
            iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
        }
    }
    icon.setHidden(p.icon.is_none());
    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
        let lines = texts.arrangedSubviews();
        if lines.len() == 2 {
            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
                tf.setStringValue(&NSString::from_str(&p.title));
            }
            let sub = lines.objectAtIndex(1);
            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
                tf.setStringValue(&NSString::from_str(&p.subtitle));
            }
            sub.setHidden(p.subtitle.is_empty());
        }
    }
    let detail = parts.objectAtIndex(2);
    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
        tf.setStringValue(&NSString::from_str(&p.detail));
    }
    detail.setHidden(p.detail.is_empty());
    parts.objectAtIndex(3).setHidden(!p.checked);
    let words = [&p.title, &p.subtitle, &p.detail]
        .into_iter()
        .filter(|w| !w.is_empty())
        .map(String::as_str)
        .collect::<Vec<_>>()
        .join(", ");
    unsafe {
        view.setAccessibilityElement(true);
        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
        view.setAccessibilitySelected(p.checked);
    }
}

/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
///
/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
/// realize would have, or a piece would show different pixels depending on whether it was
/// built or updated.
fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
    use objc2::AllocAnyThread as _;
    match source {
        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
        // path: a bundle file loaded straight into NSImage (§18.3).
        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
            .or_else(|| day_spec::resource::resolve_image_file(name))
            .and_then(|path| unsafe {
                objc2_app_kit::NSImage::initWithContentsOfFile(
                    objc2_app_kit::NSImage::alloc(),
                    &NSString::from_str(&path.to_string_lossy()),
                )
            }),
        // Bytes the app already holds (a download, a picked file, a paste) with no staged
        // resource behind them.
        day_spec::ImageSource::Bytes(bytes) => unsafe {
            objc2_app_kit::NSImage::initWithData(
                objc2_app_kit::NSImage::alloc(),
                &NSData::with_bytes(bytes),
            )
        },
        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
        day_spec::ImageSource::Decoded(id) => {
            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
        }
    }
}

/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
    use day_spec::Role;
    use objc2_app_kit::{
        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
    };
    unsafe {
        Some(match role {
            Role::Button => NSAccessibilityButtonRole,
            Role::Toggle => NSAccessibilityCheckBoxRole,
            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
            Role::Tab => NSAccessibilityRadioButtonRole,
            Role::TabList => NSAccessibilityTabGroupRole,
            Role::Slider => NSAccessibilitySliderRole,
            Role::TextInput => NSAccessibilityTextFieldRole,
            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
            // displace the text an NSTextField reports as its value, so the level stays
            // unspoken.
            Role::Heading(_) => NSAccessibilityHeadingRole,
            Role::Image => NSAccessibilityImageRole,
            Role::Meter => NSAccessibilityLevelIndicatorRole,
            Role::Group => NSAccessibilityGroupRole,
            // NSOutlineView already reports these itself; the mapping is for the audit's
            // expectation and for any composed stand-in (docs/tree.md).
            Role::Tree => NSAccessibilityOutlineRole,
            Role::TreeItem => NSAccessibilityRowRole,
            Role::None => return None,
        })
    }
}

/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
fn day_role_from_ns(ax: &str) -> day_spec::Role {
    use day_spec::Role;
    match ax {
        "AXButton" => Role::Button,
        "AXCheckBox" => Role::Toggle,
        "AXSlider" => Role::Slider,
        "AXTextField" => Role::TextInput,
        // Plain text is ambiguous with a heading, and neither carries a level; the audit
        // ignores the level either way.
        "AXStaticText" | "AXHeading" => Role::Heading(0),
        "AXOutline" => Role::Tree,
        "AXImage" => Role::Image,
        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
        "AXGroup" => Role::Group,
        "AXRadioButton" => Role::Tab,
        "AXTabGroup" => Role::TabList,
        _ => Role::None,
    }
}

// ---------------------------------------------------------------------------
// DayTarget: target/action + text delegate trampoline
// ---------------------------------------------------------------------------

struct TargetIvars {
    node: NodeId,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayTarget"]
    #[ivars = TargetIvars]
    struct DayTarget;

    unsafe impl NSObjectProtocol for DayTarget {}
    unsafe impl NSTextFieldDelegate for DayTarget {}

    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
    /// node, exactly as the sidebar's outline view does, so as far as everything above this
    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
    unsafe impl NSTabViewDelegate for DayTarget {
        #[unsafe(method(tabView:didSelectTabViewItem:))]
        fn tab_view_did_select(
            &self,
            tab_view: &objc2_app_kit::NSTabView,
            item: Option<&objc2_app_kit::NSTabViewItem>,
        ) {
            ffi_guard::contain((), || {
                if TAB_PICK_SUPPRESS.with(|s| s.get()) {
                    return;
                }
                if let Some(item) = item {
                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
                    if idx >= 0 {
                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
                    }
                }
            })
        }
    }

    impl DayTarget {
        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
        // The same guard wraps every other target/delegate entry in this backend.
        #[unsafe(method(action:))]
        fn action(&self, sender: &NSControl) {
            ffi_guard::contain((), || {
                let node = self.ivars().node;
                if sender.downcast_ref::<NSSwitch>().is_some() {
                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
                } else if sender.downcast_ref::<NSSlider>().is_some() {
                    let value = unsafe { sender.doubleValue() };
                    // The live value first: bindings follow this, so the UI tracks the thumb.
                    emit(node, Event::ValueChanged(value));
                    // Then, once, the value the user settled on. The slider is `continuous`, so
                    // this action fires on every tick of a drag; AppKit's way to tell where in the
                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
                    // press (arrow keys) moves the value by one discrete step and is already settled;
                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
                    if slider_value_settled() {
                        emit(node, Event::ValueCommitted(value));
                    }
                } else {
                    emit(node, Event::Pressed);
                    // A push-on/push-off button toggled its state on the click; Day owns the
                    // selected state (`set_button_selected`), so put back what it last asked.
                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
                        unsafe {
                            btn.setState(if on {
                                NSControlStateValueOn
                            } else {
                                NSControlStateValueOff
                            })
                        };
                    }
                }
            })
        }

        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
        /// nav host's handler writes it into the path signal, which reconciles the pop.
        #[unsafe(method(navBack:))]
        fn nav_back(&self, _sender: &NSControl) {
            ffi_guard::contain((), || {
                emit(
                    self.ivars().node,
                    Event::NavBack {
                        already_popped: false,
                    },
                );
            })
        }
    }

    unsafe impl NSControlTextEditingDelegate for DayTarget {
        #[unsafe(method(controlTextDidChange:))]
        fn control_text_did_change(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                let node = self.ivars().node;
                if let Some(obj) = unsafe { notification.object() }
                    && let Ok(tf) = obj.downcast::<NSTextField>() {
                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
                    }
            })
        }

        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
        /// first responder and re-selects, so it is not a focus loss; every other movement
        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
        #[unsafe(method(controlTextDidEndEditing:))]
        fn control_text_did_end_editing(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                let node = self.ivars().node;
                let movement = unsafe { notification.userInfo() }
                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
                    .and_then(|n| n.downcast::<NSNumber>().ok())
                    .map(|n| NSTextMovement(n.integerValue()))
                    .unwrap_or(NSTextMovement::Other);
                if movement == NSTextMovement::Return {
                    emit(node, Event::Submitted);
                } else {
                    emit(node, Event::FocusChanged(false));
                }
            })
        }
    }
);

impl DayTarget {
    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
        unsafe { msg_send![super(this), init] }
    }
}

// ---------------------------------------------------------------------------
// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
// ---------------------------------------------------------------------------

struct CursorIvars {
    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
    cursor: RefCell<Option<Retained<NSCursor>>>,
    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
    hidden: Cell<bool>,
    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
    hiding: Cell<bool>,
}

// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
// tracking area's owner when the pointer enters the area (and on request through
// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
// a button, or a plain container all get the same treatment without subclassing. Nested areas
// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayCursorOwner"]
    #[ivars = CursorIvars]
    struct DayCursorOwner;

    unsafe impl NSObjectProtocol for DayCursorOwner {}

    impl DayCursorOwner {
        #[unsafe(method(cursorUpdate:))]
        fn cursor_update(&self, _event: &NSEvent) {
            let iv = self.ivars();
            if iv.hidden.get() {
                if !iv.hiding.replace(true) {
                    NSCursor::hide();
                }
                return;
            }
            if let Some(c) = iv.cursor.borrow().as_ref() {
                c.set();
            }
        }

        #[unsafe(method(mouseExited:))]
        fn mouse_exited(&self, _event: &NSEvent) {
            if self.ivars().hiding.replace(false) {
                NSCursor::unhide();
            }
        }
    }
);

impl DayCursorOwner {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(CursorIvars {
            cursor: RefCell::new(None),
            hidden: Cell::new(false),
            hiding: Cell::new(false),
        });
        unsafe { msg_send![super(this), init] }
    }
}

/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
/// nav host, with the nearest older shape below it.
// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
// column/row resize cursors, which are probed above them; below 15 they are the shape.
#[allow(deprecated)]
fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
    Some(match c {
        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
        Cursor::Pointer => NSCursor::pointingHandCursor(),
        Cursor::Text => NSCursor::IBeamCursor(),
        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
        Cursor::Grabbing => NSCursor::closedHandCursor(),
        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
        Cursor::Copy => NSCursor::dragCopyCursor(),
        Cursor::Alias => NSCursor::dragLinkCursor(),
        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
            NSCursor::frameResizeCursorFromPosition_inDirections(
                NSCursorFrameResizePosition::TopRight,
                NSCursorFrameResizeDirections::All,
            )
        }
        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
            NSCursor::frameResizeCursorFromPosition_inDirections(
                NSCursorFrameResizePosition::TopLeft,
                NSCursorFrameResizeDirections::All,
            )
        }
        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
        Cursor::None => return None,
        Cursor::Native(name) => match &**name {
            "disappearingItem" => NSCursor::disappearingItemCursor(),
            "dragCopy" => NSCursor::dragCopyCursor(),
            "dragLink" => NSCursor::dragLinkCursor(),
            "contextualMenu" => NSCursor::contextualMenuCursor(),
            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
            _ => return None,
        },
    })
}

/// Whether the NSEvent currently being dispatched ends a slider's interaction (see the
/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
/// `setDoubleValue:` that fires the action) is not a user commit either.
fn slider_value_settled() -> bool {
    let Some(mtm) = MainThreadMarker::new() else {
        return false;
    };
    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
        return false;
    };
    matches!(
        unsafe { event.r#type() },
        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
    )
}

// ---------------------------------------------------------------------------
// DayTextField: NSTextField that reports focus gain (docs/focus.md)
// ---------------------------------------------------------------------------

struct FieldIvars {
    node: NodeId,
}

define_class!(
    #[unsafe(super(NSTextField))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayTextField"]
    #[ivars = FieldIvars]
    struct DayTextField;

    impl DayTextField {
        /// Focus gain. Key events go to the shared field editor, but the field itself receives
        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
        /// delegate.
        #[unsafe(method(becomeFirstResponder))]
        fn become_first_responder(&self) -> bool {
            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
            if ok {
                field_gained_focus(self.ivars().node);
            }
            ok
        }
    }
);

impl DayTextField {
    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
        unsafe { msg_send![super(this), init] }
    }
}

// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
define_class!(
    #[unsafe(super(NSSecureTextField))]
    #[thread_kind = MainThreadOnly]
    #[name = "DaySecureTextField"]
    #[ivars = FieldIvars]
    struct DaySecureTextField;

    impl DaySecureTextField {
        /// Focus gain, as on `DayTextField`.
        #[unsafe(method(becomeFirstResponder))]
        fn become_first_responder(&self) -> bool {
            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
            if ok {
                field_gained_focus(self.ivars().node);
            }
            ok
        }
    }
);

impl DaySecureTextField {
    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
        unsafe { msg_send![super(this), init] }
    }
}

thread_local! {
    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
    /// field to its replacement, which the app must not see as a focus change.
    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
}

/// Report a text field's focus gain, unless it is a class swap handing focus to the
/// replacement of a field that already had it.
fn field_gained_focus(node: NodeId) {
    if FIELD_SWAP.with(|s| s.get()) {
        return;
    }
    // Guard only the sink dispatch: the responder change already happened, so a contained
    // panic must not flip the answer AppKit acts on.
    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
}

/// The node a `text_field`'s view reports against, or `None` when the view is not one
/// (a label is an `NSTextField` too).
fn text_field_node(v: &NSView) -> Option<NodeId> {
    v.downcast_ref::<DayTextField>()
        .map(|f| f.ivars().node)
        .or_else(|| {
            v.downcast_ref::<DaySecureTextField>()
                .map(|f| f.ivars().node)
        })
}

/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
/// report text, submit and focus the same way against the same node.
fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
    let target = DayTarget::new(mtm, node);
    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
    // `view_of` resolves and every `NSTextField` downcast sees either class.
    let tf: Retained<NSTextField> = if secure {
        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
    } else {
        Retained::into_super(DayTextField::new(mtm, node))
    };
    unsafe {
        tf.setEditable(true);
        tf.setBezeled(true);
        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
    }
    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
    tf
}

/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
/// the field via its delegate.
fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
    window.firstResponder().is_some_and(|fr| {
        if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
            return true;
        }
        fr.downcast::<NSText>().is_ok_and(|text| {
            unsafe { text.delegate() }
                .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
        })
    })
}

/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
/// reference binds at launch, and one missing symbol would keep the whole app from starting
/// on an older system.
fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
    unsafe extern "C" {
        fn dlsym(
            handle: *mut std::ffi::c_void,
            symbol: *const std::ffi::c_char,
        ) -> *mut std::ffi::c_void;
    }
    // <dlfcn.h>: search every image loaded in the process.
    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
    // constant string.
    unsafe {
        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
        if slot.is_null() {
            None
        } else {
            (*slot).as_ref()
        }
    }
}

/// Move a view-keyed entry to the view that replaces it.
fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
    if let Some(v) = table.take(old) {
        table.insert(new, v);
    }
}

/// A label is the shared field editor's delegate. AppKit does not forward
/// `textView:clickedOnLink:atIndex:` to an NSTextField's separate control delegate, so the
/// label itself must handle it to prevent the field editor from opening the target externally.
/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
struct LabelIvars {
    node: NodeId,
    has_links: Cell<bool>,
    has_runs: Cell<bool>,
    selectable: Cell<bool>,
}

define_class!(
    #[unsafe(super(NSTextField))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayLabel"]
    #[ivars = LabelIvars]
    struct DayLabel;

    impl DayLabel {
        #[unsafe(method_id(menuForEvent:))]
        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
            ffi_guard::contain(None, || {
                if !self.isSelectable()
                    && let Some(menu) = inherited_context_menu(self, event)
                {
                    return menu;
                }
                unsafe { msg_send![super(self), menuForEvent: event] }
            })
        }

        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, dirty: NSRect) {
            // AppKit cannot propagate a table cell's background style through arbitrary
            // Day containers. Resolve selection at paint time so keyboard focus, window
            // activation, and cell reuse all use the actual native row state.
            let mut ancestor = unsafe { self.superview() };
            let mut selection_color = None;
            if !self.ivars().has_runs.get() {
                while let Some(view) = ancestor {
                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
                        if unsafe { row.isSelected() } {
                            selection_color = Some(unsafe {
                                if row.isEmphasized() {
                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
                                } else {
                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
                                }
                            });
                        }
                        break;
                    }
                    ancestor = unsafe { view.superview() };
                }
            }
            let cell = unsafe { self.cell() }
                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
            if let (Some(color), Some(cell)) = (selection_color, cell) {
                let original = unsafe { cell.textColor() };
                // Mutate the cell only for this paint; changing the field would invalidate
                // the view again. Keep the app's normal color for deselection and reuse.
                unsafe {
                    cell.setTextColor(Some(&color));
                    let _: () = msg_send![super(self), drawRect: dirty];
                    cell.setTextColor(original.as_deref());
                }
            } else {
                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
            }
        }
    }

    unsafe impl NSObjectProtocol for DayLabel {}
    unsafe impl NSTextDelegate for DayLabel {}

    unsafe impl NSTextViewDelegate for DayLabel {
        #[unsafe(method(textView:clickedOnLink:atIndex:))]
        fn clicked_on_link(
            &self,
            _tv: &NSTextView,
            link: &objc2::runtime::AnyObject,
            _index: usize,
        ) -> bool {
            ffi_guard::contain(true, || {
                // NSString targets stay verbatim (including #route); accept NSURL too.
                let url: Retained<NSString> = unsafe { msg_send![link, description] };
                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
                true // Handled: AppKit must never also open the target itself.
            })
        }
    }
);

impl DayLabel {
    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(LabelIvars {
            node,
            has_links: Cell::new(false),
            has_runs: Cell::new(false),
            selectable: Cell::new(false),
        });
        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
        unsafe {
            this.setStringValue(&NSString::from_str(text));
            this.setEditable(false);
            this.setSelectable(false);
            this.setBordered(false);
            this.setBezeled(false);
            this.setDrawsBackground(false);
        }
        this
    }

    fn set_links(&self, has_links: bool) {
        self.ivars().has_links.set(has_links);
        unsafe {
            self.setSelectable(has_links || self.ivars().selectable.get());
            self.setAllowsEditingTextAttributes(has_links);
        }
    }
}

struct PanMonitor(Retained<objc2::runtime::AnyObject>);
impl Drop for PanMonitor {
    fn drop(&mut self) {
        unsafe { NSEvent::removeMonitor(&self.0) };
    }
}

// A container pan observes horizontal wheel events over its descendants, including native
// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
fn install_container_pan_monitor() {
    PAN_MONITOR.with(|slot| {
        if slot.borrow().is_some() {
            return;
        }
        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
            let event = unsafe { raw.as_ref() };
            ffi_guard::contain(raw.as_ptr(), || {
                let dx = unsafe { event.scrollingDeltaX() };
                let dy = unsafe { event.scrollingDeltaY() };
                if dx.abs() <= dy.abs() {
                    return raw.as_ptr();
                }
                let Some(mtm) = MainThreadMarker::new() else {
                    return raw.as_ptr();
                };
                let Some(window) = event.window(mtm) else {
                    return raw.as_ptr();
                };
                let Some(content) = window.contentView() else {
                    return raw.as_ptr();
                };
                let point =
                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
                let mut view = content.hitTest(point);
                while let Some(v) = view {
                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
                        if v.downcast_ref::<DayCanvas>().is_some() {
                            return raw.as_ptr();
                        }
                        let raw_phase = unsafe { event.phase() };
                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
                            day_spec::DragPhase::Began
                        } else if raw_phase.intersects(
                            objc2_app_kit::NSEventPhase::Ended
                                | objc2_app_kit::NSEventPhase::Cancelled,
                        ) {
                            day_spec::DragPhase::Ended
                        } else {
                            day_spec::DragPhase::Changed
                        };
                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
                        emit(
                            node,
                            Event::Pan {
                                phase,
                                delta: Point::new(dx, dy),
                                location: Point::new(p.x, p.y),
                            },
                        );
                        return std::ptr::null_mut();
                    }
                    view = unsafe { v.superview() };
                }
                raw.as_ptr()
            })
        });
        *slot.borrow_mut() = unsafe {
            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
                objc2_app_kit::NSEventMask::ScrollWheel,
                &block,
            )
        }
        .map(PanMonitor);
    });
}

// ---------------------------------------------------------------------------
// DayFlipped: top-left-origin container view
// ---------------------------------------------------------------------------

/// A `background(..)` fill: `(r, g, b, a, corner_radius)`, painted in `drawRect` with NSColor.
type Surface = (f64, f64, f64, f64, f64);

#[derive(Default)]
struct FlippedIvars {
    surface: Cell<Option<Surface>>,
    /// SurfaceRole::SectionCard: `(radius,)`, drawn with a dynamic system fill resolved at
    /// draw time, so the card tracks light/dark appearance changes automatically.
    section_card: Cell<Option<f64>>,
    /// Paint the whole view with the dynamic window background before anything else: the
    /// inspector panel wrap (docs/inspector.md). The inspector NSSplitViewItem backs its pane
    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
    /// it into near-black in dark mode (and the material itself captures black offscreen; see
    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
    /// backdrop gives the cards the same ground System Settings draws them on.
    pane_backdrop: Cell<bool>,
}

define_class!(
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayFlipped"]
    #[ivars = FlippedIvars]
    struct DayFlipped;

    impl DayFlipped {
        #[unsafe(method_id(menuForEvent:))]
        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
            ffi_guard::contain(None, || {
                inherited_context_menu(self, event)
                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
            })
        }

        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
        // before (refuses first responder, forwards every key).
        #[unsafe(method(acceptsFirstResponder))]
        fn accepts_first_responder(&self) -> bool {
            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
        }

        // Clicking a focusable container focuses it, the way clicking a table does. The
        // gesture recognizers still see the press: this runs before `super`, which is what
        // forwards it to them.
        #[unsafe(method(mouseDown:))]
        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
            if transfer::pressed(self, event) { return; }
            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
                && let Some(window) = self.window()
            {
                window.makeFirstResponder(Some(self));
            }
            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
        }

        #[unsafe(method(becomeFirstResponder))]
        fn become_first_responder(&self) -> bool {
            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
            }
            true
        }

        #[unsafe(method(resignFirstResponder))]
        fn resign_first_responder(&self) -> bool {
            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
            }
            true
        }

        /// The arrows, delivered here while this container is the first responder. Anything
        /// else (and every arrow when the app registered no key handler for the node) goes
        /// to `super`, which walks the responder chain exactly as it would have without us.
        #[unsafe(method(keyDown:))]
        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
            let handled = ffi_guard::contain(false, || {
                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
                    return false;
                };
                let Some(key) = key_name(event) else {
                    return false;
                };
                if !day_spec::keys::handled(node) {
                    return false;
                }
                emit(
                    node,
                    Event::Key(day_spec::KeyEvent {
                        key: key.to_string(),
                        modifiers: key_modifiers(event.modifierFlags()),
                    }),
                );
                true
            });
            if !handled {
                let _: () = unsafe { msg_send![super(self), keyDown: event] };
            }
        }

        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
        /// regardless of how the click threads through Day's container hierarchy.
        #[unsafe(method(rightMouseDown:))]
        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
            if let Some(menu) = self.menuForEvent(event) {
                unsafe {
                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
                };
            } else {
                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
            }
        }

        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, _dirty: NSRect) {
            let paint = || {
                if self.ivars().pane_backdrop.get() {
                    let bounds = self.bounds();
                    unsafe {
                        // Resolved at draw time, like the section fill below, so the backdrop
                        // follows light/dark appearance changes automatically.
                        NSColor::windowBackgroundColor().setFill();
                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
                    }
                }
                if let Some(radius) = self.ivars().section_card.get() {
                    let bounds = self.bounds();
                    unsafe {
                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
                        // Settings uses; older systems fall back to the control background.
                        let cls = objc2::class!(NSColor);
                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
                        let color: objc2::rc::Retained<NSColor> = if has {
                            msg_send![cls, quaternarySystemFillColor]
                        } else {
                            msg_send![cls, controlBackgroundColor]
                        };
                        color.setFill();
                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
                            bounds, radius, radius,
                        );
                        path.fill();
                    }
                }
                if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
                    let bounds = self.bounds();
                    unsafe {
                        NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
                        let path = if radius > 0.0 {
                            objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
                                bounds, radius, radius,
                            )
                        } else {
                            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
                        };
                        path.fill();
                    }
                }
            };
            // Paint under the standard counterpart of this view's appearance. Inside an
            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
            // vibrant variants are opaque blend colors that only composite correctly in an
            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
            // the fills System Settings draws with, and re-resolves on every theme change
            // (this runs per draw, and appearance flips redraw).
            unsafe {
                let names = objc2_foundation::NSArray::from_slice(&[
                    objc2_app_kit::NSAppearanceNameAqua,
                    objc2_app_kit::NSAppearanceNameDarkAqua,
                ]);
                let standard = self
                    .effectiveAppearance()
                    .bestMatchFromAppearancesWithNames(&names)
                    .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
                match standard {
                    Some(appearance) => {
                        let block = block2::StackBlock::new(paint);
                        appearance.performAsCurrentDrawingAppearance(&block);
                    }
                    None => paint(),
                }
            }
        }
    }
    unsafe impl NSObjectProtocol for DayFlipped {}
    unsafe impl NSDraggingSource for DayFlipped {
        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
    }
    impl DayFlipped {
        #[unsafe(method(mouseDragged:))]
        fn transfer_dragged(&self, event: &NSEvent) {
            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
        }
        #[unsafe(method(draggingEntered:))]
        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
        #[unsafe(method(draggingUpdated:))]
        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
        #[unsafe(method(performDragOperation:))]
        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
    }

);

impl DayFlipped {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
        unsafe { msg_send![super(this), init] }
    }

    /// Apply a `background`/`corner_radius` surface. The fill (rounded by `corner_radius`) is
    /// drawn in `drawRect` with NSColor, not via the layer's `backgroundColor`, whose CGColorRef
    /// argument objc2's `msg_send` cannot type-check. A rounded child clip does use the CALayer
    /// (`cornerRadius` + `masksToBounds` are a CGFloat + `BOOL`, which are fine).
    /// SurfaceRole::SectionCard: the fill resolves dynamically in drawRect (theme-adaptive).
    fn set_section_card(&self, corner_radius: f64) {
        self.ivars().section_card.set(Some(corner_radius));
        unsafe {
            let _: () = msg_send![self, setNeedsDisplay: true];
        }
    }

    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
    fn set_pane_backdrop(&self) {
        self.ivars().pane_backdrop.set(true);
        unsafe {
            let _: () = msg_send![self, setNeedsDisplay: true];
        }
    }

    fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
        self.ivars()
            .surface
            .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
        unsafe {
            let _: () = msg_send![self, setNeedsDisplay: true];
            if clips || corner_radius > 0.0 {
                let _: () = msg_send![self, setWantsLayer: true];
                let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
                if !layer.is_null() {
                    let _: () = msg_send![layer, setCornerRadius: corner_radius];
                    let _: () = msg_send![layer, setMasksToBounds: true];
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
// ---------------------------------------------------------------------------

struct CanvasIvars;

define_class!(
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayCanvas"]
    #[ivars = CanvasIvars]
    struct DayCanvas;

    impl DayCanvas {
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
        /// is under the pointer and offer commands for that selection.
        #[unsafe(method_id(menuForEvent:))]
        fn menu_for_event(
            &self,
            event: &objc2_app_kit::NSEvent,
        ) -> Option<Retained<NSMenu>> {
            let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
            let Some(f) = f else {
                return unsafe { msg_send![super(self), menuForEvent: event] };
            };
            // Guarded: the provider is app code (it usually re-selects, then builds).
            ffi_guard::contain(None, || {
                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
                let items = f(day_spec::Point::new(p.x, p.y));
                if items.is_empty() {
                    return None;
                }
                Some(build_ns_menu(self.mtm(), "", &items))
            })
        }

        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
        // built-in piece with no native control under it, so nothing else would ever make it
        // the first responder — and without that, arrow keys aimed at what it draws could only
        // be caught by watching the whole app.
        #[unsafe(method(acceptsFirstResponder))]
        fn accepts_first_responder(&self) -> bool {
            true
        }

        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
        // is what forwards it to them.
        #[unsafe(method(mouseDown:))]
        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
            if let Some(window) = self.window() {
                window.makeFirstResponder(Some(self));
            }
            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
        }

        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
        // `assert_focused` can see it.
        #[unsafe(method(becomeFirstResponder))]
        fn become_first_responder(&self) -> bool {
            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
            }
            true
        }

        #[unsafe(method(resignFirstResponder))]
        fn resign_first_responder(&self) -> bool {
            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
            }
            true
        }

        /// The arrows, delivered to this canvas because it is the first responder. Anything
        /// else — and every arrow when the app registered no handler for this node — goes to
        /// `super`, which walks the responder chain exactly as it would have without us.
        #[unsafe(method(keyDown:))]
        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
            let handled = ffi_guard::contain(false, || {
                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
                    return false;
                };
                let Some(key) = key_name(event) else {
                    return false;
                };
                // A canvas nobody asked keys from does not get to keep them: an enclosing
                // scroll view still scrolls, and an unclaimed key still beeps the way the
                // platform means it to.
                if !day_spec::keys::handled(node) {
                    return false;
                }
                emit(
                    node,
                    Event::Key(day_spec::KeyEvent {
                        key: key.to_string(),
                        modifiers: key_modifiers(event.modifierFlags()),
                    }),
                );
                true
            });
            if !handled {
                let _: () = unsafe { msg_send![super(self), keyDown: event] };
            }
        }

        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, _dirty: NSRect) {
            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
            paint_ops(&ops);
        }

        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
        #[unsafe(method(mouseEntered:))]
        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
            self.report_hover(event, day_spec::DragPhase::Began);
        }

        #[unsafe(method(mouseMoved:))]
        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
            self.report_hover(event, day_spec::DragPhase::Changed);
        }

        #[unsafe(method(mouseExited:))]
        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
            self.report_hover(event, day_spec::DragPhase::Ended);
        }

        #[unsafe(method(scrollWheel:))]
        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
                return;
            };
            ffi_guard::contain((), || {
                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
                // arrives as a lone Changed — exactly the Event::Pan contract.
                let raw = unsafe { event.phase() };
                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
                    day_spec::DragPhase::Began
                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
                {
                    day_spec::DragPhase::Ended
                } else {
                    day_spec::DragPhase::Changed
                };
                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
                    event.scrollingDeltaY()
                });
                let win = unsafe { event.locationInWindow() };
                let loc = self.convertPoint_fromView(win, None);
                emit(
                    node,
                    Event::Pan {
                        phase,
                        delta,
                        location: Point::new(loc.x, loc.y),
                    },
                );
            })
        }
    }
);

impl DayCanvas {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
        unsafe { msg_send![super(this), init] }
    }

    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
    ///
    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
    /// its window — including outside itself. Hence the bounds test, without which a canvas
    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
    /// the window entirely still produced hover positions).
    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
        let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
        let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
            return;
        };
        ffi_guard::contain((), || {
            let win = unsafe { event.locationInWindow() };
            let loc = self.convertPoint_fromView(win, None);
            let b = self.bounds();
            let inside = loc.x >= b.origin.x
                && loc.x <= b.origin.x + b.size.width
                && loc.y >= b.origin.y
                && loc.y <= b.origin.y + b.size.height;
            // An exit is reported wherever it happens — that is the point of it — but a move
            // outside the view is not this view's hover.
            if !inside && phase != day_spec::DragPhase::Ended {
                return;
            }
            emit(
                node,
                Event::Hover {
                    phase,
                    location: Point::new(loc.x, loc.y),
                },
            );
        });
    }
}

/// The tracking area a hovering canvas needs. `InVisibleRect` makes it follow the view's bounds,
/// so there is no rect to keep in step with layout; `ActiveInKeyWindow` matches the cursor areas
/// already installed here — a background window does not report hovers.
fn install_tracking_area(h: &NSView) {
    let opts = NSTrackingAreaOptions::MouseEnteredAndExited
        | NSTrackingAreaOptions::MouseMoved
        | NSTrackingAreaOptions::ActiveInKeyWindow
        | NSTrackingAreaOptions::InVisibleRect;
    let any: &objc2::runtime::AnyObject = h;
    let area = unsafe {
        NSTrackingArea::initWithRect_options_owner_userInfo(
            NSTrackingArea::alloc(),
            NSRect::ZERO,
            opts,
            Some(any),
            None,
        )
    };
    unsafe { h.addTrackingArea(&area) };
}

// ---------------------------------------------------------------------------
// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
// ---------------------------------------------------------------------------

struct GestureIvars {
    node: NodeId,
    kind: day_spec::GestureKind,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayGesture"]
    #[ivars = GestureIvars]
    struct DayGesture;

    unsafe impl NSObjectProtocol for DayGesture {}

    impl DayGesture {
        #[unsafe(method(fire:))]
        fn fire(&self, g: &NSGestureRecognizer) {
            ffi_guard::contain((), || {
                let node = self.ivars().node;
                let view = g.view();
                let loc = g.locationInView(view.as_deref());
                let at = Point::new(loc.x, loc.y);
                let phase = match g.state() {
                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
                    NSGestureRecognizerState::Ended
                    | NSGestureRecognizerState::Cancelled
                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
                    _ => day_spec::DragPhase::Changed,
                };
                let obj: &objc2::runtime::AnyObject = g.as_ref();
                match self.ivars().kind {
                    day_spec::GestureKind::Drag => {
                        let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
                            let t = unsafe { pan.translationInView(view.as_deref()) };
                            Point::new(t.x, t.y)
                        } else {
                            Point::ZERO
                        };
                        emit(node, Event::Drag { phase, location: at, translation });
                    }
                    day_spec::GestureKind::Pinch => {
                        // Cumulative since Began: `magnification` is the total delta (0 =
                        // unchanged), and Day's contract wants a factor.
                        let scale = if let Some(m) =
                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
                        {
                            1.0 + unsafe { m.magnification() }
                        } else {
                            1.0
                        };
                        emit(node, Event::Pinch { phase, scale, location: at });
                    }
                    _ => emit(node, Event::Tap(at)),
                }
            })
        }
    }
);

impl DayGesture {
    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
        unsafe { msg_send![super(this), init] }
    }
}

// ---------------------------------------------------------------------------
// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
// page reports from setFrameSize:. Day's set_frame on pages is skipped.
// ---------------------------------------------------------------------------

/// The stack presentation's back header (desktop has no system back affordance — this bar
/// gives a pushed page its way out, like AdwNavigationView's header on GTK). Hidden at root.
struct NavHeader {
    bar: Retained<NSView>,
    title: Retained<NSTextField>,
    /// Title per stack level (index 0 = root); the field shows the last.
    titles: Vec<String>,
    _target: Retained<DayTarget>,
}

/// Height of the stack-nav back header while a pushed page is showing.
const NAV_HEADER_H: f64 = 34.0;

// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
// restoring by hand after every window resize.
use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};

/// The content-list width to place divider 1 at, once, the first time the pane is showing —
/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
fn take_list_placement(state: &mut NavState) -> Option<f64> {
    if !state.list_visible || state.list_positioned {
        return None;
    }
    state.list_positioned = true;
    state.list_width
}

/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
/// deeper, since the tabs themselves stand about a segment's height above the bezel.
const NAV_TABVIEW_INSET: f64 = 12.0;
const NAV_TABVIEW_INSET_TOP: f64 = 8.0;

/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
/// exactly as in a split: the tab view frames the selected item's view, and the page's
/// `setFrameSize:` reports it. The labels come from the NAV_MENU's rows, which arrive after
/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
/// rebuilt.
///
/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
/// ever built and a tabs host showed its first page alone.
struct TabHost {
    view: Retained<objc2_app_kit::NSTabView>,
    /// The delegate reporting a native tab pick against the NAV_MENU's node; set once the menu
    /// is known.
    target: Option<Retained<DayTarget>>,
}

thread_local! {
    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
    /// delegate must not echo it back as `SelectionChanged`.
    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Give the tab view its labels from the rows, and its selection. Rows and items are
/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
/// have.
fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
    unsafe {
        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
        for (i, title) in titles.iter().enumerate().take(n) {
            tabs.view
                .tabViewItemAtIndex(i as isize)
                .setLabel(&NSString::from_str(title));
        }
        if n > 0 {
            TAB_PICK_SUPPRESS.with(|s| s.set(true));
            tabs.view
                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
            TAB_PICK_SUPPRESS.with(|s| s.set(false));
        }
    }
}

/// A NAV_MENU reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
    let Some((titles, node)) = NAV_MENUS.with(|m| {
        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
            let ivars = d.ivars();
            (
                ivars
                    .items
                    .borrow()
                    .iter()
                    .map(|s| s.to_string())
                    .collect::<Vec<String>>(),
                ivars.node,
            )
        })
    }) else {
        return;
    };
    let mut up = unsafe { menu.superview() };
    while let Some(v) = up {
        let reached = NAV_STATE.with(|m| {
            let mut m = m.borrow_mut();
            let Some(s) = m.get_mut(&ptr_of(&v)) else {
                return false;
            };
            let selected = s.selected;
            if let Some(tabs) = s.tabs.as_mut() {
                if tabs.target.is_none() {
                    let target = DayTarget::new(mtm, node);
                    unsafe {
                        tabs.view
                            .setDelegate(Some(ProtocolObject::from_ref(&*target)))
                    };
                    tabs.target = Some(target);
                }
                sync_tab_labels(tabs, &titles, selected);
            }
            true
        });
        if reached {
            return;
        }
        up = unsafe { v.superview() };
    }
}

struct NavState {
    sidebar_wrap: Retained<NSView>,
    detail_wrap: Retained<NSView>,
    /// The container behind the host view. A view holds NO strong reference to its controller,
    /// and the split view controller is what owns the items, their holding priorities, the
    /// sidebar's material and the split's delegate duties — so it has to be retained here or
    /// the sidebar loses its treatment the moment this realize returns.
    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
    /// the path dayscript and any non-toolbar caller take.
    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
    list_wrap: Option<Retained<NSView>>,
    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
    /// first frame pass, by placing divider 1 (see `set_frame`).
    list_width: Option<f64>,
    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
    /// it, so both placement paths ask first.
    list_visible: bool,
    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
    /// app opening on a full-width destination has nothing to size then, and spending the
    /// one-time placement there is what left the list at the solver's own width when it did
    /// appear.
    list_positioned: bool,
    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
    pages: Vec<Retained<NSView>>,
    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
    /// pane and the head of `pages` (docs/size-classes.md).
    sidebar_page: Option<Retained<NSView>>,
    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
    /// into a collapsed wrap, where autoresizing can only keep it at zero.
    list_page: Option<Retained<NSView>>,
    positioned: bool,
    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
    presentation: NavPresentation,
    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
    /// changes it — push, pop and select alike — so a re-present can carry it across.
    selected: usize,
    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
    /// labeled from the same rows the sidebar's outline view shows; a pick emits
    /// `SelectionChanged` against the same NAV_MENU node.
    tabs: Option<TabHost>,
    /// Back header (stack presentation only).
    header: Option<NavHeader>,
    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
    /// with the same root title the initial build would have used.
    root_title: String,
    /// The host's node, for the same reason — a back header's button targets it.
    node: NodeId,
    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
    /// of a pinned window.
    title_strip: f64,
}

/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
/// view Day's pages and the rest of this backend frame themselves against) inside it.
///
/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
/// first strip of every page instead, blurring a detail page's heading. The host is framed up
/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
    let pane = view_of(DayFlipped::new(mtm));
    unsafe {
        wrap.setFrame(pane.bounds());
        wrap.setAutoresizingMask(
            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
        );
        pane.addSubview(wrap);
    }
    pane
}

/// Hold `wrap` `strip` points below the top of the pane that holds it.
fn place_below_strip(wrap: &NSView, strip: f64) {
    let Some(pane) = (unsafe { wrap.superview() }) else {
        return;
    };
    let b = pane.bounds();
    unsafe {
        wrap.setFrame(NSRect::new(
            NSPoint::new(0.0, strip),
            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
        ))
    };
}

/// The stack presentation's back header: a chevron + centered title docked above the pages,
/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
/// way out (docs/navigation.md).
///
/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
/// gets would be a second shape to keep in step.
fn build_nav_header(
    mtm: MainThreadMarker,
    id: NodeId,
    detail_wrap: &NSView,
    root_title: &str,
) -> NavHeader {
    let bar = view_of(DayFlipped::new(mtm));
    let target = DayTarget::new(mtm, id);
    let back = unsafe {
        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
        // on every macOS release this backend builds for.
        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
            .expect("NSGoBackTemplate");
        let tobj: &objc2::runtime::AnyObject = target.as_ref();
        objc2_app_kit::NSButton::buttonWithImage_target_action(
            &img,
            Some(tobj),
            Some(sel!(navBack:)),
            mtm,
        )
    };
    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
    unsafe {
        back.setFrame(NSRect::new(
            NSPoint::new(6.0, 4.0),
            NSSize::new(30.0, NAV_HEADER_H - 8.0),
        ));
        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
        title.setFrame(NSRect::new(
            NSPoint::new(44.0, 9.0),
            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
        ));
        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
        bar.setFrame(NSRect::new(
            NSPoint::new(0.0, 0.0),
            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
        ));
        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
        bar.addSubview(&back);
        bar.addSubview(&title);
        bar.setHidden(true);
        detail_wrap.addSubview(&bar);
    }
    NavHeader {
        bar,
        title,
        titles: vec![root_title.to_string()],
        _target: target,
    }
}

/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
/// `NSTabView`, never through here.)
fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
    let b = wrap.bounds();
    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
    NSRect::new(
        NSPoint::new(0.0, top),
        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
    )
}

/// The row titles and the NAV_MENU node of the menu inside `page`, if it has one.
///
/// The tab bar needs the same rows the sidebar shows, and they arrive at the NAV_MENU rather
/// than at the host. Rather than plumb a second copy through the props, this walks down to the
/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
/// handful of views — and reads the titles it has stored for its own outline view.
fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
        if out.is_some() {
            return;
        }
        let found = NAV_MENUS.with(|m| {
            m.borrow()
                .get(&(v as *const NSView as usize))
                .map(|(_, d)| {
                    let ivars = d.ivars();
                    (
                        ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
                        ivars.node,
                    )
                })
        });
        if found.is_some() {
            *out = found;
            return;
        }
        for sub in unsafe { v.subviews() }.iter() {
            walk(&sub, out);
        }
    }
    let mut out = None;
    walk(page, &mut out);
    out
}

/// Apply a presentation to the sidebar split item. All four are the same item at a different
/// thickness or collapsed outright, which is why a morph never rebuilds the split.
fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
    unsafe {
        item.setCanCollapse(shown);
        item.setCollapsed(!shown);
        match pres {
            NavPresentation::Split => {
                item.setAllowsFullHeightLayout(true);
                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
            }
            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
            // destinations, and a source list pinned to icon width just truncates every row to an
            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
            NavPresentation::Rail => {
                item.setAllowsFullHeightLayout(true);
                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
            }
            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
            // minimum width and the detail never reaches the window edge.
            NavPresentation::Stack | NavPresentation::Tabs => {
                item.setMinimumThickness(0.0);
                item.setMaximumThickness(0.0);
            }
        }
    }
}

/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
/// The split view of the navigation host in `window` that has a content-list pane, for the
/// tracking separator pinned to its second divider (docs/toolbars.md).
pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
    NAV_STATE.with(|m| {
        m.borrow()
            .values()
            .find(|st| {
                st.list_item.is_some()
                    && st
                        .sidebar_wrap
                        .window()
                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
            })
            .map(|st| unsafe { st._split_vc.splitView() })
    })
}

fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
    let visible = pages.len() >= 2;
    hdr.bar.setHidden(!visible);
    unsafe {
        hdr.title.setStringValue(&NSString::from_str(
            hdr.titles.last().map(String::as_str).unwrap_or(""),
        ));
    }
    let frame = nav_page_frame(wrap, visible);
    for page in pages {
        unsafe { page.setFrame(frame) };
    }
}

/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
/// chrome changes but the pages do not.
///
/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
/// touches a page's CONTENT:
///
/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
///    separator on its own),
/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
/// 3. the back header appears or hides, since only a stack has one.
///
/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
/// its scroll position, and its first responder across the move.
fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
        NAV_STATE.with(|m| {
            let st = m.borrow();
            let s = st.get(&ptr_of(host))?;
            Some((
                s.sidebar_page.clone(),
                s.detail_wrap.clone(),
                s.sidebar_wrap.clone(),
                s.sidebar_item.clone(),
                s.presentation,
                s.root_title.clone(),
                s.node,
                s.selected,
            ))
        })
    else {
        return;
    };
    if was == next {
        return;
    }
    apply_sidebar_item(&sidebar_item, next);
    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
    // split view as needing layout; without this the pane keeps its old width for one more frame,
    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
    NAV_STATE.with(|m| {
        if let Some(s) = m.borrow().get(&ptr_of(host)) {
            unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
        }
    });
    // A stack needs a back header; nothing else may show one. Built on demand and kept
    // afterwards — rebuilding it on every morph would leak a target per crossing.
    let stacked = next == NavPresentation::Stack;
    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
    if stacked && header.is_none() {
        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
    }
    if let Some(hdr) = header.as_ref() {
        hdr.bar.setHidden(true);
    }
    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
    // off), resolved the same at every width, so a host never morphs into or out of it — its
    // `NSTabView` is built at realize and lives for the host.
    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
    // shifts every index past it, so an index captured now would name the wrong page after.
    let mut pages = NAV_STATE.with(|m| {
        m.borrow()
            .get(&ptr_of(host))
            .map(|s| s.pages.clone())
            .unwrap_or_default()
    });
    let shown_page = pages.get(sel).cloned();
    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
    if let Some(page) = sidebar_page {
        pages.retain(|p| ptr_of(p) != ptr_of(&page));
        unsafe {
            if stacked {
                detail_wrap.addSubview(&page);
                pages.insert(0, page.clone());
            } else {
                page.setFrame(sidebar_wrap.bounds());
                sidebar_wrap.addSubview(&page);
            }
        }
        // A pane always shows its page; as a stack root it may have been hidden under a push.
        page.setHidden(false);
    }
    let shown = shown_page
        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
        .unwrap_or_else(|| pages.len().saturating_sub(1));
    for (i, page) in pages.iter().enumerate() {
        page.setHidden(i != shown);
    }
    NAV_STATE.with(|m| {
        let mut m = m.borrow_mut();
        if let Some(s) = m.get_mut(&ptr_of(host)) {
            s.presentation = next;
            s.pages = pages;
            s.selected = shown;
            s.header = header;
            if let Some(hdr) = s.header.as_ref() {
                // Depth drives visibility, and the header is meaningless anywhere but a stack.
                if stacked {
                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
                } else {
                    hdr.bar.setHidden(true);
                }
            }
            if !stacked {
                // Leaving the stack: the pages were inset below the header, so give them the
                // pane back.
                let frame = nav_page_frame(&s.detail_wrap, false);
                for page in &s.pages {
                    unsafe { page.setFrame(frame) };
                }
            }
        }
    });
}

// ---------------------------------------------------------------------------
// The sidebar pane holds its width through NSSplitViewController's own holding priorities
// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
// split's delegate, so Day must not install one of its own.
// ---------------------------------------------------------------------------

struct CoverSheet(Retained<NSWindow>);
impl Drop for CoverSheet {
    fn drop(&mut self) {
        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
        // core's tree borrow has ended; this retained pointer travels only to the main queue.
        let raw = Retained::into_raw(self.0.clone()) as usize;
        dispatch2::DispatchQueue::main().exec_async(move || {
            ffi_guard::contain((), || unsafe {
                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
                if let Some(parent) = window.sheetParent() {
                    parent.endSheet(&window);
                }
                window.orderOut(None);
                window.setContentView(None);
            });
        });
    }
}
struct NavPageIvars {
    node: NodeId,
    /// A presented cover's strip under the window's title bar: the page paints it (its frame
    /// starts above the layout area) but lays its content out below it, and reports the
    /// remaining height (see `pin_below_title_bar`).
    top_inset: Cell<f64>,
    sheet: Cell<bool>,
    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
    half: Cell<bool>,
}

define_class!(
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayNavPage"]
    #[ivars = NavPageIvars]
    struct DayNavPage;

    impl DayNavPage {
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        #[unsafe(method(setFrameSize:))]
        fn set_frame_size(&self, size: NSSize) {
            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
            // Pane-driven resize (splitter drag, window resize): report the usable size
            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
            ffi_guard::contain((), || {
                let inset = self.ivars().top_inset.get();
                emit(
                    self.ivars().node,
                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
                );
            })
        }
    }
);

impl DayNavPage {
    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
            node,
            top_inset: Cell::new(0.0),
            sheet: Cell::new(false),
            half: Cell::new(false),
        });
        unsafe { msg_send![super(this), init] }
    }
}

// ---------------------------------------------------------------------------
// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
// surface: its own backing material, the standard thickness handling, full-height layout
// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
// user-collapsed), so this backend never emits `Event::InspectorChanged`.
// ---------------------------------------------------------------------------

struct InspectorState {
    content_wrap: Handle,
    panel_wrap: Handle,
    /// Retained so the controller (the split's delegate) lives as long as its split.
    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
}

// ---------------------------------------------------------------------------
// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
// subviews as the panes, and a delegate that places the divider by the bound share, keeps
// both panes above the minimum, and reports a drag back as the new share.
// ---------------------------------------------------------------------------

struct SplitState {
    split: Retained<objc2_app_kit::NSSplitView>,
    first_wrap: Handle,
    second_wrap: Handle,
    delegate: Retained<DaySplitDelegate>,
}

struct SplitDelegateIvars {
    node: NodeId,
    min_pane: f64,
    /// The share as last patched or reported: what a report is compared against, and where
    /// the divider goes when the split first has a size or turns.
    share: Cell<f64>,
    /// The divider has been placed once; before that the split has no size to place it in.
    positioned: Cell<bool>,
    /// Day is moving the divider itself: the resize that follows is not a report.
    suppress: Cell<bool>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DaySplitDelegate"]
    #[ivars = SplitDelegateIvars]
    struct DaySplitDelegate;

    unsafe impl NSObjectProtocol for DaySplitDelegate {}

    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
        #[unsafe(method(splitViewDidResizeSubviews:))]
        fn did_resize(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                let Some(obj) = notification.object() else {
                    return;
                };
                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
                    return;
                };
                let iv = self.ivars();
                let usable = split_usable(&sv);
                if usable <= 0.0 {
                    return;
                }
                // The first resize with a size: place the divider by the share, once.
                if !iv.positioned.replace(true) {
                    split_place(&sv, iv);
                    return;
                }
                if iv.suppress.get() {
                    return;
                }
                let Some(first) = sv.subviews().iter().next() else {
                    return;
                };
                let f = first.frame();
                let a = if sv.isVertical() {
                    f.size.width
                } else {
                    f.size.height
                };
                let share = (a / usable).clamp(0.0, 1.0);
                if (share - iv.share.get()).abs() > 1e-4 {
                    iv.share.set(share);
                    emit(iv.node, Event::ValueChanged(share));
                }
            })
        }

        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
        fn constrain_min(
            &self,
            _sv: &objc2_app_kit::NSSplitView,
            proposed: f64,
            _index: isize,
        ) -> f64 {
            proposed.max(self.ivars().min_pane)
        }

        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
        fn constrain_max(
            &self,
            sv: &objc2_app_kit::NSSplitView,
            proposed: f64,
            _index: isize,
        ) -> f64 {
            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
        }
    }
);

impl DaySplitDelegate {
    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
            node,
            min_pane,
            share: Cell::new(share.clamp(0.0, 1.0)),
            positioned: Cell::new(false),
            suppress: Cell::new(false),
        });
        unsafe { msg_send![super(this), init] }
    }
}

/// The length the two panes share along the split's axis: the frame minus the divider.
fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
    let frame = sv.frame();
    let len = if sv.isVertical() {
        frame.size.width
    } else {
        frame.size.height
    };
    (len - sv.dividerThickness()).max(0.0)
}

/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
    let usable = split_usable(sv);
    if usable <= 0.0 {
        return;
    }
    iv.suppress.set(true);
    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
    iv.suppress.set(false);
}

// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
// ---------------------------------------------------------------------------

struct NavMenuIvars {
    node: NodeId,
    items: RefCell<Vec<Retained<NSString>>>,
    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
    /// Template images tint with the source-list's selection/appearance, so they read in light,
    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
    icon_fills: RefCell<Vec<f64>>,
    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
    /// `None` keeps the source-list's neutral template tint.
    tints: RefCell<Vec<Option<day_spec::Color>>>,
    /// Trailing accessory per item row (an unread count), `None` where a row has none.
    badges: RefCell<Vec<Option<Retained<NSString>>>>,
    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
    badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
    /// Per-row context menu (docs/menus.md), empty = none. Built into an NSMenu and attached
    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
    movable: RefCell<Vec<bool>>,
    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
    regroup: std::cell::Cell<bool>,
    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
    sorted: RefCell<Vec<bool>>,
    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
    /// goes through this map — a header must never shift what index 3 means.
    rows: RefCell<Vec<Option<usize>>>,
    /// One retained NSString per outline row: the row's text (a header's or an item's).
    row_objects: RefCell<Vec<Retained<NSString>>>,
    /// One NSNumber per outline row, holding the row's index: the outline's item IDENTITY.
    /// NSOutlineView matches items with `isEqual:`, so an NSString cannot be the identity —
    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
    row_ids: RefCell<Vec<Retained<NSNumber>>>,
    /// Programmatic selection in flight: don't re-emit SelectionChanged.
    suppress: std::cell::Cell<bool>,
}

struct NavCellIvars {
    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
    /// label ends before them.
    accessory: RefCell<Option<Retained<NSView>>>,
    /// The unread count among them, sized to follow the row's text.
    count: RefCell<Option<Retained<NSTextField>>>,
    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
    icon_fill: std::cell::Cell<f64>,
}

define_class!(
    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
    /// which AppKit knows nothing about.
    #[unsafe(super(objc2_app_kit::NSTableCellView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayNavCell"]
    #[ivars = NavCellIvars]
    struct DayNavCell;

    unsafe impl NSObjectProtocol for DayNavCell {}

    impl DayNavCell {
        #[unsafe(method(layout))]
        fn layout(&self) {
            let _: () = unsafe { msg_send![super(self), layout] };
            ffi_guard::contain((), || self.fit_accessories());
        }
    }
);

impl DayNavCell {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
            accessory: RefCell::new(None),
            count: RefCell::new(None),
            icon_fill: std::cell::Cell::new(1.0),
        });
        unsafe { msg_send![super(this), init] }
    }

    /// After AppKit's layout: the count takes a size two points under the label's, and the
    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
    /// accessories so a long title truncates instead of running under its count. A showing
    /// progress ring re-fits the icon AppKit just sized.
    fn fit_accessories(&self) {
        let label = unsafe { self.textField() };
        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
                (f.pointSize() - 2.0).max(9.0)
            });
            if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
                unsafe {
                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
                        size,
                        objc2_app_kit::NSFontWeightRegular,
                    )));
                }
                self.layoutSubtreeIfNeeded();
            }
        }
        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
            let mut frame = label.frame();
            let end = accessory.frame().origin.x - 6.0;
            if frame.origin.x + frame.size.width > end {
                frame.size.width = (end - frame.origin.x).max(0.0);
                label.setFrame(frame);
            }
        }
        if let Some(icon) = unsafe { self.imageView() } {
            fit_nav_icon(&icon, self.ivars().icon_fill.get());
            nav_progress::fit(&icon);
        }
    }
}

thread_local! {
    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
}

/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
/// setting and whatever a later macOS draws.
fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
        return;
    };
    let slot = icon.frame();
    // Configurations compare by value, and AppKit gives every cell of a row size style an
    // equal one, so the hash names the style.
    let key = config.hash() as u64;
    let side = NAV_GLYPH_SIDES
        .with(|m| m.borrow().get(&key).copied())
        .or_else(|| {
            let symbol =
                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
                    &NSString::from_str("gearshape"),
                    None,
                )?;
            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
            Some(side)
        });
    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
    // the margin of its grid inside the box, so its box is that much larger.
    let Some(side) = side
        .filter(|s| *s > 0.0)
        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
    else {
        return;
    };
    if slot.size.width <= side && slot.size.height <= side {
        return;
    }
    icon.setFrame(NSRect::new(
        NSPoint::new(
            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
        ),
        NSSize::new(side, side),
    ));
}

define_class!(
    #[unsafe(super(objc2_app_kit::NSTableRowView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayNavRowView"]
    struct DayNavRowView;

    unsafe impl NSObjectProtocol for DayNavRowView {}

    impl DayNavRowView {
        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
        /// whose window never becomes key (scripted screenshot captures) falls back to the
        /// unemphasized selection fill, which under a forced appearance rendered as a
        /// near-black pill that swallowed the row's label.
        #[unsafe(method(isEmphasized))]
        fn is_emphasized(&self) -> bool {
            true
        }
    }
);

define_class!(
    #[unsafe(super(objc2_app_kit::NSOutlineView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayNavOutlineView"]
    struct DayNavOutlineView;

    unsafe impl NSObjectProtocol for DayNavOutlineView {}

    impl DayNavOutlineView {
        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
        /// right-clicks themselves, so per-row menus are served here — resolve the row under
        /// the click, then build the same NSMenu the piece decorator would.
        #[unsafe(method_id(menuForEvent:))]
        fn menu_for_event(
            &self,
            event: &objc2_app_kit::NSEvent,
        ) -> Option<Retained<NSMenu>> {
            ffi_guard::contain(None, || {
                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
                let row = unsafe { self.rowAtPoint(point) };
                let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
                // `define_class!` rewrites the return, so no early `return` — one expression.
                match data {
                    None => None,
                    Some(d) => {
                        let items = d
                            .item_of_row(row)
                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
                            .unwrap_or_default();
                        if items.is_empty() {
                            None
                        } else {
                            Some(build_ns_menu(d.mtm(), "", &items))
                        }
                    }
                }
            })
        }
    }
);

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayNavMenuData"]
    #[ivars = NavMenuIvars]
    struct DayNavMenuData;

    unsafe impl NSObjectProtocol for DayNavMenuData {}

    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
        fn number_of_children(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: Option<&objc2::runtime::AnyObject>,
        ) -> isize {
            if item.is_none() {
                self.ivars().row_objects.borrow().len() as isize
            } else {
                0
            }
        }

        #[unsafe(method_id(outlineView:child:ofItem:))]
        fn child_of_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            index: isize,
            _item: Option<&objc2::runtime::AnyObject>,
        ) -> Retained<objc2::runtime::AnyObject> {
            let ids = self.ivars().row_ids.borrow();
            // AppKit only asks for children it was told exist, but a stale query racing a
            // reload must degrade (an unmatched identity) rather than index out of bounds —
            // a panic here unwinds into an ObjC frame and aborts.
            let id = ids
                .get(index as usize)
                .cloned()
                .unwrap_or_else(|| NSNumber::new_isize(-1));
            unsafe { objc2::rc::Retained::cast_unchecked(id) }
        }

        #[unsafe(method(outlineView:isItemExpandable:))]
        fn is_expandable(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            _item: &objc2::runtime::AnyObject,
        ) -> bool {
            false
        }

        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
        // moves within the run of movable rows around it, or, regrouping, into any section of
        // movable rows (`regroup_gap`); the app's data change brings the new order back as
        // `NavMenuPatch::Items`.

        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
        fn pasteboard_writer_for_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
            let make = || {
                let row = Self::outline_row(item);
                let index = self.item_of_row(row)?;
                if !self.is_movable(index) {
                    return None;
                }
                let pbitem = objc2_app_kit::NSPasteboardItem::new();
                unsafe {
                    pbitem.setString_forType(
                        &NSString::from_str(&row.to_string()),
                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
                    );
                }
                Some(ProtocolObject::from_retained(pbitem))
            };
            ffi_guard::contain(None, make)
        }

        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
        fn validate_drop(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
            item: Option<&objc2::runtime::AnyObject>,
            child_index: isize,
        ) -> objc2_app_kit::NSDragOperation {
            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
                    return objc2_app_kit::NSDragOperation::None;
                };
                // A drop past the run's end lands at that end: move the gap there.
                if drop.retarget {
                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
                }
                objc2_app_kit::NSDragOperation::Move
            })
        }

        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
        fn accept_drop(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
            item: Option<&objc2::runtime::AnyObject>,
            child_index: isize,
        ) -> bool {
            ffi_guard::contain(false, || {
                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
                    return false;
                };
                // Deferred through the event queue: the app's callback never runs inside
                // AppKit's drop, and its data change reloads the rows in the new order.
                match drop.moves {
                    Some(NavMove::Reorder { from, to }) => {
                        emit(self.ivars().node, Event::ListReorder { from, to });
                    }
                    Some(NavMove::Regroup {
                        from,
                        section,
                        before,
                    }) => emit(
                        self.ivars().node,
                        Event::NavRegroup {
                            from,
                            section,
                            before,
                        },
                    ),
                    None => {}
                }
                true
            })
        }
    }

    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}

    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
        /// secondary) comes free, and they are excluded from selection below.
        #[unsafe(method(outlineView:isGroupItem:))]
        fn is_group_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> bool {
            let row = Self::outline_row(item);
            row >= 0 && self.item_of_row(row).is_none()
        }

        #[unsafe(method(outlineView:shouldSelectItem:))]
        fn should_select(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> bool {
            self.item_of_row(Self::outline_row(item)).is_some()
        }

        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
        fn view_for(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            _col: Option<&objc2_app_kit::NSTableColumn>,
            item: &objc2::runtime::AnyObject,
        ) -> Option<Retained<NSView>> {
            let mtm = self.mtm();
            let row = Self::outline_row(item);
            let text = self
                .ivars()
                .row_objects
                .borrow()
                .get(usize::try_from(row).unwrap_or(usize::MAX))
                .cloned();
            // No early returns: the method_id macro owns the return conversion.
            text.map(|text| {
                let text: &NSString = &text;
                let Some(index) = self.item_of_row(row) else {
                    // A section header: a plain label. AppKit gives group rows their own
                    // typography and places the text, so this only supplies it.
                    let cell = DayNavCell::new(mtm);
                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
                    unsafe {
                        label.cell().inspect(|c| {
                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
                        });
                        cell.addSubview(&label);
                        cell.setTextField(Some(&label));
                    }
                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
                };
                let icon = self
                    .ivars()
                    .icons
                    .borrow()
                    .get(index)
                    .and_then(|o| o.clone());
                let badge = self
                    .ivars()
                    .badges
                    .borrow()
                    .get(index)
                    .and_then(|o| o.clone());
                let badge_icon = self
                    .ivars()
                    .badge_icons
                    .borrow()
                    .get(index)
                    .and_then(|o| o.clone());
                let badge_tint = self
                    .ivars()
                    .badge_tints
                    .borrow()
                    .get(index)
                    .copied()
                    .flatten();
                // The cell places the icon and the label itself, at the row size style's size
                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
                // trailing accessories.
                let cell = DayNavCell::new(mtm);
                let label = unsafe { NSTextField::labelWithString(text, mtm) };
                unsafe {
                    // Feed titles are arbitrarily long, so the label truncates with an
                    // ellipsis within the frame the cell gives it.
                    label.cell().inspect(|c| {
                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
                    });
                    cell.addSubview(&label);
                    cell.setTextField(Some(&label));
                    // The badge sits at the trailing edge and keeps its intrinsic width; the
                    // label truncates into whatever is left, so a long feed name never pushes
                    // its own unread count off the pane.
                    // Both accessories share the trailing slot: the count (if any) and then
                    // the status glyph (if any), in a stack so a row can carry either or both
                    // without the constraints below caring which it got.
                    let accessory = objc2_app_kit::NSStackView::new(mtm);
                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
                    accessory.setOrientation(
                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
                    );
                    accessory.setSpacing(4.0);
                    let mut has_accessory = false;
                    let trailing: Retained<NSView> = match &badge {
                        Some(text) => {
                            let b = NSTextField::labelWithString(text, mtm);
                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
                            b.setFont(Some(
                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
                                    objc2_app_kit::NSFont::smallSystemFontSize(),
                                    objc2_app_kit::NSFontWeightRegular,
                                ),
                            ));
                            b.setContentCompressionResistancePriority_forOrientation(
                                objc2_app_kit::NSLayoutPriorityRequired,
                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
                            );
                            *cell.ivars().count.borrow_mut() = Some(b.clone());
                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
                                objc2::rc::Retained::into_super(b),
                            ));
                            has_accessory = true;
                            let v: Retained<NSView> =
                                objc2::rc::Retained::into_super(accessory.clone());
                            v
                        }
                        None => objc2::rc::Retained::into_super(accessory.clone()),
                    };
                    // The status glyph, tinted where the app gave it a meaning-bearing color
                    // (a star is yellow because that is what a star IS, not because the theme
                    // says so). Template images take contentTintColor exactly as the row's
                    // leading icon does.
                    if let Some(img) = &badge_icon {
                        let iv = objc2_app_kit::NSImageView::new(mtm);
                        iv.setImage(Some(img));
                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
                        if let Some(c) = badge_tint {
                            iv.setContentTintColor(Some(&nscolor(c)));
                        }
                        iv.setContentCompressionResistancePriority_forOrientation(
                            objc2_app_kit::NSLayoutPriorityRequired,
                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
                        );
                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
                        has_accessory = true;
                    }
                    cell.addSubview(&trailing);
                    if has_accessory {
                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
                    }
                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
                        &objc2_foundation::NSArray::from_retained_slice(&[
                            trailing
                                .trailingAnchor()
                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
                            trailing
                                .centerYAnchor()
                                .constraintEqualToAnchor(&cell.centerYAnchor()),
                        ]),
                    );
                }
                if let Some(img) = icon {
                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
                    unsafe {
                        iv.setImage(Some(&img));
                        // Per-row tint (docs/vectors.md): the icons are template images, so
                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
                        if let Some(t) = tint {
                            iv.setContentTintColor(Some(&nscolor(t)));
                        }
                        iv.setImageScaling(
                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
                        );
                        cell.addSubview(&iv);
                        cell.setImageView(Some(&iv));
                        let progress = self
                            .ivars()
                            .icon_progress
                            .borrow()
                            .iter()
                            .find(|(row, _)| *row == index)
                            .map(|(_, f)| *f);
                        nav_progress::update(&iv, progress);
                    }
                }
                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
            })
        }

        #[unsafe(method_id(outlineView:rowViewForItem:))]
        fn row_view_for(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            _item: &objc2::runtime::AnyObject,
        ) -> Retained<objc2_app_kit::NSTableRowView> {
            let row: Retained<DayNavRowView> =
                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
            objc2::rc::Retained::into_super(row)
        }

        #[unsafe(method(outlineViewSelectionDidChange:))]
        fn selection_did_change(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                if self.ivars().suppress.get() {
                    return;
                }
                let Some(obj) = (unsafe { notification.object() }) else {
                    return;
                };
                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
                    return;
                };
                let row = unsafe { ov.selectedRow() };
                if let Some(item) = self.item_of_row(row) {
                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
                }
            })
        }
    }
);

thread_local! {
    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
    /// icon's drawing does not change with them.
    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
}

/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
fn nav_icon_fills(
    names: &[Option<String>],
    images: &[Option<Retained<objc2_app_kit::NSImage>>],
) -> Vec<f64> {
    names
        .iter()
        .zip(images)
        .map(|(name, image)| match (name, image) {
            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
                *m.borrow_mut()
                    .entry(name.clone())
                    .or_insert_with(|| nav_icon_fill(image))
            }),
            _ => 1.0,
        })
        .collect()
}

/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
/// one small render, since a plain SVG says nothing about where its drawing sits.
fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
    const PX: f64 = 64.0;
    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
        return 1.0;
    };
    let (w, h) = (
        rep.pixelsWide().max(0) as usize,
        rep.pixelsHigh().max(0) as usize,
    );
    let stride = rep.bytesPerRow().max(0) as usize;
    let data = unsafe { rep.bitmapData() };
    if data.is_null() || stride < w * 4 {
        return 1.0;
    }
    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
    // `rep` owns and keeps alive for this borrow.
    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
    for y in 0..h {
        for x in 0..w {
            if bytes[y * stride + x * 4 + 3] > 24 {
                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
            }
        }
    }
    if x1 <= x0 || y1 <= y0 {
        return 1.0;
    }
    // The render stretched the image to a square; back in the image's own proportions, the
    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
    let size = image.size();
    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
}

fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
    icons
        .iter()
        .map(|ic| {
            let name = ic.as_deref()?;
            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
            let path = day_spec::resource::resolve_vector_svg(name)
                .or_else(|| day_spec::resource::resolve_image_file(name))?;
            use objc2::AllocAnyThread as _;
            let img = unsafe {
                objc2_app_kit::NSImage::initWithContentsOfFile(
                    objc2_app_kit::NSImage::alloc(),
                    &NSString::from_str(&path.to_string_lossy()),
                )
            }?;
            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
            Some(img)
        })
        .collect()
}

impl DayNavMenuData {
    #[allow(clippy::too_many_arguments)]
    fn new(
        mtm: MainThreadMarker,
        node: NodeId,
        items: &[String],
        icons: &[Option<String>],
        badges: &[Option<String>],
        badge_icons: &[Option<String>],
        badge_tints: &[Option<day_spec::Color>],
        sections: &[Option<String>],
        tints: &[Option<day_spec::Color>],
        menus: &[Vec<day_spec::MenuItem>],
    ) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
            node,
            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
            icons: RefCell::new(resolve_nav_icons(icons)),
            tints: RefCell::new(tints.to_vec()),
            menus: RefCell::new(menus.to_vec()),
            movable: RefCell::new(Vec::new()),
            regroup: std::cell::Cell::new(false),
            sorted: RefCell::new(Vec::new()),
            badges: RefCell::new(ns_badges(badges)),
            icon_progress: RefCell::new(Vec::new()),
            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
            badge_tints: RefCell::new(badge_tints.to_vec()),
            rows: RefCell::new(Vec::new()),
            row_objects: RefCell::new(Vec::new()),
            row_ids: RefCell::new(Vec::new()),
            suppress: std::cell::Cell::new(false),
        });
        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
        this.rebuild_rows(items, sections);
        this
    }

    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
    // landing in its own ivar. Bundling them would just move the same eight fields.
    #[allow(clippy::too_many_arguments)]
    fn set_items(
        &self,
        items: &[String],
        icons: &[Option<String>],
        badges: &[Option<String>],
        badge_icons: &[Option<String>],
        badge_tints: &[Option<day_spec::Color>],
        sections: &[Option<String>],
        tints: &[Option<day_spec::Color>],
        menus: &[Vec<day_spec::MenuItem>],
    ) {
        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
        let resolved = resolve_nav_icons(icons);
        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
        *self.ivars().icons.borrow_mut() = resolved;
        *self.ivars().tints.borrow_mut() = tints.to_vec();
        *self.ivars().menus.borrow_mut() = menus.to_vec();
        *self.ivars().badges.borrow_mut() = ns_badges(badges);
        self.ivars().icon_progress.borrow_mut().clear();
        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
        self.rebuild_rows(items, sections);
    }

    /// Flatten items + section headers into the outline's display rows. Each row gets its own
    /// retained NSString so the outline can tell two rows apart by identity even when their
    /// labels match (two feeds legitimately share a title).
    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
        let mut rows = Vec::with_capacity(items.len());
        let mut objects = Vec::with_capacity(items.len());
        for (i, label) in items.iter().enumerate() {
            if let Some(Some(header)) = sections.get(i) {
                rows.push(None);
                objects.push(NSString::from_str(header));
            }
            rows.push(Some(i));
            objects.push(NSString::from_str(label));
        }
        let ids = (0..objects.len())
            .map(|i| NSNumber::new_isize(i as isize))
            .collect();
        *self.ivars().rows.borrow_mut() = rows;
        *self.ivars().row_objects.borrow_mut() = objects;
        *self.ivars().row_ids.borrow_mut() = ids;
    }

    /// The outline row an item object names — the index its NSNumber identity carries — or
    /// `-1` for anything that is not one of ours (a stale query racing a reload).
    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
        item.downcast_ref::<NSNumber>()
            .map(|n| n.integerValue())
            .unwrap_or(-1)
    }

    /// Outline row → day item index.
    fn item_of_row(&self, row: isize) -> Option<usize> {
        if row < 0 {
            return None;
        }
        self.ivars()
            .rows
            .borrow()
            .get(row as usize)
            .copied()
            .flatten()
    }

    /// Day item index → outline row.
    fn row_of_item(&self, item: usize) -> Option<usize> {
        self.ivars()
            .rows
            .borrow()
            .iter()
            .position(|r| *r == Some(item))
    }

    fn is_movable(&self, item: usize) -> bool {
        self.ivars()
            .movable
            .borrow()
            .get(item)
            .copied()
            .unwrap_or(false)
    }

    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
    fn nav_drop(
        &self,
        ov: &objc2_app_kit::NSOutlineView,
        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
        item: Option<&objc2::runtime::AnyObject>,
        child_index: isize,
    ) -> Option<NavDrop> {
        let src = unsafe { info.draggingSource() }?;
        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
        {
            return None;
        }
        let pb = unsafe { info.draggingPasteboard() };
        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
            .to_string()
            .parse::<usize>()
            .ok()?;
        let rows = self.ivars().rows.borrow();
        // The flat outline proposes a gap among the root's children, or a row itself (a drop
        // ONTO it, index -1).
        let proposed = match item {
            Some(item) => Self::outline_row(item),
            None => child_index,
        };
        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
        if self.ivars().regroup.get() {
            regroup_gap(
                &rows,
                &self.ivars().movable.borrow(),
                &self.ivars().sorted.borrow(),
                from_row,
                proposed,
                item.is_some(),
            )
        } else {
            reorder_gap(
                &rows,
                &self.ivars().movable.borrow(),
                from_row,
                proposed,
                item.is_some(),
            )
        }
    }
}

/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct NavDrop {
    /// The gap the row drops into, among the outline's rows.
    gap: usize,
    /// The proposal named some other place, and the gap moves here.
    retarget: bool,
    /// What the drop reports, or `None` for a drop back in place.
    moves: Option<NavMove>,
}

/// What a sidebar drop reports, in item indices (the rows before the move).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NavMove {
    /// `Event::ListReorder`: `from` takes `to`'s place.
    Reorder { from: usize, to: usize },
    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
    /// `before` or at the section's end.
    Regroup {
        from: usize,
        section: usize,
        before: Option<usize>,
    },
}

/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
/// one, which section headers and fixed rows end. `None` when that row cannot move.
fn reorder_gap(
    rows: &[Option<usize>],
    movable: &[bool],
    from_row: usize,
    proposed: usize,
    onto: bool,
) -> Option<NavDrop> {
    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
    let in_run = |r: usize| rows[r].is_some_and(is_movable);
    let first = (0..from_row)
        .rev()
        .take_while(|r| in_run(*r))
        .last()
        .unwrap_or(from_row);
    let last = (from_row + 1..rows.len())
        .take_while(|r| in_run(*r))
        .last()
        .unwrap_or(from_row);
    let gap = proposed.clamp(first, last + 1);
    // The row's place once it has left its own: the row whose position it takes.
    let target_row = if gap > from_row { gap - 1 } else { gap };
    let moves = (target_row != from_row)
        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
        .flatten();
    Some(NavDrop {
        gap,
        retarget: gap != proposed || onto,
        moves,
    })
}

/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
/// is the nearest header above it, or the rows above the first header; `before` is the item
/// right below the gap when that row is in the same section. A drop ONTO a header reads as
/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
/// move, the gap is above the first header with no rows there, the section holds a fixed row,
/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
fn regroup_gap(
    rows: &[Option<usize>],
    movable: &[bool],
    sorted: &[bool],
    from_row: usize,
    proposed: usize,
    onto: bool,
) -> Option<NavDrop> {
    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
    let gap = match rows.get(proposed) {
        Some(None) if onto => proposed + 1,
        _ => proposed.min(rows.len()),
    };
    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
        Some(header) => Some(header + 1),
        None => rows.first().copied().flatten().map(|_| 0),
    };
    let first = section_start(gap)?;
    let end = (first..rows.len())
        .find(|r| rows[*r].is_none())
        .unwrap_or(rows.len());
    let section = rows.get(first).copied().flatten()?;
    if !rows[first..end]
        .iter()
        .all(|r| r.is_some_and(|i| flag(movable, i)))
    {
        return None;
    }
    let own = section_start(from_row) == Some(first);
    if own && flag(sorted, from) {
        return None;
    }
    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
        from,
        section,
        before: rows.get(gap).copied().flatten(),
    });
    Some(NavDrop {
        gap,
        retarget: gap != proposed || onto,
        moves,
    })
}

#[cfg(test)]
mod nav_gap_tests {
    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};

    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
    const ROWS: [Option<usize>; 10] = [
        Some(0),
        None,
        Some(1),
        Some(2),
        Some(3),
        None,
        Some(4),
        Some(5),
        None,
        Some(6),
    ];
    /// The feeds move; today and starred are fixed.
    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
    const UNSORTED: [bool; 7] = [false; 7];

    fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
        Some(NavMove::Regroup {
            from,
            section,
            before,
        })
    }

    #[test]
    fn regroup_gaps_name_the_section_above_and_the_row_below() {
        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
        // a, into tech's first gap: before c.
        assert_eq!(
            at(2, 6),
            Some(NavDrop {
                gap: 6,
                retarget: false,
                moves: regroup(1, 4, Some(4)),
            })
        );
        // c, into the gap above tech's header: the end of news.
        assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
        // a, between c and d, and at tech's end above smart's header.
        assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
        assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
    }

    #[test]
    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
        // Smart holds starred, and the rows above the first header hold today.
        for gap in [0, 1, 9, 10] {
            assert_eq!(at(2, gap), None, "gap {gap}");
        }
        // A sorted row's own section offers no gap, its own place included.
        for gap in [2, 3, 4, 5] {
            assert_eq!(at(2, gap), None, "gap {gap}");
        }
        // Fixed rows and headers never drag.
        assert_eq!(at(0, 6), None);
        assert_eq!(at(1, 6), None);
        assert_eq!(at(9, 6), None);
    }

    #[test]
    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
        // a, between b and e.
        assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
        // a, at news's end above tech's header.
        assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
        // Back in place, either side of itself: a drop that reports nothing.
        for gap in [2, 3] {
            let drop = at(2, gap).expect("offered");
            assert_eq!(drop.moves, None, "gap {gap}");
        }
    }

    #[test]
    fn regroup_drops_onto_a_row_move_to_a_gap() {
        // Onto tech's header: its first gap. Onto d: the gap above d.
        assert_eq!(
            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
            Some(NavDrop {
                gap: 6,
                retarget: true,
                moves: regroup(1, 4, Some(4)),
            })
        );
        assert_eq!(
            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
            Some(NavDrop {
                gap: 7,
                retarget: true,
                moves: regroup(1, 4, Some(5)),
            })
        );
    }

    #[test]
    fn regroup_offers_nothing_above_a_leading_header() {
        // 0 [news], 1 a, 2 [tech], 3 b.
        let rows = [None, Some(0), None, Some(1)];
        let movable = [true, true];
        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
        assert_eq!(at(0), None);
        assert_eq!(at(1).map(|d| d.moves), Some(None));
        assert_eq!(at(2).map(|d| d.moves), Some(None));
        assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
        assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
    }

    #[test]
    fn reorder_gaps_clamp_to_the_run() {
        // a past the run's end lands at its end: e's place.
        assert_eq!(
            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
            Some(NavDrop {
                gap: 5,
                retarget: true,
                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
            })
        );
        // Back in place.
        assert_eq!(
            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
            Some(None)
        );
        // b above the run's start lands at a's place; a fixed row offers nothing.
        assert_eq!(
            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
            Some(NavMove::Reorder { from: 2, to: 1 })
        );
        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
    }
}

/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";

/// Badge strings, retained once per rebuild rather than per cell.
fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
    badges
        .iter()
        .map(|b| b.as_deref().map(NSString::from_str))
        .collect()
}

// ---------------------------------------------------------------------------
/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
fn post_realize_visible_rows(key: usize) {
    <AppKit as Platform>::post(Box::new(move || {
        if let Some((table, data)) = list_entry(key) {
            unsafe { table.layoutSubtreeIfNeeded() };
            let range = unsafe { table.rowsInRect(table.visibleRect()) };
            if let Some(source) = data.ivars().source.borrow().clone()
                && let Some(report) = &source.first_visible
            {
                report(range.location.min((source.len)().saturating_sub(1)));
            }
            for row in range.location..range.location + range.length {
                let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
                // A snapshot/layout can have requested this cell while day-core held its
                // tree borrow. The delegate then returned an empty container; AppKit caches
                // it and will not ask viewForRow again. Complete that skipped bind here.
                if let Some(cell) = cell
                    && cell.subviews().is_empty()
                {
                    let source = data.ivars().source.borrow().clone();
                    if let Some(source) = source {
                        (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
                    }
                }
            }
        }
        // The builds above queued their styling effects; drain them now — outside the pump, no
        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
        day_core::pump_events();
    }));
}

/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
/// the incremental move alone can leave its row tiling and scroll extent out of sync.
/// Preserve the user's viewport and selection; never force a jump to the moved row.
fn post_settle_list_drop(key: usize) {
    <AppKit as Platform>::post(Box::new(move || {
        // Publish the deferred on_reorder before reading the final row set. App code may
        // remove rows or close the list, so resolve the native handles only after the drain.
        day_core::pump_events();
        let Some((table, data)) = list_entry(key) else {
            return;
        };
        let Some(scroll) = table.enclosingScrollView() else {
            return;
        };
        let clip = scroll.contentView();
        let origin = clip.bounds().origin;
        let selected = table.selectedRowIndexes();
        let suppressed = data.ivars().suppress.replace(true);
        table.reloadData();
        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
        table.layoutSubtreeIfNeeded();
        let restored = objc2_foundation::NSMutableIndexSet::new();
        for row in 0..table.numberOfRows().max(0) as usize {
            if selected.containsIndex(row) {
                restored.addIndex(row);
            }
        }
        table.selectRowIndexes_byExtendingSelection(&restored, false);
        let mut bounds = clip.bounds();
        bounds.origin = origin;
        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
        scroll.reflectScrolledClipView(&clip);
        data.ivars().suppress.set(suppressed);
        post_realize_visible_rows(key);
    }));
}

// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
//
// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
// ---------------------------------------------------------------------------

define_class!(
    #[unsafe(super(NSTableView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayListView"]
    struct DayListView;
    unsafe impl NSObjectProtocol for DayListView {}
    impl DayListView {
        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
        /// its summon-time provider from the visible cell, never from the selected row.
        #[unsafe(method_id(menuForEvent:))]
        fn menu_for_event(
            &self,
            event: &objc2_app_kit::NSEvent,
        ) -> Option<Retained<NSMenu>> {
            ffi_guard::contain(None, || {
                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
                let row = unsafe { self.rowAtPoint(point) };
                let provider = if row >= 0 {
                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
                        .and_then(|cell| list_row_menu_provider(&cell))
                } else {
                    None
                };
                match provider {
                    Some((view, provider)) => {
                        let point = view.convertPoint_fromView(
                            unsafe { event.locationInWindow() }, None,
                        );
                        let items = provider(day_spec::Point::new(point.x, point.y));
                        if items.is_empty() {
                            None
                        } else {
                            Some(build_ns_menu(self.mtm(), "", &items))
                        }
                    }
                    None => unsafe { msg_send![super(self), menuForEvent: event] },
                }
            })
        }

        #[unsafe(method(becomeFirstResponder))]
        fn become_first_responder(&self) -> bool {
            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
            if accepted {
                self.report_focus(true);
            }
            accepted
        }

        #[unsafe(method(resignFirstResponder))]
        fn resign_first_responder(&self) -> bool {
            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
            if accepted {
                self.report_focus(false);
            }
            accepted
        }

        #[unsafe(method(keyDown:))]
        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
            ffi_guard::contain((), || {
                let key = unsafe { event.keyCode() };
                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
                    let row = unsafe { self.selectedRow() };
                    if row >= 0 && let Some(target) = unsafe { self.target() } {
                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
                        return;
                    }
                }
                let _: () = unsafe { msg_send![super(self), keyDown: event] };
            });
        }
    }
);

/// The cell can wrap its decorated row in layout containers. Search only this visible
/// cell, not other rows; cloning the provider releases the registry borrow before app code.
fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
    if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
        return Some((view.retain(), provider));
    }
    view.subviews()
        .iter()
        .find_map(|view| list_row_menu_provider(&view))
}

/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
/// owner without copying providers onto descendants (which would go stale on recycling).
/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
fn inherited_context_menu(
    view: &NSView,
    event: &objc2_app_kit::NSEvent,
) -> Option<Option<Retained<NSMenu>>> {
    let mut current = Some(view.retain());
    while let Some(view) = current {
        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
            let items = provider(day_spec::Point::new(point.x, point.y));
            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
        }
        current = unsafe { view.superview() };
    }
    None
}

impl DayListView {
    fn report_focus(&self, focused: bool) {
        ffi_guard::contain((), || {
            if let Some(target) = unsafe { self.target() }
                && let Some(data) = target.downcast_ref::<DayListData>()
            {
                emit(data.ivars().node, Event::FocusChanged(focused));
            }
        });
    }
}

struct ListIvars {
    node: NodeId,
    /// Injected by `attach_list` once day-core wires the driver.
    source: RefCell<Option<ListSource>>,
    selectable: std::cell::Cell<bool>,
    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
    multi: std::cell::Cell<bool>,
    /// Programmatic selection in flight: don't re-emit SelectionChanged.
    suppress: std::cell::Cell<bool>,
    /// The row-token order this table currently displays — the baseline `permutation_moves`
    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
    tokens: RefCell<Vec<u64>>,
    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
    /// NSTableView keeps its fixed-pitch fast path.
    automatic: bool,
    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
    /// at the top as their section scrolls under them. A header sizes to its content in any
    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
    sections: bool,
    /// The height a header nobody has bound yet is given, like `estimate` for rows.
    header_estimate: std::cell::Cell<f64>,
    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
    /// splice or a drag moves rows without rebinding them.
    heights: RefCell<std::collections::HashMap<u64, f64>>,
    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
    /// finds the height it corrects.
    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
    /// of like rows scrolls without its rows jumping as they arrive.
    estimate: std::cell::Cell<f64>,
    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
    heights_pending: std::cell::Cell<bool>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayListData"]
    #[ivars = ListIvars]
    struct DayListData;

    unsafe impl NSObjectProtocol for DayListData {}
    unsafe impl NSControlTextEditingDelegate for DayListData {}

    impl DayListData {
        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
        #[unsafe(method(respondsToSelector:))]
        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
            if selector == objc2::sel!(tableView:heightOfRow:)
                && !self.ivars().automatic
                && !self.ivars().sections
            {
                false
            } else {
                unsafe { msg_send![super(self), respondsToSelector: selector] }
            }
        }

        #[unsafe(method(listViewportChanged:))]
        fn list_viewport_changed(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                let source = self.ivars().source.borrow().clone();
                if let Some(source) = source && let Some(report) = &source.first_visible
                    && let Some(object) = notification.object()
                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
                    && let Some(document) = clip.documentView()
                    && let Some(table) = document.downcast_ref::<NSTableView>() {
                    let visible = unsafe { table.rowsInRect(table.visibleRect()) };
                    report(visible.location.min((source.len)().saturating_sub(1)));
                }
            });
        }

        #[unsafe(method(activateRow:))]
        fn activate_row(&self, table: &NSTableView) {
            ffi_guard::contain((), || {
                let row = unsafe { table.selectedRow() };
                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
            });
        }
        #[unsafe(method(doubleClickRow:))]
        fn double_click_row(&self, table: &NSTableView) {
            ffi_guard::contain((), || {
                let row = unsafe { table.clickedRow() };
                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
            });
        }
    }

    unsafe impl NSTableViewDataSource for DayListData {
        #[unsafe(method(numberOfRowsInTableView:))]
        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
            // Reads the piece's snapshot only (no tree access) — safe even when called
            // synchronously from reloadData inside a with_tree borrow. Guarded because
            // `len` is a day-core closure.
            ffi_guard::contain(0, || {
                self.ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .map(|s| (s.len)() as isize)
                    .unwrap_or(0)
            })
        }

        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.

        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
        fn pasteboard_writer_for_row(
            &self,
            _tv: &NSTableView,
            row: isize,
        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
            // (Closure body: define_class converts only the TAIL expression, so early `return`s
            // must not escape the method itself.)
            let make = || {
                // Only reorderable lists write drag items — no seam, no drag.
                let reorderable = self
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .is_some_and(|s| s.reorder.is_some());
                // A group row (a section header) never lifts (docs/list.md "Sections").
                if !reorderable || row < 0 || self.is_header(row) {
                    return None;
                }
                let item = objc2_app_kit::NSPasteboardItem::new();
                unsafe {
                    item.setString_forType(
                        &NSString::from_str(&row.to_string()),
                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
                    );
                }
                Some(ProtocolObject::from_retained(item))
            };
            ffi_guard::contain(None, make)
        }

        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
        fn validate_drop(
            &self,
            tv: &NSTableView,
            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
            row: isize,
            _op: objc2_app_kit::NSTableViewDropOperation,
        ) -> objc2_app_kit::NSDragOperation {
            // Guarded: `can_move` consults the app's reorder guard closure.
            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
                let Some((from, len)) = self.drag_context(tv, info) else {
                    return objc2_app_kit::NSDragOperation::None;
                };
                // Normalize to an above insertion point (the gap style's semantics), convert to
                // the post-removal target index, and ask the guard.
                let ins = row.clamp(0, len as isize) as usize;
                let to = insertion_to_target(from, ins, len);
                let accepted = self.can_move(from, to);
                if accepted < 0 {
                    return objc2_app_kit::NSDragOperation::None;
                }
                let accepted = (accepted as usize).min(len.saturating_sub(1));
                if accepted != to {
                    // The guard retargeted: move the gap to where the drop would actually land.
                    unsafe {
                        tv.setDropRow_dropOperation(
                            target_to_insertion(from, accepted) as isize,
                            objc2_app_kit::NSTableViewDropOperation::Above,
                        );
                    }
                }
                objc2_app_kit::NSDragOperation::Move
            })
        }

        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
        fn accept_drop(
            &self,
            tv: &NSTableView,
            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
            row: isize,
            _op: objc2_app_kit::NSTableViewDropOperation,
        ) -> bool {
            // (Closure body: early `return`s must not escape the define_class method itself.)
            let drop = || {
                let Some((from, len)) = self.drag_context(tv, info) else {
                    return false;
                };
                let ins = row.clamp(0, len as isize) as usize;
                let to = insertion_to_target(from, ins, len);
                let accepted = self.can_move(from, to);
                if accepted < 0 {
                    return false;
                }
                let accepted = (accepted as usize).min(len.saturating_sub(1));
                if accepted == from {
                    return true; // dropped back home — nothing to commit
                }
                // Commit through the sync seam (rotates Day's snapshot, defers the app
                // callback), THEN animate the native move — the data source already answers in
                // the new order.
                let mv = self
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
                let Some(mv) = mv else { return false };
                mv(from, accepted);
                // Keep the displayed-order cache in step (the commit's echo skips the Reload
                // that would otherwise refresh it — see `permutation_moves`).
                {
                    let mut toks = self.ivars().tokens.borrow_mut();
                    if from < toks.len() && accepted < toks.len() {
                        let t = toks.remove(from);
                        toks.insert(accepted, t);
                    }
                }
                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
                if let Some(scroll) = tv.enclosingScrollView() {
                    post_settle_list_drop(ptr_of(&scroll));
                }
                true
            };
            // Guarded: the commit runs the seam's move closure into day-core and the app.
            ffi_guard::contain(false, drop)
        }
    }

    unsafe impl NSTableViewDelegate for DayListData {
        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
        /// once it has been bound, the running estimate until then. Asked before the row's view
        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
        /// table's own record and the source's token snapshot.
        #[unsafe(method(tableView:heightOfRow:))]
        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
            ffi_guard::contain(44.0, || {
                let ivars = self.ivars();
                let header = self.is_header(row);
                // A uniform sectioned list: rows keep the fixed pitch, headers size themselves.
                if !header && !ivars.automatic {
                    return unsafe { tv.rowHeight() };
                }
                let token = ivars
                    .source
                    .borrow()
                    .as_ref()
                    .filter(|s| row >= 0 && (row as usize) < (s.len)())
                    .map(|s| (s.token_at)(row as usize));
                token
                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
                    .unwrap_or_else(|| {
                        if header {
                            ivars.header_estimate.get()
                        } else {
                            ivars.estimate.get()
                        }
                    })
            })
        }

        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
        /// group style, spanning the row, and floated over their section by
        /// `floatsGroupRows`.
        #[unsafe(method(tableView:isGroupRow:))]
        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
            ffi_guard::contain(false, || self.is_header(row))
        }

        /// A header is not an item: clicks and arrow keys pass over it.
        #[unsafe(method(tableView:shouldSelectRow:))]
        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
            ffi_guard::contain(true, || !self.is_header(row))
        }

        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
        fn view_for_row(
            &self,
            tv: &NSTableView,
            _col: Option<&NSTableColumn>,
            row: isize,
        ) -> Option<Retained<NSView>> {
            // Guarded: `bind_row` builds the app's row content.
            ffi_guard::contain(None, || {
                let mtm = self.mtm();
                // Headers pool apart from rows, so a recycled cell keeps its kind and rebinds.
                let header = self.is_header(row);
                let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
                // Recycle a cell view if one is free; else make a fresh flipped container.
                let cell: Retained<NSView> =
                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
                        unsafe { v.setIdentifier(Some(&ident)) };
                        v
                    });
                // Day builds row content the first time it sees this cell, and rebinds
                // (slot-write) when the cell is recycled. NSTableView calls this outside
                // reloadData's stack, so the re-entry into with_tree is safe.
                let source = self.ivars().source.borrow().clone();
                if let Some(source) = source {
                    let raw = Retained::as_ptr(&cell) as RawHandle;
                    (source.bind_row)(row as usize, raw);
                    if self.ivars().automatic || header {
                        self.note_row_height(tv, &source, row, raw, header);
                    }
                }
                Some(cell)
            })
        }

        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
        fn did_remove_row_view(
            &self,
            _tv: &NSTableView,
            row_view: &objc2_app_kit::NSTableRowView,
            _row: isize,
        ) {
            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
            // scroll): clear its day element ids so it stops answering lookups, as the tree's
            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
            // turn's reload already reused has a window again, and its fresh ids must survive.
            ffi_guard::contain((), || {
                let Some(cell) = row_view.subviews().iter().find(|sub| {
                    sub.identifier()
                        .map(|i| {
                            let i = i.to_string();
                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL
                        })
                        .unwrap_or(false)
                }) else {
                    return;
                };
                // Raw +1 pointers across the post (the closure must be Send, which Retained is
                // not; everything stays on the main thread). AppKit may free a removed row view.
                let cell = Retained::into_raw(cell) as usize;
                let Some(this) = (unsafe {
                    Retained::retain(self as *const DayListData as *mut DayListData)
                }) else {
                    return;
                };
                let this = Retained::into_raw(this) as usize;
                <AppKit as Platform>::post(Box::new(move || {
                    // Reclaim both +1s first, so every early return balances them.
                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
                    let (Some(this), Some(cell)) = (this, cell) else {
                        return;
                    };
                    if cell.window().is_some() {
                        return; // reused already: its ids are the live row's
                    }
                    let recycle = this
                        .ivars()
                        .source
                        .borrow()
                        .as_ref()
                        .map(|s| s.recycle.clone());
                    if let Some(recycle) = recycle {
                        recycle(Retained::as_ptr(&cell) as RawHandle);
                    }
                }));
            })
        }

        #[unsafe(method(tableViewSelectionDidChange:))]
        fn selection_did_change(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
                    return;
                }
                let Some(obj) = (unsafe { notification.object() }) else {
                    return;
                };
                let Ok(tv) = obj.downcast::<NSTableView>() else {
                    return;
                };
                if self.ivars().multi.get() {
                    // Multi-select: report the FULL set (ascending; empty = cleared).
                    let idx = unsafe { tv.selectedRowIndexes() };
                    let mut rows = Vec::with_capacity(idx.count());
                    let mut i = idx.firstIndex();
                    while i != objc2_foundation::NSNotFound as usize {
                        rows.push(i as i64);
                        i = unsafe { idx.indexGreaterThanIndex(i) };
                    }
                    emit(self.ivars().node, Event::SelectionSet(rows));
                } else {
                    let row = unsafe { tv.selectedRow() };
                    if row >= 0 {
                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
                    } else {
                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
                        // be called with — but the app still has to hear about it, or a detail
                        // pane goes on showing the row the user just deselected. The empty set is
                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
                        // a silent contract break, since single-selection backends are documented
                        // as firing it with a one-element OR EMPTY set.
                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
                    }
                }
            })
        }

        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
        // this as the two-finger swipe starts, so the offer reflects the row's state at
        // GESTURE time; a full swipe across activates the first action (AppKit's own
        // full-slide behavior). The handler commits through the seam, which defers the app's
        // callback to the event drain.
        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
        fn row_actions_for_row(
            &self,
            tv: &NSTableView,
            row: isize,
            edge: objc2_app_kit::NSTableRowActionEdge,
        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
            // Guarded: `actions_at` runs the app's provider closure.
            ffi_guard::contain(NSArray::new(), || {
                let sw = self
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .and_then(|s| s.swipe.clone());
                let Some(sw) = sw else {
                    return NSArray::new();
                };
                if row < 0 {
                    return NSArray::new();
                }
                // AppKit's Leading/Trailing already speak reading direction, same as ours.
                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
                    day_spec::SwipeEdge::Leading
                } else {
                    day_spec::SwipeEdge::Trailing
                };
                let offer = (sw.actions_at)(row as usize, day_edge);
                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
                    .iter()
                    .enumerate()
                    .map(|(i, a)| {
                        let style = if a.destructive {
                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
                        } else {
                            objc2_app_kit::NSTableViewRowActionStyle::Regular
                        };
                        let perform = sw.perform.clone();
                        // Retained only for the swipe session: AppKit releases the actions
                        // (and this block) when the revealed buttons close.
                        let table = tv.retain();
                        let handler = block2::RcBlock::new(
                            move |_action: std::ptr::NonNull<
                                objc2_app_kit::NSTableViewRowAction,
                            >,
                                  row: isize| {
                                ffi_guard::contain((), || {
                                    perform(row as usize, day_edge, i);
                                    // A button press leaves the buttons revealed; close
                                    // them (a full slide already closed itself).
                                    unsafe { table.setRowActionsVisible(false) };
                                })
                            },
                        );
                        let action =
                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
                                style,
                                &NSString::from_str(&a.label),
                                &handler,
                            );
                        if let Some(t) = a.tint {
                            unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
                        }
                        // Glyph above the label — the Mail row-action look. The SF symbol
                        // resolves per OS release; an unknown name yields no image and the
                        // button keeps its label alone.
                        if let Some(sym) = a.symbol {
                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
                                None,
                            );
                            if let Some(img) = img {
                                unsafe { action.setImage(Some(&img)) };
                            }
                        }
                        action
                    })
                    .collect();
                NSArray::from_retained_slice(&actions)
            })
        }
    }
);

impl DayListData {
    fn new(
        mtm: MainThreadMarker,
        node: NodeId,
        selectable: bool,
        multi: bool,
        automatic: bool,
        sections: bool,
    ) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(ListIvars {
            node,
            source: RefCell::new(None),
            selectable: std::cell::Cell::new(selectable),
            multi: std::cell::Cell::new(multi),
            suppress: std::cell::Cell::new(false),
            tokens: RefCell::new(Vec::new()),
            automatic,
            sections,
            header_estimate: std::cell::Cell::new(28.0),
            heights: RefCell::new(std::collections::HashMap::new()),
            cell_tokens: RefCell::new(std::collections::HashMap::new()),
            estimate: std::cell::Cell::new(44.0),
            heights_pending: std::cell::Cell::new(false),
        });
        unsafe { msg_send![super(this), init] }
    }

    /// A self-sizing row was just bound to `cell`: record the height Day laid it at, and if
    /// the table drew the row at another height (the estimate, or the row's old content),
    /// correct it on the next turn. Not here: this runs inside NSTableView's own tiling.
    fn note_row_height(
        &self,
        table: &NSTableView,
        source: &ListSource,
        row: isize,
        cell: RawHandle,
        header: bool,
    ) {
        let height = (source.cell_height)(cell);
        if height <= 0.0 || row < 0 {
            return;
        }
        let token = (source.token_at)(row as usize);
        self.ivars()
            .cell_tokens
            .borrow_mut()
            .insert(cell as usize, token);
        self.ivars().heights.borrow_mut().insert(token, height);
        if header {
            self.ivars().header_estimate.set(height);
        } else {
            self.ivars().estimate.set(height);
        }
        let drawn = unsafe { table.rectOfRow(row) }.size.height;
        if (drawn - height).abs() > 0.5 {
            self.post_row_heights(table);
        }
    }

    /// Whether display row `row` is a section header (docs/list.md "Sections").
    fn is_header(&self, row: isize) -> bool {
        row >= 0
            && self
                .ivars()
                .source
                .borrow()
                .as_ref()
                .and_then(|s| s.is_header.clone())
                .is_some_and(|is_header| is_header(row as usize))
    }

    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
    /// the day-core borrow, so it only records the height; the table is told after the pass.
    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
        if let Some(token) = token {
            self.ivars().heights.borrow_mut().insert(token, height);
            self.post_row_heights(table);
        }
    }

    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
    /// posts one correction.
    fn post_row_heights(&self, table: &NSTableView) {
        if self.ivars().heights_pending.replace(true) {
            return;
        }
        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
        // everything stays on the main thread).
        let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
            return;
        };
        let this = Retained::into_raw(this) as usize;
        let table = Retained::into_raw(table.retain()) as usize;
        <AppKit as Platform>::post(Box::new(move || {
            // Reclaim both +1s first, so every early return balances them.
            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
            let (Some(this), Some(table)) = (this, table) else {
                return;
            };
            this.ivars().heights_pending.set(false);
            ffi_guard::contain((), || this.apply_row_heights(&table));
        }));
    }

    fn apply_row_heights(&self, table: &NSTableView) {
        let Some(source) = self.ivars().source.borrow().clone() else {
            return;
        };
        let count = unsafe { table.numberOfRows() }.max(0) as usize;
        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
        // The viewport and the rows AppKit prepares around it.
        let first = shown.location.saturating_sub(8);
        let last = (shown.location + shown.length + 8)
            .min(count)
            .min((source.len)());
        let changed = objc2_foundation::NSMutableIndexSet::new();
        {
            let heights = self.ivars().heights.borrow();
            for row in first..last {
                if let Some(&height) = heights.get(&(source.token_at)(row)) {
                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
                    if (drawn - height).abs() > 0.5 {
                        unsafe { changed.addIndex(row) };
                    }
                }
            }
        }
        if changed.count() == 0 {
            return;
        }
        // Unanimated: the row takes its content's height, it does not grow into it.
        NSAnimationContext::beginGrouping();
        NSAnimationContext::currentContext().setDuration(0.0);
        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
        NSAnimationContext::endGrouping();
    }

    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
    /// steps (each `(from, to)` interpreted against the already-moved rows, NSTableView's
    /// semantics) that transform the displayed order into the new one — and `None` for
    /// anything else (insert/remove/content change/no change), which reloads flat. Always
    /// refreshes the displayed-order cache.
    ///
    /// Every row that changes position must have a REALIZED row view (`table`): moving a
    /// viewless row (its old position sat outside the viewport, so it was never bound)
    /// animates nothing and leaves the row unbound at its new position — its content, and any
    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
    /// reloads flat, which realizes and binds the row at its new position.
    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
        let source = self.ivars().source.borrow();
        let source = source.as_ref()?;
        let n = (source.len)();
        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
        if old.len() != n || n == 0 || old == new {
            return None;
        }
        let (mut so, mut sn) = (old.clone(), new.clone());
        so.sort_unstable();
        sn.sort_unstable();
        if so != sn {
            return None;
        }
        for i in 0..n {
            if old[i] != new[i]
                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
            {
                return None;
            }
        }
        let mut work = old;
        let mut moves = Vec::new();
        for i in 0..n {
            if work[i] == new[i] {
                continue;
            }
            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
            let t = work.remove(j);
            work.insert(i, t);
            moves.push((j, i));
        }
        Some(moves)
    }

    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
    /// the pasteboard doesn't carry the day row type.
    fn drag_context(
        &self,
        tv: &NSTableView,
        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
    ) -> Option<(usize, usize)> {
        let src = unsafe { info.draggingSource() }?;
        if Retained::as_ptr(&src) as *const std::ffi::c_void
            != tv as *const NSTableView as *const std::ffi::c_void
        {
            return None;
        }
        let pb = unsafe { info.draggingPasteboard() };
        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
            .to_string()
            .parse::<usize>()
            .ok()?;
        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
        (from < len).then_some((from, len))
    }

    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
    fn can_move(&self, from: usize, to: usize) -> i64 {
        self.ivars()
            .source
            .borrow()
            .as_ref()
            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
            .unwrap_or(-1)
    }
}

/// The reuse identifiers of a list's row cells and its section-header cells.
const DAY_ROW_CELL: &str = "day.cell";
const DAY_HEADER_CELL: &str = "day.header";

/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";

/// An NSTableView drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
    let to = if ins > from { ins - 1 } else { ins };
    to.min(len.saturating_sub(1))
}

/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
fn target_to_insertion(from: usize, to: usize) -> usize {
    if to > from { to + 1 } else { to }
}

/// A realized LIST's scroll view ptr → (table, data source) for attach_list / update / measure.
type ListEntry = (Retained<NSTableView>, Retained<DayListData>);

/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
/// able to take its own borrow at that depth. Holding the map across any of them was the
/// "RefCell already borrowed" contained panic every list walkthrough used to log, 24 a run.
fn list_entry(key: usize) -> Option<ListEntry> {
    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
}

// ---------------------------------------------------------------------------
// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
// ---------------------------------------------------------------------------

struct TreeIvars {
    node: NodeId,
    /// Injected by `attach_tree` once day-core wires the driver.
    source: RefCell<Option<TreeSource>>,
    selectable: std::cell::Cell<bool>,
    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
    suppress: std::cell::Cell<bool>,
    /// token → its interned NSNumber. NSOutlineView tracks items (selection, expansion,
    /// rowForItem) by object identity/equality, so every query for a token must answer with
    /// the same object — which is also what preserves expansion across reloadData.
    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayTreeData"]
    #[ivars = TreeIvars]
    struct DayTreeData;

    unsafe impl NSObjectProtocol for DayTreeData {}

    unsafe impl NSOutlineViewDataSource for DayTreeData {
        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
        fn number_of_children(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: Option<&objc2::runtime::AnyObject>,
        ) -> isize {
            // Reads the piece's snapshot only (no tree access) — safe even when called
            // synchronously from reloadData inside a with_tree borrow. Guarded because
            // the closures are day-core's.
            ffi_guard::contain(0, || {
                let parent = item.and_then(Self::token_of_item);
                if item.is_some() && parent.is_none() {
                    return 0; // not one of ours (stale query racing a reload)
                }
                self.ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .map(|s| (s.children_len)(parent) as isize)
                    .unwrap_or(0)
            })
        }

        #[unsafe(method_id(outlineView:child:ofItem:))]
        fn child_of_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            index: isize,
            item: Option<&objc2::runtime::AnyObject>,
        ) -> Retained<objc2::runtime::AnyObject> {
            // AppKit only asks for children it was told exist, but a stale query racing a
            // reload must degrade (token 0, an unmatched identity) rather than panic — an
            // unwind here crosses an ObjC frame and aborts.
            let token = ffi_guard::contain(0, || {
                let parent = item.and_then(Self::token_of_item);
                self.ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .map(|s| (s.child_token)(parent, index.max(0) as usize))
                    .unwrap_or(0)
            });
            let ns = self.intern(token);
            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
        }

        #[unsafe(method(outlineView:isItemExpandable:))]
        fn is_expandable(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> bool {
            ffi_guard::contain(false, || {
                let Some(token) = Self::token_of_item(item) else {
                    return false;
                };
                self.ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .map(|s| (s.expandable)(token))
                    .unwrap_or(false)
            })
        }

        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
        // private-typed token string; `validateDrop` consults the guard live (forbidden
        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
        // `acceptDrop` commits through the sync seam — the app's own data write reloads.

        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
        fn pasteboard_writer_for_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
            let make = || {
                let movable = self
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .is_some_and(|s| s.moves.is_some());
                let token = Self::token_of_item(item)?;
                if !movable {
                    return None;
                }
                let pbitem = objc2_app_kit::NSPasteboardItem::new();
                unsafe {
                    pbitem.setString_forType(
                        &NSString::from_str(&token.to_string()),
                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
                    );
                }
                Some(ProtocolObject::from_retained(pbitem))
            };
            ffi_guard::contain(None, make)
        }

        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
        fn validate_drop(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
            item: Option<&objc2::runtime::AnyObject>,
            child_index: isize,
        ) -> objc2_app_kit::NSDragOperation {
            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
                match self.drop_proposal(ov, info, item, child_index) {
                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
                        objc2_app_kit::NSDragOperation::Move
                    }
                    _ => objc2_app_kit::NSDragOperation::None,
                }
            })
        }

        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
        fn accept_drop(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
            item: Option<&objc2::runtime::AnyObject>,
            child_index: isize,
        ) -> bool {
            let drop = || {
                let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
                else {
                    return false;
                };
                if !self.can_move(token, parent, index) {
                    return false;
                }
                // Commit through the sync seam: defers the app's `on_move`; the app's own
                // data write drives the Reload (no native row animation on this path).
                let mv = self
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
                let Some(mv) = mv else { return false };
                mv(token, parent, index);
                true
            };
            ffi_guard::contain(false, drop)
        }
    }

    unsafe impl NSControlTextEditingDelegate for DayTreeData {}

    unsafe impl NSOutlineViewDelegate for DayTreeData {
        #[unsafe(method(outlineView:isGroupItem:))]
        fn is_group_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> bool {
            Self::token_of_item(item).is_some_and(|t| {
                self.ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .is_some_and(|s| (s.section_header)(t))
            })
        }
        #[unsafe(method(outlineView:shouldSelectItem:))]
        fn should_select_item(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            item: &objc2::runtime::AnyObject,
        ) -> bool {
            Self::token_of_item(item).is_some_and(|t| {
                self.ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .is_some_and(|s| !(s.section_header)(t))
            })
        }

        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
        fn view_for_item(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            _col: Option<&NSTableColumn>,
            item: &objc2::runtime::AnyObject,
        ) -> Option<Retained<NSView>> {
            // Guarded: `bind_row` builds the app's row content.
            ffi_guard::contain(None, || {
                let mtm = self.mtm();
                let token = Self::token_of_item(item)?;
                let ident = NSString::from_str("day.tree.cell");
                // Recycle a cell view if one is free; else make a fresh flipped container
                // (DayTreeCell re-lays its Day row at its own width — indentation makes
                // every tree cell's width per-row).
                let cell: Retained<NSView> =
                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
                        let v: Retained<NSView> =
                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
                        unsafe { v.setIdentifier(Some(&ident)) };
                        v
                    });
                if let Some(source) = self.ivars().source.borrow().as_ref() {
                    let raw = Retained::as_ptr(&cell) as RawHandle;
                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
                        unsafe {
                            cell.setTextField(None);
                        }
                    }
                    (source.bind_row)(token, raw);
                    // Associate the actual Day label with NSTableCellView so AppKit can
                    // apply group typography and source-list background styles normally.
                    if (source.section_header)(token) {
                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
                            for child in unsafe { view.subviews() }.iter() {
                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
                                    return Some(label);
                                }
                                if let Some(label) = label_in(&child) {
                                    return Some(label);
                                }
                            }
                            None
                        }
                        if let Some(label) = label_in(&cell) {
                            let cell = cell.downcast_ref::<DayTreeCell>()?;
                            unsafe {
                                cell.setTextField(Some(&label));
                            }
                        }
                    }
                }
                Some(cell)
            })
        }

        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
        fn type_select_string(
            &self,
            _ov: &objc2_app_kit::NSOutlineView,
            _col: Option<&NSTableColumn>,
            item: &objc2::runtime::AnyObject,
        ) -> Option<Retained<NSString>> {
            ffi_guard::contain(None, || {
                let token = Self::token_of_item(item)?;
                let text = self
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .map(|s| (s.type_select_text)(token))
                    .unwrap_or_default();
                // Empty = this row doesn't participate in type-select.
                (!text.is_empty()).then(|| NSString::from_str(&text))
            })
        }

        #[unsafe(method_id(outlineView:rowViewForItem:))]
        fn row_view_for_item(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            _item: &objc2::runtime::AnyObject,
        ) -> Retained<objc2_app_kit::NSTableRowView> {
            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
                // AppKit owns source-list group backgrounds, floating headers and selection.
                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
            } else {
                // The rounded-selection row (see DayTreeRowView).
                let rv: Retained<DayTreeRowView> =
                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
                Retained::into_super(rv)
            }
        }

        #[unsafe(method(outlineViewSelectionDidChange:))]
        fn selection_did_change(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
                    return;
                }
                let Some(obj) = (unsafe { notification.object() }) else {
                    return;
                };
                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
                    return;
                };
                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
                let idx = unsafe { ov.selectedRowIndexes() };
                let mut tokens = Vec::with_capacity(idx.count());
                let mut i = idx.firstIndex();
                while i != objc2_foundation::NSNotFound as usize {
                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
                        && let Some(tok) = Self::token_of_item(&item)
                    {
                        tokens.push(tok);
                    }
                    i = unsafe { idx.indexGreaterThanIndex(i) };
                }
                emit(self.ivars().node, Event::TreeSelection(tokens));
            })
        }

        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
        fn did_remove_row_view(
            &self,
            ov: &objc2_app_kit::NSOutlineView,
            row_view: &objc2_app_kit::NSTableRowView,
            _row: isize,
        ) {
            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
            // a cell already reused by the same turn's reload has a window again, and its
            // fresh ids must survive.
            ffi_guard::contain((), || {
                let mut cell_ptr: Option<usize> = None;
                for sub in row_view.subviews().iter() {
                    let is_cell = sub
                        .identifier()
                        .map(|i| i.to_string() == "day.tree.cell")
                        .unwrap_or(false);
                    if is_cell {
                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
                    }
                }
                let Some(cell) = cell_ptr else { return };
                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
                    return;
                };
                let key = Retained::as_ptr(&scroll) as usize;
                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
                // be Send, which Retained is not; we stay on the main thread throughout).
                // AppKit is free to dealloc removed row views — a bare pointer died here once.
                let retained =
                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
                        as usize;
                <AppKit as Platform>::post(Box::new(move || {
                    // Reclaim the +1 first, unconditionally — every early return below must
                    // still balance the retain.
                    let cell_view: Retained<NSView> =
                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
                            Some(v) => v,
                            None => return,
                        };
                    let recycle = tree_entry(key).and_then(|(_, data)| {
                        data.ivars()
                            .source
                            .borrow()
                            .as_ref()
                            .map(|s| s.recycle.clone())
                    });
                    let Some(recycle) = recycle else { return };
                    if cell_view.window().is_some() {
                        return; // reused already — its ids are the live row's
                    }
                    recycle(cell as RawHandle);
                }));
            })
        }

        #[unsafe(method(outlineViewItemDidExpand:))]
        fn item_did_expand(&self, notification: &NSNotification) {
            self.report_disclosure(notification, true);
        }

        #[unsafe(method(outlineViewItemDidCollapse:))]
        fn item_did_collapse(&self, notification: &NSNotification) {
            self.report_disclosure(notification, false);
        }
    }
);

impl DayTreeData {
    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(TreeIvars {
            node,
            source: RefCell::new(None),
            selectable: std::cell::Cell::new(selectable),
            suppress: std::cell::Cell::new(false),
            items: RefCell::new(HashMap::new()),
        });
        unsafe { msg_send![super(this), init] }
    }

    /// The same NSNumber for a token, every time — NSOutlineView's item identity.
    fn intern(&self, token: u64) -> Retained<NSNumber> {
        self.ivars()
            .items
            .borrow_mut()
            .entry(token)
            .or_insert_with(|| NSNumber::new_u64(token))
            .clone()
    }

    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
        item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
    }

    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
        ffi_guard::contain((), || {
            if self.ivars().suppress.get() {
                return;
            }
            let token = unsafe { notification.userInfo() }
                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
                .and_then(|item| Self::token_of_item(&item));
            if let Some(token) = token {
                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
            }
        })
    }

    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
    /// means "ONTO the parent" (NSOutlineView's childIndex -1, `NSOutlineViewDropOnItemIndex`).
    fn drop_proposal(
        &self,
        ov: &objc2_app_kit::NSOutlineView,
        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
        item: Option<&objc2::runtime::AnyObject>,
        child_index: isize,
    ) -> Option<(u64, Option<u64>, Option<usize>)> {
        let src = unsafe { info.draggingSource() }?;
        if Retained::as_ptr(&src) as *const std::ffi::c_void
            != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
        {
            return None;
        }
        let pb = unsafe { info.draggingPasteboard() };
        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
            .to_string()
            .parse::<u64>()
            .ok()?;
        let parent = match item {
            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
            None => None,
        };
        let index = (child_index >= 0).then_some(child_index as usize);
        Some((token, parent, index))
    }

    /// The guard's live verdict through the sync seam.
    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
        self.ivars()
            .source
            .borrow()
            .as_ref()
            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
            .map(|v| v == MoveVerdict::Allow)
            .unwrap_or(false)
    }
}

// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
// in occasional deferred posts — closes every window where a stale width could draw.
define_class!(
    #[unsafe(super(objc2_app_kit::NSOutlineView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayOutlineView"]
    struct DayOutlineView;

    impl DayOutlineView {
        #[unsafe(method(layout))]
        fn layout(&self) {
            sync_tree_width(self);
            let _: () = unsafe { msg_send![super(self), layout] };
        }

        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
        /// the tree's `row_menu` provider for the row under the pointer.
        #[unsafe(method_id(menuForEvent:))]
        fn menu_for_event(
            &self,
            event: &objc2_app_kit::NSEvent,
        ) -> Option<Retained<NSMenu>> {
            ffi_guard::contain(None, || {
                let scroll = unsafe { self.enclosingScrollView() }?;
                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
                let row_menu = data
                    .ivars()
                    .source
                    .borrow()
                    .as_ref()
                    .and_then(|s| s.row_menu.clone())?;
                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
                let row = unsafe { self.rowAtPoint(p) };
                if row < 0 {
                    return None;
                }
                let token =
                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
                let items = row_menu(token);
                if items.is_empty() {
                    return None;
                }
                Some(build_ns_menu(self.mtm(), "", &items))
            })
        }
    }
);

// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
// and a hand-drawn plain color also captures correctly offscreen, where materials go black
// (docs/navigation.md's sidebar-screenshot rule).
define_class!(
    #[unsafe(super(objc2_app_kit::NSTableRowView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayTreeRowView"]
    struct DayTreeRowView;

    impl DayTreeRowView {
        #[unsafe(method(drawSelectionInRect:))]
        fn draw_selection_in_rect(&self, _dirty: NSRect) {
            if !unsafe { self.isSelected() } {
                return;
            }
            let color = if unsafe { self.isEmphasized() } {
                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
            } else {
                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
            };
            let b = self.bounds();
            let pill = NSRect::new(
                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
                NSSize::new(
                    (b.size.width - 10.0).max(0.0),
                    (b.size.height - 2.0).max(0.0),
                ),
            );
            unsafe {
                color.setFill();
                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
                    pill, 5.0, 5.0,
                )
                .fill();
            }
        }
    }
);

// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
// content inside it at that width through the seam's `layout_cell`.
define_class!(
    #[unsafe(super(objc2_app_kit::NSTableCellView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayTreeCell"]
    struct DayTreeCell;

    impl DayTreeCell {
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        #[unsafe(method(layout))]
        fn layout(&self) {
            let _: () = unsafe { msg_send![super(self), layout] };
            ffi_guard::contain((), || {
                let width = self.bounds().size.width;
                if width <= 0.0 {
                    return;
                }
                // This cell's tree: walk up to the outline, then to its scroll host, which
                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
                // tree may be mid-teardown; both just skip.)
                let mut cur = unsafe { self.superview() };
                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
                while let Some(v) = cur {
                    cur = unsafe { v.superview() };
                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
                        outline = Some(ov);
                        break;
                    }
                }
                let Some(ov) = outline else { return };
                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
                    return;
                };
                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
                    .and_then(|(_, data)| {
                        data.ivars()
                            .source
                            .borrow()
                            .as_ref()
                            .map(|s| s.layout_cell_size.clone())
                    });
                if let Some(f) = f {
                    f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
                }
            })
        }
    }
);

impl DayTreeCell {
    fn new(mtm: MainThreadMarker) -> Retained<Self> {
        unsafe { msg_send![Self::alloc(mtm), init] }
    }
}

/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";

/// A realized TREE's scroll view ptr → (outline, data source).
type TreeEntry = (
    Retained<objc2_app_kit::NSOutlineView>,
    Retained<DayTreeData>,
);

/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
/// re-entrancy rule as `list_entry` (its comment has the war story).
fn tree_entry(key: usize) -> Option<TreeEntry> {
    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
}

/// Keep the outline exactly as wide as its clip — DayOutlineView calls this on every layout
/// pass (its comment has the why). The list never noticed the width drift because it lays
/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
        return;
    };
    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
    let f = outline.frame();
    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
        unsafe {
            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
            outline.sizeLastColumnToFit();
        }
    }
}

/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
fn post_realize_visible_tree_rows(key: usize) {
    <AppKit as Platform>::post(Box::new(move || {
        if let Some((outline, _)) = tree_entry(key) {
            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
            for row in range.location..range.location + range.length {
                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
            }
        }
        day_core::pump_events();
    }));
}

/// A realized NAV_MENU's native outline view paired with its data-source object.
type NavMenuEntry = (
    Retained<objc2_app_kit::NSOutlineView>,
    Retained<DayNavMenuData>,
);

fn ns_rect(r: day_spec::Rect) -> NSRect {
    NSRect::new(
        NSPoint::new(r.origin.x, r.origin.y),
        NSSize::new(r.size.width, r.size.height),
    )
}

fn draw_op(op: &DrawOp) {
    unsafe {
        match op {
            // One path for the whole batch, then one fill or stroke: the template is appended
            // once per position, so the rasterizer is entered once however many copies there are
            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
            // which is what makes a stamped scatter shade across the group rather than repeating
            // the ramp inside every dot.
            DrawOp::Stamp(st) => {
                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
                for p in &st.at {
                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
                        unsafe { batch.appendBezierPath(&copy) };
                    }
                }
                let color = match &st.paint {
                    day_spec::Paint::Solid(c) => *c,
                    // A gradient over a stamped batch clips to the whole batch path; the solid
                    // fallback below keeps the marks visible on a backend path that cannot.
                    _ => day_spec::Color::WHITE,
                };
                match &st.stroke {
                    None => {
                        nscolor(color).setFill();
                        unsafe { batch.fill() };
                    }
                    Some(style) => {
                        nscolor(color).setStroke();
                        apply_stroke_style(&batch, style);
                        unsafe { batch.stroke() };
                    }
                }
            }
            DrawOp::Fill(shape, paint) => match paint {
                day_spec::Paint::Solid(color) => {
                    nscolor(*color).setFill();
                    if let Some(p) = bezier(shape) {
                        p.fill();
                    }
                }
                day_spec::Paint::Linear(g) => {
                    // Native linear gradient: clip to the shape's path, then NSGradient along
                    // the line resolved from the gradient's unit points in the shape's bounds.
                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
                        let b = shape.bounds();
                        let (s, e) = (g.start.resolve(b), g.end.resolve(b));
                        NSGraphicsContext::saveGraphicsState_class();
                        p.addClip();
                        grad.drawFromPoint_toPoint_options(
                            NSPoint::new(s.x, s.y),
                            NSPoint::new(e.x, e.y),
                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
                        );
                        NSGraphicsContext::restoreGraphicsState_class();
                    }
                }
                day_spec::Paint::Radial(g) => {
                    // Native radial gradient: clip to the path, map unit space onto the bounds
                    // (elliptical in non-square bounds), draw circular in unit coordinates.
                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
                        let b = shape.bounds();
                        NSGraphicsContext::saveGraphicsState_class();
                        p.addClip();
                        concat_unit_to_bounds(b);
                        let c = NSPoint::new(g.center.x, g.center.y);
                        grad.drawFromCenter_radius_toCenter_radius_options(
                            c,
                            0.0,
                            c,
                            g.radius,
                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
                        );
                        NSGraphicsContext::restoreGraphicsState_class();
                    }
                }
            },
            DrawOp::Stroke(shape, paint, style) => {
                if let Some(p) = bezier(shape) {
                    apply_stroke_style(&p, style);
                    match paint {
                        day_spec::Paint::Solid(color) => {
                            nscolor(*color).setStroke();
                            p.stroke();
                        }
                        // No gradient-stroke primitive here either: turn the stroke into the
                        // region it covers and draw the gradient through that clip.
                        // No gradient-stroke primitive: convert the stroke into the REGION it
                        // covers (CoreGraphics can, and NSGraphicsContext hands us its context),
                        // clip to that, then draw the gradient through it.
                        _ => {
                            let Some(ctx) = NSGraphicsContext::currentContext() else {
                                return;
                            };
                            let cg = ctx.CGContext();
                            NSGraphicsContext::saveGraphicsState_class();
                            objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
                            objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
                                &cg,
                            ));
                            objc2_core_graphics::CGContext::clip(Some(&cg));
                            draw_gradient_in(paint, shape.bounds());
                            NSGraphicsContext::restoreGraphicsState_class();
                        }
                    }
                }
            }
            DrawOp::Clip(shape) => {
                // `addClip` intersects with the current clip and honors the path's winding rule.
                if let Some(p) = bezier(shape) {
                    p.addClip();
                }
            }
            DrawOp::Text {
                text,
                at,
                size,
                color,
                anchor,
                font,
            } => {
                let font = canvas_nsfont(*size, font);
                let attrs = canvas_text_attrs(&font, *color);
                let ns = NSString::from_str(text);
                let mut origin = NSPoint::new(at.x, at.y);
                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
                // anchor is an offset from it. The size comes from the attributes the draw is
                // about to use, which is why the alignment belongs here and not in the app: the
                // caller would have to ask for these same metrics through `measure_text` first.
                if *anchor != day_spec::TextAnchor::LEADING {
                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
                    origin.x += dx;
                    origin.y += dy;
                }
                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
            }
            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
            // on every tracked read, so a handle can be dropped between the record and the
            // replay, and a frame that flashes a grey box is worse than one that omits the image.
            DrawOp::Image {
                image,
                rect,
                opacity,
            } => {
                let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
                if let Some(img) = img {
                    let dest = NSRect::new(
                        NSPoint::new(rect.origin.x, rect.origin.y),
                        NSSize::new(rect.size.width, rect.size.height),
                    );
                    // DayCanvas is flipped (top-left origin). Respect that context so image
                    // rows stay upright, including under the canvas's rotation/zoom transforms.
                    // A zero `fromRect` means the whole image; `fraction` multiplies its alpha.
                    img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
                        dest,
                        NSRect::ZERO,
                        objc2_app_kit::NSCompositingOperation::SourceOver,
                        *opacity,
                        true,
                        None,
                    );
                }
            }
            DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
            DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
            DrawOp::Concat(m) => {
                let t = NSAffineTransform::new();
                t.setTransformStruct(NSAffineTransformStruct {
                    m11: m.a,
                    m12: m.b,
                    m21: m.c,
                    m22: m.d,
                    tX: m.tx,
                    tY: m.ty,
                });
                t.concat();
            }
        }
    }
}

/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
fn nsgradient(
    stops: &[(f64, day_spec::Color)],
) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
    if stops.is_empty() {
        return None;
    }
    let colors = objc2_foundation::NSArray::from_retained_slice(
        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
    );
    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
    unsafe {
        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
            objc2_app_kit::NSGradient::alloc(),
            &colors,
            locations.as_ptr(),
            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
        )
    }
}

/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
fn concat_unit_to_bounds(b: day_spec::Rect) {
    let t = NSAffineTransform::new();
    t.setTransformStruct(NSAffineTransformStruct {
        m11: b.size.width,
        m12: 0.0,
        m21: 0.0,
        m22: b.size.height,
        tX: b.origin.x,
        tY: b.origin.y,
    });
    unsafe { t.concat() };
}

/// Put a [`day_spec::StrokeStyle`] onto a path.
///
/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
/// default is BUTT — the same default the spec and every other backend use. A line that wants
/// round ends asks for `StrokeStyle::round`.
fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
    use day_spec::{LineCap, LineJoin};
    unsafe {
        p.setLineWidth(style.width);
        p.setLineCapStyle(match style.cap {
            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
        });
        if style.is_plain() {
            return;
        }
        p.setLineJoinStyle(match style.join {
            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
        });
        p.setMiterLimit(style.miter_limit);
        if !style.dash.is_empty() {
            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
        }
    }
}

/// Draw a gradient through whatever clip is installed, in AppKit's own NSGradient terms.
/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
/// clipped to first.
fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
    match paint {
        day_spec::Paint::Linear(g) => {
            if let Some(grad) = nsgradient(&g.stops) {
                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
                unsafe {
                    grad.drawFromPoint_toPoint_options(
                        NSPoint::new(s.x, s.y),
                        NSPoint::new(e.x, e.y),
                        opts,
                    )
                };
            }
        }
        day_spec::Paint::Radial(g) => {
            if let Some(grad) = nsgradient(&g.stops) {
                NSGraphicsContext::saveGraphicsState_class();
                concat_unit_to_bounds(bounds);
                let c = NSPoint::new(g.center.x, g.center.y);
                unsafe {
                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
                };
                NSGraphicsContext::restoreGraphicsState_class();
            }
        }
        day_spec::Paint::Solid(_) => {}
    }
}

fn apply_button_content(
    btn: &NSButton,
    title: &str,
    icon: Option<&day_spec::Icon>,
    icon_only: bool,
) {
    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
    if let Some(image) = &image {
        let size = image.size();
        let longest = size.width.max(size.height);
        if longest > 0.0 {
            image.setSize(objc2_foundation::NSSize::new(
                size.width * 20.0 / longest,
                size.height * 20.0 / longest,
            ));
        }
    }
    let style = BUTTON_STYLES
        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
        .unwrap_or_default();
    BUTTON_IMAGES.with(|images| {
        images.remove(ptr_of(btn));
        if let Some(image) = &image {
            images.insert(ptr_of(btn), image.clone());
        }
    });
    set_button_title(btn, title, style);
    // The position first: the image setter pads a glyph that sits beside a title, and leaves
    // an icon-only one alone, by reading it.
    unsafe {
        btn.setImagePosition(if image.is_none() {
            objc2_app_kit::NSCellImagePosition::NoImage
        } else if icon_only {
            objc2_app_kit::NSCellImagePosition::ImageOnly
        } else {
            objc2_app_kit::NSCellImagePosition::ImageLeading
        });
    }
    set_button_image(btn, style);
    unsafe {
        // The title is the spoken name (an icon-only button shows none), unless the app named
        // the button itself; overwriting that here replaced app labels on every title change.
        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
        }
        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
        btn.setToolTip(tooltip.as_deref());
    }
}

/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
/// the native button, but supply an image that draws the original vector's alpha in
/// the requested contrast color at the destination resolution.
fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
    use day_spec::props::ButtonStyleSpec as S;
    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
    let image = image.map(|source| {
        let S::Tinted(fill) = style else {
            return source;
        };
        let size = source.size();
        let ink = nscolor(S::on_tint(fill));
        let draw = block2::RcBlock::new(move |rect: NSRect| {
            source.drawInRect_fromRect_operation_fraction(
                rect,
                NSRect::ZERO,
                objc2_app_kit::NSCompositingOperation::SourceOver,
                1.0,
            );
            unsafe {
                ink.setFill();
                objc2_app_kit::NSRectFillUsingOperation(
                    rect,
                    objc2_app_kit::NSCompositingOperation::SourceIn,
                );
            }
            objc2::runtime::Bool::YES
        });
        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
    });
    unsafe {
        let position = btn.imagePosition();
        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
        // against the text, so the image carries the space itself (a template stays one, so
        // the label color still tints it). The cell centers the image in its slot, so half
        // the extra width lands on each side.
        let image = image.map(|source| {
            // The position is set after this on a fresh button, so an unset one counts as
            // "beside a title"; only an icon-only button keeps the glyph as drawn.
            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
                return source;
            }
            let size = source.size();
            let template = source.isTemplate();
            let padded = NSSize::new(size.width + 8.0, size.height);
            let draw = block2::RcBlock::new(move |_rect: NSRect| {
                source.drawInRect_fromRect_operation_fraction(
                    NSRect::new(NSPoint::new(0.0, 0.0), size),
                    NSRect::ZERO,
                    objc2_app_kit::NSCompositingOperation::SourceOver,
                    1.0,
                );
                objc2::runtime::Bool::YES
            });
            let out =
                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
            out.setTemplate(template);
            out
        });
        btn.setImage(image.as_deref());
        btn.setImagePosition(position);
        btn.setImageHugsTitle(true);
    }
}

/// Put `ButtonProps::selected` on an `NSButton`, keeping it an NSButton. A momentary button
/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
/// selects keeps its momentary type. A click toggles the state natively before the action
/// runs, so the `action:` handler restores the value recorded here.
fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
    unsafe {
        if on {
            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
        }
        btn.setState(if on {
            NSControlStateValueOn
        } else {
            NSControlStateValueOff
        });
    }
}

/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
/// bezel's own, so the fill reads as the bezel rather than as a box around it.
const TINT_CORNER_RADIUS: f64 = 6.0;

/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an NSButton.
///
/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
/// look all still come from the control rather than from us painting a rectangle. macOS 26
/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
/// backing layer, where the translucent material lets it through; on older systems the opaque
/// tinted bezel covers that layer, so nothing changes there.
fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
    use day_spec::props::ButtonStyleSpec as S;
    let title = unsafe { btn.title() }.to_string();
    unsafe {
        // Reset first, so a patch from one style to another leaves nothing of the old one.
        btn.setKeyEquivalent(&NSString::from_str(""));
        btn.setBezelColor(None);
        btn.setBordered(!matches!(style, S::Plain));
        match style {
            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
            S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
        }
        btn.setWantsLayer(true);
        if let Some(layer) = btn.layer() {
            match style {
                S::Tinted(c) => {
                    layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
                    layer.setCornerRadius(TINT_CORNER_RADIUS);
                }
                _ => layer.setBackgroundColor(None),
            }
        }
    }
    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
    let ink = match style {
        S::Tinted(c) => Some(nscolor(S::on_tint(c))),
        _ => None,
    };
    unsafe {
        btn.setContentTintColor(ink.as_deref());
    }
    set_button_title(btn, &title, style);
    set_button_image(btn, style);
}

/// Set a button's title, coloring it for the tint where there is one.
///
/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
/// AppKit keeps drawing the title in its own control text color — which is how a
/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
/// control the text color, so that is what a tinted button gets.
///
/// The button's own font is carried into the attributes: an attributed title supplies the whole
/// run, so leaving the font out would drop the control font and render at the system default.
fn set_button_title(
    btn: &objc2_app_kit::NSButton,
    title: &str,
    style: day_spec::props::ButtonStyleSpec,
) {
    use day_spec::props::ButtonStyleSpec as S;
    // Changing an attributed title can reset NSButton's image placement. A reactive
    // tint must keep an icon-only button icon-only, including its native template tint.
    let position = unsafe { btn.imagePosition() };
    let S::Tinted(fill) = style else {
        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
        unsafe {
            btn.setTitle(&NSString::from_str(title));
            btn.setImagePosition(position);
        }
        return;
    };
    unsafe {
        let col = nscolor(S::on_tint(fill));
        let font = btn
            .font()
            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
        // Centered, matching a plain NSButton title: an attributed title carries its own
        // paragraph style, and the default is left-aligned.
        let para = objc2_app_kit::NSMutableParagraphStyle::new();
        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
        let keys: [&NSString; 3] = [
            objc2_app_kit::NSFontAttributeName,
            objc2_app_kit::NSForegroundColorAttributeName,
            objc2_app_kit::NSParagraphStyleAttributeName,
        ];
        let objs: [&objc2::runtime::AnyObject; 3] = [
            font.as_ref() as &objc2::runtime::AnyObject,
            col.as_ref() as &objc2::runtime::AnyObject,
            para.as_ref() as &objc2::runtime::AnyObject,
        ];
        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
            objc2_foundation::NSAttributedString::alloc(),
            &NSString::from_str(title),
            Some(&attrs),
        );
        btn.setAttributedTitle(&s);
        btn.setImagePosition(position);
    }
}

// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
// the center and clip to the view; this retains vector rendering and template tinting.
define_class!(
    #[unsafe(super(objc2_app_kit::NSImageView))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayFillImageView"]
    struct FillImageView;

    impl FillImageView {
        #[unsafe(method(drawRect:))]
        fn draw_rect(&self, dirty: NSRect) {
            let bounds = self.bounds();
            let image = unsafe { self.image() };
            let Some(size) = image.map(|image| image.size()).filter(|size| {
                size.width > 0.0 && size.height > 0.0
                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
            }) else {
                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
                return;
            };
            let x = bounds.size.width / size.width;
            let y = bounds.size.height / size.height;
            let scale = x.max(y) / x.min(y);
            let cx = bounds.origin.x + bounds.size.width / 2.0;
            let cy = bounds.origin.y + bounds.size.height / 2.0;
            NSGraphicsContext::saveGraphicsState_class();
            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
            let transform = NSAffineTransform::transform();
            transform.translateXBy_yBy(cx, cy);
            transform.scaleBy(scale);
            transform.translateXBy_yBy(-cx, -cy);
            transform.concat();
            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
            NSGraphicsContext::restoreGraphicsState_class();
        }

        #[unsafe(method(setFrameSize:))]
        fn set_frame_size(&self, size: NSSize) {
            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
            NSView::setNeedsDisplay(self, true);
        }
    }
);

fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
    use day_spec::Shape;
    use objc2_app_kit::NSBezierPath;
    unsafe {
        Some(match shape {
            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
            Shape::RoundedRect(r, rad) => {
                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
            }
            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
            Shape::Arc {
                rect,
                start_deg,
                sweep_deg,
            } => {
                let p = NSBezierPath::new();
                let center = NSPoint::new(
                    rect.origin.x + rect.size.width / 2.0,
                    rect.origin.y + rect.size.height / 2.0,
                );
                let radius = rect.size.width.min(rect.size.height) / 2.0;
                // Flipped view: increasing angle is visually clockwise, matching the spec.
                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
                    center,
                    radius,
                    *start_deg,
                    *start_deg + *sweep_deg,
                );
                p
            }
            Shape::Line(a, b) => {
                let p = NSBezierPath::new();
                p.moveToPoint(NSPoint::new(a.x, a.y));
                p.lineToPoint(NSPoint::new(b.x, b.y));
                p
            }
            Shape::Polygon(pts) => {
                if pts.len() < 2 {
                    return None;
                }
                let p = NSBezierPath::new();
                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
                for pt in &pts[1..] {
                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
                }
                p.closePath();
                p
            }
            Shape::Path(path) => {
                use day_spec::PathSeg;
                if path.segs.is_empty() {
                    return None;
                }
                let p = NSBezierPath::new();
                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
                // p1)), which is exact rather than an approximation.
                let mut cur = NSPoint::new(0.0, 0.0);
                for seg in &path.segs {
                    match seg {
                        PathSeg::Move(a) => {
                            cur = NSPoint::new(a.x, a.y);
                            p.moveToPoint(cur);
                        }
                        PathSeg::Line(a) => {
                            cur = NSPoint::new(a.x, a.y);
                            p.lineToPoint(cur);
                        }
                        PathSeg::Quad(c, a) => {
                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
                            let c1 = NSPoint::new(
                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
                            );
                            let c2 = NSPoint::new(
                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
                            );
                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
                            cur = end;
                        }
                        PathSeg::Cubic(c1, c2, a) => {
                            cur = NSPoint::new(a.x, a.y);
                            p.curveToPoint_controlPoint1_controlPoint2(
                                cur,
                                NSPoint::new(c1.x, c1.y),
                                NSPoint::new(c2.x, c2.y),
                            );
                        }
                        PathSeg::Close => p.closePath(),
                    }
                }
                p.setWindingRule(match path.rule {
                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
                });
                p
            }
        })
    }
}

// ---------------------------------------------------------------------------
// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
// ---------------------------------------------------------------------------

/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
/// questions and forwards invocations — two histories can never fork.
struct UndoIvars {
    state: std::cell::RefCell<day_spec::UndoState>,
}

define_class!(
    #[unsafe(super(objc2_foundation::NSUndoManager))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayUndoManager"]
    #[ivars = UndoIvars]
    struct DayUndoManager;

    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
    /// other event). Registration/grouping machinery of the superclass is never used.
    impl DayUndoManager {
        #[unsafe(method(canUndo))]
        fn can_undo(&self) -> bool {
            self.ivars().state.borrow().can_undo
        }

        #[unsafe(method(canRedo))]
        fn can_redo(&self) -> bool {
            self.ivars().state.borrow().can_redo
        }

        #[unsafe(method(undo))]
        fn do_undo(&self) {
            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
        }

        #[unsafe(method(redo))]
        fn do_redo(&self) {
            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
        }

        #[unsafe(method_id(undoMenuItemTitle))]
        fn undo_menu_item_title(&self) -> Retained<NSString> {
            // Route through the superclass's own title former, so "Undo" itself comes out in
            // the system language; the action label arrived already localized from the app.
            let label = self.ivars().state.borrow().undo_label.clone();
            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
        }

        #[unsafe(method_id(redoMenuItemTitle))]
        fn redo_menu_item_title(&self) -> Retained<NSString> {
            let label = self.ivars().state.borrow().redo_label.clone();
            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
        }
    }
);

fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
    UNDO_FRONT.with(|u| {
        u.borrow_mut()
            .get_or_insert_with(|| {
                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
                });
                unsafe { msg_send![super(this), init] }
            })
            .clone()
    })
}

// ---------------------------------------------------------------------------
// DayWinDelegate — resize + close + key tracking, per window
// ---------------------------------------------------------------------------

/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
/// (docs/windows.md) reports to its own root and close tears down just that window.
struct WinIvars {
    node: Option<NodeId>,
    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
    /// tab bar's "+" opens another window of the same group.
    group: Option<String>,
    /// The last display state reported (`WindowState::code`), so a resize that does not change
    /// the zoom state reports nothing.
    last_state: Cell<i32>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayWinDelegate"]
    #[ivars = WinIvars]
    struct DayWinDelegate;

    unsafe impl NSObjectProtocol for DayWinDelegate {}

    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
    impl DayWinDelegate {
        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
        /// plain views, so the delegate is where the chain lands — resolving through the
        /// acting manager keeps a focused field's typing undo ahead of the document stack.
        #[unsafe(method(undo:))]
        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
            ffi_guard::contain((), || {
                if let Some(m) = self.acting_undo_manager() {
                    unsafe { m.undo() };
                }
            });
        }

        /// Edit ▸ Redo.
        #[unsafe(method(redo:))]
        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
            ffi_guard::contain((), || {
                if let Some(m) = self.acting_undo_manager() {
                    unsafe { m.redo() };
                }
            });
        }

        #[unsafe(method(cut:))]
        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
        }

        #[unsafe(method(copy:))]
        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
        }

        #[unsafe(method(paste:))]
        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
        }

        #[unsafe(method(selectAll:))]
        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
            ffi_guard::contain((), || {
                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
            });
        }

        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
        /// the bridge state answers for cut/copy, and paste additionally requires the
        /// pasteboard to actually hold text.
        #[unsafe(method(validateMenuItem:))]
        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
            ffi_guard::contain(false, || {
                let state = EDIT_STATE.with(|s| s.get());
                match unsafe { item.action() } {
                    // The undo pair enables from the acting manager and takes its titles
                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
                        Some(m) => {
                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
                            unsafe { m.canUndo() }
                        }
                        None => false,
                    },
                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
                        Some(m) => {
                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
                            unsafe { m.canRedo() }
                        }
                        None => false,
                    },
                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
                    Some(a) if a == sel!(cut:) => state.can_cut,
                    Some(a) if a == sel!(copy:) => state.can_copy,
                    Some(a) if a == sel!(paste:) => {
                        state.can_paste && {
                            let pb = unsafe { NSPasteboard::generalPasteboard() };
                            pb.types().is_some_and(|types| !types.is_empty())
                        }
                    }
                    _ => true,
                }
            })
        }
    }

    unsafe impl NSWindowDelegate for DayWinDelegate {
        #[unsafe(method(windowDidResize:))]
        fn window_did_resize(&self, notification: &NSNotification) {
            ffi_guard::contain((), || {
                if let Some(obj) = unsafe { notification.object() }
                    && let Ok(win) = obj.downcast::<NSWindow>()
                    && let Some(size) = pin_below_title_bar(&win)
                {
                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
                    emit(target, Event::WindowResized(size));
                }
                // Zooming is a resize with no notification of its own.
                self.report_state_of(notification);
            })
        }

        #[unsafe(method(windowShouldClose:))]
        fn window_should_close(&self, _window: &NSWindow) -> bool {
            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
        }

        #[unsafe(method(windowWillClose:))]
        fn window_will_close(&self, _notification: &NSNotification) {
            ffi_guard::contain((), || {
                match self.ivars().node {
                    // Secondary window: confirm the close to day-core, which tears the
                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
                    Some(node) => emit(node, Event::WindowClosed),
                    // Primary window: closing it quits, taking secondaries with it
                    // (docs/windows.md close policy), unless the app keeps running without a
                    // window (a status item, `KeepRunning::Always`): then it closes like any
                    // other window and day-core decides.
                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
                    None => {
                        let app = NSApplication::sharedApplication(self.mtm());
                        unsafe { app.terminate(None) };
                    }
                }
            })
        }

        #[unsafe(method_id(windowWillReturnUndoManager:))]
        fn window_will_return_undo_manager(
            &self,
            _window: &NSWindow,
        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
            // The responder chain already gave a focused text field its OWN manager before
            // asking the window — typing undo stays the field's, the model stack gets the
            // rest, exactly the precedence the plan's typing rule wants.
            ffi_guard::contain(None, || {
                UNDO_FRONT.with(|u| {
                    u.borrow()
                        .as_ref()
                        .map(|m| Retained::into_super(m.clone()))
                })
            })
        }

        #[unsafe(method(windowDidBecomeKey:))]
        fn window_did_become_key(&self, _notification: &NSNotification) {
            ffi_guard::contain((), || {
                if let Some(node) = self.ivars().node {
                    emit(node, Event::WindowFocused(true));
                }
            })
        }

        #[unsafe(method(windowDidResignKey:))]
        fn window_did_resign_key(&self, _notification: &NSNotification) {
            ffi_guard::contain((), || {
                if let Some(node) = self.ivars().node {
                    emit(node, Event::WindowFocused(false));
                }
            })
        }

        #[unsafe(method(windowDidMiniaturize:))]
        fn window_did_miniaturize(&self, notification: &NSNotification) {
            ffi_guard::contain((), || self.report_state_of(notification))
        }

        #[unsafe(method(windowDidDeminiaturize:))]
        fn window_did_deminiaturize(&self, notification: &NSNotification) {
            ffi_guard::contain((), || self.report_state_of(notification))
        }

        #[unsafe(method(windowDidEnterFullScreen:))]
        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
            ffi_guard::contain((), || self.report_state_of(notification))
        }

        #[unsafe(method(windowDidExitFullScreen:))]
        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
            ffi_guard::contain((), || self.report_state_of(notification))
        }
    }

    // The tab bar's "+" button walks the responder chain (window → delegate) for
    // `newWindowForTab:` — present only when the app registered a new-window builder
    // (otherwise automatic tabbing is off and no "+" exists).
    impl DayWinDelegate {
        #[unsafe(method(newWindowForTab:))]
        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
            ffi_guard::contain((), || {
                // A window in a tab group of its own gets another window of that group
                // (`register_new_window_for`); everything else gets File ▸ New Window's.
                let _ = match self.ivars().group.as_deref() {
                    Some(group) => day_core::windows::open_new_window_for_group(group),
                    None => day_core::windows::open_new_window(),
                };
            })
        }
    }
);

impl DayWinDelegate {
    fn report_state_of(&self, notification: &NSNotification) {
        if let Some(obj) = unsafe { notification.object() }
            && let Ok(win) = obj.downcast::<NSWindow>()
        {
            self.report_state(&win);
        }
    }
}

/// The day name for a key press, or `None` for every key the route does not carry — the
/// [`day_spec::KeyEvent`] names (docs/menus.md).
fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
    match unsafe { event.keyCode() } {
        123 => Some("ArrowLeft"),
        124 => Some("ArrowRight"),
        125 => Some("ArrowDown"),
        126 => Some("ArrowUp"),
        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
        // Delete its own Edit menu was going to act on.
        //
        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
        // combinations are accelerators, and claiming one would starve the menu the same way.
        _ => {
            let held = NSEventModifierFlags::Command
                | NSEventModifierFlags::Option
                | NSEventModifierFlags::Control;
            if event.modifierFlags().intersects(held) {
                return None;
            }
            let typed = event.characters()?.to_string();
            let mut chars = typed.chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
                _ => None,
            }
        }
    }
}

/// AppKit's modifier flags as day's mask.
fn key_modifiers(f: NSEventModifierFlags) -> u8 {
    let mut modifiers = 0u8;
    if f.contains(NSEventModifierFlags::Shift) {
        modifiers |= day_spec::KeyEvent::SHIFT;
    }
    if f.contains(NSEventModifierFlags::Command) {
        modifiers |= day_spec::KeyEvent::PRIMARY;
    }
    if f.contains(NSEventModifierFlags::Option) {
        modifiers |= day_spec::KeyEvent::ALT;
    }
    modifiers
}

impl DayWinDelegate {
    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
    /// `undoManager` walks the chain itself — a field editor answers with its typing
    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
    /// the app's front. Falls back to the front when no window is key yet.
    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
        let responder = NSApplication::sharedApplication(self.mtm())
            .keyWindow()
            .and_then(|w| w.firstResponder());
        responder
            .and_then(|r| unsafe { r.undoManager() })
            .or_else(|| {
                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
            })
    }
}

impl DayWinDelegate {
    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(WinIvars {
            node,
            group,
            last_state: Cell::new(day_spec::WindowState::Normal.code()),
        });
        unsafe { msg_send![super(this), init] }
    }

    /// Report the window's display state if it changed since the last report
    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
    /// primary, the same routing as `WindowResized`.
    fn report_state(&self, window: &NSWindow) {
        let state = ns_window_state(window);
        if self.ivars().last_state.replace(state.code()) != state.code() {
            log::debug!("appkit: window state now {state:?}");
            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
            emit(target, Event::WindowStateChanged(state));
        }
    }
}

/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
    if window.isMiniaturized() {
        day_spec::WindowState::Minimized
    } else if window
        .styleMask()
        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
    {
        day_spec::WindowState::Fullscreen
    } else if window.isZoomed() {
        day_spec::WindowState::Maximized
    } else {
        day_spec::WindowState::Normal
    }
}

/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
/// have to be left before a window can zoom, and each is its own toggle.
fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
    use day_spec::WindowState as S;
    let current = ns_window_state(window);
    if current == state {
        return;
    }
    unsafe {
        match current {
            S::Minimized => window.deminiaturize(None),
            // Leaving fullscreen animates; asking for another state in the same turn would be
            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
            // signal reads back `Normal`, and a second request takes it from there.
            S::Fullscreen => {
                window.toggleFullScreen(None);
                return;
            }
            S::Maximized if state != S::Minimized => window.zoom(None),
            _ => {}
        }
        match state {
            S::Normal => {}
            S::Minimized => window.miniaturize(None),
            S::Maximized => {
                if !window.isZoomed() {
                    window.zoom(None)
                }
            }
            S::Fullscreen => window.toggleFullScreen(None),
        }
    }
}

// ---------------------------------------------------------------------------
// The backend
// ---------------------------------------------------------------------------

/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
#[distributed_slice]
pub static RENDERERS: [fn() -> Renderer<AppKit>];

/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
struct SecondaryWin {
    window: Retained<NSWindow>,
    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
    delegate: Retained<DayWinDelegate>,
    content: Handle,
}

/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
/// The monitor is local to this process and removed with the backend.
struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
impl Drop for MenuEscapeMonitor {
    fn drop(&mut self) {
        unsafe { NSEvent::removeMonitor(&self.0) };
    }
}

pub struct AppKit {
    menu_escape_monitor: Option<MenuEscapeMonitor>,
    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,

    mtm: MainThreadMarker,
    registry: Registry<AppKit>,
    window: Option<Retained<NSWindow>>,
    content: Option<Handle>,
    secondary: Vec<SecondaryWin>,
    app_name: String,
    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
    /// answers the point after it, so threading that answer through here is the whole
    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
    cascade: Option<NSPoint>,
    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
    /// view pointer. Removed when the cursor goes back to `Default`.
    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
}

impl AppKit {
    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
    /// where the old view was: same text, look and place among its siblings, same focus and
    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
    /// without a `release`, so nothing keyed by it may stay behind.
    fn swap_text_field(
        &mut self,
        h: &Handle,
        old: &NSTextField,
        node: NodeId,
        secure: bool,
    ) -> Retained<NSTextField> {
        let new = new_text_field(self.mtm, node, secure);
        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
        // Focus and selection first: reading them is only meaningful while the old field
        // still edits. `stringValue` below answers the field editor's live text.
        let window = h.window();
        let focused = window
            .as_deref()
            .is_some_and(|w| owns_first_responder(w, h));
        let selection = old.currentEditor().map(|e| e.selectedRange());
        unsafe {
            new.setStringValue(&old.stringValue());
            new.setPlaceholderString(old.placeholderString().as_deref());
            new.setEnabled(old.isEnabled());
            new.setFont(old.font().as_deref());
            new.setFrame(h.frame());
            new.setHidden(h.isHidden());
            new.setMenu(h.menu().as_deref());
            new.setToolTip(h.toolTip().as_deref());
            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
            if h.wantsLayer() {
                new.setWantsLayer(true);
                new.setAlphaValue(h.alphaValue());
                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
                if !from.is_null() && !to.is_null() {
                    let t: CGAffineTransform = msg_send![from, affineTransform];
                    let _: () = msg_send![to, setAffineTransform: t];
                }
            }
            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
            // keeps its own defaults (a secure field's role and hidden value) for the rest.
            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
                new.setAccessibilityIdentifier(Some(&id));
            }
            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
                new.setAccessibilityLabel(Some(&label));
            }
            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
                new.setAccessibilityHelp(Some(&help));
            }
            if !h.isAccessibilityElement() {
                new.setAccessibilityElement(false);
            }
        }
        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
        for r in unsafe { h.gestureRecognizers() }.iter() {
            unsafe {
                h.removeGestureRecognizer(&r);
                new.addGestureRecognizer(&r);
            }
        }
        GESTURES.with(|m| {
            let mut m = m.borrow_mut();
            if let Some(targets) = m.remove(&old_key) {
                m.insert(new_key, targets);
            }
        });
        if let Some((owner, area)) = self.cursors.remove(&old_key) {
            unsafe {
                h.removeTrackingArea(&area);
                new.addTrackingArea(&area);
            }
            self.cursors.insert(new_key, (owner, area));
        }
        PAN_NODES.with(|t| rekey(t, old_key, new_key));
        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
        KEY_NODES.with(|t| rekey(t, old_key, new_key));
        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
        transfer::moved(h, &new);
        // The old field goes silent before it leaves: ending its editing session would
        // otherwise report a focus loss for a node that keeps its focus.
        unsafe { old.setDelegate(None) };
        TARGETS.with(|m| {
            m.borrow_mut().remove(&old_key);
        });
        if let Some(parent) = unsafe { h.superview() } {
            unsafe {
                parent.addSubview_positioned_relativeTo(
                    &new,
                    objc2_app_kit::NSWindowOrderingMode::Above,
                    Some(h),
                );
                h.removeFromSuperview();
            }
        }
        if focused && let Some(window) = window {
            FIELD_SWAP.with(|s| s.set(true));
            let taken = window.makeFirstResponder(Some(&new));
            FIELD_SWAP.with(|s| s.set(false));
            // Taking focus selects the whole text; put back what was selected (the caret,
            // usually). Both classes count in UTF-16 units, so the range carries over.
            if taken && let Some(editor) = new.currentEditor() {
                let len = unsafe { new.stringValue() }.length();
                let range = selection
                    .filter(|r| r.location.saturating_add(r.length) <= len)
                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
                editor.setSelectedRange(range);
            }
        }
        // Whatever else was keyed by the old view goes with it.
        day_spec::sidetable::sweep(old_key);
        new
    }

    pub fn new() -> Self {
        let mtm =
            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
        let mut registry = Registry::default();
        for f in RENDERERS {
            registry.register(f());
        }
        AppKit {
            menu_escape_monitor: None,
            mtm,
            registry,
            window: None,
            sharing: None,
            content: None,
            secondary: Vec::new(),
            app_name: "Day".into(),
            cascade: None,
            cursors: HashMap::new(),
        }
    }

    /// Public helper for external renderers.
    pub fn mtm(&self) -> MainThreadMarker {
        self.mtm
    }

    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
        if let Some(w) = self
            .secondary
            .iter()
            .find(|w| ptr_of(&w.content) == ptr_of(host))
        {
            return Some(w.window.clone());
        }
        self.content
            .as_ref()
            .filter(|c| ptr_of(c) == ptr_of(host))
            .and(self.window.clone())
    }

    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
    /// the AppKit default would double-release under us on close.
    fn make_window(
        &self,
        options: &WindowOptions,
        prefs_style: bool,
        node: Option<NodeId>,
    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
        let mtm = self.mtm;
        let (title, size, min_size, tabbing) = (
            options.title.as_str(),
            options.size,
            options.min_size,
            &options.tabbing,
        );
        let content_rect =
            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
        let style = window_chrome::style_mask(options, prefs_style);
        let window = window_chrome::alloc_window(
            mtm,
            content_rect,
            style,
            options.chrome == day_spec::WindowChrome::Frameless,
        );
        unsafe { window.setReleasedWhenClosed(false) };
        window.setTitle(&NSString::from_str(title));
        if let Some(min) = min_size {
            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
        }
        if let Some(max) = options.max_size {
            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
        }
        use day_spec::WindowTabbing as T;
        use objc2_app_kit::NSWindowTabbingMode as M;
        let group = match tabbing {
            T::Group(g) | T::Preferred(g) => Some(g.clone()),
            T::Automatic | T::Disallowed => None,
        };
        match tabbing {
            _ if prefs_style => window.setTabbingMode(M::Disallowed),
            T::Disallowed => window.setTabbingMode(M::Disallowed),
            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
            // window can exist; inert while automatic tabbing is globally off (see `run`).
            T::Automatic => unsafe {
                window.setTabbingIdentifier(&NSString::from_str("day.normal"))
            },
            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
            T::Preferred(g) => {
                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
                window.setTabbingMode(M::Preferred);
            }
        }
        if group.is_some() {
            // A named group is the app asking for tabs, so the class-wide switch `run` may have
            // turned off (no New Window builder) goes back on for it.
            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
        }
        let delegate = DayWinDelegate::new(mtm, node, group);
        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
        let content = view_of(DayFlipped::new(mtm));
        window.setContentView(Some(&content));
        window_chrome::apply(&window, &content, options);
        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
        // Day backend gets traversal from its widget order for free; this is the one that has to
        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
        // loop on hierarchy changes is the same rule expressed once.
        window.setAutorecalculatesKeyViewLoop(true);
        (window, delegate, content)
    }
}

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

fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
    Retained::from(x.as_ref())
}

fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
}

/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
    use objc2_app_kit::*;
    unsafe {
        Some(match f {
            Font::LargeTitle => NSFontTextStyleLargeTitle,
            Font::Title => NSFontTextStyleTitle1,
            Font::Title2 => NSFontTextStyleTitle2,
            Font::Title3 => NSFontTextStyleTitle3,
            Font::Headline => NSFontTextStyleHeadline,
            Font::Subheadline => NSFontTextStyleSubheadline,
            Font::Body => NSFontTextStyleBody,
            Font::Callout => NSFontTextStyleCallout,
            Font::Footnote => NSFontTextStyleFootnote,
            Font::Caption => NSFontTextStyleCaption1,
            Font::Caption2 => NSFontTextStyleCaption2,
            Font::System(_) | Font::Custom(..) => return None,
        })
    }
}

fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
    use day_spec::FontWeight as W;
    use objc2_app_kit::*;
    unsafe {
        match w {
            W::UltraLight => NSFontWeightUltraLight,
            W::Thin => NSFontWeightThin,
            W::Light => NSFontWeightLight,
            W::Regular => NSFontWeightRegular,
            W::Medium => NSFontWeightMedium,
            W::Semibold => NSFontWeightSemibold,
            W::Bold => NSFontWeightBold,
            W::Heavy => NSFontWeightHeavy,
            W::Black => NSFontWeightBlack,
        }
    }
}

/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
fn nsfm_weight(w: day_spec::FontWeight) -> isize {
    use day_spec::FontWeight as W;
    match w {
        W::UltraLight => 2,
        W::Thin => 3,
        W::Light => 4,
        W::Regular => 5,
        W::Medium => 6,
        W::Semibold => 8,
        W::Bold => 9,
        W::Heavy => 10,
        W::Black => 12,
    }
}

/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
/// registered in `run`) and then to the system font with one warning.
fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
    use objc2_app_kit::*;
    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
    let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
    let mut traits = NSFontTraitMask::empty();
    if weight >= day_spec::FontWeight::Semibold {
        traits |= NSFontTraitMask::BoldFontMask;
    }
    if font.italic {
        traits |= NSFontTraitMask::ItalicFontMask;
    }
    let Some(family) = font.family.as_deref() else {
        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
        return if font.italic {
            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
        } else {
            base
        };
    };
    let ns_family = NSString::from_str(family);
    if let Some(f) = unsafe {
        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
    } {
        return f;
    }
    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
        return if traits.is_empty() {
            f
        } else {
            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
        };
    }
    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
}

/// The attribute dictionary canvas text draws and measures with (the same one, so
/// `measure_text` and `replay` agree on the line box).
fn canvas_text_attrs(
    font: &NSFont,
    color: day_spec::Color,
) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
    let col = nscolor(color);
    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
    let keys: [&NSString; 2] = unsafe {
        [
            objc2_app_kit::NSFontAttributeName,
            objc2_app_kit::NSForegroundColorAttributeName,
        ]
    };
    let objs: [&objc2::runtime::AnyObject; 2] = [
        font as &objc2::runtime::AnyObject,
        col.as_ref() as &objc2::runtime::AnyObject,
    ];
    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
}

/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
    use objc2_app_kit::*;
    let base: Retained<NSFont> = match spec.style {
        Font::System(pt) => {
            let w = spec
                .weight
                .map(ns_weight)
                .unwrap_or(unsafe { NSFontWeightRegular });
            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
        }
        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
        // family, full, and PostScript names. A weight override maps to the bold trait (the
        // family decides what it can supply); unknown families fall back to the system font.
        Font::Custom(name, pt) => {
            match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
                Some(f) => {
                    if spec
                        .weight
                        .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
                    {
                        let mtm = objc2::MainThreadMarker::new()
                            .expect("labels realize on the main thread");
                        unsafe {
                            NSFontManager::sharedFontManager(mtm)
                                .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
                        }
                    } else {
                        f
                    }
                }
                None => {
                    log::warn!(
                        "unknown font family {name:?} — falling back to the system font \
                         (is the file in the project's fonts/ directory?)"
                    );
                    let w = spec
                        .weight
                        .map(ns_weight)
                        .unwrap_or(unsafe { NSFontWeightRegular });
                    unsafe { NSFont::systemFontOfSize_weight(pt, w) }
                }
            }
        }
        style => {
            // Invariant: System/Custom matched above, so only the semantic styles — which
            // `ns_text_style` maps exhaustively — can reach this arm.
            let ts = ns_text_style(style).expect("semantic style");
            let opts = objc2_foundation::NSDictionary::new();
            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
            match spec.weight {
                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
                None => f,
            }
        }
    };
    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
    // system font at the resolved size/weight rather than converting — which is why it only
    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
    // for the system's monospaced-digit face there would silently swap the typeface).
    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
        let w = spec
            .weight
            .map(ns_weight)
            .unwrap_or(unsafe { NSFontWeightRegular });
        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
    } else {
        base
    };
    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
        let w = spec
            .weight
            .map(ns_weight)
            .unwrap_or(unsafe { NSFontWeightRegular });
        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
    } else {
        base
    };
    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
    // re-picking the system font here would undo the Custom/monospace/tabular work above.
    let base = if spec.scale != 1.0 {
        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
        let pts = spec.resolved_points(base.pointSize());
        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
    } else {
        base
    };
    if spec.italic {
        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
        unsafe {
            NSFontManager::sharedFontManager(mtm)
                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
        }
    } else {
        base
    }
}

/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
///
/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
/// character makes the two disagree, and an off-by-N range there styles the wrong words.
/// Stamp a paragraph alignment across a label's whole attributed string.
///
/// Separate from `setAlignment:` because the two live in different places: the cell has a
/// paragraph style, the attributed string carries its own, and the string's wins.
fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
    use objc2_foundation::{NSMutableAttributedString, NSRange};
    unsafe {
        let cur = tf.attributedStringValue();
        let m = NSMutableAttributedString::initWithAttributedString(
            NSMutableAttributedString::alloc(),
            &cur,
        );
        let style = objc2_app_kit::NSMutableParagraphStyle::new();
        style.setAlignment(align);
        // Wrapping is what makes alignment observable at all, and the default paragraph style a
        // fresh NSMutableParagraphStyle carries would otherwise reset it to clipping.
        style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
        m.addAttribute_value_range(
            objc2_app_kit::NSParagraphStyleAttributeName,
            &style,
            NSRange::new(0, cur.length()),
        );
        tf.setAttributedStringValue(&m);
    }
}

fn attributed_label(
    text: &str,
    base_font: &NSFont,
    color: Option<day_spec::Color>,
    role: day_spec::props::TextRole,
    runs: &[day_spec::TextRun],
) -> Retained<objc2_foundation::NSAttributedString> {
    use objc2_foundation::{NSMutableAttributedString, NSRange};
    let ns = NSString::from_str(text);
    let s = unsafe {
        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
    };
    let whole = NSRange::new(0, ns.length());
    unsafe {
        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
        // Always a foreground: an attributed range with no color attribute draws in black,
        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
        // would have used on its own.
        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
        // Both are adaptive, which is the point of asking for a role instead of a grey: the
        // secondary label is legible against either appearance's background, and a literal one
        // cannot be.
        let fg = color.map(nscolor).unwrap_or_else(|| match role {
            day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
            day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
        });
        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
    }
    for r in runs {
        let Some(range) = utf16_range(text, &r.range) else {
            continue;
        };
        unsafe {
            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
            if let Some(c) = r.color {
                s.addAttribute_value_range(
                    objc2_app_kit::NSForegroundColorAttributeName,
                    &nscolor(c),
                    range,
                );
            }
            if let Some(c) = r.background {
                s.addAttribute_value_range(
                    objc2_app_kit::NSBackgroundColorAttributeName,
                    &nscolor(c),
                    range,
                );
            }
            if r.underline.is_on() {
                let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
                s.addAttribute_value_range(
                    objc2_app_kit::NSUnderlineStyleAttributeName,
                    &style,
                    range,
                );
            }
            if r.strikethrough {
                let one = objc2_foundation::NSNumber::new_i64(1);
                s.addAttribute_value_range(
                    objc2_app_kit::NSStrikethroughStyleAttributeName,
                    &one,
                    range,
                );
            }
            if let Some(url) = r.link.as_deref() {
                // The native field editor hit-tests this attribute; DayLabel handles its
                // delegate callback and reports LinkActivated without opening the URL itself.
                let value = NSString::from_str(url);
                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
            }
        }
    }
    s.into_super()
}

/// [`Underline`](day_spec::Underline) as an `NSUnderlineStyle` bitmask: the line style in the low
/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
/// exactly how AppKit spells them.
fn ns_underline(u: day_spec::Underline) -> i64 {
    use day_spec::Underline as U;
    match u {
        U::None => 0,
        U::Single => 0x01,
        U::Double => 0x09,
        U::Dotted => 0x01 | 0x0100,
        U::Wavy => 0x01 | 0x0400,
    }
}

/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
    let start = text.get(..r.start)?.encode_utf16().count();
    let len = text.get(r.clone())?.encode_utf16().count();
    Some(objc2_foundation::NSRange::new(start, len))
}

/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
/// means that family won't resolve, so it logs and moves on.
fn register_bundled_fonts() {
    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
    #[link(name = "CoreText", kind = "framework")]
    unsafe extern "C" {
        fn CTFontManagerRegisterFontsForURL(
            font_url: *const std::ffi::c_void,
            scope: u32, // kCTFontManagerScopeProcess = 1
            error: *mut *const std::ffi::c_void,
        ) -> bool;
    }
    for path in day_spec::fonts::bundled_fonts() {
        let url = unsafe {
            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
        };
        let ok = unsafe {
            CTFontManagerRegisterFontsForURL(
                Retained::as_ptr(&url) as *const std::ffi::c_void,
                1,
                std::ptr::null_mut(),
            )
        };
        if !ok {
            log::warn!("could not register bundled font {}", path.display());
        }
    }
}

/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
    match a {
        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
    }
}

fn configure_label_cell(tf: &NSTextField) {
    if let Some(cell) = unsafe { tf.cell() } {
        unsafe {
            cell.setWraps(true);
            cell.setUsesSingleLineMode(false);
            cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
        }
    }
}

/// If `parent` is a scroll view, children go into its (flipped) document view.
fn content_of(parent: &Handle) -> Retained<NSView> {
    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
        && let Some(doc) = unsafe { sv.documentView() }
    {
        return doc;
    }
    parent.clone()
}

/// Run `body` (which sets animatable properties on a layer-backed view) inside an
/// `NSAnimationContext` group so AppKit interpolates the change on the render server with the
/// curve's timing function, or immediately when `anim` is `None` (§8.4). `allowsImplicitAnimation`
/// makes direct property changes on layer-backed views animate. A spring maps to an overshooting
/// cubic-bezier timing function (a visible bounce without an explicit `CASpringAnimation`).
fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
    let Some(a) = anim else {
        body();
        return;
    };
    let (dur, timing) = appkit_timing(a);
    unsafe {
        NSAnimationContext::beginGrouping();
        let ctx = NSAnimationContext::currentContext();
        ctx.setDuration(dur);
        ctx.setTimingFunction(Some(&timing));
        ctx.setAllowsImplicitAnimation(true);
        body();
        NSAnimationContext::endGrouping();
    }
}

/// The `(duration_secs, timing function)` for a curve. Springs render as an overshooting bezier
/// (control point y > 1) whose overshoot grows as damping falls, over a response-derived duration.
fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
    unsafe {
        let named = |n| {
            (
                a.duration_secs().max(0.01),
                CAMediaTimingFunction::functionWithName(n),
            )
        };
        match a.curve {
            Curve::Linear => named(kCAMediaTimingFunctionLinear),
            Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
            Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
            Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
            Curve::Spring { damping, .. } => {
                // Overshoot bezier over exactly the specified duration (authoritative timing).
                let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
                (
                    a.duration_secs().max(0.05),
                    CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
                )
            }
        }
    }
}

/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
/// per kind so a placeholder rendered every frame doesn't spam the log.
fn warn_missing_renderer(kind: PieceKind) {
    day_spec::placeholder::report(kind, "appkit");
}

/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
/// (the warning is already reported by `props_of` itself).
pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
    view_of(unsafe {
        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
    })
}

impl Toolkit for AppKit {
    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
    fn ui_idle(&mut self) -> bool {
        toolbar::chrome_settled()
    }

    type Handle = Handle;

    fn dark_mode(&mut self) -> bool {
        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
        // launch force (applied as an NSApp override at startup), and a set_appearance call.
        let app = NSApplication::sharedApplication(self.mtm());
        app.effectiveAppearance()
            .name()
            .to_string()
            .contains("Dark")
    }

    /// System Settings › Accessibility › Display › "Reduce motion", as NSWorkspace reports it
    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
    fn reduce_motion(&mut self) -> bool {
        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
    }

    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
    /// clears it (docs/badge.md).
    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
        use day_spec::AppBadge;
        let label = match badge {
            AppBadge::None => None,
            // Zero clears, matching the platform convention the doc states.
            AppBadge::Count(0) => None,
            AppBadge::Count(n) => Some(n.to_string()),
            AppBadge::Text(t) if t.is_empty() => None,
            AppBadge::Text(t) => Some(t.clone()),
            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
            AppBadge::Dot => Some("\u{2022}".to_string()),
        };
        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
        unsafe { tile.setBadgeLabel(ns.as_deref()) };
        tile.display();
    }

    fn set_appearance(&mut self, dark: Option<bool>) {
        let app = NSApplication::sharedApplication(self.mtm());
        let appearance = dark.and_then(|d| {
            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
                if d {
                    objc2_app_kit::NSAppearanceNameDarkAqua
                } else {
                    objc2_app_kit::NSAppearanceNameAqua
                }
            })
        });
        // `None` clears the override — back to the system appearance.
        unsafe { app.setAppearance(appearance.as_deref()) };
    }

    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
        controls::refresh_gesture::attach(handle, host);
    }

    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
        unsafe {
            handle.setHidden(!visible);
        }
    }

    fn capability(&self, cap: Cap) -> Support {
        match cap {
            Cap::SearchField => Support::Native,
            Cap::ComboBox => Support::Native,
            Cap::Stepper => Support::Native,
            Cap::DateTimePicker => Support::Native,
            Cap::ColorPicker => Support::Native,
            Cap::PullRefresh => Support::Emulated,
            Cap::Pager => Support::Emulated,
            Cap::PullRefreshGesture => Support::Emulated,
            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
            // diagonal-resize cursors need macOS 15.
            Cap::Cursor => Support::Native,
            // `NSFontManager` enumerates every family and member (docs/fonts.md).
            Cap::FontList => Support::Native,
            // An image-and-text table cell's content (docs/list.md "List items").
            Cap::ListItem => Support::Native,
            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
            // (docs/images.md).
            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
            // The announcement-requested notification, posted from the primary window
            // (docs/accessibility.md).
            Cap::Announce => Support::Native,
            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
            // posts its display-options change (docs/accessibility.md).
            Cap::ReduceMotion => Support::Native,
            Cap::Snapshot
            | Cap::NativeSymbols
            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
            // NSTabView owns its own page content, the opposite of Day's model — so the bar
            // is composed from the control a Mac uses for a one-of-N switch this size.
            //
            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
            // through to the `Unsupported` arm below.
            | Cap::NavTabs
            | Cap::NavSplit
            // Both presentations are the same NSSplitViewController — a stack is that split with
            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
            // that re-parents the sidebar page (docs/size-classes.md).
            | Cap::NavRepresent
            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
            // persists through every presentation (docs/navigation.md).
            | Cap::NavContentList
            | Cap::Dialogs
            | Cap::FileDialogs
            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
            | Cap::FolderDialog
            | Cap::Animation
            // NSTextView natively honors all three text-area attributes.
            | Cap::TextEditable
            | Cap::TextSelectable
            | Cap::TextSpellCheck
            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
            // lists and in the source-list sidebar itself (docs/navigation.md).
            | Cap::NavReorder | Cap::ListReorder
            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
            | Cap::ListRecycling
            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
            // activation (docs/list.md).
            | Cap::ListSwipeActions
            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
            | Cap::ListSections
            // NSOutlineView hosts Day-built rows natively, drag-reparent included
            // (docs/tree.md).
            | Cap::Tree
            | Cap::TreeSections
            | Cap::TreeMove
            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
            | Cap::MultiWindow
            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
            // delegate's notifications (docs/windows.md "Window properties").
            | Cap::WindowStates
            | Cap::WindowFullscreen
            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
            | Cap::ContentProtection
            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
            // own builder.
            | Cap::WindowTabbing
            // `applicationDockMenu:` on the app delegate (docs/menus.md).
            | Cap::DockMenu
            // Borderless windows that still take key, a transparent title bar over the
            // content, a clear window background, and `NSVisualEffectView` materials behind the
            // content (docs/window-chrome.md).
            | Cap::FramelessWindow
            | Cap::OverlayTitleBar
            | Cap::TransparentWindow
            | Cap::WindowMaterial
            // `performWindowDragWithEvent:` from a press on the region's own background.
            | Cap::DragRegion
            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
            // accessory activation policy (docs/status-item.md).
            | Cap::StatusItem
            | Cap::AppProgress
            | Cap::DockVisibility
            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
            // bounces, and `NSScreen` (docs/windows.md "Window properties").
            | Cap::WindowGeometry
            | Cap::WindowPosition
            | Cap::WindowLevel
            | Cap::WindowAppearance
            | Cap::RequestAttention
            | Cap::Monitors
            // Run-time shortcuts appear in the Dock menu beside the declared ones.
            | Cap::DynamicShortcuts
            // A real NSToolbar in the title bar (docs/toolbars.md).
            | Cap::Toolbar
            // The bar holds a native search field (docs/search.md).
            | Cap::ToolbarSearch
            | Cap::AppMenu
            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
            // only backend where Text is real (docs/badge.md).
            | Cap::AppBadgeCount
            | Cap::AppBadgeText
            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
            | Cap::UndoBridge
            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
            | Cap::AppBadgeDot
            | Cap::Appearance
            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
            | Cap::BaselineAlignment
            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
            // trailing-pane material and full-height layout (docs/inspector.md).
            | Cap::Inspector
            // A plain NSSplitView with two arranged panes (docs/split.md).
            | Cap::Split
            | Cap::TextRuns
            | Cap::TextLinks => Support::Native,
            // A topmost autoresizing child of the content view — not a system modal
            // (docs/cover.md's ArkUI tier).
            Cap::Cover => Support::Emulated,
            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
            Cap::CoverSheet => Support::Native,
            _ => Support::Unsupported,
        }
    }

    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
        let mtm = self.mtm;
        match Builtin::from_key(kind) {
            Some(Builtin::Container) => {
                let v = DayFlipped::new(mtm);
                if let Some(p) = props.downcast_ref::<ContainerProps>() {
                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
                        v.set_section_card(p.corner_radius);
                    } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
                        v.set_surface(p.background, p.corner_radius, p.clips);
                    }
                }
                view_of(v)
            }
            Some(Builtin::Scroll) => {
                let horizontal = props
                    .downcast_ref::<day_spec::props::ScrollProps>()
                    .map(|p| p.horizontal)
                    .unwrap_or(false);
                let sv = unsafe { NSScrollView::new(mtm) };
                unsafe {
                    sv.setHasVerticalScroller(!horizontal);
                    sv.setHasHorizontalScroller(horizontal);
                    sv.setDrawsBackground(false);
                    // Overlay scrollers ALWAYS: day lays content out at the scroll's full frame
                    // width, and a legacy scroller (the "always show scroll bars" system
                    // setting, or a mouse attached) would reserve ~15pt and clip trailing
                    // content. Overlay floats above content instead — and matches the GTK/Qt
                    // backends.
                    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
                }
                let doc = DayFlipped::new(mtm);
                unsafe { sv.setDocumentView(Some(doc.as_ref())) };
                view_of(sv)
            }
            Some(Builtin::Label) => {
                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
                // (a piece registered under a builtin key, or a day-core regression) warns once
                // per kind and degrades to the placeholder — realize runs inside native
                // up-calls, where a panic is a process kill.
                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let tf = DayLabel::new(mtm, id, &p.text);
                configure_label_cell(&tf);
                if !p.wraps || p.max_lines > 0 {
                    unsafe {
                        tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
                        if !p.wraps || p.max_lines == 1 {
                            tf.setUsesSingleLineMode(true);
                            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
                        }
                    }
                }
                unsafe { tf.setFont(Some(&nsfont(p.font))) };
                // The PLAIN path needs the role as much as the attributed one below: a label
                // with no runs never reaches `attributed_label`, and reading the role only there
                // left every ordinary `.secondary()` label rendering in the primary color.
                match (p.color, p.role) {
                    (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
                    (None, day_spec::props::TextRole::Secondary) => unsafe {
                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
                    },
                    (None, day_spec::props::TextRole::Primary) => {}
                }
                if !p.runs.is_empty() {
                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
                    unsafe { tf.setAttributedStringValue(&s) };
                }
                tf.ivars().has_runs.set(!p.runs.is_empty());
                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
                // Alignment goes on last and, for a runs label, has to reach inside the
                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
                // attributed string then overrides wholesale with its own — so a markdown label
                // set only through the cell comes out leading-aligned no matter what was asked.
                if p.align != day_spec::props::TextAlign::Leading {
                    unsafe { tf.setAlignment(nstextalign(p.align)) };
                    if !p.runs.is_empty() {
                        set_paragraph_alignment(&tf, nstextalign(p.align));
                    }
                }
                view_of(Retained::into_super(tf))
            }
            Some(Builtin::Button) => {
                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let target = DayTarget::new(mtm, id);
                let btn = unsafe {
                    NSButton::buttonWithTitle_target_action(
                        &NSString::from_str(&p.title),
                        Some(&*target),
                        Some(sel!(action:)),
                        mtm,
                    )
                };
                apply_button_style(&btn, p.style);
                if p.icon.is_some() {
                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
                }
                unsafe { btn.setEnabled(p.enabled) };
                set_button_selected(&btn, p.selected);
                let view = view_of(btn);
                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
                view
            }
            Some(Builtin::Toggle) => {
                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let target = DayTarget::new(mtm, id);
                let sw = unsafe { NSSwitch::new(mtm) };
                unsafe {
                    sw.setState(if p.on { 1 } else { 0 });
                    sw.setEnabled(p.enabled);
                    sw.setTarget(Some(&*target));
                    sw.setAction(Some(sel!(action:)));
                }
                let view = view_of(sw);
                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
                view
            }
            Some(Builtin::Slider) => {
                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let target = DayTarget::new(mtm, id);
                let sl = unsafe {
                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
                        p.value,
                        p.min,
                        p.max,
                        Some(&*target),
                        Some(sel!(action:)),
                        mtm,
                    )
                };
                unsafe { sl.setContinuous(true) };
                let view = view_of(sl);
                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
                view
            }
            Some(Builtin::Picker) => picker::realize_any(self, props, id),
            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
            Some(Builtin::TextField) => {
                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let tf = new_text_field(mtm, id, false);
                unsafe {
                    tf.setStringValue(&NSString::from_str(&p.text));
                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
                }
                view_of(tf)
            }
            Some(Builtin::Divider) => {
                let b = unsafe { NSBox::new(mtm) };
                unsafe { b.setBoxType(NSBoxType::Separator) };
                view_of(b)
            }
            Some(Builtin::Progress) => {
                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                if p.value.is_none() {
                    return crate::controls::spinner::make(self, p, id);
                }
                let pi = unsafe { NSProgressIndicator::new(mtm) };
                unsafe {
                    match p.value {
                        Some(v) => {
                            pi.setStyle(NSProgressIndicatorStyle::Bar);
                            pi.setIndeterminate(false);
                            pi.setMinValue(0.0);
                            pi.setMaxValue(1.0);
                            pi.setDoubleValue(v);
                        }
                        None => {
                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
                            pi.setIndeterminate(true);
                            pi.startAnimation(None);
                        }
                    }
                }
                view_of(pi)
            }
            Some(Builtin::Canvas) => {
                let canvas = DayCanvas::new(mtm);
                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
                view_of(canvas)
            }
            Some(Builtin::Inspector) => {
                let (visible, width, leading) = props
                    .downcast_ref::<InspectorProps>()
                    .map(|p| {
                        (
                            p.visible,
                            p.width,
                            p.edge == day_spec::props::PaneEdge::Leading,
                        )
                    })
                    .unwrap_or((false, 280.0, false));
                let content_wrap = view_of(DayFlipped::new(mtm));
                let panel_flipped = DayFlipped::new(mtm);
                // The panel draws an opaque window-background backdrop over the item's
                // vibrancy material — without it the section cards' thin quaternary fill
                // composites into near-black in dark mode (see `FlippedIvars`).
                panel_flipped.set_pane_backdrop();
                let panel_wrap = view_of(panel_flipped);
                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
                // Force loadView before the items go in — the same lifecycle rule the nav
                // host below documents.
                let _ = unsafe { split_vc.view() };
                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
                unsafe {
                    content_vc.setView(&content_wrap);
                    panel_vc.setView(&panel_wrap);
                }
                let content_item = unsafe {
                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
                };
                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
                // one is a plain item placed first: `sidebarWithViewController:` would bring
                // sidebar material, which captures black offscreen (docs/navigation.md), and
                // the panel wrap already paints its own backdrop.
                let panel_item = unsafe {
                    if leading {
                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
                    } else {
                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
                    }
                };
                unsafe {
                    // Day's signal is the only visibility driver: with the pinned width the
                    // divider has nothing to drag and the pane cannot be user-collapsed, so
                    // there is no native-initiated change to report back.
                    panel_item.setCanCollapse(false);
                    panel_item.setCollapsed(!visible);
                    panel_item.setMinimumThickness(width);
                    panel_item.setMaximumThickness(width);
                    panel_item.setAllowsFullHeightLayout(true);
                    if leading {
                        split_vc.addSplitViewItem(&panel_item);
                        split_vc.addSplitViewItem(&content_item);
                    } else {
                        split_vc.addSplitViewItem(&content_item);
                        split_vc.addSplitViewItem(&panel_item);
                    }
                }
                let split = unsafe { split_vc.splitView() };
                unsafe {
                    split.setVertical(true);
                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
                    // The same Auto Layout hand-back as the nav host below: Day owns this
                    // view's frame outside the split; the controller's own constraints keep
                    // doing the pane sizing inside it.
                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
                }
                let view = view_of(split);
                INSPECTOR_STATE.with(|m| {
                    m.borrow_mut().insert(
                        ptr_of(&view),
                        InspectorState {
                            content_wrap,
                            panel_wrap,
                            _split_vc: split_vc,
                            panel_item,
                        },
                    )
                });
                view
            }
            Some(Builtin::InspectorPane) => {
                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
                // frame is native-owned (the split sizes it), exactly like a nav page —
                // NAV_PAGES membership is what makes `set_frame` skip it.
                let pane = view_of(DayNavPage::new(mtm, id));
                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
                let panel = props
                    .downcast_ref::<InspectorPaneProps>()
                    .map(|p| p.panel)
                    .unwrap_or(false);
                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
                pane
            }
            Some(Builtin::Split) => {
                let (axis, fraction, min_pane) = props
                    .downcast_ref::<SplitProps>()
                    .map(|p| (p.axis, p.fraction, p.min_pane))
                    .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
                let wrap = view_of(DayFlipped::new(mtm));
                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
                let first_wrap = view_of(DayFlipped::new(mtm));
                let second_wrap = view_of(DayFlipped::new(mtm));
                unsafe {
                    // AppKit's "vertical" is the divider's orientation: panes side by side.
                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
                    split.addArrangedSubview(&first_wrap);
                    split.addArrangedSubview(&second_wrap);
                    split.setFrame(wrap.bounds());
                    split.setAutoresizingMask(
                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                    );
                    wrap.addSubview(&split);
                }
                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
                SPLIT_STATE.with(|m| {
                    m.borrow_mut().insert(
                        ptr_of(&wrap),
                        SplitState {
                            split,
                            first_wrap,
                            second_wrap,
                            delegate,
                        },
                    )
                });
                wrap
            }
            Some(Builtin::SplitPane) => {
                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
                // `setFrameSize:` reports `FrameChanged`.
                let pane = view_of(DayNavPage::new(mtm, id));
                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
                let second = props
                    .downcast_ref::<SplitPaneProps>()
                    .map(|p| p.second)
                    .unwrap_or(false);
                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
                pane
            }
            Some(Builtin::Nav) => {
                let presentation = props
                    .downcast_ref::<NavProps>()
                    .map(|p| p.presentation)
                    .unwrap_or(NavPresentation::Split);
                let is_split = presentation.is_split();
                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
                // the system treatment: AppKit installs its own backing material and vibrancy
                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
                // holding priority, animates collapse/expand, and drives the window's titlebar
                // separator. Day still owns the CONTENT of each pane — the two wraps below are
                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
                // unchanged.
                let sidebar_wrap = view_of(DayFlipped::new(mtm));
                let detail_wrap = view_of(DayFlipped::new(mtm));
                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
                // installs an item's view into the split as the item is added, which it can
                // only do once its own view exists — and reading `splitView` does not trigger
                // the lifecycle the way reading `view` does. Skipping this leaves a split view
                // with zero subviews: correct frame, nothing in it.
                let _ = unsafe { split_vc.view() };
                // Plain NSViewControllers with their view set explicitly: setting `view` up
                // front is what stops NSViewController looking for a nib named after itself.
                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
                unsafe {
                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
                }
                let sidebar_item = unsafe {
                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
                };
                let detail_item = unsafe {
                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
                };
                // The content-list pane (docs/navigation.md): a REAL `contentList`
                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
                // as the sidebar page fills its own wrap, and the pane persists through every
                // presentation (only `NavPatch::ListVisible` collapses it).
                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
                // Set before the item joins the split, exactly as the sidebar's is below. A
                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
                // that has not been displayed — reports as collapsed and is then laid back out
                // from the item's holding priorities, which is how an app whose first
                // destination has no list opened with one beside it anyway.
                let list_visible = props
                    .downcast_ref::<NavProps>()
                    .is_none_or(|p| p.list_visible);
                let (list_wrap, list_item) = match list_width {
                    Some(w) => {
                        let wrap = view_of(DayFlipped::new(mtm));
                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
                        let item = unsafe {
                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
                        };
                        unsafe {
                            item.setCanCollapse(true);
                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
                            item.setCollapsed(!list_visible);
                        }
                        (Some(wrap), Some(item))
                    }
                    None => (None, None),
                };
                unsafe {
                    // A stack presentation has no sidebar to show: collapse the (empty) pane
                    // and refuse the drag, so the detail owns the full width.
                    sidebar_item.setCanCollapse(is_split);
                    sidebar_item.setCollapsed(!is_split);
                    if is_split {
                        // Run the sidebar's material to the top of the window, under the
                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
                        // style the window already uses (toolbar.rs).
                        sidebar_item.setAllowsFullHeightLayout(true);
                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
                    } else {
                        sidebar_item.setMinimumThickness(0.0);
                        sidebar_item.setMaximumThickness(0.0);
                    }
                    split_vc.addSplitViewItem(&sidebar_item);
                    if let Some(item) = list_item.as_ref() {
                        split_vc.addSplitViewItem(item);
                    }
                    split_vc.addSplitViewItem(&detail_item);
                }
                let split = unsafe { split_vc.splitView() };
                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
                // and NSSplitViewController implements it — but a view controller only patches
                // itself into that chain when it is parented (a window's contentViewController
                // or another controller's child), and Day's tree is view-based all the way to
                // the window. Insert it by hand, directly after the split view, so a first
                // responder anywhere inside either pane walks up through it.
                unsafe {
                    let after = split.nextResponder();
                    split.setNextResponder(Some(&split_vc));
                    // The controller must never end up aiming at itself or at its OWN view,
                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
                    // splices itself out with `view.nextResponder = self.nextResponder`, and
                    // if that lands the view on itself AppKit raises "The next responder
                    // should never be yourself!" — an NSException that unwinds into Rust and
                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
                    // loaded split view's next IS the controller, and on 15+ `view` is a
                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
                    // that wrapper. Neither is a real upstream hop, so drop them.
                    let own_view = split_vc.view();
                    let vc_resp: *const objc2_app_kit::NSResponder = {
                        let r: &objc2_app_kit::NSResponder = &split_vc;
                        r
                    };
                    let view_resp: *const objc2_app_kit::NSResponder = {
                        let r: &objc2_app_kit::NSResponder = &own_view;
                        r
                    };
                    let upstream = after.filter(|a| {
                        let p: *const objc2_app_kit::NSResponder = &**a;
                        p != vc_resp && p != view_resp
                    });
                    split_vc.setNextResponder(upstream.as_deref());
                }
                unsafe {
                    split.setVertical(true);
                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
                    // Day owns this view's frame (`set_frame`). A split view vended by
                    // NSSplitViewController arrives switched over to Auto Layout, which
                    // ignores that frame and lays the split out at zero — a window with
                    // chrome and nothing under it. Hand it back to autoresizing translation
                    // so Day stays the layout owner outside the split; the constraints the
                    // controller installs BETWEEN the split and its panes are untouched and
                    // keep doing the pane sizing.
                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
                }
                let root_title = props
                    .downcast_ref::<NavProps>()
                    .map(|p| p.title.clone())
                    .unwrap_or_default();
                // Stack presentation: a back header (hidden at root) — desktop has no system
                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
                let header = if presentation == NavPresentation::Stack {
                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
                } else {
                    None
                };
                // A tabs host: the Mac's own tab control fills the detail pane and takes the
                // detail pages as its items (`TabHost`).
                let tabs = (presentation == NavPresentation::Tabs).then(|| {
                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
                    // Inset from the pane, the way a tab view sits in any Mac window: its
                    // tabs stand above the bezel, so flush to the top they run into the
                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
                    // autoresizing mask keeps the margins as the pane resizes.
                    let b = detail_wrap.bounds();
                    let frame = NSRect::new(
                        NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
                        NSSize::new(
                            (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
                            (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
                        ),
                    );
                    unsafe {
                        tv.setTabViewType(
                            if props
                                .downcast_ref::<NavProps>()
                                .is_some_and(|p| p.documents.is_some())
                            {
                                objc2_app_kit::NSTabViewType::NoTabsNoBorder
                            } else {
                                objc2_app_kit::NSTabViewType::TopTabsBezelBorder
                            },
                        );
                        tv.setFrame(frame);
                        tv.setAutoresizingMask(
                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                        );
                        detail_wrap.addSubview(&tv);
                    }
                    TabHost {
                        view: tv,
                        target: None,
                    }
                });
                let view = view_of(split);
                NAV_STATE.with(|m| {
                    m.borrow_mut().insert(
                        ptr_of(&view),
                        NavState {
                            sidebar_wrap,
                            detail_wrap,
                            _split_vc: split_vc,
                            sidebar_item,
                            list_wrap,
                            list_item,
                            pages: Vec::new(),
                            list_page: None,
                            sidebar_page: None,
                            list_width,
                            list_visible,
                            list_positioned: false,
                            positioned: false,
                            presentation,
                            selected: 0,
                            tabs,
                            header,
                            root_title,
                            node: id,
                            title_strip: 0.0,
                        },
                    )
                });
                view
            }
            Some(Builtin::NavPage) => {
                let page = view_of(DayNavPage::new(mtm, id));
                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
                }
                page
            }
            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
            Some(Builtin::Cover) => {
                let page = DayNavPage::new(mtm, id);
                let cover_props = props.downcast_ref::<CoverProps>();
                // A half sheet is a sheet here: macOS has no half-height presentation of its
                // own, so the window sheet stands in, at half the parent's height.
                page.ivars()
                    .sheet
                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
                unsafe { page.setHidden(true) };
                view_of(page)
            }
            Some(Builtin::NavMenu) => {
                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let data = DayNavMenuData::new(
                    mtm,
                    id,
                    &p.items,
                    &p.icons,
                    &p.badges,
                    &p.badge_icons,
                    &p.badge_tints,
                    &p.sections,
                    &p.tints,
                    &p.menus,
                );
                *data.ivars().movable.borrow_mut() = p.movable.clone();
                data.ivars().regroup.set(p.regroup);
                *data.ivars().sorted.borrow_mut() = p.sorted.clone();
                // The Day subclass serves per-row context menus via menuForEvent:.
                let outline: Retained<objc2_app_kit::NSOutlineView> = {
                    let o: Retained<DayNavOutlineView> =
                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
                    NAV_OUTLINE_MENUS
                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
                    unsafe { msg_send![&*o, self] }
                };
                let col = unsafe {
                    objc2_app_kit::NSTableColumn::initWithIdentifier(
                        objc2_app_kit::NSTableColumn::alloc(mtm),
                        &NSString::from_str("item"),
                    )
                };
                unsafe {
                    outline.addTableColumn(&col);
                    outline.setOutlineTableColumn(Some(&col));
                    outline.setHeaderView(None);
                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
                    // material and the vibrancy the source-list selection composites through.
                    // This was Inset until 2026-08 because the earlier hand-rolled
                    // NSVisualEffectView blended behind the window, and an offscreen capture
                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
                    // a black pill that swallowed the row label. The material is AppKit's own
                    // now, and captures go through the window server (`snapshot_view`), which
                    // composites the material for real instead of guessing at it.
                    // `style = SourceList` is the whole switch: the matching
                    // `selectionHighlightStyle` constant is deprecated precisely because the
                    // style property now implies it.
                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
                    // The default row size style follows the system's Sidebar icon size
                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
                    // sets the row height, the label's font and the icon's size. A table made
                    // in code starts at Custom, which ignores the setting.
                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
                    // Section headers pin to the top of the scroll as their group passes under
                    // it, the way Finder's sidebar groups do.
                    outline.setFloatsGroupRows(true);
                    outline.setIndentationPerLevel(0.0);
                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
                    outline.registerForDraggedTypes(
                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
                            DAY_NAV_PASTEBOARD_TYPE,
                        )]),
                    );
                    outline.setDraggingSourceOperationMask_forLocal(
                        objc2_app_kit::NSDragOperation::Move,
                        true,
                    );
                    outline.setDraggingSourceOperationMask_forLocal(
                        objc2_app_kit::NSDragOperation::None,
                        false,
                    );
                    outline.setDraggingDestinationFeedbackStyle(
                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
                    );
                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
                    outline.reloadData();
                }
                let scroll = unsafe { NSScrollView::new(mtm) };
                unsafe {
                    scroll.setDrawsBackground(false);
                    scroll.setHasVerticalScroller(true);
                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
                    // clip the trailing edge of rows laid out at the full frame width (see
                    // the SCROLL realize).
                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
                    // One column, sized to the pane: a sidebar never scrolls sideways.
                    scroll.setHasHorizontalScroller(false);
                    outline.setAutoresizingMask(
                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
                    );
                    outline.setColumnAutoresizingStyle(
                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
                    );
                    scroll.setDocumentView(Some(&outline));
                }
                let view = view_of(scroll);
                // Day selects by ITEM index; section headers make that differ from the
                // outline's row index, so every programmatic selection maps through `rows`.
                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
                    data.ivars().suppress.set(true);
                    unsafe {
                        outline.selectRowIndexes_byExtendingSelection(
                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
                            false,
                        )
                    };
                    data.ivars().suppress.set(false);
                }
                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
                view
            }
            Some(Builtin::List) => {
                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                // Every list reports responder changes, even without an activation handler.
                let table: Retained<DayListView> =
                    unsafe { msg_send![DayListView::alloc(mtm), init] };
                let table = Retained::into_super(table);
                let col = unsafe {
                    NSTableColumn::initWithIdentifier(
                        NSTableColumn::alloc(mtm),
                        &NSString::from_str("day.list.col"),
                    )
                };
                let data = DayListData::new(
                    mtm,
                    id,
                    p.selectable,
                    p.multi_select,
                    p.row_height == RowHeight::Automatic,
                    p.sections,
                );
                unsafe {
                    if p.multi_select {
                        table.setAllowsMultipleSelection(true);
                    }
                    table.addTableColumn(&col);
                    table.setHeaderView(None);
                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
                    // row content laid out at the host's full frame width. This table ran
                    // FullWidth with a custom NSTableRowView pinning cells back to the row
                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
                    // AppKit performs for row-action swipes, so the actions revealed behind a
                    // row whose CONTENT never moved. Plain has no inset to fight: standard
                    // row views, standard cell frames, and the swipe slide works untouched.
                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
                    // same way — the last few points of a trailing control. Day rows own all
                    // of their spacing.
                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
                    // Host-drawn row separators (docs/list.md): the native horizontal grid
                    // line, which sits exactly at the row boundary — aligned with the
                    // selection, stationary under a row-action swipe, the Mail look.
                    if p.separators == Some(true) {
                        table.setGridStyleMask(
                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
                        );
                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
                    }
                    table.setColumnAutoresizingStyle(
                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
                    );
                    // Section headers pin to the top while their section scrolls under them,
                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
                    table.setFloatsGroupRows(p.sections);
                    match p.row_height {
                        RowHeight::Uniform(h) => table.setRowHeight(h),
                        RowHeight::Automatic => table.setRowHeight(44.0),
                    }
                    if !p.selectable {
                        table.setSelectionHighlightStyle(
                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
                        );
                    }
                    // Transparent: day panes own their backgrounds — the stock
                    // controlBackgroundColor would paint an appearance-colored slab that
                    // fights a themed app (visible whenever rows don't fill the viewport).
                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
                    table.setTarget(Some(&*data));
                    if p.activatable {
                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
                    }
                    if p.reorderable {
                        // Native drag-to-reorder (docs/list.md): rows drag within this table
                        // only (move locally, nothing leaves the app), and the drop target shows
                        // macOS's temporary placeholder GAP while the drag is over the table.
                        table.registerForDraggedTypes(
                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
                                DAY_ROW_PASTEBOARD_TYPE,
                            )]),
                        );
                        table.setDraggingSourceOperationMask_forLocal(
                            objc2_app_kit::NSDragOperation::Move,
                            true,
                        );
                        table.setDraggingSourceOperationMask_forLocal(
                            objc2_app_kit::NSDragOperation::None,
                            false,
                        );
                        table.setDraggingDestinationFeedbackStyle(
                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
                        );
                    }
                }
                let scroll = unsafe { NSScrollView::new(mtm) };
                unsafe {
                    scroll.setDrawsBackground(false);
                    scroll.setHasVerticalScroller(true);
                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
                    // clip the trailing edge of rows laid out at the full frame width (see
                    // the SCROLL realize).
                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
                    scroll.setDocumentView(Some(&table));
                    let clip = scroll.contentView();
                    clip.setPostsBoundsChangedNotifications(true);
                    objc2_foundation::NSNotificationCenter::defaultCenter()
                        .addObserver_selector_name_object(
                            &data,
                            sel!(listViewportChanged:),
                            Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
                            Some(&clip),
                        );
                }
                let view = view_of(scroll);
                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
                view
            }
            Some(Builtin::Tree) => {
                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                // The width-pinning subclass (see DayOutlineView).
                let outline: Retained<objc2_app_kit::NSOutlineView> = {
                    let o: Retained<DayOutlineView> =
                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
                    unsafe { msg_send![&*o, self] }
                };
                let col = unsafe {
                    NSTableColumn::initWithIdentifier(
                        NSTableColumn::alloc(mtm),
                        &NSString::from_str("day.tree.col"),
                    )
                };
                let data = DayTreeData::new(mtm, id, p.selectable);
                unsafe {
                    if p.multi_select {
                        outline.setAllowsMultipleSelection(true);
                    }
                    outline.addTableColumn(&col);
                    outline.setOutlineTableColumn(Some(&col));
                    outline.setHeaderView(None);
                    if p.section_headers {
                        // Real source-list groups use AppKit's trailing, hover-revealed
                        // show/hide button and float over their children while scrolling.
                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
                        outline.setFloatsGroupRows(true);
                    } else {
                        // Generic trees keep their existing full-width cells and rounded
                        // DayTreeRowView selection. Source lists use native row drawing.
                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
                    }
                    outline.setColumnAutoresizingStyle(
                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
                    );
                    outline.setAutoresizesOutlineColumn(true);
                    if let Some(indent) = p.indent {
                        outline.setIndentationPerLevel(indent);
                    }
                    match p.row_height {
                        RowHeight::Uniform(h) => outline.setRowHeight(h),
                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
                        RowHeight::Automatic => {}
                    }
                    if !p.selectable {
                        outline.setSelectionHighlightStyle(
                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
                        );
                    }
                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
                    if p.movable {
                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
                        // must distinguish "between rows" (insertion line) from "ONTO a row"
                        // (the highlighted-parent drop), and Gap has no onto affordance.
                        outline.registerForDraggedTypes(
                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
                                DAY_TREE_PASTEBOARD_TYPE,
                            )]),
                        );
                        outline.setDraggingSourceOperationMask_forLocal(
                            objc2_app_kit::NSDragOperation::Move,
                            true,
                        );
                        outline.setDraggingSourceOperationMask_forLocal(
                            objc2_app_kit::NSDragOperation::None,
                            false,
                        );
                    }
                }
                let scroll = unsafe { NSScrollView::new(mtm) };
                unsafe {
                    scroll.setDrawsBackground(false);
                    scroll.setHasVerticalScroller(true);
                    scroll.setHasHorizontalScroller(false);
                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
                    outline.setAutoresizingMask(
                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
                    );
                    scroll.setDocumentView(Some(&outline));
                }
                let view = view_of(scroll);
                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
                view
            }
            Some(Builtin::Image) => {
                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
                    return placeholder_view(mtm, kind);
                };
                let iv: Retained<objc2_app_kit::NSImageView> =
                    if p.content_mode == ContentMode::Fill {
                        let view: Retained<FillImageView> =
                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
                        Retained::from(
                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
                        )
                    } else {
                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
                    };
                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
                // scales each axis independently, and Fit keeps the stock image view.
                let scaling = match p.content_mode {
                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
                };
                unsafe { iv.setImageScaling(scaling) };
                if let Some(img) = appkit_image_for(&p.source) {
                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's
                    // content tint — AppKit recolors the alpha mask natively. A template with
                    // no tint keeps the view's nil tint: the neutral template color the nav
                    // menu's own rows draw with, light in dark mode, dark in light.
                    if p.tint.is_some() || p.template {
                        unsafe { img.setTemplate(true) };
                    }
                    unsafe { iv.setImage(Some(&img)) };
                }
                if let Some(t) = p.tint {
                    unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
                }
                IMAGE_MODES.with(|t| {
                    t.insert(
                        ptr_of(&iv),
                        ImageMode {
                            template: p.template,
                            tinted: p.tint.is_some(),
                        },
                    )
                });
                view_of(iv)
            }
            Some(Builtin::ListItem) => {
                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
                else {
                    return placeholder_view(mtm, kind);
                };
                make_list_item(p, mtm)
            }
            // A recycled list cell is ADOPTED from the native list, never realized
            // through this path; anything else is an extension piece.
            Some(Builtin::ListCell) | None => {
                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
                    return make(self, props, id);
                }
                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
                // placeholder (§8.2's debug check will panic first in debug builds once the
                // required-kinds set lands).
                warn_missing_renderer(kind);
                placeholder_view(mtm, kind)
            }
        }
    }

    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
        match kind {
            kinds::LIST_ITEM => {
                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
                    return;
                };
                let props = LIST_ITEMS.with(|m| {
                    let mut m = m.borrow_mut();
                    let props = m.get_mut(&ptr_of(h))?;
                    use day_spec::props::ListItemPatch as P;
                    match p {
                        P::Title(t) => props.title = t.clone(),
                        P::Subtitle(t) => props.subtitle = t.clone(),
                        P::Detail(t) => props.detail = t.clone(),
                        P::Icon(i) => props.icon = i.clone(),
                        P::IconTint(c) => props.icon_tint = *c,
                        P::Checked(on) => props.checked = *on,
                    }
                    Some(props.clone())
                });
                if let Some(props) = props {
                    dress_list_item(h, &props, self.mtm());
                }
            }
            kinds::IMAGE => {
                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
                    match p {
                        day_spec::props::ImagePatch::Tint(c) => {
                            // Template rendering + the view's content tint, exactly as at realize
                            // — the glyph repaints in place rather than being rebuilt
                            // (docs/vectors.md). A template glyph stays one when the tint goes.
                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
                                let key = ptr_of(&iv);
                                let template = IMAGE_MODES
                                    .with(|t| {
                                        t.with(key, |m| {
                                            m.tinted = c.is_some();
                                            m.renders_template()
                                        })
                                    })
                                    .unwrap_or(c.is_some());
                                if let Some(img) = unsafe { iv.image() } {
                                    unsafe { img.setTemplate(template) };
                                }
                                unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
                            }
                        }
                        // A source swap repaints the same view (docs/images.md), so an `image()`
                        // bound to a signal shows new pixels without rebuilding its subtree —
                        // which is what makes a decode-then-show flow a patch and not a rebuild.
                        day_spec::props::ImagePatch::Source(source) => {
                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
                                // A source that will not load leaves the view showing what it
                                // was — the patch's contract, and what GTK, Qt and Android do.
                                // The new image renders the way the view does: a tinted or
                                // template glyph stays one, so a recycled sidebar row shows the
                                // icon it was rebound to in the same color.
                                if let Some(img) = appkit_image_for(source) {
                                    let template = IMAGE_MODES
                                        .with(|t| t.get(ptr_of(&iv)))
                                        .is_some_and(|m| m.renders_template());
                                    unsafe {
                                        img.setTemplate(template);
                                        iv.setImage(Some(&img));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            kinds::CONTAINER => {
                if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
                    patch.downcast_ref::<ContainerPatch>(),
                    h.clone().downcast::<DayFlipped>(),
                ) {
                    // A background patch only targets a background container (corner radius 0).
                    // The AnimSpec is not honored: the fill is drawRect content
                    // (rasterized by our own drawing code so dynamic system colors re-resolve
                    // per appearance), not a CALayer property, and Core Animation only
                    // interpolates layer properties, so there is nothing for the render server
                    // to tween. Day animates only what the toolkit's animator can execute
                    // (§8.4), so an animated background change applies at commit here.
                    v.set_surface(*c, 0.0, false);
                }
            }
            kinds::LABEL => {
                if let (Some(p), Ok(tf)) = (
                    patch.downcast_ref::<LabelPatch>(),
                    h.clone().downcast::<NSTextField>(),
                ) {
                    match p {
                        LabelPatch::Text(t) => {
                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
                            if let Some(label) = h.downcast_ref::<DayLabel>() {
                                label.ivars().has_runs.set(false);
                                label.set_links(false);
                            }
                        }
                        LabelPatch::Color(c) => unsafe {
                            tf.setTextColor(c.map(nscolor).as_deref())
                        },
                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
                        LabelPatch::Runs(text, runs) => {
                            // The field's current font is the base the runs sit on, taken as the
                            // live object rather than rebuilt from a `FontSpec`, which would lose
                            // the semantic style behind the resolved size.
                            let base = unsafe { tf.font() };
                            let s = match base.as_deref() {
                                Some(f) => {
                                    attributed_label(text, f, None, Default::default(), runs)
                                }
                                None => attributed_label(
                                    text,
                                    &nsfont(day_spec::FontSpec::default()),
                                    None,
                                    Default::default(),
                                    runs,
                                ),
                            };
                            unsafe { tf.setAttributedStringValue(&s) };
                            // Preserve paragraph alignment and activate links introduced by a
                            // reactive markdown update without replacing the native label.
                            set_paragraph_alignment(&tf, unsafe { tf.alignment() });
                            if let Some(label) = h.downcast_ref::<DayLabel>() {
                                label.ivars().has_runs.set(!runs.is_empty());
                                label.set_links(runs.iter().any(|r| r.link.is_some()));
                            }
                        }
                    }
                }
            }
            kinds::BUTTON => {
                if let (Some(p), Ok(btn)) = (
                    patch.downcast_ref::<ButtonPatch>(),
                    h.clone().downcast::<NSButton>(),
                ) {
                    match p {
                        ButtonPatch::Content(c) => {
                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
                        }
                        ButtonPatch::Title(t) => {
                            let style = BUTTON_STYLES
                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
                                .unwrap_or_default();
                            set_button_title(&btn, t, style);
                        }
                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
                    }
                }
            }
            kinds::TOGGLE => {
                if let (Some(p), Ok(sw)) = (
                    patch.downcast_ref::<TogglePatch>(),
                    h.clone().downcast::<NSSwitch>(),
                ) {
                    match p {
                        TogglePatch::On(on) => {
                            let want = if *on { 1 } else { 0 };
                            if unsafe { sw.state() } != want {
                                unsafe { sw.setState(want) };
                            }
                        }
                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
                    }
                }
            }
            kinds::SLIDER => {
                if let (Some(p), Ok(sl)) = (
                    patch.downcast_ref::<SliderPatch>(),
                    h.clone().downcast::<NSSlider>(),
                ) {
                    match p {
                        SliderPatch::Value(v) => {
                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
                                unsafe { sl.setDoubleValue(*v) };
                            }
                        }
                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
                    }
                }
            }
            kinds::PROGRESS => {
                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
                {
                    crate::controls::spinner::update(self, h, p);
                    return;
                }

                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
                    patch.downcast_ref::<ProgressPatch>(),
                    h.clone().downcast::<NSProgressIndicator>(),
                ) {
                    unsafe {
                        match v {
                            Some(val) => {
                                if pi.isIndeterminate() {
                                    pi.stopAnimation(None);
                                    pi.setIndeterminate(false);
                                    pi.setStyle(NSProgressIndicatorStyle::Bar);
                                    pi.setMinValue(0.0);
                                    pi.setMaxValue(1.0);
                                }
                                if (pi.doubleValue() - val).abs() > 0.0001 {
                                    pi.setDoubleValue(*val);
                                }
                            }
                            None => {
                                pi.setIndeterminate(true);
                                pi.setStyle(NSProgressIndicatorStyle::Spinning);
                                pi.startAnimation(None);
                            }
                        }
                    }
                }
            }
            kinds::NAV_MENU => {
                if let Some(NavMenuPatch::Items {
                    items,
                    icons,
                    badges,
                    badge_icons,
                    badge_tints,
                    sections,
                    tints,
                    menus,
                    movable,
                    sorted,
                    selected,
                    rows_changed,
                    ..
                }) = patch.downcast_ref::<NavMenuPatch>()
                {
                    NAV_MENUS.with(|m| {
                        let m = m.borrow();
                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
                            return;
                        };
                        *data.ivars().movable.borrow_mut() = movable.clone();
                        *data.ivars().sorted.borrow_mut() = sorted.clone();
                        data.set_items(
                            items,
                            icons,
                            badges,
                            badge_icons,
                            badge_tints,
                            sections,
                            tints,
                            menus,
                        );
                        data.ivars().suppress.set(true);
                        // The same rows with new words or counts: reload just those rows, which
                        // keeps the selection and every other row's view.
                        if let Some(rows) = rows_changed {
                            let set = objc2_foundation::NSMutableIndexSet::new();
                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
                                unsafe { set.addIndex(row) };
                            }
                            unsafe {
                                outline.reloadDataForRowIndexes_columnIndexes(
                                    &set,
                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
                                )
                            };
                            data.ivars().suppress.set(false);
                            return;
                        }
                        unsafe {
                            outline.reloadData();
                            match selected.and_then(|i| data.row_of_item(i)) {
                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
                                    false,
                                ),
                                None => outline.deselectAll(None),
                            }
                        }
                        data.ivars().suppress.set(false);
                    });
                    // The rows are a tabs host's labels where the menu sits in one.
                    adopt_menu_for_tabs(self.mtm(), h);
                } else if let Some(NavMenuPatch::IconProgress(progress)) =
                    patch.downcast_ref::<NavMenuPatch>()
                {
                    NAV_MENUS.with(|menus| {
                        let menus = menus.borrow();
                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
                            return;
                        };
                        let previous = data.ivars().icon_progress.replace(progress.clone());
                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
                            let Some(index) = item else {
                                continue;
                            };
                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
                                continue;
                            }
                            if let Some(view) = unsafe {
                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
                            } && let Some(cell) =
                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
                                && let Some(icon) = unsafe { cell.imageView() }
                            {
                                nav_progress::update(&icon, value);
                            }
                        }
                    });
                } else if let Some(NavMenuPatch::Selected(sel)) =
                    patch.downcast_ref::<NavMenuPatch>()
                {
                    NAV_MENUS.with(|m| {
                        let m = m.borrow();
                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
                            return;
                        };
                        data.ivars().suppress.set(true);
                        unsafe {
                            match sel.and_then(|i| data.row_of_item(i)) {
                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
                                    false,
                                ),
                                None => outline.deselectAll(None),
                            }
                        }
                        data.ivars().suppress.set(false);
                    });
                }
            }
            kinds::INSPECTOR => {
                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
                    INSPECTOR_STATE.with(|m| {
                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
                            // Directly, not through the animator proxy: a screenshot must not
                            // catch a mid-animation pane (the sidebar-toggle rule).
                            state.panel_item.setCollapsed(!*v);
                        }
                    });
                }
            }
            kinds::SPLIT => {
                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
                    SPLIT_STATE.with(|m| {
                        let m = m.borrow();
                        let Some(state) = m.get(&ptr_of(h)) else {
                            return;
                        };
                        let iv = state.delegate.ivars();
                        match p {
                            SplitPatch::Fraction(f) => {
                                iv.share.set(f.clamp(0.0, 1.0));
                                if iv.positioned.get() {
                                    split_place(&state.split, iv);
                                }
                            }
                            SplitPatch::Axis(axis) => unsafe {
                                state
                                    .split
                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
                                state.split.adjustSubviews();
                                if iv.positioned.get() {
                                    split_place(&state.split, iv);
                                }
                            },
                        }
                    });
                }
            }
            kinds::NAV => {
                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
                    nav_present(self.mtm(), h, *next);
                    return;
                }
                if let Some(p) = patch.downcast_ref::<NavPatch>() {
                    NAV_STATE.with(|m| {
                        let mut m = m.borrow_mut();
                        let Some(state) = m.get_mut(&ptr_of(h)) else {
                            return;
                        };
                        match p {
                            NavPatch::Pushed { title, .. } => {
                                // Only the new top detail page stays visible.
                                let last = state.pages.len().saturating_sub(1);
                                state.selected = last;
                                for (i, page) in state.pages.iter().enumerate() {
                                    page.setHidden(i != last);
                                }
                                if let Some(hdr) = state.header.as_mut() {
                                    hdr.titles.push(title.clone());
                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
                                }
                            }
                            NavPatch::Popped => {
                                // Hide the outgoing top; reveal its predecessor (Day
                                // removes the popped page right after this patch).
                                let n = state.pages.len();
                                if let Some(top) = state.pages.last() {
                                    top.setHidden(true);
                                }
                                if n >= 2 {
                                    state.pages[n - 2].setHidden(false);
                                }
                                state.selected = n.saturating_sub(2);
                                if let Some(hdr) = state.header.as_mut() {
                                    if hdr.titles.len() > 1 {
                                        hdr.titles.pop();
                                    }
                                    // The popped page is still in `pages` here (Day removes
                                    // it right after this patch), so frame for depth-after-pop.
                                    let after: Vec<Retained<NSView>> = state
                                        .pages
                                        .iter()
                                        .take(n.saturating_sub(1))
                                        .cloned()
                                        .collect();
                                    sync_nav_header(hdr, &state.detail_wrap, &after);
                                }
                            }
                            NavPatch::Title(t) => {
                                if let Some(hdr) = state.header.as_mut() {
                                    if let Some(last) = hdr.titles.last_mut() {
                                        *last = t.clone();
                                    }
                                    unsafe {
                                        hdr.title.setStringValue(&NSString::from_str(t));
                                    }
                                }
                            }
                            // The custom back header always routes back through Day
                            // (NavBack{already_popped:false}), so there is no native auto-pop to
                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
                            NavPatch::GuardTop(_) => {}
                            NavPatch::Reorder(order) => {
                                let old = state.pages.clone();
                                state.pages =
                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
                                if let Some(tabs) = &state.tabs {
                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
                                    unsafe {
                                        let items = tabs.view.tabViewItems();
                                        for item in items.iter() {
                                            tabs.view.removeTabViewItem(&item);
                                        }
                                        for i in order {
                                            if let Some(item) = items.iter().nth(*i) {
                                                tabs.view.addTabViewItem(&item);
                                            }
                                        }
                                    }
                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
                                }
                            }
                            // Handled outside this borrow (it re-homes views and builds chrome).
                            NavPatch::Presentation(_) => {}
                            // Resident-page switch (docs/navigation.md): every page stays in the
                            // view hierarchy and only one is unhidden, so switching tabs keeps
                            // each page's scroll position and first responder exactly as left.
                            NavPatch::Select(i) => {
                                state.selected = *i;
                                match state.tabs.as_ref() {
                                    // The tab view shows exactly its selected item's page.
                                    Some(tabs) => {
                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
                                        if (*i as isize) < n {
                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
                                            unsafe {
                                                tabs.view.selectTabViewItemAtIndex(*i as isize)
                                            };
                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
                                        }
                                    }
                                    None => {
                                        for (n, page) in state.pages.iter().enumerate() {
                                            page.setHidden(n != *i);
                                        }
                                    }
                                }
                            }
                            // Per-destination pane visibility (docs/navigation.md). Directly,
                            // not through the animator proxy: a screenshot must not catch a
                            // mid-animation pane (the sidebar-toggle rule), and settled now,
                            // like a re-present, so the detail's frame is right the instant
                            // the patch returns rather than one layout pass later.
                            NavPatch::ListVisible(v) => {
                                state.list_visible = *v;
                                if let Some(item) = state.list_item.as_ref() {
                                    item.setCollapsed(!*v);
                                    let split = unsafe { state._split_vc.splitView() };
                                    unsafe { split.layoutSubtreeIfNeeded() };
                                    // First time this pane is actually on screen: give it the
                                    // width the app asked for. The frame pass that would
                                    // otherwise do it has already run, back when there was no
                                    // pane to size.
                                    if let Some(w) = take_list_placement(state) {
                                        unsafe {
                                            split.setPosition_ofDividerAtIndex(
                                                day_spec::NAV_SIDEBAR_WIDTH + w,
                                                1,
                                            );
                                        }
                                    }
                                    // Re-frame the pane's page to the wrap it fills. A page
                                    // inserted while the pane was collapsed got a zero-width
                                    // frame, and `ViewWidthSizable` scales zero to zero however
                                    // wide the wrap becomes, so the list stayed invisible while
                                    // its rows were still there to click. An app opening on a
                                    // full-page section hits this on the first reveal.
                                    if *v
                                        && let Some(wrap) = state.list_wrap.as_ref()
                                        && let Some(page) = state.list_page.as_ref()
                                    {
                                        unsafe {
                                            wrap.layoutSubtreeIfNeeded();
                                            page.setFrame(wrap.bounds());
                                        }
                                    }
                                }
                            }
                            // Never arrives here: the pane persists through every presentation
                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
                            // for the merged-stack shape.
                            NavPatch::ListInStack(_) => {}
                        }
                    });
                }
            }
            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
            // this backend, so DismissDisabled has nothing to disable.
            kinds::COVER => {
                if let (Some(p), Ok(page)) = (
                    patch.downcast_ref::<CoverPatch>(),
                    h.clone().downcast::<DayNavPage>(),
                ) {
                    let node = page.ivars().node;
                    match p {
                        CoverPatch::Present { background, .. } => {
                            if page.ivars().sheet.get() {
                                if let Some(parent) =
                                    primary_content().and_then(|v| unsafe { v.window() })
                                {
                                    let bounds = parent.frame().size;
                                    let height = if page.ivars().half.get() {
                                        (bounds.height * 0.5).clamp(160.0, 620.0)
                                    } else {
                                        (bounds.height - 80.0).clamp(300.0, 620.0)
                                    };
                                    let size = NSSize::new(
                                        (bounds.width - 40.0).clamp(320.0, 640.0),
                                        height,
                                    );
                                    let window = unsafe {
                                        NSWindow::initWithContentRect_styleMask_backing_defer(
                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
                                            NSWindowStyleMask::Titled,
                                            NSBackingStoreType::Buffered,
                                            false,
                                        )
                                    };
                                    unsafe {
                                        window.setReleasedWhenClosed(false);
                                        page.removeFromSuperview();
                                        page.setHidden(false);
                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
                                        window.setContentView(Some(&page));
                                    }
                                    let key = ptr_of(h);
                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
                                    dispatch2::DispatchQueue::main().exec_async(move || {
                                        ffi_guard::contain((), || {
                                            let window =
                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
                                            if let (Some(window), Some(parent)) = (
                                                window,
                                                primary_content()
                                                    .and_then(|v| unsafe { v.window() }),
                                            ) {
                                                unsafe {
                                                    parent.beginSheet_completionHandler(
                                                        &window, None,
                                                    );
                                                }
                                            }
                                        });
                                    });
                                    emit(
                                        node,
                                        Event::FrameChanged(Size::new(size.width, size.height)),
                                    );
                                }
                                return;
                            }
                            // A cover must occlude the window (the native tiers' modal surfaces
                            // are opaque): default to the window background when the app sets
                            // no explicit color.
                            unsafe {
                                page.setWantsLayer(true);
                                if let Some(layer) = page.layer() {
                                    let color = match background {
                                        Some(bg) => nscolor(*bg),
                                        None => NSColor::windowBackgroundColor(),
                                    };
                                    layer.setBackgroundColor(Some(&color.CGColor()));
                                }
                            }
                            // The primary window's content, specifically: firstObject()
                            // is arbitrary once secondary windows exist (docs/windows.md).
                            if let Some(content) = primary_content() {
                                if let Some(window) = unsafe { content.window() } {
                                    toolbar::cover_presented(ptr_of(h), &window);
                                }
                                // Edge to edge like the root's own background, laid out below
                                // the title bar like the root's content: the page starts at the
                                // top of the window (above the pinned content origin) and
                                // keeps the same strip above its own layout origin.
                                let top = title_bar_inset(&content);
                                let full = content.frame().size;
                                page.ivars().top_inset.set(top);
                                unsafe {
                                    page.removeFromSuperview();
                                    content.addSubview(&page);
                                    page.setFrame(NSRect::new(
                                        NSPoint::new(0.0, -top),
                                        NSSize::new(full.width, full.height),
                                    ));
                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
                                    page.setAutoresizingMask(
                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                                    );
                                    page.setHidden(false);
                                }
                                emit(
                                    node,
                                    Event::FrameChanged(Size::new(
                                        full.width,
                                        (full.height - top).max(0.0),
                                    )),
                                );
                            }
                        }
                        CoverPatch::DismissDisabled(_) => {}
                        CoverPatch::Dismiss => {
                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
                            toolbar::cover_dismissed(ptr_of(h));
                            unsafe {
                                page.setHidden(true);
                                page.removeFromSuperview();
                            }
                            emit(node, Event::CoverHidden);
                        }
                    }
                }
            }
            kinds::PICKER => picker::update_any(self, h, patch),
            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
            kinds::TEXT_FIELD => {
                if let (Some(p), Ok(tf)) = (
                    patch.downcast_ref::<TextFieldPatch>(),
                    h.clone().downcast::<NSTextField>(),
                ) {
                    match p {
                        TextFieldPatch::Text { text, from_native } => {
                            // Origin-tagged echo suppression (§4.4).
                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
                            }
                        }
                        TextFieldPatch::Placeholder(t) => unsafe {
                            tf.setPlaceholderString(Some(&NSString::from_str(t)))
                        },
                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
                    }
                }
            }
            kinds::LIST => match patch.downcast_ref::<ListPatch>() {
                Some(ListPatch::Splice(deltas)) => {
                    // The set changed by exactly these deltas: animate each row in, out, or
                    // across, the thing a reload cannot express. Indexes are sequential, so
                    // each delta gets its own begin/endUpdates batch (NSTableView's combined
                    // batch semantics re-interpret indexes; one-at-a-time stays literal).
                    // Row realization stays deferred, as with Reload.
                    if let Some((table, data)) = list_entry(ptr_of(h)) {
                        use objc2_app_kit::NSTableViewAnimationOptions;
                        for d in deltas {
                            unsafe {
                                table.beginUpdates();
                                match d {
                                    day_spec::props::RowDelta::Insert(i) => table
                                        .insertRowsAtIndexes_withAnimation(
                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
                                            NSTableViewAnimationOptions::SlideDown,
                                        ),
                                    day_spec::props::RowDelta::Remove(i) => table
                                        .removeRowsAtIndexes_withAnimation(
                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
                                            NSTableViewAnimationOptions::SlideUp,
                                        ),
                                    day_spec::props::RowDelta::Move(from, to) => {
                                        table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
                                    }
                                }
                                table.endUpdates();
                            }
                        }
                        // The displayed order matches the source again: refresh the cache a
                        // committed drag keeps in step and `permutation_moves` compares, or the
                        // next Reload finds a stale length and reloads flat instead of animating.
                        if let Some(source) = data.ivars().source.borrow().as_ref() {
                            let n = (source.len)();
                            *data.ivars().tokens.borrow_mut() =
                                (0..n).map(|i| (source.token_at)(i)).collect();
                        }
                    }
                    post_realize_visible_rows(ptr_of(h));
                }
                Some(ListPatch::Reload) => {
                    if let Some((table, data)) = list_entry(ptr_of(h)) {
                        // NSTableView reloadData clears selection for this view-based source.
                        // Preserve identities, not indexes, across refreshes/reorders; removed
                        // items disappear from the selection without selecting their successor.
                        let selected = unsafe { table.selectedRowIndexes() };
                        let tokens: Vec<u64> = data
                            .ivars()
                            .tokens
                            .borrow()
                            .iter()
                            .enumerate()
                            .filter(|(row, _)| selected.containsIndex(*row))
                            .map(|(_, token)| *token)
                            .collect();
                        data.ivars().suppress.set(true);
                        // A reload whose rows are the same set in a new order (a shuffle,
                        // a programmatic sort) animates as native row moves instead of a
                        // blink: a `moveRowAtIndex` batch, the same animation a drag commit
                        // gets. Anything else (insert/remove/content change) reloads flat.
                        // reloadData queries numberOfRows synchronously (snapshot only, no
                        // tree) and defers viewForRow, so both paths are safe in with_tree.
                        if let Some(moves) = data.permutation_moves(&table) {
                            unsafe {
                                table.beginUpdates();
                                for (from, to) in moves {
                                    table.moveRowAtIndex_toIndex(from as isize, to as isize);
                                }
                                table.endUpdates();
                            }
                        } else {
                            unsafe { table.reloadData() };
                        }
                        let restored = objc2_foundation::NSMutableIndexSet::new();
                        for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
                            if tokens.contains(token) {
                                restored.addIndex(row);
                            }
                        }
                        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
                        data.ivars().suppress.set(false);
                    }
                    // Realize the visible rows on the next main-loop turn, outside this borrow.
                    // An occluded window (locked screen, covered, headless CI) gets no normal
                    // draw pass; NSTableView would first realize these rows inside a snapshot's
                    // `cacheDisplayInRect`, where `bind_row` must skip the held borrow and the
                    // table would cache permanently blank cells.
                    post_realize_visible_rows(ptr_of(h));
                }
                Some(ListPatch::ScrollToRow(row)) => {
                    // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
                    // synchronously, which must happen outside this `with_tree` borrow.
                    let (key, row) = (ptr_of(h), *row);
                    <AppKit as Platform>::post(Box::new(move || {
                        if let Some((table, _)) = list_entry(key) {
                            let rows = unsafe { table.numberOfRows() };
                            if rows > 0 {
                                unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
                            }
                        }
                    }));
                    post_realize_visible_rows(ptr_of(h));
                }
                Some(ListPatch::ScrollToEnd) => {
                    // Deferred to the next main-loop turn: an actual scroll forces NSTableView
                    // to tile (realize) the target rows synchronously, and this patch arrives
                    // inside a `with_tree` borrow where `bind_row` must skip; the table would
                    // cache blank cells for every newly exposed row (see Reload above).
                    let key = ptr_of(h);
                    <AppKit as Platform>::post(Box::new(move || {
                        if let Some((table, _)) = list_entry(key) {
                            let rows = unsafe { table.numberOfRows() };
                            if rows > 0 {
                                unsafe { table.scrollRowToVisible(rows - 1) };
                            }
                        }
                    }));
                    // ...and realize whatever the scroll exposed, still outside the borrow.
                    post_realize_visible_rows(ptr_of(h));
                }
                Some(ListPatch::Selected(rows)) => {
                    // Programmatic selection sync (empty = clear), suppressed so the
                    // delegate does not echo it back as a selection event.
                    if let Some((table, data)) = list_entry(ptr_of(h)) {
                        data.ivars().suppress.set(true);
                        unsafe {
                            if rows.is_empty() {
                                table.deselectAll(None);
                            } else {
                                let set = objc2_foundation::NSMutableIndexSet::new();
                                let count = table.numberOfRows().max(0) as usize;
                                for r in rows.iter().copied().filter(|r| *r < count) {
                                    set.addIndex(r);
                                }
                                table.selectRowIndexes_byExtendingSelection(&set, false);
                            }
                        }
                        data.ivars().suppress.set(false);
                    }
                }
                Some(ListPatch::RowSizeInvalidated { cell, height }) => {
                    if let Some((table, data)) = list_entry(ptr_of(h)) {
                        data.row_resized(&table, *cell, *height);
                    }
                }
                // `None` = a patch for another kind's enum. A desktop table has no editing mode
                // (Cap::ListEditing is Unsupported).
                Some(ListPatch::Editing(_)) | None => {}
            },
            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
                Some(TreePatch::Reload) => {
                    // Interned items keep their identity across reloadData, so NSOutlineView
                    // itself preserves expansion; the piece re-asserts it (and the selection)
                    // by token right after, belt and braces. reloadData queries the child
                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
                        unsafe { outline.reloadData() };
                    }
                    post_realize_visible_tree_rows(ptr_of(h));
                }
                Some(TreePatch::Expand(token, on)) => {
                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
                    // where `bind_row` must skip; the outline would cache permanently blank,
                    // id-less rows (the ScrollToEnd rule, one arm over).
                    let (key, token, on) = (ptr_of(h), *token, *on);
                    <AppKit as Platform>::post(Box::new(move || {
                        if let Some((outline, data)) = tree_entry(key) {
                            let item = data.intern(token);
                            // Suppressed: a programmatic disclosure must not echo back as
                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
                            data.ivars().suppress.set(true);
                            unsafe {
                                if on {
                                    outline.expandItem(Some(&item));
                                } else {
                                    outline.collapseItem(Some(&item));
                                }
                            }
                            data.ivars().suppress.set(false);
                        }
                        day_core::pump_events();
                    }));
                    post_realize_visible_tree_rows(ptr_of(h));
                }
                Some(TreePatch::Selected(tokens)) => {
                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
                        data.ivars().suppress.set(true);
                        unsafe {
                            if tokens.is_empty() {
                                outline.deselectAll(None);
                            } else {
                                let set = objc2_foundation::NSMutableIndexSet::new();
                                for t in tokens {
                                    // A token under a collapsed ancestor has no row, so it is
                                    // skipped; the piece re-applies after expansion changes.
                                    let row = outline.rowForItem(Some(&data.intern(*t)));
                                    if row >= 0 {
                                        set.addIndex(row as usize);
                                    }
                                }
                                outline.selectRowIndexes_byExtendingSelection(&set, false);
                            }
                        }
                        data.ivars().suppress.set(false);
                    }
                }
                Some(TreePatch::Reveal(token)) => {
                    // Deferred: the scroll tiles target rows synchronously, which must
                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
                    let (key, token) = (ptr_of(h), *token);
                    <AppKit as Platform>::post(Box::new(move || {
                        if let Some((outline, data)) = tree_entry(key) {
                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
                            if row >= 0 {
                                unsafe { outline.scrollRowToVisible(row) };
                            }
                        }
                    }));
                    post_realize_visible_tree_rows(ptr_of(h));
                }
                None => {}
            },
            _ => {
                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
                    update(self, h, patch);
                }
            }
        }
    }

    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
        // the hook needs it mutably.
        let f = self.registry.get(kind).and_then(|r| r.release);
        if let Some(f) = f {
            f(self, h);
        }
    }
    fn release(&mut self, h: Handle) {
        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
        // A released window content = that window is gone (docs/windows.md teardown):
        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
        self.secondary.retain(|w| {
            if ptr_of(&w.content) == ptr_of(&h) {
                w.window.close();
                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
                // keyed by the window pointer) used to survive a secondary close, and its
                // items, targets, retained NSToolbar and delegate all leaked.
                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
                false
            } else {
                true
            }
        });
        TARGETS.with(|m| {
            m.borrow_mut().remove(&ptr_of(&h));
        });
        LIST_STATE.with(|m| {
            m.borrow_mut().remove(&ptr_of(&h));
        });
        TREE_STATE.with(|m| {
            m.borrow_mut().remove(&ptr_of(&h));
        });
        GESTURES.with(|m| {
            m.borrow_mut().remove(&ptr_of(&h));
        });
        NAV_STATE.with(|m| {
            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
                // Unhook the split view controller from the responder chain before the drop
                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
                // split resets its next to the superview; the controller's own view keeps
                // aiming at the controller), and a controller whose next responder is its own
                // view dies in dealloc's chain splice with the "next responder should never
                // be yourself" NSException, foreign to Rust, so it aborts the process
                // instead of unwinding (the Stack-page teardown crash, 2026-08).
                unsafe {
                    nav._split_vc.setNextResponder(None);
                    let split = nav._split_vc.splitView();
                    if split.nextResponder().is_some_and(|r| {
                        core::ptr::eq::<objc2::runtime::AnyObject>(
                            r.as_ref(),
                            nav._split_vc.as_ref(),
                        )
                    }) {
                        split.setNextResponder(None);
                    }
                }
            }
        });
        NAV_PAGES.with(|set| {
            set.borrow_mut().remove(&ptr_of(&h));
        });
        SPLIT_STATE.with(|m| {
            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
                state.split.setDelegate(None);
            }
        });
        INSPECTOR_STATE.with(|m| {
            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
                // The same dealloc-splice guard as the nav host above: never let the
                // controller (or its split) dealloc aiming at itself.
                unsafe {
                    insp._split_vc.setNextResponder(None);
                    let split = insp._split_vc.splitView();
                    if split.nextResponder().is_some_and(|r| {
                        core::ptr::eq::<objc2::runtime::AnyObject>(
                            r.as_ref(),
                            insp._split_vc.as_ref(),
                        )
                    }) {
                        split.setNextResponder(None);
                    }
                }
            }
        });
        NAV_MENUS.with(|m| {
            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
                // The outline registers under its pointer (`menuForEvent:` resolves by
                // outline, not by this scroll handle): sweep that auxiliary key too, so
                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
                // surviving entry served the dead menu's rows once the address was recycled.
                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
            }
        });
        // One call reclaims this handle's entry from every SideTable on this thread (canvas
        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
        // table's teardown hook (day-spec sidetable). The explicit removals above are the
        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
        // them without another line here.
        day_spec::sidetable::sweep(ptr_of(&h));
        unsafe { h.removeFromSuperview() };
    }

    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
        // page joined the host, so this is the first moment the host can see its rows.
        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
            unsafe { content_of(parent).addSubview(child) };
            adopt_menu_for_tabs(self.mtm(), child);
            return;
        }
        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
        // fill their pane via autoresizing; the pane, not Day, owns their frames.
        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
        let handled = NAV_STATE.with(|m| {
            let mut m = m.borrow_mut();
            let Some(state) = m.get_mut(&ptr_of(parent)) else {
                return false;
            };
            // The content-list page fills its pane at every presentation
            // (docs/navigation.md), never a member of the detail stack.
            if page_pane == Some(day_spec::props::Pane::List)
                && let Some(wrap) = state.list_wrap.as_ref()
            {
                state.list_page = Some(child.clone());
                unsafe {
                    child.setFrame(wrap.bounds());
                    child.setAutoresizingMask(
                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                    );
                    wrap.addSubview(child);
                }
                return true;
            }
            if is_sidebar_page {
                state.sidebar_page = Some(child.clone());
            }
            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
            // detail pages. Stack: every page, including the sidebar's, which is the stack's
            // root, lives in the detail pane so push/pop visibility covers them all.
            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
            // it is the stack root and joins the detail pages instead.
            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
            // A tabs host's detail page becomes an item of its tab view, which frames it (the
            // page's `setFrameSize:` reports the size to Day). Its label comes with the
            // menu's rows: already here when a page joins a live host, otherwise when the
            // menu is inserted (`adopt_menu_for_tabs`).
            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
                state.pages.push(child.clone());
                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
                unsafe {
                    child.setAutoresizingMask(
                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                    );
                    item.setView(Some(child));
                    tabs.view.addTabViewItem(&item);
                }
                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
                    sync_tab_labels(tabs, &titles, state.selected);
                }
                return true;
            }
            let (wrap, frame) = if to_pane {
                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
            } else {
                state.pages.push(child.clone());
                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
                (
                    &state.detail_wrap,
                    nav_page_frame(&state.detail_wrap, visible),
                )
            };
            unsafe {
                child.setFrame(frame);
                child.setAutoresizingMask(
                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                );
                wrap.addSubview(child);
            }
            true
        });
        if handled {
            return;
        }
        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
        let split_pane = SPLIT_STATE.with(|m| {
            let m = m.borrow();
            let Some(state) = m.get(&ptr_of(parent)) else {
                return false;
            };
            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
            let wrap = if second {
                &state.second_wrap
            } else {
                &state.first_wrap
            };
            unsafe {
                child.setFrame(wrap.bounds());
                child.setAutoresizingMask(
                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                );
                wrap.addSubview(child);
            }
            true
        });
        if split_pane {
            return;
        }
        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
        // the split, not Day, owns the pane frames (docs/inspector.md).
        let inspected = INSPECTOR_STATE.with(|m| {
            let m = m.borrow();
            let Some(state) = m.get(&ptr_of(parent)) else {
                return false;
            };
            let panel = INSPECTOR_PANES
                .with(|t| t.get(ptr_of(child)))
                .unwrap_or(false);
            let wrap = if panel {
                &state.panel_wrap
            } else {
                &state.content_wrap
            };
            unsafe {
                child.setFrame(wrap.bounds());
                child.setAutoresizingMask(
                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
                );
                wrap.addSubview(child);
            }
            true
        });
        if !inspected {
            // Absolute positioning: z-order is build order; index is irrelevant for
            // non-overlapping frames (stack_z will need ordered insertion later).
            unsafe { content_of(parent).addSubview(child) };
        }
    }

    fn remove(&mut self, parent: &Handle, child: &Handle) {
        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
        let mtm = self.mtm();
        NAV_STATE.with(|m| {
            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
                // A tabs host: the page leaves with its tab item.
                if let Some(tabs) = state.tabs.as_ref() {
                    unsafe {
                        let n = tabs.view.numberOfTabViewItems();
                        for i in 0..n {
                            let item = tabs.view.tabViewItemAtIndex(i);
                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
                                tabs.view.removeTabViewItem(&item);
                                break;
                            }
                        }
                    }
                }
                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
                    state.sidebar_page = None;
                }
            }
        });
        unsafe { child.removeFromSuperview() };
    }

    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
        unsafe { content_of(parent).addSubview(child) };
    }

    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
        match kind {
            kinds::LABEL => {
                if let Some(tf) = h.downcast_ref::<NSTextField>() {
                    let w = p.width.unwrap_or(1.0e6);
                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
                    let mut height = s.height.ceil();
                    // AppKit's truncating single-line mode still measures explicit newlines
                    // as multiple lines. Bound that case using AppKit's own font metrics.
                    if tf.maximumNumberOfLines() == 1 {
                        thread_local! {
                            static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
                        }
                        if let Some(font) = unsafe { tf.font() } {
                            height = height.min(
                                METRICS
                                    .with(|metrics| metrics.defaultLineHeightForFont(&font))
                                    .ceil(),
                            );
                        }
                    }
                    return Size::new(s.width.ceil().min(w), height);
                }
                Size::ZERO
            }
            kinds::BUTTON | kinds::TOGGLE => {
                let s = unsafe { h.fittingSize() };
                Size::new(s.width.ceil(), s.height.ceil())
            }
            kinds::SLIDER => {
                let s = unsafe { h.fittingSize() };
                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
            }
            kinds::PICKER => picker::measure_any(self, h, p),
            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
            kinds::TEXT_FIELD => {
                let s = unsafe { h.fittingSize() };
                Size::new(
                    p.width.unwrap_or(s.width.max(160.0)),
                    s.height.max(22.0).ceil(),
                )
            }
            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
            // the row's width.
            kinds::LIST_ITEM => {
                let s = h.fittingSize();
                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
            }
            kinds::PROGRESS => {
                // Indeterminate spinner is a fixed square; determinate bar fills width.
                let indeterminate = h
                    .clone()
                    .downcast::<NSProgressIndicator>()
                    .map(|pi| unsafe { pi.isIndeterminate() })
                    .unwrap_or(false);
                if indeterminate {
                    let large = h
                        .downcast_ref::<NSProgressIndicator>()
                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
                    let side = if large { 32.0 } else { 20.0 };
                    Size::new(side, side)
                } else {
                    Size::new(p.width.unwrap_or(180.0), 20.0)
                }
            }
            kinds::NAV_MENU => {
                let rows = NAV_MENUS.with(|m| {
                    m.borrow()
                        .get(&ptr_of(h))
                        .map(|(_, d)| d.ivars().items.borrow().len())
                        .unwrap_or(0)
                });
                Size::new(
                    p.width.unwrap_or(220.0),
                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
                )
            }
            // The recycling list fills the space it is offered (its native scroll owns overflow).
            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
            _ => {
                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
                    measure(self, h, p)
                } else {
                    let s = unsafe { h.fittingSize() };
                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
                }
            }
        }
    }

    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
        unsafe {
            h.setWantsLayer(true);
        }
        let v = h.clone();
        with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
    }

    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it.
        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
        let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
        let v = h.clone();
        with_appkit_anim(anim, move || {
            if let Some(base) = base {
                apply_geometry(&v, base, t);
            }
        });
    }

    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
        if let Some(label) = h.downcast_ref::<DayLabel>() {
            label.ivars().selectable.set(selectable);
            label.set_links(label.ivars().has_links.get());
        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
            unsafe { tf.setSelectable(selectable) };
        }
        None
    }

    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
        let node = text_field_node(h)?;
        let old = h.downcast_ref::<NSTextField>()?;
        // Hidden characters are a class on AppKit. A field already of the right class is
        // dressed in place; otherwise its replacement is, and the node moves to it.
        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
            .then(|| self.swap_text_field(h, old, node, traits.secure));
        let tf = swapped.as_deref().unwrap_or(old);
        unsafe {
            // Read-only keeps the bezel and the ordinary text color; the text stays
            // selectable, so it can still be copied.
            tf.setEditable(!traits.read_only);
            tf.setSelectable(true);
        }
        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
        // detail the system offers. `Number` and `Decimal` have no content type. A constant
        // newer than the running system leaves the field untyped.
        let content_type = match traits.purpose {
            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
        };
        unsafe {
            tf.setContentType(content_type);
            // Only free text wants the system finishing words; a name, an address or a code
            // is typed exactly.
            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
        }
        // No on-screen keyboard, so no action key to label; and no native length limit:
        // day-pieces holds `max_length`.
        swapped.map(view_of)
    }

    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
        let key = Retained::as_ptr(h) as usize;
        if cursor == Cursor::Default {
            // Release: drop the tracking area, and the hide if this owner holds one.
            if let Some((owner, area)) = self.cursors.remove(&key) {
                unsafe { h.removeTrackingArea(&area) };
                if owner.ivars().hiding.replace(false) {
                    NSCursor::unhide();
                }
            }
            return;
        }
        let hidden = cursor == Cursor::None;
        let shape = if hidden { None } else { ns_cursor(&cursor) };
        let mtm = self.mtm;
        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
            let owner = DayCursorOwner::new(mtm);
            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
            let opts = NSTrackingAreaOptions::CursorUpdate
                | NSTrackingAreaOptions::MouseEnteredAndExited
                | NSTrackingAreaOptions::ActiveInKeyWindow
                | NSTrackingAreaOptions::InVisibleRect;
            let any: &objc2::runtime::AnyObject = &owner;
            let area = unsafe {
                NSTrackingArea::initWithRect_options_owner_userInfo(
                    NSTrackingArea::alloc(),
                    NSRect::ZERO,
                    opts,
                    Some(any),
                    None,
                )
            };
            unsafe { h.addTrackingArea(&area) };
            (owner, area)
        });
        let changed = {
            let iv = owner.ivars();
            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
                (None, None) => true,
                _ => false,
            };
            *iv.cursor.borrow_mut() = shape;
            let was_hidden = iv.hidden.replace(hidden);
            !same || was_hidden != hidden
        };
        // A reactive change while the pointer is already inside: AppKit only asks on entry,
        // so ask it to re-evaluate now.
        if changed && let Some(w) = h.window() {
            unsafe { w.invalidateCursorRectsForView(h) };
        }
    }

    /// Where the control actually draws its first line of text (docs/baseline.md).
    ///
    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
    /// is exactly the drift baseline alignment exists to remove.
    ///
    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
    /// Controls with no font of their own keep AppKit's answer.
    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
        if !day_spec::kind_has_baseline(kind) {
            return None;
        }
        // The view has to be at the height the row settled on before it answers: a control
        // that centers its text vertically moves its baseline with its box.
        let current = unsafe { h.frame() };
        if (current.size.height - size.height).abs() > 0.5 {
            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
        }
        let insets = unsafe { h.alignmentRectInsets() };
        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
        let font = h
            .downcast_ref::<NSControl>()
            .and_then(|c| unsafe { c.font() });
        let offset = match font {
            // A multi-line editor's first line sits at the top of its text container, not
            // centered in it, so the centering model would put its baseline half a box too low.
            Some(_) if kind == kinds::TEXT_AREA => reported,
            Some(f) => {
                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
                let line = ascender - descender;
                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
            }
            None => reported,
        };
        // AppKit's documented "no baseline" answer is the view's own height.
        (offset > 0.0 && offset < size.height).then_some(offset)
    }

    fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
            return;
        }
        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
        // so top-left frames apply directly.
        let r = NSRect::new(
            NSPoint::new(frame.origin.x, frame.origin.y),
            NSSize::new(frame.size.width, frame.size.height),
        );
        // Nav host: the sidebar holds its width when the window resizes and the detail pane
        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
        // only thing left to do here is give the split its frame and place the divider once;
        // re-placing it on every resize would fight the item and undo a user's drag.
        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
            // A host at the top of a window's pinned content reaches up under the title bar,
            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
            // their content below the strip, so nothing Day laid out moves.
            let strip = unsafe { split.superview() }
                .and_then(|sup| {
                    let content = unsafe { sup.window() }?.contentView()?;
                    // Layout wrappers (for example zstack with a reader cover) may sit
                    // between the window root and its navigation host. A direct-parent
                    // check misses them and puts AppKit's frosted pocket over page text.
                    let mut ancestor = Some(sup.clone());
                    while let Some(view) = ancestor {
                        if std::ptr::eq(&*view, &*content) {
                            break;
                        }
                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
                            return None; // nested navigation belongs to the outer pane
                        }
                        ancestor = unsafe { view.superview() };
                    }
                    let point = unsafe {
                        sup.convertPoint_toView(
                            NSPoint::new(frame.origin.x, frame.origin.y),
                            Some(&content),
                        )
                    };
                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
                })
                .unwrap_or(0.0);
            let r = NSRect::new(
                NSPoint::new(r.origin.x, r.origin.y - strip),
                NSSize::new(r.size.width, r.size.height + strip),
            );
            let wraps = NAV_STATE.with(|m| {
                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
                    (s.title_strip != strip).then(|| {
                        s.title_strip = strip;
                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
                        w.extend(s.list_wrap.clone());
                        w
                    })
                })
            });
            let first = NAV_STATE.with(|m| {
                m.borrow_mut()
                    .get_mut(&ptr_of(h))
                    .map(|s| {
                        if !s.presentation.is_split() {
                            return (false, None);
                        }
                        let sidebar = !std::mem::replace(&mut s.positioned, true);
                        // The list's divider waits for the pane to be showing. Placing it while
                        // the pane is collapsed re-opens it (which is how an app whose first
                        // destination has no list opened with one beside it) and spends the one
                        // placement the pane gets, leaving it at the solver's width later on.
                        (sidebar, take_list_placement(s))
                    })
                    .unwrap_or((false, None))
            });
            unsafe {
                split.setFrame(r);
                split.layoutSubtreeIfNeeded();
            }
            // After the panes have their new size, so each wrap is placed in the final pane;
            // autoresizing keeps the strip from then on.
            for wrap in wraps.iter().flatten() {
                place_below_strip(wrap, strip);
            }
            unsafe {
                if first.0 {
                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
                }
                // A triple split has a second divider, and nothing else places it: left alone,
                // the controller's initial constraint pass lands it wherever the solver liked, so
                // the content list opens at an arbitrary width and the detail pane gets the
                // leftovers until the first manual drag re-settles them.
                if let Some(w) = first.1 {
                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
                }
            }
        } else {
            BASE_FRAMES.with(|m| {
                m.insert(
                    ptr_of(h),
                    [
                        frame.origin.x,
                        frame.origin.y,
                        frame.size.width,
                        frame.size.height,
                    ],
                )
            });
            // A transform (`set_transform`) is applied to the frame Day laid out.
            match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
                Some(t) => apply_geometry(
                    h,
                    [
                        frame.origin.x,
                        frame.origin.y,
                        frame.size.width,
                        frame.size.height,
                    ],
                    t,
                ),
                None => unsafe { h.setFrame(r) },
            }
        }
    }

    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
        if let Some(sv) = h.downcast_ref::<NSScrollView>()
            && let Some(doc) = unsafe { sv.documentView() }
        {
            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
        }
    }

    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
        day_spec::RowMetrics {
            insets: day_spec::Insets {
                top: 4.0,
                leading: 8.0,
                bottom: 4.0,
                trailing: 8.0,
            },
            min_height: 28.0,
        }
    }

    fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
        if let Some(sv) = h.downcast_ref::<NSScrollView>()
            && let Some(doc) = unsafe { sv.documentView() }
        {
            unsafe {
                doc.scrollRectToVisible(NSRect::new(
                    NSPoint::new(target.origin.x, target.origin.y),
                    NSSize::new(target.size.width, target.size.height),
                ))
            };
        }
    }

    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
        let Some(window) = h.window() else { return };
        // A list's public handle is its scroll view; keyboard focus belongs to the table.
        let list = list_entry(ptr_of(h));
        let responder: &NSResponder = match &list {
            Some((table, _)) => table,
            None => h,
        };
        let responder_ptr = responder as *const NSResponder as usize;
        if focused {
            window.makeFirstResponder(Some(responder));
            return;
        }
        // Resign only while this view still owns focus, so a stale release can't blur a
        // sibling.
        let owns = window
            .firstResponder()
            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
            || owns_first_responder(&window, h);
        if owns {
            window.makeFirstResponder(None);
        }
    }

    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
        // The overrides live on `DayFlipped` (the container view); registering any other
        // view is harmless but inert, the graceful silence the duty documents.
        if focusable {
            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
        } else {
            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
        }
    }

    fn set_event_sink(&mut self, sink: EventSink) {
        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
    }

    fn set_edit_state(&mut self, state: &day_spec::EditState) {
        EDIT_STATE.with(|s| s.set(*state));
    }

    fn modifiers(&mut self) -> day_spec::Modifiers {
        let f = NSEvent::modifierFlags_class();
        day_spec::Modifiers {
            shift: f.contains(NSEventModifierFlags::Shift),
            primary: f.contains(NSEventModifierFlags::Command),
            alt: f.contains(NSEventModifierFlags::Option),
        }
    }

    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
        let front = undo_front(self.mtm);
        *front.ivars().state.borrow_mut() = state.clone();
    }

    fn attach_list(&mut self, host: &Handle, source: ListSource) {
        let key = ptr_of(host);
        if let Some((table, data)) = list_entry(key) {
            data.ivars().source.replace(Some(source));
            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
            unsafe { table.reloadData() };
        }
        // Force the table to realize its visible row views on the next main-loop turn, outside
        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
        post_realize_visible_rows(key);
    }

    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
        let key = ptr_of(host);
        if let Some((outline, data)) = tree_entry(key) {
            data.ivars().source.replace(Some(source));
            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
            unsafe { outline.reloadData() };
        }
        // Realize visible rows on the next main-loop turn, outside any borrow (the
        // attach_list comment has the occluded-window story).
        <AppKit as Platform>::post(Box::new(move || {
            if let Some((outline, _)) = tree_entry(key) {
                unsafe { outline.layoutSubtreeIfNeeded() };
            }
        }));
    }

    fn adopt(&mut self, raw: RawHandle) -> Handle {
        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
        // Invariant, not app input: day-core only passes back the cell pointer this backend
        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
        let ptr = raw as *mut NSView;
        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
    }

    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
        self.edit_toolbar(h, ops)
    }

    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
        self.patch_toolbar(h, patch);
    }

    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
        let mtm = self.mtm;
        if self.menu_escape_monitor.is_none() {
            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
                ffi_guard::contain(event.as_ptr(), || {
                    let event_ref = unsafe { event.as_ref() };
                    let app = NSApplication::sharedApplication(mtm);
                    // Native dialogs retain their cancellation behavior. Only an enabled
                    // menu key equivalent can consume Escape, never the general key stream.
                    if app.modalWindow().is_none()
                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
                        && unsafe { event_ref.charactersIgnoringModifiers() }
                            .is_some_and(|s| s.to_string() == "\u{1b}")
                        && app
                            .mainMenu()
                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
                    {
                        std::ptr::null_mut()
                    } else {
                        event.as_ptr()
                    }
                })
            });
            self.menu_escape_monitor = unsafe {
                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
                    objc2_app_kit::NSEventMask::KeyDown,
                    &block,
                )
            }
            .map(MenuEscapeMonitor);
        }
        let app = NSApplication::sharedApplication(mtm);
        let menubar = NSMenu::new(mtm);
        // macOS owns the application menu; relocate app-level roles while preserving
        // their callbacks, shortcuts, and enabled state.
        let mut items = items.to_vec();
        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
        let services =
            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
        // Fill the standard slots the app did not claim, in the platform's bar order
        // (day-core owns that policy so every backend arranges its bar the same way).
        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
        // installed natively below, so the style deliberately supplies none.
        let items =
            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
        // Each top-level entry becomes a menu-bar menu.
        for item in &items {
            match item {
                day_spec::MenuItem::Submenu { label, items, role } => {
                    let sub = build_ns_menu(mtm, label, items);
                    let it = NSMenuItem::new(mtm);
                    // Help is held back: the Window menu is installed natively after this loop
                    // (AppKit owns it so it can append the live window list), and Help sits
                    // last on every Mac menu bar.
                    if *role == Some(day_spec::MenuBarRole::Help)
                        || *label == day_localization::t(day_localization::key::day_help)
                    {
                        help_menu = Some((label.clone(), sub));
                        continue;
                    }
                    it.setTitle(&NSString::from_str(label));
                    it.setSubmenu(Some(&sub));
                    menubar.addItem(&it);
                }
                other => {
                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
                    let it = NSMenuItem::new(mtm);
                    it.setSubmenu(Some(&sub));
                    menubar.addItem(&it);
                }
            }
        }
        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
        // `MenuRole::Minimize` (then the app is composing its own window management).
        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
            install_windows_menu(mtm, &app, &menubar);
        }
        if let Some((label, help)) = help_menu {
            let it = NSMenuItem::new(mtm);
            it.setTitle(&NSString::from_str(&label));
            it.setSubmenu(Some(&help));
            menubar.addItem(&it);
            // Registering it makes AppKit add the Help search field and index the help book —
            // behavior no hand-built menu reproduces.
            unsafe { app.setHelpMenu(Some(&help)) };
        }
        app.setMainMenu(Some(&menubar));
        unsafe { app.setServicesMenu(Some(&services)) };
    }

    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
        let Some(view) = h.downcast_ref::<NSView>() else {
            return;
        };
        if items.is_empty() {
            unsafe { view.setMenu(None) };
            return;
        }
        let menu = build_ns_menu(self.mtm, "", items);
        // Attach to the view AND its current subviews: a right-click that hit-tests a child
        // control (the label inside a padded target) must find the menu on the view it hit —
        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
        // show their `.menu` through their own default path.
        unsafe { view.setMenu(Some(&menu)) };
        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
            for sub in v.subviews() {
                unsafe { sub.setMenu(Some(menu)) };
                apply_to_subviews(&sub, menu);
            }
        }
        apply_to_subviews(view, &menu);
    }

    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
        transfer::source(h, source);
    }
    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
        transfer::target(h, target);
    }
    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
        // "Dynamic context menus" lists the covered surfaces per backend).
        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
    }

    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
        let key = ptr_of(h);
        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
        if kind == day_spec::GestureKind::Pan {
            PAN_NODES.with(|t| t.insert(key, node));
            install_container_pan_monitor();
            return;
        }
        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
        // which only `DayCanvas` overrides — a hover enabled on another view emits nothing, the
        // same limitation Pan has.
        if kind == day_spec::GestureKind::Hover {
            // Idempotent, and it has to be checked here rather than falling through to the
            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
            // tracking area on the same view means a second copy of every hover event.
            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
            HOVER_NODES.with(|t| t.insert(key, node));
            if first {
                install_tracking_area(h);
            }
            return;
        }
        // Idempotent: attach each kind at most once per view.
        let already = GESTURES.with(|m| {
            m.borrow()
                .get(&key)
                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
        });
        if already {
            return;
        }
        let mtm = self.mtm;
        let target = DayGesture::new(mtm, node, kind);
        let recognizer: Retained<NSGestureRecognizer> = unsafe {
            match kind {
                day_spec::GestureKind::Drag => {
                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
                        NSPanGestureRecognizer::alloc(mtm),
                        Some(&target),
                        Some(sel!(fire:)),
                    ))
                }
                day_spec::GestureKind::Pinch => Retained::into_super(
                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
                        Some(&target),
                        Some(sel!(fire:)),
                    ),
                ),
                _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
                    NSClickGestureRecognizer::alloc(mtm),
                    Some(&target),
                    Some(sel!(fire:)),
                )),
            }
        };
        unsafe { h.addGestureRecognizer(&recognizer) };
        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
    }

    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
        unsafe {
            if let Some(id) = &a11y.identifier {
                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
            }
            if let Some(label) = &a11y.label {
                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
            } else {
                APP_LABELED.with(|t| t.remove(ptr_of(h)));
            }
            if let Some(hint) = &a11y.hint {
                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
            }
            if let Some(value) = &a11y.value {
                let ns = NSString::from_str(value);
                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
            }
            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
            // already report the right role, so Day records but doesn't override theirs (§13).
            if let Some(role) = ns_role(a11y.role) {
                h.setAccessibilityRole(Some(role));
            }
            if a11y.role == day_spec::Role::Tab {
                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
            }
            if let Some(on) = a11y.selected {
                h.setAccessibilitySelected(on);
            }
            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
            // not enough — AppKit promotes an ignored element's children into its parent's
            // list — so the subtree is cut off too, which also covers subviews added later
            // (list rows, re-created children). Hidden never flips back, so the override is
            // never lifted.
            if a11y.hidden {
                h.setAccessibilityElement(false);
                h.setAccessibilityChildren(Some(&NSArray::new()));
            }
        }
    }

    /// The announcement request goes out from the primary window (any live element will
    /// do; the app object stands in before the window exists). Without VoiceOver nothing
    /// observes the notification, so posting is free.
    fn announce(&mut self, text: &str, urgent: bool) {
        use objc2_app_kit::{
            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
            NSAccessibilityPriorityLevel,
        };
        let app = NSApplication::sharedApplication(self.mtm());
        let window = primary_content().and_then(|content| content.window());
        let element: &objc2::runtime::AnyObject = match &window {
            Some(window) => window,
            None => &app,
        };
        // High priority interrupts the current sentence; medium waits its turn.
        let priority = if urgent {
            NSAccessibilityPriorityLevel::High
        } else {
            NSAccessibilityPriorityLevel::Medium
        };
        let announcement = NSString::from_str(text);
        let priority = NSNumber::new_isize(priority.0);
        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
        // SAFETY: the keys are AppKit's constants and both values are the types the
        // announcement notification documents (an NSString and an NSNumber).
        unsafe {
            let user_info = NSDictionary::from_slices::<NSString>(
                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
                &values,
            );
            NSAccessibilityPostNotificationWithUserInfo(
                element,
                NSAccessibilityAnnouncementRequestedNotification,
                Some(&user_info),
            );
        }
    }

    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
        unsafe {
            let role = h
                .accessibilityRole()
                .map(|r| day_role_from_ns(&r.to_string()))
                .unwrap_or(day_spec::Role::None);
            // A picker answers its displayed selection and its enabled state itself: the
            // inline style is a stack of radios, not one control.
            let picker = picker::read_native(h);
            day_spec::NativeSnapshot {
                found: true,
                role,
                label: h.accessibilityLabel().map(|s| s.to_string()),
                value: h
                    .accessibilityValue()
                    .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
                identifier: h
                    .accessibilityIdentifier()
                    .map(|s| s.to_string())
                    .filter(|s| !s.is_empty()),
                text: match &picker {
                    Some((text, _)) => text.clone(),
                    None => native_text(h),
                },
                number: native_number(h),
                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
                    match sw.state() {
                        s if s == NSControlStateValueOn => Some(true),
                        s if s == NSControlStateValueOff => Some(false),
                        // Mixed is neither on nor off.
                        _ => None,
                    }
                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
                    // A Day button's selected state (`ButtonProps::selected`): its own
                    // `state`, which a momentary button holds off at rest.
                    BUTTON_SELECTED
                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
                        .then(|| btn.state() == NSControlStateValueOn)
                } else {
                    None
                },
                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
                // input; every other control answers for itself.
                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
                    (Some((_, on)), _) => *on,
                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
                    (None, Some(c)) => Some(c.isEnabled()),
                    (None, None) => None,
                },
                // Off-window counts as not shown: nothing of it reaches the screen.
                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
                frame: native_frame(h),
            }
        }
    }

    fn request_frame(
        &mut self,
        host: &Handle,
        cb: day_spec::FrameCallback,
    ) -> day_spec::CancelFrame {
        frame::request(host, cb)
    }

    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
        unsafe { h.setNeedsDisplay(true) };
    }
    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
        NAV_STATE.with(|m| {
            let m = m.borrow();
            let Some(st) = m.get(&ptr_of(host)) else {
                return false;
            };
            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
            // keeps its rows in the chrome, where hiding them would strand the user.
            if !matches!(
                st.presentation,
                NavPresentation::Split | NavPresentation::Rail
            ) {
                return false;
            }
            let item = &st.sidebar_item;
            // Set directly, not through the `animator` proxy. The proxy defers the change to
            // an animation the dayscript screenshot step does not wait on, so a scripted
            // toggle captured a sidebar that had not moved yet. AppKit's own
            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
            // controller and never comes through here.
            let collapsed = unsafe { item.isCollapsed() };
            unsafe { item.setCollapsed(!collapsed) };
            true
        })
    }

    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
        let content = self.content.as_ref().ok_or("no window content")?;
        snapshot_view(content)
    }

    /// Decode bytes into an `NSImage` (docs/images.md).
    ///
    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
    /// two-thirds its real width), and it is the only thing here that can re-encode later.
    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
        use objc2::AllocAnyThread as _;
        let data = NSData::with_bytes(bytes);
        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
        else {
            emit(
                WINDOW_NODE,
                Event::ImageDecoded {
                    req,
                    result: Err(day_spec::ImageError::Decode),
                },
            );
            return;
        };
        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
        let info = day_spec::BitmapInfo {
            pixels: Size::new(w, h),
            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
            // asset has a scale, and that arrives through the named path instead.
            scale: 1.0,
            format: day_spec::ImageFormat::sniff(bytes),
            has_alpha: unsafe { rep.hasAlpha() },
        };
        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
        // a 144-DPI photo for no reason the app asked for.
        let image = unsafe {
            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
        };
        unsafe { image.addRepresentation(&rep) };
        BITMAPS.with(|m| {
            m.borrow_mut().insert(
                id.0,
                AppKitBitmap {
                    image,
                    rep: Some(rep),
                    info,
                },
            )
        });
        emit(
            WINDOW_NODE,
            Event::ImageDecoded {
                req,
                result: Ok(info),
            },
        );
    }

    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
    }

    /// The container's own metadata (docs/images.md).
    ///
    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
    /// itself believes — and it is right for containers that record resolution in ways EXIF
    /// does not.
    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
        let mut out = day_spec::ImageProperties::default();
        let size = unsafe { rep.size() };
        if size.width > 0.0 {
            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
            // the file never stated.
            if (dpi - 72.0).abs() > 0.5 {
                out.dpi = Some(dpi);
            }
        }
        // EXIF arrives as a dictionary of the format's own keys. It is walked through
        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
        // `DowncastTarget`.
        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
            for key in keys.iter() {
                let value: Option<Retained<objc2::runtime::AnyObject>> =
                    unsafe { msg_send![&*exif, objectForKey: &*key] };
                let Some(value) = value else { continue };
                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
                let (k, v) = (key.to_string(), text.to_string());
                match k.as_str() {
                    "Orientation" => out.orientation = v.parse().ok(),
                    "DateTimeOriginal" => out.created = Some(v.clone()),
                    _ => {}
                }
                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
                // the doc for `extra` promises exactly that.
                out.extra.push((k, v));
            }
        }
        Some(out)
    }

    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
    /// letting `Cap::ImageEncode` imply every format round-trips.
    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
        vec![Png, Jpeg, Tiff, Bmp, Gif]
    }

    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
        let result = encode_bitmap(id, spec);
        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
    }

    fn release_image(&mut self, id: day_spec::BitmapId) {
        release_bitmap(id);
    }

    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
    /// it like any decoded bitmap.
    fn render_bitmap(
        &mut self,
        req: u64,
        id: day_spec::BitmapId,
        ops: &[DrawOp],
        size: Size,
        scale: f64,
    ) {
        let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
            let info = bitmap.info;
            BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
            info
        });
        emit(WINDOW_NODE, Event::BitmapRendered { req, result });
    }

    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
        let result = render_pdf_bytes(pages, info);
        emit(WINDOW_NODE, Event::PdfRendered { req, result });
    }

    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
    /// families are the system's private UI faces and are skipped, as Font Book skips them.
    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
        use day_spec::FontWeight as W;
        let mtm =
            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
        let mut out = Vec::new();
        for family in unsafe { manager.availableFontFamilies() }.iter() {
            let name = family.to_string();
            if name.starts_with('.') {
                continue;
            }
            let mut faces = Vec::new();
            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
                for member in members.iter() {
                    if member.count() < 4 {
                        continue;
                    }
                    let style = member
                        .objectAtIndex(1)
                        .downcast_ref::<NSString>()
                        .map(|s| s.to_string())
                        .unwrap_or_default();
                    let weight = member
                        .objectAtIndex(2)
                        .downcast_ref::<objc2_foundation::NSNumber>()
                        .map(|n| n.integerValue())
                        .unwrap_or(5);
                    let traits = member
                        .objectAtIndex(3)
                        .downcast_ref::<objc2_foundation::NSNumber>()
                        .map(|n| n.integerValue())
                        .unwrap_or(0);
                    let weight = match weight {
                        ..=2 => W::UltraLight,
                        3 => W::Thin,
                        4 => W::Light,
                        5 => W::Regular,
                        6 => W::Medium,
                        7 | 8 => W::Semibold,
                        9 => W::Bold,
                        10 | 11 => W::Heavy,
                        _ => W::Black,
                    };
                    let italic = traits & 0x1 != 0; // NSItalicFontMask
                    faces.push(day_spec::FontFace {
                        name: if style.is_empty() {
                            day_spec::FontFace::synthesized_name(weight, italic)
                        } else {
                            style
                        },
                        weight,
                        italic,
                    });
                }
            }
            out.push(day_spec::FontFamilyInfo {
                family: name,
                faces,
            });
        }
        out
    }

    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
    fn measure_text(
        &mut self,
        text: &str,
        size: f64,
        font: &day_spec::CanvasFont,
    ) -> Option<day_spec::TextMetrics> {
        let nsfont = canvas_nsfont(size, font);
        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
        let ns = NSString::from_str(text);
        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
        let unbounded = NSSize::new(f64::MAX, f64::MAX);
        let ink: NSRect = unsafe {
            msg_send![
                &ns,
                boundingRectWithSize: unbounded,
                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
                attributes: &*attrs,
            ]
        };
        Some(day_spec::TextMetrics::from_baseline(
            sz.width,
            nsfont.ascender(),
            sz.height - nsfont.ascender(),
            nsfont.capHeight(),
            day_spec::Rect::new(
                ink.origin.x,
                -(ink.origin.y + ink.size.height),
                ink.size.width,
                ink.size.height,
            ),
        ))
    }

    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
        let content = self.content.as_ref().ok_or("no window content")?;
        snapshot_view_chrome(content)
    }

    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
        snapshot_view(host)
    }

    fn open_window(
        &mut self,
        id: NodeId,
        options: &WindowOptions,
        kind: day_spec::WindowKind,
    ) -> day_spec::WindowOpenReply<Handle> {
        let prefs = kind.is_panel();
        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
        if prefs {
            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
            // menu — the macOS convention every stock app follows (docs/windows.md).
            window.center();
            unsafe { window.setExcludedFromWindowsMenu(true) };
        } else {
            // Stagger, don't stack. Without this every window opens at the same centered frame
            // and the one underneath is invisible — which is exactly what two Day windows did.
            //
            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
            // the point for the one after, so the series has to be primed from the primary
            // rather than seeded with its corner — seeding lands the first new window exactly
            // on top of the primary, which is the bug this replaces.
            let from = match self.cascade {
                Some(p) => p,
                None => self
                    .window
                    .as_ref()
                    .map(|w| {
                        let f = w.frame();
                        let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
                        // Asking the primary to cascade from where it already is leaves it
                        // there and answers the next slot — the offset the first new window wants.
                        unsafe { w.cascadeTopLeftFromPoint(top_left) }
                    })
                    .unwrap_or(NSPoint::new(0.0, 0.0)),
            };
            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
        }
        window_chrome::place(&window, options.placement);
        // Secondary windows need the same initial client-coordinate pinning as the
        // primary. Native document pages may move here before any resize notification.
        let _ = pin_below_title_bar(&window);
        if !options.start_hidden {
            window.makeKeyAndOrderFront(None);
        }
        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
        // first turn drops pre-run layer displays — nudge every layer once.
        mark_tree_needs_display(&content);
        self.secondary.push(SecondaryWin {
            window,
            delegate,
            content: content.clone(),
        });
        day_spec::WindowOpenReply::Open(content)
    }

    fn native_window_tabs(&self) -> bool {
        true
    }
    fn group_windows(&mut self, hosts: &[Handle]) {
        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
        let Some(first) = windows.first() else {
            return;
        };
        unsafe {
            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
        }
        // Explicit insertion respects the model even when system automatic tabbing is off.
        for window in windows.iter().skip(1) {
            unsafe {
                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
            }
        }
        if let Some(group) = first.tabGroup() {
            if !group.isTabBarVisible() {
                unsafe {
                    first.toggleTabBar(None);
                }
            }
            for (i, window) in windows.iter().enumerate() {
                group.insertWindow_atIndex(window, i as isize);
            }
        }
        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
        // resizing the window. Re-pin every member and tell the layout tree its usable size.
        for window in &windows {
            if let Some(size) = pin_below_title_bar(window) {
                let node = window
                    .delegate()
                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
                    .and_then(|d| d.ivars().node)
                    .unwrap_or(WINDOW_NODE);
                emit(node, Event::WindowResized(size));
            }
        }
    }
    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
        let Some(window) = self.ns_window_for(host) else {
            return Vec::new();
        };
        let windows = window.tabGroup().map(|g| g.windows());
        let Some(windows) = windows else {
            return Vec::new();
        };
        windows
            .iter()
            .filter_map(|window| {
                self.secondary
                    .iter()
                    .find(|w| std::ptr::eq(&*w.window, &*window))
                    .and_then(|w| w.delegate.ivars().node)
            })
            .collect()
    }

    fn close_window(&mut self, host: &Handle) {
        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
        // day-core teardown — so programmatic and title-bar closes are one code path.
        if let Some(w) = self
            .secondary
            .iter()
            .find(|w| ptr_of(&w.content) == ptr_of(host))
        {
            w.window.close();
        }
    }

    fn focus_window(&mut self, host: &Handle) {
        if let Some(w) = self
            .secondary
            .iter()
            .find(|w| ptr_of(&w.content) == ptr_of(host))
        {
            w.window.makeKeyAndOrderFront(None);
        }
    }

    fn fit_window(&mut self, host: &Handle, size: Size) {
        let Some(w) = self
            .secondary
            .iter()
            .find(|w| ptr_of(&w.content) == ptr_of(host))
        else {
            return;
        };
        unsafe {
            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
            // of the panel and clip the last row by exactly that much.
            w.window
                .setContentSize(NSSize::new(size.width, size.height));
            // A settings panel that fits its content has no reason to be resizable, and macOS
            // panels are not — dropping the mask also stops the user dragging it back to a size
            // the content does not fill.
            let mask = w.window.styleMask();
            w.window
                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
            w.window.center();
        }
    }

    fn set_window_title(&mut self, host: &Handle, title: &str) {
        if let Some(w) = self
            .secondary
            .iter()
            .find(|w| ptr_of(&w.content) == ptr_of(host))
        {
            w.window.setTitle(&NSString::from_str(title));
            return;
        }
        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
        // arrive here — and searching only the secondary list silently dropped them.
        if self
            .content
            .as_ref()
            .is_some_and(|c| ptr_of(c) == ptr_of(host))
            && let Some(w) = self.window.as_ref()
        {
            w.setTitle(&NSString::from_str(title));
        }
    }

    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
        use day_spec::WindowChange as C;
        let Some(window) = self.ns_window_for(host) else {
            return;
        };
        match change {
            C::State(state) => set_ns_window_state(&window, *state),
            // Screen capture, recording and sharing see an empty window; the user still does.
            C::ContentProtected(on) => window.setSharingType(if *on {
                objc2_app_kit::NSWindowSharingType::None
            } else {
                objc2_app_kit::NSWindowSharingType::ReadOnly
            }),
            other => window_chrome::apply_property(&window, other),
        }
    }

    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
        self.ns_window_for(host)
            .map(|w| window_chrome::frame_of(&w))
    }

    fn monitors(&self) -> Vec<day_spec::Monitor> {
        window_chrome::monitors(self.mtm)
    }

    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
    /// through `set_dock_menu`, so there is nothing more to install here.
    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}

    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
        dock::set_app_items(self.mtm, items);
    }

    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
        window_chrome::set_drag_region(h, drag);
    }

    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
        status_item::set_items(self.mtm, items);
    }

    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
        status_item::set_progress(self.mtm, progress);
    }

    fn set_dock_visible(&mut self, visible: bool) {
        status_item::set_dock_visible(self.mtm, visible);
    }

    fn set_keep_running(&mut self, keep: bool) {
        status_item::set_keep_running(keep);
    }

    fn quit_app(&mut self) {
        let app = NSApplication::sharedApplication(self.mtm);
        unsafe { app.terminate(None) };
    }

    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
        use present::PresentSpec;
        let mtm = self.mtm;
        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
        // raised from a secondary/preferences window belongs on it; primary is the
        // fallback when no DAY window is key (a system panel may hold key status).
        let app = NSApplication::sharedApplication(mtm);
        let key = app.keyWindow().filter(|k| {
            let mut owner = k.clone();
            while let Some(parent) = owner.sheetParent() {
                owner = parent;
            }
            self.window
                .as_deref()
                .is_some_and(|w| std::ptr::eq(w, &*owner))
                || self
                    .secondary
                    .iter()
                    .any(|s| std::ptr::eq(&*s.window, &*owner))
        });
        let Some(mut window) = key.or_else(|| self.window.clone()) else {
            emit(
                WINDOW_NODE,
                Event::PresentResult {
                    req,
                    result: present::PresentResult::Dismissed,
                },
            );
            return;
        };
        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
        while let Some(sheet) = window.attachedSheet() {
            window = sheet;
        }
        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
        match spec {
            PresentSpec::OpenFile {
                filters, multiple, ..
            } => {
                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
                unsafe {
                    panel.setCanChooseFiles(true);
                    panel.setCanChooseDirectories(false);
                    panel.setAllowsMultipleSelection(*multiple);
                    panel.setMessage(Some(&NSString::from_str(spec.title())));
                }
                apply_allowed_file_types(&panel, filters);
                let p = panel.clone();
                // Completion blocks run inside a C ABI frame, so their bodies are contained
                // like every other trampoline (§8.5) — this one and the four below.
                let handler: block2::RcBlock<dyn Fn(isize)> =
                    block2::RcBlock::new(move |resp: isize| {
                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
                    });
                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
                return;
            }
            // The folder chooser is the same NSOpenPanel with files and directories swapped.
            PresentSpec::OpenFolder { .. } => {
                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
                unsafe {
                    panel.setCanChooseFiles(false);
                    panel.setCanChooseDirectories(true);
                    panel.setCanCreateDirectories(true);
                    panel.setAllowsMultipleSelection(false);
                    panel.setMessage(Some(&NSString::from_str(spec.title())));
                }
                let p = panel.clone();
                let handler: block2::RcBlock<dyn Fn(isize)> =
                    block2::RcBlock::new(move |resp: isize| {
                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
                    });
                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
                return;
            }
            PresentSpec::SaveFile { suggested_name, .. } => {
                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
                unsafe {
                    panel.setMessage(Some(&NSString::from_str(spec.title())));
                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
                }
                apply_allowed_file_types(&panel, spec.filters());
                let p = panel.clone();
                let handler: block2::RcBlock<dyn Fn(isize)> =
                    block2::RcBlock::new(move |resp: isize| {
                        // The pieces layer copies the staged bytes to the chosen local path.
                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
                    });
                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
                return;
            }
            _ => {}
        }
        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
        if let Some(msg) = spec.message() {
            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
        }
        // The completion handler must outlive this call, so it's a heap (Rc) block.
        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
            PresentSpec::Dialog { buttons, .. } => {
                if buttons
                    .iter()
                    .any(|b| b.role == present::ButtonRole::Destructive)
                {
                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
                }
                for b in buttons {
                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
                }
                block2::RcBlock::new(move |resp: isize| {
                    ffi_guard::contain((), || {
                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
                        let idx = resp - 1000;
                        emit(
                            WINDOW_NODE,
                            Event::PresentResult {
                                req,
                                result: present::PresentResult::Button(idx as i64),
                            },
                        );
                        PRESENT_ALERTS.with(|m| {
                            m.borrow_mut().remove(&req);
                        });
                    })
                })
            }
            PresentSpec::Prompt {
                placeholder,
                initial,
                ok,
                cancel,
                ..
            } => {
                let tf = unsafe { NSTextField::new(mtm) };
                unsafe {
                    tf.setFrame(NSRect::new(
                        NSPoint::new(0.0, 0.0),
                        NSSize::new(260.0, 24.0),
                    ));
                    tf.setEditable(true);
                    tf.setBezeled(true);
                    tf.setStringValue(&NSString::from_str(initial));
                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
                    alert.setAccessoryView(Some(&tf));
                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
                }
                block2::RcBlock::new(move |resp: isize| {
                    ffi_guard::contain((), || {
                        let result = if resp == 1000 {
                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
                        } else {
                            present::PresentResult::Dismissed
                        };
                        emit(WINDOW_NODE, Event::PresentResult { req, result });
                        PRESENT_ALERTS.with(|m| {
                            m.borrow_mut().remove(&req);
                        });
                    })
                })
            }
            // File pickers returned early above.
            PresentSpec::OpenFile { .. }
            | PresentSpec::OpenFolder { .. }
            | PresentSpec::SaveFile { .. } => unreachable!(),
        };
        unsafe {
            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
        }
        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
    }

    fn dismiss(&mut self, req: u64) {
        // Close the sheet; its completion handler fires but its (native) result is dropped
        // because day-core already removed the pending request when it resolved.
        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
        if let Some(alert) = alert {
            let sheet = alert.window();
            if let Some(parent) = sheet.sheetParent() {
                unsafe { parent.endSheet(&sheet) };
            }
        }
        // File-picker sheets are their own NSWindow.
        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
        if let Some(panel) = panel
            && let Some(parent) = panel.sheetParent()
        {
            unsafe { parent.endSheet(&panel) };
        }
    }

    fn application_handlers(
        &mut self,
        query: &day_spec::applications::HandlerQuery,
    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
    {
        applications::handlers(query)
    }

    fn open_url_with_application(
        &mut self,
        url: &str,
        application: &str,
        completion: day_spec::applications::OpenApplicationCompletion,
    ) {
        applications::open(url, application, completion);
    }

    fn share_support(&self) -> day_spec::Support {
        day_spec::Support::Native
    }
    fn share_url(&mut self, url: &str, _title: &str) -> bool {
        use objc2::{msg_send, runtime::AnyObject};
        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
        let Some(mtm) = objc2::MainThreadMarker::new() else {
            return false;
        };
        let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
            return false;
        };
        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
        let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
            return false;
        };
        unsafe {
            let items = NSArray::from_retained_slice(&[url]);
            let picker: objc2::rc::Allocated<AnyObject> =
                msg_send![objc2::class!(NSSharingServicePicker), alloc];
            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
            let bounds = view.bounds();
            let y = if view.isFlipped() {
                30.0
            } else {
                bounds.size.height - 30.0
            };
            let rect = NSRect::new(
                NSPoint::new(bounds.size.width - 30.0, y),
                NSSize::new(1.0, 1.0),
            );
            let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
            self.sharing = Some(picker);
        }
        true
    }
    fn open_url(&mut self, url: &str) {
        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
        if let Some(nsurl) = nsurl {
            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
        }
    }
}

/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
#[allow(deprecated)]
fn apply_allowed_file_types(
    panel: &objc2_app_kit::NSSavePanel,
    filters: &[day_spec::present::FileFilter],
) {
    let exts: Vec<Retained<NSString>> = filters
        .iter()
        .flat_map(|f| f.extensions.iter())
        .map(|e| NSString::from_str(e))
        .collect();
    if !exts.is_empty() {
        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
        let arr = objc2_foundation::NSArray::from_slice(&refs);
        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
    }
}

/// Turn an open panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1):
/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
/// chooser its one directory).
fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
    let mut paths = Vec::new();
    if resp == 1 {
        for url in unsafe { panel.URLs() }.iter() {
            if let Some(p) = unsafe { url.path() } {
                paths.push(p.to_string());
            }
        }
    }
    let result = if paths.is_empty() {
        present::PresentResult::Dismissed
    } else {
        present::PresentResult::Files(paths)
    };
    emit(WINDOW_NODE, Event::PresentResult { req, result });
    PRESENT_PANELS.with(|m| {
        m.borrow_mut().remove(&req);
    });
}

/// Turn a save panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1).
fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
    let result = if resp == 1 {
        unsafe { panel.URL() }
            .and_then(|url| unsafe { url.path() })
            .map(|p| present::PresentResult::Files(vec![p.to_string()]))
            .unwrap_or(present::PresentResult::Dismissed)
    } else {
        present::PresentResult::Dismissed
    };
    emit(WINDOW_NODE, Event::PresentResult { req, result });
    PRESENT_PANELS.with(|m| {
        m.borrow_mut().remove(&req);
    });
}

impl Platform for AppKit {
    const TARGET: &'static str = "macos-appkit";
    const TOOLKIT: &'static str = "appkit";

    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
        let mtm = self.mtm;
        // The App menu / About use the app's display name. `app_name` overrides the (possibly
        // decorated) window title; setting the process name also makes the standard About panel and
        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
        self.app_name = options
            .app_name
            .clone()
            .unwrap_or_else(|| options.title.clone());
        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
        // it, not just when `app_name` was given explicitly — an app that only set `title` was
        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
        //
        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
        // where the name falls back to the executable's file name. Writing the info dictionary
        // covers the bundled case; the process name covers the unbundled one.
        unsafe {
            objc2_foundation::NSProcessInfo::processInfo()
                .setProcessName(&NSString::from_str(&self.app_name));
            let bundle = objc2_foundation::NSBundle::mainBundle();
            let info: Option<Retained<objc2_foundation::NSDictionary>> =
                msg_send![&bundle, infoDictionary];
            if let Some(info) = info {
                let key = NSString::from_str("CFBundleName");
                let value = NSString::from_str(&self.app_name);
                // `infoDictionary` is documented immutable, but the instance backing an
                // unbundled process is a mutable dictionary; guard the send so a genuinely
                // immutable one is left alone instead of raising.
                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
                }
            }
        }
        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
        // read at NSApplication init, so register before sharedApplication. Registration
        // domain only: volatile, never persisted to the app's defaults.
        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
            unsafe {
                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
                    .into_super()
                    .into_super()
                    .into_super();
                let dict = NSDictionary::from_retained_objects(
                    &[
                        &*NSString::from_str("AppleTextDirection"),
                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
                    ],
                    &[yes.clone(), yes],
                );
                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
            }
        }
        let app = NSApplication::sharedApplication(mtm);
        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
            || unsafe {
                let bundle = objc2_foundation::NSBundle::mainBundle();
                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
                    &bundle,
                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
                ];
                value.is_some_and(|v| {
                    let on: bool = msg_send![&v, boolValue];
                    on
                })
            };
        app.setActivationPolicy(if menu_bar_app {
            NSApplicationActivationPolicy::Accessory
        } else {
            NSApplicationActivationPolicy::Regular
        });
        let document_delegate = documents::delegate(mtm);
        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
        // local theme checks); unset ⇒ follow the system.
        if let Ok(theme) = std::env::var("DAY_THEME") {
            let name = match theme.as_str() {
                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
                _ => None,
            };
            if let Some(name) = name {
                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
                unsafe { app.setAppearance(appearance.as_deref()) };
            }
        }
        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
        register_bundled_fonts();

        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
        // on the app's registrations — see there.
        let app_name = self.app_name.clone();
        install_main_menu(mtm, &app, &app_name);
        // App activation / termination → day lifecycle events (docs/lifecycle.md).
        install_lifecycle_observers();
        install_appearance_observer();
        install_reduce_motion_observer();

        let (window, delegate, content) = self.make_window(&options, false, None);
        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
        // its own colors instead of following the system appearance. Unset = follow the system.
        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
            _ => None,
        };
        if let Some(name) = appearance_name
            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
        {
            window.setAppearance(Some(&appearance));
        }
        // The primary delegate lives for the process (this frame never returns); secondary
        // delegates are retained in `self.secondary`.
        std::mem::forget(delegate);

        self.window = Some(window.clone());
        self.content = Some(content.clone());
        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));

        // The root lays out below the title bar, not under it (§7.7).
        let layout = pin_below_title_bar(&window)
            .unwrap_or(Size::new(options.size.width, options.size.height));
        ready(self, content, layout);

        // `ready` ran the app's root() — registrations are in. Without a new-window
        // builder only one Normal window can ever exist: turn automatic tabbing off so no
        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
        if day_core::windows::new_window_action_id() == 0
            && options.tabbing == day_spec::WindowTabbing::Automatic
        {
            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
        }
        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
        // they can. An app with its own `app_menu` model already replaced the whole bar and
        // gets its items through the injection path instead.
        if !day_core::has_app_menu() {
            install_main_menu(mtm, &app, &app_name);
        }

        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
        // autosave name and hands it back on request; `setFrameUsingName` answers false the
        // first time, which is when centering is the right answer.
        //
        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
        // would make every captured screenshot's dimensions depend on where the developer last
        // dragged the window, and the capture suites compare those across machines.
        let deterministic =
            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
        let autosave = NSString::from_str("day.main");
        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
            window.center();
            // An explicit placement wins over centering, but not over the frame the user left.
            window_chrome::place(&window, options.placement);
        }
        // A scripted run whose capture needs a display scale this host's displays lack opens on
        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
        // capture is the window server's pixels, so it has the scale of the display under it.
        if let Some(screen) = capture_screen(mtm) {
            let (visible, frame) = (screen.visibleFrame(), window.frame());
            window.setFrameOrigin(NSPoint::new(
                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
            ));
        }
        if !deterministic {
            unsafe { window.setFrameAutosaveName(&autosave) };
        }
        if !options.start_hidden {
            window.makeKeyAndOrderFront(None);
            app.activate();
        }
        // The root was mounted before the window was shown (ready() runs first), and on
        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
        // before the app finishes launching — the window stays blank until the next real
        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
        if let Some(content) = window.contentView() {
            mark_tree_needs_display(&content);
        }
        if std::env::var_os("DAY_DUMP").is_some() {
            std::thread::spawn(|| {
                std::thread::sleep(std::time::Duration::from_millis(2000));
                Self::post(Box::new(|| {
                    // The primary's content specifically (docs/windows.md).
                    if let Some(content) = primary_content() {
                        let desc: Retained<NSString> =
                            unsafe { msg_send![&*content, _subtreeDescription] };
                        log::warn!("{desc}");
                    }
                }));
            });
        }
        app.run();
    }

    fn post(f: Box<dyn FnOnce() + Send>) {
        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
        // panic is contained here rather than unwinding into libdispatch.
        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
    }

    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
        let when =
            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
                .unwrap_or(dispatch2::DispatchTime::FOREVER);
        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
            ffi_guard::contain((), f);
        }) {
            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
        }
    }

    fn locale_hints(&self) -> Vec<String> {
        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
        objc2_foundation::NSLocale::preferredLanguages()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }
}

// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
// than taken from a binding because the availability attribute would refuse the call outright,
// and every use below treats a NULL return as "ask the offscreen path instead".
unsafe extern "C" {
    fn CGWindowListCreateImage(
        bounds: objc2_core_foundation::CGRect,
        list_option: u32,
        window_id: u32,
        image_option: u32,
    ) -> *mut objc2_core_graphics::CGImage;
}

/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
/// it (another app, a CI runner's stray window) cannot appear in the capture.
const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
/// makes the returned image exactly `window.frame()` at the backing scale.
const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;

/// Encode a captured rep as PNG, in sRGB.
///
/// A capture arrives in the color space of the display it was composited for, and a PNG of it
/// embeds that display's ICC profile: the same color then has different sample values on every
/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
/// macOS capture's samples comparable with theirs and independent of the capturing display.
fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
        objc2_app_kit::NSColorRenderingIntent::Default,
    );
    let rep = srgb.as_deref().unwrap_or(rep);
    let data = unsafe {
        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
    }
    .ok_or("png encode failed")?;
    Ok(data.to_vec())
}

/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
///
/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
/// sidebar. The window server has the real pixels, including the rows.
///
/// It answers only while the window is actually on screen. A hidden, minimized or
/// never-composited window has no image to hand back (verified: hiding the app makes this return
/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
/// falls back rather than failing the capture.
fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
    let window = content.window().ok_or("view is not in a window")?;
    // An attached sheet is the active modal surface and has its own composited window.
    // Capturing only the parent's window would show dimmed content without the modal UI.
    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
        return snapshot_via_window_server(&sheet, chrome);
    }
    let number = window.windowNumber();
    if number <= 0 {
        return Err(format!("window {number} is not on screen"));
    }
    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
    // app has changed the view tree since. A capture taken right after a state change then shows
    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
    // then commit the layer tree to the render server.
    unsafe { content.layoutSubtreeIfNeeded() };
    window.displayIfNeeded();
    CATransaction::flush();
    // CGRectNull asks for the window's own bounds rather than a screen region.
    let null_rect = objc2_core_foundation::CGRect::new(
        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
        objc2_core_foundation::CGSize::new(0.0, 0.0),
    );
    let shot = unsafe {
        CGWindowListCreateImage(
            null_rect,
            CG_WINDOW_LIST_INCLUDING_WINDOW,
            number as u32,
            CG_WINDOW_IMAGE_IGNORE_FRAMING,
        )
    };
    if shot.is_null() {
        return Err("the window server has no image for this window".into());
    }
    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
    // ownership over, so it is released exactly once.
    let shot = unsafe {
        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
    };

    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
    // rounded corners included — so it is done here, before the crop.
    if chrome {
        let rep = unsafe {
            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
                objc2_app_kit::NSBitmapImageRep::alloc(),
                &shot,
            )
        };
        return png_of_rep(&rep);
    }

    // Crop the window frame down to the content view. Keeping the framing identical to the
    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
    // published gallery shot would otherwise change size.
    let frame = window.frame();
    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
        return Err("zero-size window".into());
    }
    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
    // from the window top is what the crop needs.
    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
    let crop = objc2_core_foundation::CGRect::new(
        objc2_core_foundation::CGPoint::new(
            (in_window.origin.x * scale).round(),
            (from_top * scale).round(),
        ),
        objc2_core_foundation::CGSize::new(
            (in_window.size.width * scale).round(),
            (in_window.size.height * scale).round(),
        ),
    );
    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
        .ok_or("crop to the content view failed")?;
    let rep = unsafe {
        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
            objc2_app_kit::NSBitmapImageRep::alloc(),
            &cropped,
        )
    };
    png_of_rep(&rep)
}

/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
///
/// The window server first, because it is the only one of the two that can show macOS's own
/// composited materials; the offscreen render when it declines, because it is the only one of the
/// two that works with no window on screen. See each for why.
/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
    let [x, y, w, h] = base;
    let (sw, sh) = (w * t.sx, h * t.sy);
    let frame = NSRect::new(
        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
        NSSize::new(sw, sh),
    );
    unsafe {
        // The rotation goes first and comes back last: a rotated view's frame is its bounding
        // box, so setting the frame of a rotated view would scale it.
        v.setFrameCenterRotation(0.0);
        v.setFrame(frame);
        v.setBoundsSize(NSSize::new(w, h));
        if t.rotate_deg != 0.0 {
            v.setFrameCenterRotation(t.rotate_deg);
        }
    }
}

fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
    let modal = content
        .window()
        .and_then(|w| w.attachedSheet())
        .and_then(|s| s.contentView());
    let content = modal.as_deref().unwrap_or(content);
    match snapshot_via_window_server(content, false) {
        Ok(bytes) => Ok(bytes),
        Err(_) => snapshot_view_cache(content),
    }
}

/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
/// (`day::window_image().chrome()`, docs/window-image.md).
///
/// Only the window server can produce this: the offscreen path renders the content view's own
/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
/// the content capture stands in — a smaller image beats no image, and it is what the caller
/// would have got from the plain duty.
fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
    let modal = content
        .window()
        .and_then(|w| w.attachedSheet())
        .and_then(|s| s.contentView());
    let content = modal.as_deref().unwrap_or(content);
    match snapshot_via_window_server(content, true) {
        Ok(bytes) => Ok(bytes),
        Err(_) => snapshot_view_cache(content),
    }
}

/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
/// server composites (see `snapshot_via_window_server`).
fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
    let bounds = content.bounds();
    let rep =
        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
    // Day containers are transparent (the window server paints the backdrop), so pre-fill
    // the rep with the window background — resolved for the window's light/dark appearance —
    // before compositing the view hierarchy over it (§14).
    let ctx =
        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
    NSGraphicsContext::saveGraphicsState_class();
    NSGraphicsContext::setCurrentContext(Some(&ctx));
    content
        .effectiveAppearance()
        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
            NSColor::windowBackgroundColor().setFill();
            objc2_app_kit::NSRectFill(bounds);
        }));
    NSGraphicsContext::restoreGraphicsState_class();
    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
    png_of_rep(&rep)
}

/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the CGDirectDisplayID of the
/// capture display `day launch --script` provides when no attached display has the capture's
/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
        .ok()?
        .trim()
        .parse()
        .ok()?;
    let key = NSString::from_str("NSScreenNumber");
    objc2_app_kit::NSScreen::screens(mtm)
        .into_iter()
        .find(|screen| {
            let number: Option<Retained<objc2_foundation::NSNumber>> =
                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
            number.is_some_and(|n| n.unsignedIntValue() == wanted)
        })
}

/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
fn mark_tree_needs_display(view: &NSView) {
    view.setNeedsDisplay(true);
    for sub in view.subviews() {
        mark_tree_needs_display(&sub);
    }
}

/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
    phase.is_universal()
}

/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
/// "AppleInterfaceThemeChangedNotification" on a theme switch, and AppKit updates
/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
fn install_appearance_observer() {
    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
        dispatch2::DispatchQueue::main()
            .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
    });
    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
    let token = unsafe {
        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
    };
    std::mem::forget(token);
}

/// Follow the SYSTEM reduce-motion switch while the app runs: NSWorkspace posts
/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
/// center when any Accessibility › Display option flips, and
/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
/// poster's stack, as the appearance observer does. The token is leaked to observe for the
/// app's lifetime.
fn install_reduce_motion_observer() {
    use objc2_foundation::NSNotification;
    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
        dispatch2::DispatchQueue::main()
            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
    });
    let token = unsafe {
        center.addObserverForName_object_queue_usingBlock(
            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
            None,
            None,
            &block,
        )
    };
    std::mem::forget(token);
}

/// Bridge the NSApplication activation/termination notifications to day lifecycle events
/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
fn install_lifecycle_observers() {
    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
    let center = unsafe { NSNotificationCenter::defaultCenter() };
    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
        });
        let token = unsafe {
            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
        };
        std::mem::forget(token); // observe for the app's lifetime
    };
    unsafe {
        observe(
            NSApplicationDidBecomeActiveNotification,
            day_spec::Lifecycle::DidBecomeActive,
        );
        observe(
            NSApplicationWillResignActiveNotification,
            day_spec::Lifecycle::WillResignActive,
        );
        observe(
            NSApplicationWillTerminateNotification,
            day_spec::Lifecycle::WillTerminate,
        );
        // `terminate:` exits the process from inside the run loop, so the loop never returns to
        // `launch_with`: the last Day code to run is this notification's second observer, which
        // NSNotificationCenter calls after the first (docs/lifecycle.md).
        observe(
            NSApplicationWillTerminateNotification,
            day_spec::Lifecycle::DidExit,
        );
    }
}

day_localization_ui::locales!();

/// Shared by the initial menu and every reactive replacement. AppKit owns Services
/// and the hide actions; these commands must not depend on a window or app callback.
fn install_application_menu(
    mtm: MainThreadMarker,
    menubar: &NSMenu,
    title: &str,
    about: Option<day_spec::MenuItem>,
    updates: Option<day_spec::MenuItem>,
    prefs: Option<day_spec::MenuItem>,
    quit: Option<day_spec::MenuItem>,
) -> Retained<NSMenu> {
    let app = NSApplication::sharedApplication(mtm);
    use day_spec::{MenuItem as M, MenuRole as R};
    let standard = |role, label| M::Action {
        id: None,
        action: 0,
        label,
        shortcut: None,
        enabled: true,
        checked: None,
        role: Some(role),
        icon: None,
    };
    let mut about =
        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
    for (item, title) in [
        (&mut about, res::str::about_app(title).format()),
        (&mut quit, res::str::quit_app(title).format()),
    ] {
        if let M::Action { label, .. } = item {
            *label = title;
        }
    }
    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
    if let M::Action { action, .. } = &mut about
        && *action == 0
    {
        *action = day_core::windows::about_action_id();
    }
    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
    // placed the role itself or the updater only registered its action.
    let updates_id = day_core::windows::check_for_updates_action_id();
    let updates = updates.or_else(|| {
        (updates_id != 0).then(|| {
            standard(
                R::CheckForUpdates,
                day_localization::t(day_localization::key::day_check_for_updates),
            )
        })
    });
    let mut head = vec![about];
    if let Some(mut updates) = updates {
        if let M::Action { action, .. } = &mut updates
            && *action == 0
        {
            *action = updates_id;
        }
        head.push(updates);
    }
    head.push(M::Separator);
    let menu = build_ns_menu(mtm, title, &head);
    if let Some(mut prefs) = prefs {
        if let M::Action { label, .. } = &mut prefs {
            *label = res::str::settings().format();
        }
        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
        for item in section.itemArray() {
            section.removeItem(&item);
            menu.addItem(&item);
        }
    }
    // AppKit keeps the registered Services menu across main-menu replacements.
    // Move that same menu to the new bar rather than abandoning its system-populated items.
    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
    if let Some(parent) = unsafe { services.supermenu() } {
        let index = parent.indexOfItemWithSubmenu(Some(&services));
        if index >= 0 {
            parent.itemAtIndex(index).unwrap().setSubmenu(None);
        }
    }
    let services_item = NSMenuItem::new(mtm);
    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
    services_item.setSubmenu(Some(&services));
    menu.addItem(&services_item);
    menu.addItem(&NSMenuItem::separatorItem(mtm));
    for (label, selector, shortcut) in [
        (
            res::str::hide_app(title).format(),
            sel!(hide:),
            Some(day_spec::Shortcut::primary("h")),
        ),
        (
            res::str::hide_others().format(),
            sel!(hideOtherApplications:),
            Some(day_spec::Shortcut::primary("h").alt()),
        ),
        (
            res::str::show_all().format(),
            sel!(unhideAllApplications:),
            None,
        ),
    ] {
        let item = unsafe {
            NSMenuItem::initWithTitle_action_keyEquivalent(
                NSMenuItem::alloc(mtm),
                &NSString::from_str(&label),
                Some(selector),
                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
            )
        };
        if let Some(shortcut) = shortcut {
            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
        }
        // Explicitly target the application so window responders cannot override Hide.
        unsafe { item.setTarget(Some(&app)) };
        menu.addItem(&item);
    }
    menu.addItem(&NSMenuItem::separatorItem(mtm));
    let section = build_ns_menu(mtm, title, &[quit]);
    let quit = section.itemAtIndex(0).unwrap();
    section.removeItem(&quit);
    menu.addItem(&quit);
    let item = NSMenuItem::new(mtm);
    item.setSubmenu(Some(&menu));
    menubar.addItem(&item);
    services
}

/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
/// chain so Cmd+C/V/X/A work in NSTextFields; Window menu basics.
fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
    let menubar = NSMenu::new(mtm);

    let prefs_id = day_core::windows::preferences_action_id();
    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
        id: None,
        action: prefs_id,
        label: res::str::settings().format(),
        shortcut: None,
        enabled: true,
        checked: None,
        role: Some(day_spec::MenuRole::Preferences),
        icon: None,
    });
    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);

    // File ▸ New Window / Close, when the app registered a new-window builder — the same
    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
    // File ▸ New Window, because the default menu bar has no File menu to put it in.
    let new_window_id = day_core::windows::new_window_action_id();
    if new_window_id != 0 {
        let file_item = NSMenuItem::new(mtm);
        let file_menu = unsafe {
            NSMenu::initWithTitle(
                NSMenu::alloc(mtm),
                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
            )
        };
        let new_window = unsafe {
            NSMenuItem::initWithTitle_action_keyEquivalent(
                NSMenuItem::alloc(mtm),
                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
                Some(sel!(fire:)),
                &NSString::from_str("n"),
            )
        };
        let target = menu_target(mtm);
        let tobj: &objc2::runtime::AnyObject = target.as_ref();
        unsafe { new_window.setTarget(Some(tobj)) };
        new_window.setTag(new_window_id as isize);
        file_menu.addItem(&new_window);
        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
        // Nil-targeted, so it closes whatever window is key — the standard responder route.
        let close = unsafe {
            NSMenuItem::initWithTitle_action_keyEquivalent(
                NSMenuItem::alloc(mtm),
                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
                Some(sel!(performClose:)),
                &NSString::from_str("w"),
            )
        };
        file_menu.addItem(&close);
        file_item.setSubmenu(Some(&file_menu));
        menubar.addItem(&file_item);
    }

    let edit_item = NSMenuItem::new(mtm);
    let edit_menu = unsafe {
        NSMenu::initWithTitle(
            NSMenu::alloc(mtm),
            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
        )
    };
    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
        let item = unsafe {
            NSMenuItem::initWithTitle_action_keyEquivalent(
                NSMenuItem::alloc(mtm),
                &NSString::from_str(&day_localization::t(key)),
                Some(action),
                &NSString::from_str(accel),
            )
        };
        edit_menu.addItem(&item);
    };
    add("day_undo", sel!(undo:), "z");
    add("day_redo", sel!(redo:), "Z");
    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
    add("day_cut", sel!(cut:), "x");
    add("day_copy", sel!(copy:), "c");
    add("day_paste", sel!(paste:), "v");
    add("day_select_all", sel!(selectAll:), "a");
    edit_item.setSubmenu(Some(&edit_menu));
    menubar.addItem(&edit_item);

    install_windows_menu(mtm, app, &menubar);

    app.setMainMenu(Some(&menubar));
    unsafe { app.setServicesMenu(Some(&services)) };
}

/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
/// nav hosts are nil-targeted (responder chain), so they act on the key window.
fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
    let menu = unsafe {
        NSMenu::initWithTitle(
            NSMenu::alloc(mtm),
            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
        )
    };
    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
        let item = unsafe {
            NSMenuItem::initWithTitle_action_keyEquivalent(
                NSMenuItem::alloc(mtm),
                &NSString::from_str(&day_localization::t(key)),
                Some(action),
                &NSString::from_str(accel),
            )
        };
        menu.addItem(&item);
    };
    add("day_minimize", sel!(performMiniaturize:), "m");
    add("day_zoom", sel!(performZoom:), "");
    menu.addItem(&NSMenuItem::separatorItem(mtm));
    add("day_bring_all_front", sel!(arrangeInFront:), "");
    let item = NSMenuItem::new(mtm);
    item.setTitle(&NSString::from_str(&day_localization::t(
        day_localization::key::day_window,
    )));
    item.setSubmenu(Some(&menu));
    menubar.addItem(&item);
    unsafe { app.setWindowsMenu(Some(&menu)) };
}

/// Hoist application roles even from nested menus. First declaration wins; remove
/// duplicates and empty containers, then normalize separators left by the move.
fn extract_app_role(
    items: &mut Vec<day_spec::MenuItem>,
    role: day_spec::MenuRole,
) -> Option<day_spec::MenuItem> {
    use day_spec::MenuItem as M;
    let mut found = None;
    let mut remaining = Vec::new();
    for mut item in items.drain(..) {
        match &mut item {
            M::Action { role: Some(r), .. } if *r == role => {
                found.get_or_insert(item);
                continue;
            }
            M::Submenu { items, .. } => {
                let nested = extract_app_role(items, role);
                if found.is_none() {
                    found = nested;
                }
                if items.is_empty() {
                    continue;
                }
            }
            M::Separator
                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
            {
                continue;
            }
            _ => {}
        }
        remaining.push(item);
    }
    while matches!(remaining.last(), Some(M::Separator)) {
        remaining.pop();
    }
    *items = remaining;
    found
}

/// Whether any action in the model (recursively) carries `role`.
fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
    items.iter().any(|it| match it {
        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
        day_spec::MenuItem::Separator => false,
    })
}

// ---------------------------------------------------------------------------
// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
// ---------------------------------------------------------------------------

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "DayMenuTarget"]
    #[ivars = ()]
    struct DayMenuTarget;

    unsafe impl NSObjectProtocol for DayMenuTarget {}

    impl DayMenuTarget {
        #[unsafe(method(fire:))]
        fn fire(&self, sender: &NSMenuItem) {
            ffi_guard::contain((), || {
                let id = sender.tag() as u64;
                if id != 0 {
                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
                }
            })
        }
    }
);

/// The primary window's content view (set once in `run`).
/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
/// resize, and a toolbar coming or going.
pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
    let content = window.contentView()?;
    let full = content.frame().size;
    let layout = unsafe { window.contentLayoutRect() }.size;
    let top = (full.height - layout.height).max(0.0);
    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
    // inset so it can pad its own content.
    if window_chrome::is_overlay(window) {
        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
        window_chrome::report_title_bar_inset(window, top);
        return Some(Size::new(full.width, full.height));
    }
    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
    Some(Size::new(full.width, (full.height - top).max(0.0)))
}

/// The text a widget displays, for `read_native`: a label's or text field's string, a
/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
/// icon-only button (its title is a tooltip), and every other view.
fn native_text(h: &NSView) -> Option<String> {
    if h.downcast_ref::<NSSecureTextField>().is_some() {
        return None;
    }
    if let Some(tf) = h.downcast_ref::<NSTextField>() {
        // `stringValue` answers the field editor's live text while the field edits.
        return Some(tf.stringValue().to_string());
    }
    if let Some(btn) = h.downcast_ref::<NSButton>() {
        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
            return None;
        }
        return Some(btn.title().to_string());
    }
    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
    let sv = h.downcast_ref::<NSScrollView>()?;
    let doc = sv.documentView()?;
    let tv = doc.downcast_ref::<NSTextView>()?;
    Some(tv.string().to_string())
}

/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
fn native_number(h: &NSView) -> Option<f64> {
    if let Some(sl) = h.downcast_ref::<NSSlider>() {
        return Some(sl.doubleValue());
    }
    let pi = h.downcast_ref::<NSProgressIndicator>()?;
    (!pi.isIndeterminate()).then(|| pi.doubleValue())
}

/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
/// converting into it gives Day's layout space; an unflipped content view is flipped here.
fn native_frame(h: &NSView) -> Option<Rect> {
    let content = h.window()?.contentView()?;
    let r = h.convertRect_toView(h.bounds(), Some(&content));
    let y = if content.isFlipped() {
        r.origin.y
    } else {
        let b = content.bounds();
        b.origin.y + b.size.height - (r.origin.y + r.size.height)
    };
    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
}

/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
fn title_bar_inset(content: &NSView) -> f64 {
    (-content.bounds().origin.y).max(0.0)
}

fn primary_content() -> Option<Retained<NSView>> {
    PRIMARY_CONTENT.with(|c| c.borrow().clone())
}

fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
    MENU_TARGET.with(|t| {
        t.borrow_mut()
            .get_or_insert_with(|| {
                let this = DayMenuTarget::alloc(mtm).set_ivars(());
                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
                obj
            })
            .clone()
    })
}

fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
    use objc2_app_kit::NSEventModifierFlags as F;
    let mut m = F::empty();
    if s.primary {
        m |= F::Command;
    }
    if s.shift {
        m |= F::Shift;
    }
    if s.alt {
        m |= F::Option;
    }
    if s.control {
        m |= F::Control;
    }
    m
}

/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
fn ns_key_equivalent(key: &str) -> String {
    match key {
        "Return" | "Enter" => "\r".into(),
        "Tab" => "\t".into(),
        "Delete" | "Backspace" => "\u{8}".into(),
        "Escape" => "\u{1b}".into(),
        "Space" => " ".into(),
        k if k.chars().count() == 1 => k.to_lowercase(),
        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
    }
}

/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
/// (the app should attach its own via a custom item); the role then only supplies label placement.
fn role_spec(
    role: day_spec::MenuRole,
) -> (
    &'static str,
    Option<objc2::runtime::Sel>,
    Option<day_spec::Shortcut>,
) {
    use day_spec::MenuRole as R;
    use day_spec::Shortcut as S;
    match role {
        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
        R::Delete => ("Delete", Some(sel!(delete:)), None),
        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
        R::Preferences => ("Settings…", None, Some(S::primary(","))),
        R::Minimize => (
            "Minimize",
            Some(sel!(performMiniaturize:)),
            Some(S::primary("m")),
        ),
        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
        R::Fullscreen => (
            "Enter Full Screen",
            Some(sel!(toggleFullScreen:)),
            Some(S::primary("f").control()),
        ),
        // No native selector (docs/windows.md): the item dispatches the registered
        // new-window action through the ordinary custom-item path (`fire:`).
        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
        // Likewise: no selector, the registered updater action fires through `fire:`.
        R::CheckForUpdates => ("Check for Updates…", None, None),
    }
}

pub(crate) fn build_ns_menu(
    mtm: MainThreadMarker,
    title: &str,
    items: &[day_spec::MenuItem],
) -> Retained<NSMenu> {
    use day_spec::MenuItem as MI;
    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
    let target = menu_target(mtm);
    for item in items {
        match item {
            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
            MI::Submenu { label, items, .. } => {
                let sub = build_ns_menu(mtm, label, items);
                let it = NSMenuItem::new(mtm);
                it.setTitle(&NSString::from_str(label));
                it.setSubmenu(Some(&sub));
                menu.addItem(&it);
            }
            MI::Action {
                action,
                label,
                shortcut,
                enabled,
                checked,
                role,
                icon,
                ..
            } => {
                // Resolve label/nav host/shortcut, folding in the role's native defaults.
                let (mut lbl, sel, mut sc) = match role {
                    Some(r) => {
                        let (dl, ds, dsc) = role_spec(*r);
                        (dl.to_string(), ds, dsc)
                    }
                    None => (String::new(), None, None),
                };
                if !label.is_empty() {
                    lbl = label.clone();
                }
                if shortcut.is_some() {
                    sc = shortcut.clone();
                }
                // Custom action (nonzero id) overrides any role nav host and targets our
                // trampoline — except the responder-routed set (undo pair, clipboard trio),
                // whose nonzero ids are only the other platforms' fallback dispatchers: here
                // the nil-target nav hosts must stay, so the responder chain resolves the
                // acting object (a focused text field before the app's bridge).
                let responder_role = matches!(
                    role,
                    Some(
                        day_spec::MenuRole::Undo
                            | day_spec::MenuRole::Redo
                            | day_spec::MenuRole::Cut
                            | day_spec::MenuRole::Copy
                            | day_spec::MenuRole::Paste
                            | day_spec::MenuRole::SelectAll
                    )
                );
                let custom = *action != 0 && !responder_role;
                let key = sc
                    .as_ref()
                    .map(|s| ns_key_equivalent(&s.key))
                    .unwrap_or_default();
                let it = unsafe {
                    NSMenuItem::initWithTitle_action_keyEquivalent(
                        NSMenuItem::alloc(mtm),
                        &NSString::from_str(&lbl),
                        if custom { Some(sel!(fire:)) } else { sel },
                        &NSString::from_str(&key),
                    )
                };
                if let Some(s) = &sc {
                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
                    // key equivalent the current keyboard layout cannot type, and MIRROR
                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
                    // shortcut localization; the catalog half is the `.key` attribute
                    // (docs/localization.md).
                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
                }
                if custom {
                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
                    unsafe { it.setTarget(Some(tobj)) };
                    it.setTag(*action as isize);
                }
                it.setEnabled(*enabled);
                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
                if let Some(on) = checked {
                    it.setState(if *on {
                        NSControlStateValueOn
                    } else {
                        NSControlStateValueOff
                    });
                }
                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
                // template-tinted, sized to the menu's text.
                if let Some(icon) = icon
                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
                {
                    img.setSize(NSSize::new(16.0, 16.0));
                    it.setImage(Some(&img));
                }
                menu.addItem(&it);
            }
        }
    }
    menu
}

// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
// The registry already released the native images in that case.
fn release_bitmap(id: day_spec::BitmapId) {
    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
}

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

    #[test]
    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
        if std::env::var_os(CHILD).is_some() {
            struct LateRelease;
            impl Drop for LateRelease {
                fn drop(&mut self) {
                    assert!(BITMAPS.try_with(|_| ()).is_err());
                    // Same duty called by Bitmap::drop; no NSApplication is needed.
                    release_bitmap(day_spec::BitmapId(1));
                }
            }
            std::thread_local! {
                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
            }
            std::thread::spawn(|| {
                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
                BITMAPS.with(|_| ()); // initialized last, destroyed first
            })
            .join()
            .unwrap();
            return;
        }
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
                "--nocapture",
            ])
            .env(CHILD, "1")
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}