ferrokit 0.10.0

Native macOS GUI framework for Rust: every view a real AppKit control (NSTableView, NSOutlineView, NSTextView), updated in place by fine-grained signals
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
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
//! ferrokit's regression suite (grows with each F1 milestone). `CHECK=all`
//! runs the unattended checks and exits non-zero on failure; without it the
//! app just runs.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use ferrokit::{
    Align, App, AppEvent, Effect, Identifiable, Signal, View, ViewExt, Window, batch, button, segmented_with, read_stored, write_stored, remove_stored, checkbox, dynamic, effect_runs,
    for_each, grid, hstack, later, layout_stats, layout_passes, layout_times_us, live_nodes, open, secure_field, spacer, spawn, text,
    text_field, toggle, vstack, windows, divider, image, picker, progress, scroll, slider, stepper, table, Column, Sort,
    TableKey, TableModel, ViewId, TreeNode, outline, sidebar, TextModel, text_editor, split, toolbar_button, toolbar_space,
    toolbar_search, menu_item, menu_separator, MenuItem, Modifier, submenu, stored, set_undoable, Alert, OpenOptions, SheetHandle, alert, open_panel, save_panel, sheet,
};
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSTextField, NSView};
use ferrokit::testing::{
    ax_tree, context_menu_for_word, footprint_mb, has_ax, heap_in_use_mb, is_misspelled, menu_key, post_edit, send_action, shortcut, snapshot_windows,
};
use objc2_app_kit::{NSAppearanceCustomization, NSTextInputClient};
use objc2_foundation::NSString;


thread_local! {
    static FAILED: Cell<u32> = const { Cell::new(0) };
}

/// What could keep posted input from arriving, for a real-input check's
/// note when it fails: the run loop's mode (AppKit's event tracking, as
/// while the real mouse drags or scrolls over a window of the app, takes
/// events off the queue itself), the pointer and the buttons held.
fn input_state() -> String {
    let p = objc2_app_kit::NSEvent::mouseLocation();
    let mode = objc2_foundation::NSRunLoop::currentRunLoop().currentMode().map(|m| m.to_string()).unwrap_or_default();
    format!("run loop {mode}, pointer {:.0},{:.0}, buttons held {}", p.x, p.y, objc2_app_kit::NSEvent::pressedMouseButtons())
}

fn check(name: &str, pass: bool, note: String) {
    eprintln!("[check] {name} {} {note}", if pass { "PASS" } else { "FAIL" });
    if !pass {
        FAILED.with(|f| f.set(f.get() + 1));
    }
}

fn mtm() -> MainThreadMarker {
    MainThreadMarker::new().unwrap()
}

/// Whether an image view is hidden from VoiceOver: the view and its cell
/// (which answers for it on macOS 15 and 26).
fn ax_hidden(view: &objc2_app_kit::NSImageView) -> bool {
    let on = |o: &objc2::runtime::AnyObject| -> bool { unsafe { objc2::msg_send![o, isAccessibilityElement] } };
    !on(view) && view.cell().is_none_or(|c| !on(&c))
}

fn field(text: &str) -> Retained<NSView> {
    let f = NSTextField::textFieldWithString(&NSString::from_str(text), mtm());
    f.setFrame(objc2_foundation::NSRect::new(
        objc2_foundation::NSPoint::new(20.0, 20.0),
        objc2_foundation::NSSize::new(300.0, 24.0),
    ));
    let content = NSView::new(mtm());
    content.addSubview(&f);
    content
}

/// A top-level menu by title.
fn bar_menu(title: &str) -> Retained<objc2_app_kit::NSMenu> {
    let bar = NSApplication::sharedApplication(mtm()).mainMenu().unwrap();
    bar.itemWithTitle(&NSString::from_str(title)).and_then(|i| i.submenu()).unwrap()
}

/// The titles and key equivalents of a top-level menu's items.
fn menu_items(title: &str) -> Vec<(String, String, bool)> {
    let menu = bar_menu(title);
    (0..menu.numberOfItems())
        .filter_map(|i| menu.itemAtIndex(i))
        .map(|i| {
            let shift = i.keyEquivalentModifierMask().contains(NSEventModifierFlags::Shift);
            (i.title().to_string(), i.keyEquivalent().to_string(), shift)
        })
        .collect()
}

fn has(items: &[(String, String, bool)], title: &str, key: &str) -> bool {
    items.iter().any(|(t, k, _)| t == title && k == key)
}

fn run_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let app = NSApplication::sharedApplication(mtm());

    // Menu bar: App, Edit, Window, Help.
    let bar = app.mainMenu().unwrap();
    let titles: Vec<String> = (0..bar.numberOfItems()).filter_map(|i| bar.itemAtIndex(i)).map(|i| i.title().to_string()).collect();
    check("menu-bar", titles == ["Checklist", "File", "Edit", "View", "Window", "Help"], format!("{titles:?}"));
    let app_menu = menu_items("Checklist");
    check(
        "app-menu",
        has(&app_menu, "Quit Checklist", "q") && has(&app_menu, "Hide Checklist", "h") && has(&app_menu, "About Checklist", ""),
        format!("{} items", app_menu.len()),
    );
    let edit = menu_items("Edit");
    let redo_shift = edit.iter().any(|(t, k, _)| t == "Redo" && k == "Z");
    check(
        "edit-menu",
        ["Undo", "Cut", "Copy", "Paste", "Select All"].iter().zip(["z", "x", "c", "v", "a"]).all(|(t, k)| has(&edit, t, k)) && redo_shift,
        format!("{:?}", edit.iter().map(|e| &e.0).collect::<Vec<_>>()),
    );

    // Windows: both open; AppKit lists them in the Window menu.
    let ws = windows();
    let visible = ws.iter().filter(|w| w.isVisible()).count();
    check("windows", ws.len() == 12 && visible == 12, format!("{} windows, {visible} visible", ws.len()));
    let window_menu = menu_items("Window");
    let listed = ["First", "Second", "Views", "Layout", "Controls", "Controls B", "Teardown", "Table", "Outline", "Editor", "Chrome", "Dialogs"].iter().all(|t| window_menu.iter().any(|(title, _, _)| title == t));
    check("window-menu-lists-windows", listed && app.windowsMenu().is_some(), format!("{:?}", window_menu.iter().map(|e| &e.0).collect::<Vec<_>>()));
    check("help-menu", app.helpMenu().is_some(), String::new());

    // Edit menu → responder chain: Select All selects the focused field's text.
    let first = &ws[0];
    let field = first.contentView().unwrap().subviews().firstObject().unwrap().downcast::<NSTextField>().unwrap();
    first.makeFirstResponder(Some(&field));
    let edit_menu = bar_menu("Edit");
    let select_all = edit_menu.indexOfItemWithTitle(&NSString::from_str("Select All"));
    edit_menu.performActionForItemAtIndex(select_all);
    let selected = field.currentEditor().map(|e| e.selectedRange().length).unwrap_or(0);
    check("edit-select-all", selected == 11, format!("{selected} characters selected in \"hello world\""));

    // Signals: cost of one update (one subscribed effect), and batching.
    let n = Signal::new(0u64);
    let n2 = n;
    let seen = Rc::new(Cell::new(0u64));
    let s2 = seen.clone();
    let effect = Effect::new(move || s2.set(n2.get()));
    let t = std::time::Instant::now();
    for i in 1..=100_000u64 {
        n.set(i);
    }
    let per = t.elapsed().as_secs_f64() * 1e9 / 100_000.0;
    check("signal-update-cost", seen.get() == 100_000 && (per < 500.0 || on_ci()), format!("{per:.0} ns per set + effect run (budget 500{})", ci_note()));
    let runs = effect_runs();
    batch(|| (0..1000).for_each(|i| n.set(i)));
    check("signal-batch", effect_runs() - runs == 1, format!("{} effect run(s) for 1,000 sets in one batch", effect_runs() - runs));
    drop(effect);

    // spawn: work on a background thread, continuation on the main thread in one batch.
    let main_thread = std::thread::current().id();
    let result = Signal::new(String::new());
    let r2 = result;
    let runs_seen = Rc::new(Cell::new(0u32));
    let rs = runs_seen.clone();
    let watcher = Effect::new(move || {
        let _ = r2.get();
        rs.set(rs.get() + 1);
    });
    let r3 = result;
    spawn(
        move || {
            std::thread::sleep(std::time::Duration::from_millis(50));
            (std::thread::current().id(), (1..=1000u64).sum::<u64>())
        },
        move |(worker, sum)| {
            r3.set("partial".into());
            r3.set(format!("sum {sum}"));
            let on_main = std::thread::current().id() == main_thread;
            later(move || {
                let _ = &watcher;
                check(
                    "spawn",
                    worker != main_thread && on_main && result.get_untracked() == "sum 500500" && runs_seen.get() == 2,
                    format!("worker off main: {}, continuation on main: {on_main}, value {:?}, watcher runs {}", worker != main_thread, result.get_untracked(), runs_seen.get()),
                );
                resource_checks(events.clone());
            });
        },
    );
}

/// Runs `f` on the main thread after `ms` milliseconds.
fn wait(ms: u64, f: impl FnOnce() + 'static) {
    spawn(move || std::thread::sleep(std::time::Duration::from_millis(ms)), move |()| f());
}

/// Runs `f` once `ready` holds, or after `max_ms` if it never does (for
/// what AppKit shows in its own time, like a popover).
fn until(ready: impl Fn() -> bool + 'static, max_ms: u64, f: impl FnOnce() + 'static) {
    if ready() || max_ms == 0 {
        return f();
    }
    wait(50, move || until(ready, max_ms.saturating_sub(50), f));
}

/// Resources: loading off the main thread, a stale load overtaken by a newer
/// one (cancelled, never shown), errors keeping the last value, refetch, and
/// the running load cancelled when its window closes.
fn resource_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Cancel, Load, Resource};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    let main_thread = std::thread::current().id();
    let q = Signal::new(1i64);
    let fetches = Arc::new(AtomicUsize::new(0));
    let stale_saw_cancel = Arc::new(AtomicBool::new(false));
    let off_main = Arc::new(AtomicBool::new(true));
    let (f, sc, om) = (fetches.clone(), stale_saw_cancel.clone(), off_main.clone());
    let r = Resource::new(move || q.get(), move |q: i64, cancel: &Cancel| {
        f.fetch_add(1, Ordering::Relaxed);
        if std::thread::current().id() == main_thread {
            om.store(false, Ordering::Relaxed);
        }
        if q < 0 {
            return Err("negative");
        }
        // Query 2 is slow: it's overtaken by 3 and should see the cancel.
        let ms = if q == 2 { 300 } else { 20 };
        for _ in 0..ms / 10 {
            std::thread::sleep(std::time::Duration::from_millis(10));
            if cancel.is_cancelled() {
                sc.store(q == 2, Ordering::Relaxed);
                break;
            }
        }
        Ok(q * 10)
    });
    let shown = Rc::new(RefCell::new(Vec::new()));
    let sh = shown.clone();
    let watcher = Effect::new(move || {
        if let Some(v) = r.get() {
            sh.borrow_mut().push(v);
        }
    });
    let first = (r.state(), r.loading());
    wait(150, move || {
        let loaded = (r.get(), r.loading(), r.state());
        check(
            "resource-load",
            first == (Load::Loading, true) && loaded == (Some(10), false, Load::Ready(10)) && off_main.load(Ordering::Relaxed),
            format!("before: {first:?}; after: {loaded:?}; fetched off main {}", off_main.load(Ordering::Relaxed)),
        );
        // Separate passes: this continuation is itself a batch, so two sets
        // here would coalesce into one load.
        q.set(2);
        wait(50, move || {
            let reloading = (r.get(), r.loading());
            q.set(3);
            wait(450, move || {
                let seen = shown.borrow().clone();
                check(
                    "resource-stale",
                    reloading == (Some(10), true) && seen == [10, 30] && r.get() == Some(30) && !r.loading() && stale_saw_cancel.load(Ordering::Relaxed),
                    format!("while reloading: {reloading:?}; values shown {seen:?}; slow load saw its cancel {}", stale_saw_cancel.load(Ordering::Relaxed)),
                );
                q.set(-1);
                wait(150, move || {
                    let failed = (r.state(), r.get(), r.error());
                    let before = fetches.load(Ordering::Relaxed);
                    q.set(4);
                    wait(150, move || {
                        r.refetch();
                        wait(150, move || {
                            let _ = &watcher;
                            let refetched = fetches.load(Ordering::Relaxed) - before;
                            check(
                                "resource-error",
                                failed == (Load::Failed("negative".into()), Some(30), Some("negative".into())) && r.state() == Load::Ready(40) && r.error().is_none(),
                                format!("failed: {failed:?}; after the next load: {:?}", r.state()),
                            );
                            check("resource-refetch", refetched == 2 && r.get() == Some(40), format!("{refetched} fetches for a change and a refetch; value {:?}", r.get()));
                            resource_owner_check(events.clone());
                        });
                    });
                });
            });
        });
    });
}

/// A resource made in a window's view tree: closing the window cancels its
/// running load, and the result is dropped (no panic, nothing shown).
fn resource_owner_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Cancel, Resource};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    let saw_cancel = Arc::new(AtomicBool::new(false));
    let finished = Arc::new(AtomicBool::new(false));
    let (sc, fin) = (saw_cancel.clone(), finished.clone());
    let signals = ferrokit::live_signals();
    let w = open(Window::new("Resource Owner").size(200.0, 80.0).view(dynamic(move || {
        let (sc, fin) = (sc.clone(), fin.clone());
        let r = Resource::new(|| (), move |(), cancel: &Cancel| {
            for _ in 0..30 {
                std::thread::sleep(std::time::Duration::from_millis(10));
                if cancel.is_cancelled() {
                    sc.store(true, Ordering::Relaxed);
                    break;
                }
            }
            fin.store(true, Ordering::Relaxed);
            Ok::<_, String>(1)
        });
        text(move || if r.loading() { "loading".into() } else { "done".into() })
    })));
    wait(50, move || {
        ferrokit::close_window(&w);
        wait(400, move || {
            let left = ferrokit::live_signals() as i64 - signals as i64;
            check(
                "resource-owner",
                saw_cancel.load(Ordering::Relaxed) && finished.load(Ordering::Relaxed) && left == 0,
                format!("closing the window cancelled the load: {}; signals left {left}", saw_cancel.load(Ordering::Relaxed)),
            );
            // Outside this continuation's batch, as the checks expect.
            let events = events.clone();
            later(move || async_checks(events.clone()));
        });
    });
}

/// Sets its flag when dropped (a task's future was dropped).
struct DropFlag(Rc<Cell<bool>>);

impl Drop for DropFlag {
    fn drop(&mut self) {
        self.0.set(true);
    }
}

/// Async tasks (`spawn_local`): polled on the main thread on a later pass,
/// each poll a batch, awaiting background work and a timer.
fn async_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{background, sleep, spawn_local};
    use std::time::{Duration, Instant};
    let main_thread = std::thread::current().id();
    let steps = Signal::new(Vec::<String>::new());
    let runs = Rc::new(Cell::new(0u32));
    let rs = runs.clone();
    let watcher = Effect::new(move || {
        let _ = steps.get();
        rs.set(rs.get() + 1);
    });
    let (ran, on_main, slept) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(true)), Rc::new(Cell::new(Duration::ZERO)));
    let (r, om, sl) = (ran.clone(), on_main.clone(), slept.clone());
    let task = spawn_local(async move {
        r.set(true);
        om.set(om.get() && std::thread::current().id() == main_thread);
        steps.set(vec!["start".into()]);
        let (worker, sum) = background(|| (std::thread::current().id(), (1..=1000u64).sum::<u64>())).await;
        om.set(om.get() && std::thread::current().id() == main_thread);
        let t = Instant::now();
        sleep(Duration::from_millis(80)).await;
        sl.set(t.elapsed());
        let mut v = steps.get_untracked();
        v.push(format!("sum {sum}"));
        v.push(if worker != main_thread { "worker off main" } else { "worker ON MAIN" }.into());
        steps.set(v);
    });
    let polled_inline = ran.get();
    until(move || task.is_finished(), 3000, move || {
        let _ = &watcher;
        let got = steps.get_untracked();
        check(
            "async-task",
            !polled_inline && task.is_finished() && on_main.get() && got == ["start", "sum 500500", "worker off main"] && slept.get() >= Duration::from_millis(75) && runs.get() == 3,
            format!("first poll inside spawn_local: {polled_inline}; finished {}; polls on main {}; steps {got:?}; slept {:?}; watcher runs {} (3: one per set, each poll a batch)", task.is_finished(), on_main.get(), slept.get(), runs.get()),
        );
        async_cancel_checks(events);
    });
}

/// Cancelling a task: by its handle (the future dropped at once), and from
/// inside its own poll (dropped when the poll returns).
fn async_cancel_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Task, sleep, spawn_local};
    use std::time::Duration;
    let (dropped, reached) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
    let (d, r) = (dropped.clone(), reached.clone());
    let task = spawn_local(async move {
        let _flag = DropFlag(d);
        sleep(Duration::from_secs(10)).await;
        r.set(true);
    });
    wait(100, move || {
        let before = (dropped.get(), task.is_finished());
        task.cancel();
        let after = (dropped.get(), task.is_finished());
        let me: Rc<Cell<Option<Task>>> = Rc::new(Cell::new(None));
        let (self_dropped, self_reached) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
        let (m, sd, sr) = (me.clone(), self_dropped.clone(), self_reached.clone());
        let own = spawn_local(async move {
            let _flag = DropFlag(sd);
            sleep(Duration::from_millis(20)).await;
            if let Some(t) = m.get() {
                t.cancel();
            }
            sleep(Duration::from_millis(20)).await;
            sr.set(true);
        });
        me.set(Some(own));
        wait(250, move || {
            check(
                "async-task-cancel",
                before == (false, false) && after == (true, true) && !reached.get() && self_dropped.get() && !self_reached.get() && own.is_finished(),
                format!("(dropped, finished) before cancel {before:?}, after {after:?}; ran past its await {}; cancelled itself: dropped {}, ran on {}", reached.get(), self_dropped.get(), self_reached.get()),
            );
            async_owner_check(events);
        });
    });
}

/// A task started in a window's view tree stops when the window closes; a
/// detached one goes on; the window's signals are all freed.
fn async_owner_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{sleep, spawn_local};
    use std::time::Duration;
    let (owned_dropped, owned_reached, detached_done) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
    let (od, or, dd) = (owned_dropped.clone(), owned_reached.clone(), detached_done.clone());
    let signals = ferrokit::live_signals();
    let w = open(Window::new("Async Owner").size(200.0, 80.0).view(dynamic(move || {
        let shown = Signal::new(0);
        let (od, or, dd) = (od.clone(), or.clone(), dd.clone());
        spawn_local(async move {
            let _flag = DropFlag(od);
            sleep(Duration::from_secs(5)).await;
            shown.set(1);
            or.set(true);
        });
        spawn_local(async move {
            sleep(Duration::from_millis(150)).await;
            dd.set(true);
        })
        .detach();
        text(move || format!("{}", shown.get()))
    })));
    wait(50, move || {
        ferrokit::close_window(&w);
        wait(400, move || {
            let left = ferrokit::live_signals() as i64 - signals as i64;
            check(
                "async-task-owner",
                owned_dropped.get() && !owned_reached.get() && detached_done.get() && left == 0,
                format!("closing the window dropped its task: {} (ran on: {}); the detached one finished: {}; signals left {left}", owned_dropped.get(), owned_reached.get(), detached_done.get()),
            );
            async_panic_check(events);
        });
    });
}

/// A panic in a task, or in background work it awaits, is reported and
/// ends only that task.
fn async_panic_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::failures;
    use ferrokit::{background, sleep, spawn_local};
    use std::time::Duration;
    let before = failures().len();
    let t1 = spawn_local(async {
        sleep(Duration::from_millis(20)).await;
        panic!("deliberate async panic");
    });
    let (dropped, reached, other) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
    let (d, r, o) = (dropped.clone(), reached.clone(), other.clone());
    let t2 = spawn_local(async move {
        let _flag = DropFlag(d);
        let _: u32 = background(|| panic!("deliberate background panic")).await;
        r.set(true);
    });
    let t3 = spawn_local(async move {
        sleep(Duration::from_millis(60)).await;
        o.set(true);
    });
    until(move || t1.is_finished() && t2.is_finished() && t3.is_finished(), 3000, move || {
        let caught: Vec<(&str, String)> = failures().into_iter().skip(before).map(|f| (f.place, f.message)).collect();
        let in_task = caught.iter().any(|(p, m)| *p == "an async task" && m.contains("deliberate async panic"));
        let in_work = caught.iter().any(|(p, m)| *p == "a background task" && m.contains("deliberate background panic"));
        check(
            "async-task-panic",
            in_task && in_work && t1.is_finished() && t2.is_finished() && dropped.get() && !reached.get() && other.get(),
            format!("reported {caught:?}; the background panic ended its task: {} (ran on: {}); another task finished: {}", dropped.get(), reached.get(), other.get()),
        );
        async_tracking_check(events);
    });
}

/// Tasks go on in a nested run loop in event-tracking mode (as while a
/// menu is open): timers and wakes from other threads both arrive.
fn async_tracking_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{background, sleep, spawn_local};
    use objc2_foundation::{NSDate, NSRunLoop};
    use std::time::{Duration, Instant};
    let done = Rc::new(Cell::new(false));
    let d = done.clone();
    let task = spawn_local(async move {
        sleep(Duration::from_millis(30)).await;
        let n = background(|| 2 + 2).await;
        sleep(Duration::from_millis(30)).await;
        d.set(n == 4);
    });
    later(move || {
        if !done.get() && !task.is_finished() {
            let start = Instant::now();
            let mode = NSString::from_str("NSEventTrackingRunLoopMode");
            while !task.is_finished() && start.elapsed() < Duration::from_secs(2) {
                NSRunLoop::currentRunLoop().runMode_beforeDate(&mode, &NSDate::dateWithTimeIntervalSinceNow(0.02));
            }
            check(
                "async-task-tracking",
                done.get() && task.is_finished(),
                format!("the task finished inside an event-tracking run loop: {} after {:?}", done.get(), start.elapsed()),
            );
        } else {
            check("async-task-tracking", false, "the task finished before the nested run loop started".to_string());
        }
        async_nested_wake_check(events.clone());
    });
}

/// A task woken while its own poll is running a nested run loop (a modal
/// AppKit call inside it): the wake isn't lost, and the task resumes once
/// that poll returns.
fn async_nested_wake_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{sleep, spawn_local};
    use objc2_foundation::{NSDate, NSRunLoop};
    use std::future::Future;
    use std::task::Poll;
    use std::time::{Duration, Instant};
    let (woken_inside, done) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
    let (wi, d) = (woken_inside.clone(), done.clone());
    let task = spawn_local(async move {
        // Start a timer (its waker is this task's), then wait for it in a
        // nested run loop inside this same poll.
        let mut timer = Box::pin(sleep(Duration::from_millis(20)));
        std::future::poll_fn(|cx| {
            let _ = timer.as_mut().poll(cx);
            let start = Instant::now();
            let mode = NSString::from_str("NSEventTrackingRunLoopMode");
            while start.elapsed() < Duration::from_millis(200) {
                NSRunLoop::currentRunLoop().runMode_beforeDate(&mode, &NSDate::dateWithTimeIntervalSinceNow(0.02));
            }
            wi.set(timer.as_mut().poll(cx).is_ready());
            Poll::Ready(())
        })
        .await;
        // Pending once, with no wake of its own: only the wake that came
        // during the nested loop gets the task polled again.
        let mut first = true;
        std::future::poll_fn(move |_| {
            if std::mem::take(&mut first) { Poll::Pending } else { Poll::Ready(()) }
        })
        .await;
        d.set(true);
    });
    until(move || task.is_finished(), 2000, move || {
        check(
            "async-task-nested-wake",
            woken_inside.get() && done.get(),
            format!("the timer fired inside the poll's nested run loop: {}; the task resumed afterwards: {}", woken_inside.get(), done.get()),
        );
        let events = events.clone();
        later(move || command_checks(events.clone()));
    });
}

#[derive(Clone)]
struct MenuState {
    items: Signal<i64>,
    sidebar: Signal<bool>,
    sort: Signal<u8>,
    refreshed: Signal<u32>,
    renamed: Signal<String>,
}

thread_local! {
    static MENU: MenuState = MenuState {
        items: Signal::new(0),
        sidebar: Signal::new(true),
        sort: Signal::new(0),
        refreshed: Signal::new(0),
        renamed: Signal::new("A".into()),
    };
}

fn file_menu() -> Vec<MenuItem> {
    let m = MENU.with(Clone::clone);
    let (add, remove) = (m.items, m.items);
    let has = m.items;
    vec![
        menu_item("New Item", move || add.update(|n| *n += 1)).key("n"),
        menu_item("Remove Item", move || remove.update(|n| *n -= 1)).key_with("n", &[Modifier::Option]).disabled(move || has.get() <= 0),
    ]
}

fn view_menu() -> Vec<MenuItem> {
    let m = MENU.with(Clone::clone);
    let (s1, s2) = (m.sidebar, m.sidebar);
    let sort_item = |title: &str, v: u8| {
        let (a, b) = (m.sort, m.sort);
        menu_item(title, move || a.set(v)).checked(move || b.get() == v)
    };
    let r = m.refreshed;
    let rn = m.renamed;
    vec![
        menu_item("Show Sidebar", move || s1.update(|s| *s = !*s)).key_with("s", &[Modifier::Control]).checked(move || s2.get()),
        submenu("Sort By", vec![sort_item("Name", 0), sort_item("Date", 1)]),
        menu_separator(),
        menu_item("Refresh", move || r.update(|n| *n += 1)).key("R"),
        menu_item("Rename", move || set_undoable("Rename", &rn, format!("{}+", rn.get_untracked()))).key_with("e", &[Modifier::Control]),
        menu_separator(),
        ferrokit::menu_command("Rename Item", RENAME_ITEM).key_with("r", &[Modifier::Control]),
    ]
}

const RENAME_ITEM: ferrokit::Command = ferrokit::Command::new("rename-item");
const REFRESH_LIST: ferrokit::Command = ferrokit::Command::new("refresh-list");
const SHOW_HELP: ferrokit::Command = ferrokit::Command::new("show-help");
const SHELL_ADD: ferrokit::Command = ferrokit::Command::new("shell-add");

thread_local! {
    static HELP_SHOWN: Cell<u32> = const { Cell::new(0) };
    static SHELL_ADDS: Cell<u32> = const { Cell::new(0) };
}

/// Commands resolve from the focus outwards: the focused subtree's handler,
/// a disabled handler answering (and blocking outer ones), the window's,
/// then the app's; focused values the same way; a menu command validates
/// against the focus; handlers go with their subtree.
fn command_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{can_perform_in, focused_value_in, perform_in};
    use objc2_app_kit::NSResponder;
    let (left_hits, right_hits, refreshes) = (Signal::new(0u32), Signal::new(0u32), Signal::new(0u32));
    let (name_l, name_r) = (Signal::new(String::from("left")), Signal::new(String::from("right")));
    let show_detail = Signal::new(true);
    let w = open(
        Window::new("Commands")
            .size(360.0, 120.0)
            .on_command(REFRESH_LIST, move || refreshes.update(|n| *n += 1))
            .view(hstack((
                text_field(&name_l).accessibility_label("Left").on_command(RENAME_ITEM, move || left_hits.update(|n| *n += 1)).focused_value("side", "left"),
                dynamic(move || {
                    if show_detail.get() {
                        ferrokit::AnyView::new(
                            text_field(&name_r)
                                .accessibility_label("Right")
                                .on_command_when(RENAME_ITEM, || false, move || right_hits.update(|n| *n += 1))
                                .focused_value("side", "right"),
                        )
                    } else {
                        ferrokit::AnyView::new(text("no detail"))
                    }
                }),
            ))),
    );
    let fields = || -> Vec<Retained<NSTextField>> { w.contentView().unwrap().subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok()).collect() };
    let focus = |v: Option<&NSResponder>| w.makeFirstResponder(v);
    let fs = fields();
    let (left, right) = (fs[0].clone(), fs[1].clone());

    focus(Some(&left));
    let l = (can_perform_in(Some(&w), RENAME_ITEM), perform_in(Some(&w), RENAME_ITEM), focused_value_in::<&str>(&w, "side"));
    focus(Some(&right));
    let r = (can_perform_in(Some(&w), RENAME_ITEM), perform_in(Some(&w), RENAME_ITEM), focused_value_in::<&str>(&w, "side"));
    let refreshed = perform_in(Some(&w), REFRESH_LIST);
    focus(None);
    let none = (can_perform_in(Some(&w), RENAME_ITEM), perform_in(Some(&w), REFRESH_LIST), focused_value_in::<&str>(&w, "side"));
    let help = (perform_in(Some(&w), SHOW_HELP), perform_in(None, SHOW_HELP), HELP_SHOWN.get());
    check(
        "commands-resolve",
        l == (true, true, Some("left"))
            && r == (false, false, Some("right"))
            && refreshed
            && none == (false, true, None)
            && help == (true, true, 2)
            && (left_hits.get_untracked(), right_hits.get_untracked(), refreshes.get_untracked()) == (1, 0, 2),
        format!(
            "left focused (can, ran, value) {l:?}; right (disabled handler) {r:?}; window handler from right: {refreshed}; nothing focused {none:?}; app handler (in window, no window, count) {help:?}; hits left/right/refresh {}/{}/{}",
            left_hits.get_untracked(),
            right_hits.get_untracked(),
            refreshes.get_untracked()
        ),
    );

    // The menu item validates against the focused window's focus.
    let item = || {
        let main = NSApplication::sharedApplication(MainThreadMarker::new().unwrap()).mainMenu().unwrap();
        let view = main.itemWithTitle(&NSString::from_str("View")).unwrap().submenu().unwrap();
        view.update();
        view.itemWithTitle(&NSString::from_str("Rename Item")).unwrap().isEnabled()
    };
    let target = ferrokit::focused_window();
    let is_ours = target.as_ref().is_some_and(|t| std::ptr::eq(&**t, &*w));
    focus(Some(&left));
    let on_left = item();
    focus(Some(&right));
    let on_right = item();
    check(
        "commands-menu",
        !is_ours || (on_left && !on_right),
        format!("{}menu item enabled with the left field focused {on_left}, the right {on_right}", if is_ours { "" } else { "skipped: another window has focus; " }),
    );

    // A removed subtree's handler goes with it.
    focus(Some(&right));
    batch(|| show_detail.set(false));
    let after = (can_perform_in(Some(&w), RENAME_ITEM), focused_value_in::<&str>(&w, "side"));
    focus(Some(&left));
    let left_again = can_perform_in(Some(&w), RENAME_ITEM);
    ferrokit::close_window(&w);
    check("commands-teardown", !after.0 && after.1.is_none() && left_again, format!("after removing the focused field: (can, value) {after:?}; left still handles it {left_again}"));
    later(move || styled_text_checks(events.clone()));
}

/// Styled text: syntax highlighting applied before an edit is drawn, kept
/// out of undo, restyled when a signal the highlighter reads changes, and
/// byte ranges mapped across multi-byte characters.
fn styled_text_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Syntax, Color, TextModel, TextStyle};
    let keyword = TextStyle::new().color(Color::Pink).bold();
    let model = TextModel::new(ViewId(70), "let x = 42; // hi");
    let term = Signal::new(String::new());
    let rust = Syntax::rust();
    let w = open(
        Window::new("Styled").size(360.0, 140.0).view(
            text_editor(&model)
                .highlight(move |text| {
                    let mut runs = rust.highlight(text);
                    let t = term.get();
                    if !t.is_empty() {
                        runs.extend(text.match_indices(t.as_str()).map(|(at, m)| (at..at + m.len(), TextStyle::new().background(Color::Yellow))));
                    }
                    runs
                })
                .accessibility_label("Code"),
        ),
    );
    let s = |at| model.style_at(at);
    check(
        "styled-highlight",
        s(0) == keyword && s(4) == TextStyle::new() && s(8) == TextStyle::new().color(Color::Blue) && s(12) == TextStyle::new().color(Color::Gray).italic(),
        format!("let {:?}; x {:?}; 42 {:?}; comment {:?}", s(0), s(4), s(8), s(12)),
    );

    // Typing: styled before anything is drawn (no run-loop pass between).
    let tv = model.text_view();
    let um = tv.undoManager().unwrap();
    um.setGroupsByEvent(false);
    um.beginUndoGrouping();
    unsafe { objc2::msg_send![&*tv, insertText: &*NSString::from_str("fn "), replacementRange: objc2_foundation::NSRange::new(0, 0)] }
    um.endUndoGrouping();
    let typed = (s(0) == keyword, s(3) == keyword, s(1) == keyword);
    um.undo();
    let undone = model.text() == "let x = 42; // hi" && s(0) == keyword && s(12) == TextStyle::new().color(Color::Gray).italic() && !um.canUndo();
    check(
        "styled-typing-undo",
        typed == (true, true, true) && undone,
        format!("typed \"fn \": fn and let styled at once {typed:?}; one undo restores the text with its styles and leaves nothing to undo: {undone}"),
    );

    // A signal the highlighter reads restyles it.
    term.set("x".into());
    let marked = s(4).background == Some(Color::Yellow);
    term.set(String::new());
    let cleared = s(4).background.is_none();
    check("styled-reactive", marked && cleared, format!("search term marks x: {marked}; clearing it unmarks: {cleared}"));

    // Fonts: the base font changes, the bold stays.
    model.set_font(Some("Menlo"), 12.0);
    let font = model.text_view().font().map(|f| f.familyName().map(|n| n.to_string()).unwrap_or_default()).unwrap_or_default();
    check("styled-font", s(0) == keyword && font == "Menlo", format!("after set_font(Menlo): let {:?}; font {font:?}", s(0)));

    // Multi-byte text before a keyword: byte ranges map to UTF-16 correctly.
    model.set_text("\"é😀\" let");
    let at = model.text().find("let").unwrap();
    check(
        "styled-unicode",
        s(at) == keyword && s(at + 2) == keyword && s(1) == TextStyle::new().color(Color::Red),
        format!("set_text restyles; let at byte {at} {:?}; the string {:?}", s(at), s(1)),
    );
    // Cost: the whole text is restyled on each edit.
    let big: String = (0..5_000).map(|i| format!("let value_{i}: u64 = {i} * 2; // line {i}\n")).collect();
    model.set_text(&big);
    let um = model.text_view().undoManager().unwrap();
    let start = std::time::Instant::now();
    um.beginUndoGrouping();
    unsafe { objc2::msg_send![&*model.text_view(), insertText: &*NSString::from_str("x"), replacementRange: objc2_foundation::NSRange::new(0, 0)] }
    um.endUndoGrouping();
    let ms = start.elapsed().as_secs_f64() * 1e3;
    // Informational on CI runners (shared virtual machines).
    check("styled-large", ms < 100.0 || std::env::var_os("CI").is_some(), format!("a keystroke in {} KB of Rust (5,000 lines, ~35,000 runs) restyles in {ms:.1} ms", big.len() / 1024));
    // An edit that changes styles far from it: opening a block comment at
    // the top turns the whole file into a comment, and removing it restores
    // every line.
    let tv = model.text_view();
    let last_let = |m: &TextModel| m.text().rfind("let").unwrap();
    // (Grouped by hand: this editor's undo groups aren't made per event.)
    um.beginUndoGrouping();
    unsafe { objc2::msg_send![&*tv, insertText: &*NSString::from_str("/*"), replacementRange: objc2_foundation::NSRange::new(0, 0)] }
    um.endUndoGrouping();
    let commented = s(last_let(&model)) == TextStyle::new().color(Color::Gray).italic();
    um.beginUndoGrouping();
    unsafe { objc2::msg_send![&*tv, insertText: &*NSString::from_str(""), replacementRange: objc2_foundation::NSRange::new(0, 2)] }
    um.endUndoGrouping();
    let restored = s(last_let(&model)) == keyword && s(model.text().len() - 3) == TextStyle::new().color(Color::Gray).italic();
    check("styled-far-edit", commented && restored, format!("/* at the top comments out the last line: {commented}; removing it restores keywords and comments there: {restored}"));
    // Typing in the middle of a line keeps the caret there: the rest of the
    // restyle waits until the edit is done (it used to widen the edit, and
    // the text view put the caret at the end of the restyled span).
    model.set_text("let a = 1; let b = 2;");
    tv.setSelectedRange(objc2_foundation::NSRange::new(4, 0));
    for c in ["x", "y"] {
        um.beginUndoGrouping();
        unsafe { objc2::msg_send![&*tv, insertText: &*NSString::from_str(c), replacementRange: tv.selectedRange()] }
        um.endUndoGrouping();
    }
    let caret = tv.selectedRange();
    let second_let = model.text().rfind("let").unwrap();
    check(
        "styled-caret-mid-line",
        model.text() == "let xya = 1; let b = 2;" && caret.location == 6 && caret.length == 0 && s(second_let) == keyword && s(4) != keyword,
        format!("{:?}, caret at {}; the second let styled {}", model.text(), caret.location, s(second_let) == keyword),
    );
    // Typing over a selection of everything, as key presses, drawing after
    // each. Restyling used to set typing attributes mid-edit, which read the
    // old selection past the end of the new text: the exception stopped the
    // edit halfway, TextKit 2's layout fell behind the text, and the next
    // draw aborted the app.
    let all = tv.string().length();
    tv.window().map(|w| w.makeFirstResponder(Some(&tv)));
    tv.setSelectedRange(objc2_foundation::NSRange::new(0, all));
    // (Key presses group their own undo, as in an app.)
    um.setGroupsByEvent(true);
    let drawn = objc2::exception::catch(std::panic::AssertUnwindSafe(|| {
        for c in ["f", "n", " ", "x"] {
            let chars = NSString::from_str(c);
            let event = objc2_app_kit::NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
                objc2_app_kit::NSEventType::KeyDown,
                objc2_foundation::NSPoint::ZERO,
                NSEventModifierFlags::empty(),
                0.0,
                tv.window().map_or(0, |w| w.windowNumber()),
                None,
                &chars,
                &chars,
                false,
                0,
            );
            if let Some(event) = event {
                tv.keyDown(&event);
            }
            if let Some(window) = tv.window() {
                window.displayIfNeeded();
            }
        }
    }));
    if let Err(Some(e)) = &drawn {
        eprintln!("styled-replace-draw exception: {e:?}");
    }
    let laid_out = objc2::exception::catch(std::panic::AssertUnwindSafe(|| laid_out_length(&tv))).ok().flatten();
    check(
        "styled-replace-draw",
        drawn.is_ok() && laid_out == Some(4) && s(0) == keyword,
        format!("typed \"fn x\" over {all} selected characters, drawing after each key: drawn without an exception {}; layout covers {laid_out:?} characters (4); fn styled {}", drawn.is_ok(), s(0) == keyword),
    );
    ferrokit::close_window(&w);
    later(move || popover_teardown_check(events.clone()));
}

/// A popover whose view goes away while it's open closes, and its
/// content (views, signals) is freed with it.
fn popover_teardown_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    let (show_anchor, open_pop) = (Signal::new(true), Signal::new(false));
    let w = open(Window::new("Popover").size(300.0, 120.0).view(dynamic(move || {
        if show_anchor.get() {
            ferrokit::AnyView::new(button("Details", || {}).popover(&open_pop, || {
                let n = Signal::new(0u32);
                vstack((text("Inside"), button("More", move || n.update(|x| *x += 1))))
            }))
        } else {
            ferrokit::AnyView::new(text("gone"))
        }
    })));
    let popovers = || {
        NSApplication::sharedApplication(MainThreadMarker::new().unwrap())
            .windows()
            .iter()
            .filter(|w| w.isVisible() && w.class().name().to_string_lossy().contains("Popover"))
            .count()
    };
    let before = ferrokit::live_signals();
    open_pop.set(true);
    until(move || popovers() > 0, 3000, move || {
        let shown = popovers();
        let inside = ferrokit::live_signals() > before;
        show_anchor.set(false);
        // It closes with an animation, slower on a busy machine (CI runners).
        until(move || popovers() == 0, 3000, move || {
            let closed = popovers() == 0;
            let freed = ferrokit::live_signals() <= before;
            check(
                "popover-teardown",
                shown == 1 && inside && closed && freed && !open_pop.get(),
                format!("shown {shown} (its content's signal alive {inside}); anchor removed → closed {closed}, content freed {freed}, signal {}", open_pop.get()),
            );
            ferrokit::close_window(&w);
            later(move || canvas_checks(events.clone()));
        });
    });
}

/// The canvas: redrawn when a signal it reads changes and when it resizes,
/// drawn pixels, clicks in its own coordinates, and VoiceOver's view of it.
fn canvas_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::canvas_drawing;
    use ferrokit::{Align, Color, canvas};
    use objc2_app_kit::NSAccessibility;
    let level = Signal::new(0.5);
    let clicks = Rc::new(RefCell::new(Vec::new()));
    let c = clicks.clone();
    let doubles = Rc::new(RefCell::new(Vec::new()));
    let d = doubles.clone();
    let drags = Rc::new(RefCell::new(Vec::new()));
    let dr = drags.clone();
    let w = open(Window::new("Canvas").size(300.0, 200.0).view(
        canvas(move |p| {
            p.fill_rect(0.0, 0.0, p.width() * level.get(), p.height(), Color::Rgb(1.0, 0.0, 0.0));
            p.text(4.0, 4.0, &format!("{:.0}%", level.get() * 100.0), 12.0, Color::Primary, Align::Start);
        })
        .on_click(move |x, y| c.borrow_mut().push((x.round(), y.round())))
        .on_double_click(move |x, y| d.borrow_mut().push((x.round(), y.round())))
        .on_drag(move |e| dr.borrow_mut().push(e))
        .description(move || format!("Level {:.0}%", level.get() * 100.0)),
    ));
    let view = || {
        let mut all = Vec::new();
        fn walk(v: &NSView, out: &mut Vec<Retained<NSView>>) {
            for s in v.subviews().iter() {
                out.push(s.clone());
                walk(&s, out);
            }
        }
        walk(&w.contentView().unwrap(), &mut all);
        all.into_iter().find(|v| canvas_drawing(v).is_some()).unwrap()
    };
    let v = view();
    let first = canvas_drawing(&v).unwrap();
    level.set(0.25);
    let second = canvas_drawing(&v).unwrap();
    check(
        "canvas-reactive",
        first == ["fill rect 0,0 150x200 Rgb(1.0, 0.0, 0.0)", "text \"50%\" 12pt"] && second[0] == "fill rect 0,0 75x200 Rgb(1.0, 0.0, 0.0)",
        format!("{first:?} → after the signal changes {second:?}"),
    );
    // Resizing the window redraws at the new size.
    w.setContentSize(objc2_foundation::NSSize::new(400.0, 200.0));
    let resized = canvas_drawing(&v).unwrap();
    check("canvas-resize", resized[0] == "fill rect 0,0 100x200 Rgb(1.0, 0.0, 0.0)", format!("at 400 points wide: {:?}", resized[0]));
    // A drag inside the canvas: began where it started, moves, ended.
    let dragged = ferrokit::testing::canvas_move(&v, (10.0, 10.0), (60.0, 40.0));
    use ferrokit::CanvasDrag::{Began, Ended, Moved};
    let got = drags.borrow().clone();
    check("canvas-drag", dragged && got == [Began(10.0, 10.0), Moved(35.0, 25.0), Moved(60.0, 40.0), Ended(60.0, 40.0)], format!("{got:?}"));
    // What AppKit draws: red at the left, not at the right.
    let rep = v.bitmapImageRepForCachingDisplayInRect(v.bounds()).unwrap();
    v.cacheDisplayInRect_toBitmapImageRep(v.bounds(), &rep);
    let scale = rep.pixelsWide() as f64 / v.bounds().size.width;
    // (Pure sRGB red reads about (0.92, 0.2, 0.15) in the bitmap's space.)
    let px = |x: f64, y: f64| rep.colorAtX_y((x * scale) as isize, (y * scale) as isize).map(|c| (c.redComponent(), c.greenComponent(), c.alphaComponent()));
    let (left, right) = (px(50.0, 100.0), px(300.0, 100.0));
    check(
        "canvas-pixels",
        left.is_some_and(|(r, g, a)| r > 0.85 && g < 0.3 && a > 0.99) && right.is_some_and(|(_, _, a)| a < 0.01),
        format!("(r, g, alpha) at x=50: {left:?}; at x=300 (nothing drawn): {right:?}"),
    );
    // A click arrives in the canvas's coordinates (top-left origin).
    let at = v.convertPoint_toView(objc2_foundation::NSPoint::new(30.0, 20.0), None);
    let down = objc2_app_kit::NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
        objc2_app_kit::NSEventType::LeftMouseDown,
        at,
        NSEventModifierFlags::empty(),
        0.0,
        w.windowNumber(),
        None,
        0,
        1,
        1.0,
    )
    .unwrap();
    let _: () = unsafe { objc2::msg_send![&*v, mouseDown: &*down] };
    let single_only = doubles.borrow().is_empty();
    // The second click of a double click: a click, then the double click.
    let second = objc2_app_kit::NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
        objc2_app_kit::NSEventType::LeftMouseDown,
        at,
        NSEventModifierFlags::empty(),
        0.0,
        w.windowNumber(),
        None,
        0,
        2,
        1.0,
    )
    .unwrap();
    let _: () = unsafe { objc2::msg_send![&*v, mouseDown: &*second] };
    check(
        "canvas-double-click",
        single_only && *clicks.borrow() == [(30.0, 20.0), (30.0, 20.0)] && *doubles.borrow() == [(30.0, 20.0)],
        format!("first click: no double {single_only}; clicks {:?}; double clicks {:?}", clicks.borrow(), doubles.borrow()),
    );
    clicks.borrow_mut().truncate(1);
    let label = v.accessibilityLabel().map(|l| l.to_string());
    let role = v.accessibilityRole().map(|r| r.to_string());
    check(
        "canvas-click-ax",
        *clicks.borrow() == [(30.0, 20.0)] && label.as_deref() == Some("Level 25%") && role.as_deref() == Some("AXImage"),
        format!("click → {:?}; VoiceOver: {role:?} {label:?}", clicks.borrow()),
    );
    ferrokit::close_window(&w);
    // A pie with an empty slice in the middle: the others keep their colours
    // and their indices (an empty slice used to shift both).
    let pick = Signal::new(Some(2usize));
    let pw = open(Window::new("Pie").size(320.0, 200.0).view(
        ferrokit::pie_chart(|| vec![("A".to_string(), 1.0), ("B".to_string(), 0.0), ("C".to_string(), 2.0)]).colors(&[Color::Red, Color::Green, Color::Blue]).selection(&pick),
    ));
    let mut found = Vec::new();
    fn walk(v: &NSView, out: &mut Vec<Retained<NSView>>) {
        for s in v.subviews().iter() {
            out.push(s.clone());
            walk(&s, out);
        }
    }
    walk(&pw.contentView().unwrap(), &mut found);
    let pie = found.into_iter().find(|v| canvas_drawing(v).is_some()).unwrap();
    let ops = canvas_drawing(&pie).unwrap();
    let fills: Vec<&String> = ops.iter().filter(|o| o.starts_with("fill path")).collect();
    let said = pie.accessibilityLabel().map(|l| l.to_string()).unwrap_or_default();
    check(
        "chart-pie-empty-slice",
        fills.len() == 2 && fills[0].ends_with("Red") && fills[1].ends_with("Blue") && said.contains("selected C"),
        format!("slices {fills:?}; VoiceOver {said:?}"),
    );
    ferrokit::close_window(&pw);
    later(move || clipboard_drop_checks(events.clone()));
}

/// The clipboard (a private pasteboard: the real one is never touched),
/// drag items, and files dropped on a window.
fn clipboard_drop_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::{canvas_drag, canvas_drawing, drop_on_view};
    use ferrokit::{Clipboard, DragItem, Color, canvas};
    let dir = std::env::temp_dir().join(format!("ferrokit-transfer-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let clip = Clipboard::private();
    clip.set_text("héllo, 世界");
    let back = clip.text();
    let png: Vec<u8> = b"\x89PNG\r\n\x1a\nnot really".to_vec();
    clip.set_png(&png);
    let png_back = clip.png();
    let (a, b) = (dir.join("a.txt"), dir.join("b.csv"));
    std::fs::write(&a, "a").unwrap();
    std::fs::write(&b, "b").unwrap();
    clip.set_files(&[a.clone(), b.clone()]);
    let files: Vec<_> = clip.files().iter().map(|p| p.canonicalize().unwrap()).collect();
    clip.set(&DragItem::promise("made.txt", |path| std::fs::write(path, "made on demand")));
    let promised = clip.files().first().and_then(|p| std::fs::read_to_string(p).ok());
    check(
        "clipboard-roundtrip",
        back.as_deref() == Some("héllo, 世界") && png_back.as_deref() == Some(&png[..]) && files == [a.canonicalize().unwrap(), b.canonicalize().unwrap()] && promised.as_deref() == Some("made on demand"),
        format!("text {back:?}; png back: {}; files {}; a promised file written and put on: {promised:?}", png_back.is_some(), files.len()),
    );

    // Files dropped on a window: only the extensions it takes; any file
    // when it names none.
    let got: Rc<RefCell<Vec<String>>> = Rc::default();
    let g = got.clone();
    let w = open(
        Window::new("Drops")
            .size(300.0, 160.0)
            .on_drop_files(&["CSV"], move |paths| g.borrow_mut().extend(paths.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned())))
            .view(
                canvas(|p| p.fill_rect(0.0, 0.0, p.width(), p.height(), Color::Separator))
                    .draggable(|| Some(DragItem::Text("dragged text".into())))
                    .min_size(100.0, 40.0),
            ),
    );
    let any = open(Window::new("Any drop").size(200.0, 100.0).on_drop_files(&[], |_| {}).view(text("any")));
    let content = w.contentView().unwrap();
    let drop_files = |view: &NSView, paths: &[std::path::PathBuf]| {
        let c = Clipboard::private();
        c.set_files(paths);
        drop_on_view(view, c.pasteboard())
    };
    let txt_refused = !drop_files(&content, std::slice::from_ref(&a));
    let csv_taken = drop_files(&content, &[a.clone(), b.clone()]);
    let any_taken = drop_files(&any.contentView().unwrap(), std::slice::from_ref(&a));
    let mut views = Vec::new();
    fn walk(v: &NSView, out: &mut Vec<Retained<NSView>>) {
        for s in v.subviews().iter() {
            out.push(s.clone());
            walk(&s, out);
        }
    }
    walk(&content, &mut views);
    let dragged = views.iter().find(|v| canvas_drawing(v).is_some()).and_then(|v| canvas_drag(v));
    let dragged_text = match dragged {
        Some(DragItem::Text(t)) => Some(t),
        _ => None,
    };
    let dir2 = dir.clone();
    wait(100, move || {
        let got = got.borrow().clone();
        check(
            "window-drop-files",
            txt_refused && csv_taken && got == ["b.csv"] && any_taken && dragged_text.as_deref() == Some("dragged text"),
            format!("a .txt refused {txt_refused}; a .txt and a .csv: taken {csv_taken}, the action got {got:?} (extensions match in any case); a window taking any file: {any_taken}; a canvas drags {dragged_text:?}"),
        );
        ferrokit::close_window(&w);
        ferrokit::close_window(&any);
        let _ = std::fs::remove_dir_all(&dir2);
        later(move || l10n_checks(events.clone()));
    });
}

/// Localisation: the app's tables over the framework's, untranslated keys,
/// placeholders, plural rules, numbers by region.
fn l10n_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{format_number_for, language, set_language, t, t_plural, t_with};
    let system = language();
    set_language(Some("de"));
    let de = (t("Rename Item"), t("Save"), t("Open…"), t("Not in any table"), t_with("Quit {name}", &[("name", &"Checklist")]));
    let de_plural = (t_plural(1, "{n} file", "{n} files"), t_plural(1_000, "{n} file", "{n} files"));
    set_language(Some("fr"));
    let fr = (t("Rename Item"), t("Save"), t_with("The document “{name}” couldn't be saved.", &[("name", &"a.txt")]));
    set_language(Some("ru"));
    let ru: Vec<String> = [1, 2, 5, 21, 112].iter().map(|&n| t_plural(n, "{n} file", "{n} files")).collect();
    set_language(None);
    let back = (language(), t("Save"));
    check(
        "l10n-lookup",
        de == ("Objekt umbenennen".into(), "Speichern (App)".into(), "Öffnen …".into(), "Not in any table".into(), "Checklist beenden".into())
            && fr == ("Rename Item".into(), "Enregistrer".into(), "Le document « a.txt » n’a pas pu être enregistré.".into())
            && back.0 == system,
        format!("de {de:?}; fr (no app table: framework strings only) {fr:?}; back to {back:?}"),
    );
    let numbers = (format_number_for(1_234_567.5, 1, "en_US"), format_number_for(1_234_567.5, 1, "de_DE"), format_number_for(1_234_567.5, 1, "fr_FR"));
    check(
        "l10n-plurals-numbers",
        de_plural.0 == "1 Datei"
            && de_plural.1.ends_with(" Dateien")
            && ru.iter().map(|s| s.split(' ').nth(1).unwrap_or_default()).collect::<Vec<_>>() == ["файл", "файла", "файлов", "файл", "файлов"]
            && numbers.0 == "1,234,567.5"
            && numbers.1 == "1.234.567,5"
            && numbers.2.replace(['\u{202f}', '\u{a0}'], " ") == "1 234 567,5",
        format!("de {de_plural:?}; ru {ru:?}; numbers en/de/fr {numbers:?}"),
    );
    later(move || view_checks(events.clone()));
}

fn settings_window() -> Window {
    let dark = stored("check.settings.dark", false);
    let name = stored("check.settings.name", "Untitled".to_string());
    Window::new("Settings").size(360.0, 140.0).view(vstack((toggle("Dark tables", &dark), text_field(&name))).padding(20.0))
}

fn menu_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSControlStateValueOn, NSWindowStyleMask};
    let m = MENU.with(Clone::clone);
    let file = bar_menu("File");
    let file_items = menu_items("File");
    let titles: Vec<&str> = file_items.iter().map(|e| e.0.as_str()).collect();
    check(
        "file-menu",
        // AppKit adds Close All (⌥) after Close itself.
        titles.starts_with(&["New Item", "Remove Item", "", "Close"]) && has(&file_items, "New Item", "n") && has(&file_items, "Close", "w"),
        format!("{titles:?}"),
    );

    // Custom items: actions, key equivalents, enabled state from signals.
    file.update();
    let remove = file.itemWithTitle(&NSString::from_str("Remove Item")).unwrap();
    let off = !remove.isEnabled();
    let cmd = NSEventModifierFlags::Command;
    // A disabled item's shortcut is taken (AppKit beeps) but doesn't run.
    menu_key("n", cmd | NSEventModifierFlags::Option);
    let blocked = m.items.get_untracked() == 0;
    let new_key = menu_key("n", cmd);
    file.update();
    let on = remove.isEnabled();
    let alt_key = menu_key("n", cmd | NSEventModifierFlags::Option);
    let after = m.items.get_untracked();
    let refresh = menu_key("R", cmd | NSEventModifierFlags::Shift);
    // testing::shortcut runs the app's own items too (it used to send
    // their action along the responder chain, where nothing answered).
    let before = m.items.get_untracked();
    let via_shortcut = windows().first().is_some_and(|w| ferrokit::testing::shortcut(w, "n", false)) && m.items.get_untracked() == before + 1;
    m.items.set(before);
    check("shortcut-runs-app-items", via_shortcut, format!("⌘N through testing::shortcut: {via_shortcut}"));
    check(
        "menu-key-equivalents",
        off && blocked && new_key && on && alt_key && after == 0 && refresh && m.refreshed.get_untracked() == 1,
        format!(
            "Remove disabled at 0: {off}; its ⌥⌘N ran nothing: {blocked}; ⌘N fired: {new_key}; Remove enabled at 1: {on}; ⌥⌘N fired: {alt_key} → {after}; ⇧⌘R: {refresh}"
        ),
    );

    // Checked state and submenus.
    let view = bar_menu("View");
    let sidebar = view.itemWithTitle(&NSString::from_str("Show Sidebar")).unwrap();
    view.update();
    let checked0 = sidebar.state() == NSControlStateValueOn;
    let toggled = menu_key("s", cmd | NSEventModifierFlags::Control);
    view.update();
    let checked1 = sidebar.state() == NSControlStateValueOn;
    let sort = view.itemWithTitle(&NSString::from_str("Sort By")).and_then(|i| i.submenu()).unwrap();
    let date = sort.indexOfItemWithTitle(&NSString::from_str("Date"));
    sort.performActionForItemAtIndex(date);
    sort.update();
    let marks: Vec<bool> = (0..sort.numberOfItems()).map(|i| sort.itemAtIndex(i).unwrap().state() == NSControlStateValueOn).collect();
    check(
        "menu-checked-submenu",
        checked0 && toggled && !checked1 && !m.sidebar.get_untracked() && m.sort.get_untracked() == 1 && marks == [false, true],
        format!("sidebar ✓ {checked0} → ⌃⌘S → {checked1}; Sort By › Date → sort {} marks {marks:?}", m.sort.get_untracked()),
    );

    // Settings: ⌘, in the app menu; built once, then brought to the front.
    let app_items = menu_items("Checklist");
    let item_ok = has(&app_items, "Settings…", ",");
    let before = NSApplication::sharedApplication(mtm()).windows().count();
    let fired = menu_key(",", cmd);
    let s1 = NSApplication::sharedApplication(mtm()).windows().iter().find(|w| w.title().to_string() == "Settings");
    let built = NSApplication::sharedApplication(mtm()).windows().count();
    if let Some(w) = &s1 {
        w.close();
    }
    let s2 = ferrokit::open_settings();
    let after = NSApplication::sharedApplication(mtm()).windows().count();
    let same = s1.as_ref().zip(s2.as_ref()).is_some_and(|(a, b)| std::ptr::eq(&**a, &**b));
    let fixed = s2.as_ref().is_some_and(|w| !w.styleMask().contains(NSWindowStyleMask::Resizable) && w.isExcludedFromWindowsMenu() && w.isVisible());
    let unlisted = !menu_items("Window").iter().any(|(t, _, _)| t == "Settings");
    check(
        "settings-window",
        item_ok && fired && built == before + 1 && after == built && same && fixed && unlisted,
        format!("Settings… ⌘, listed: {item_ok}; fired: {fired}; windows {before} → {built} → reopen {after}; same window: {same}; fixed, unlisted: {fixed} {unlisted}"),
    );

    // Stored settings: the toggle writes user defaults; a new signal reads them.
    let w = s2.unwrap();
    let toggle_v = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSSwitch>().ok());
    let defaults = objc2_foundation::NSUserDefaults::standardUserDefaults();
    let key = NSString::from_str("check.settings.dark");
    let unset = defaults.objectForKey(&key).is_none();
    if let Some(t) = &toggle_v {
        t.setState(NSControlStateValueOn);
        send_action(t);
    }
    let written = defaults.boolForKey(&key);
    let reread = stored("check.settings.dark", false).get_untracked();
    check("stored-settings", unset && toggle_v.is_some() && written && reread, format!("unset before: {unset}; toggle → defaults {written}; a new stored signal reads {reread}"));
    w.close();
    defaults.removeObjectForKey(&key);

    // Frame autosave: a window moved and resized; a new one with the same
    // name opens there.
    let frame_key = NSString::from_str("NSWindow Frame check restore");
    defaults.removeObjectForKey(&frame_key);
    let a = open(Window::new("Restore A").size(300.0, 200.0).remember_frame("check restore"));
    let target = objc2_foundation::NSRect::new(objc2_foundation::NSPoint::new(140.0, 160.0), objc2_foundation::NSSize::new(420.0, 260.0));
    a.setFrame_display(target, true);
    let saved = defaults.stringForKey(&frame_key).map(|s| s.to_string());
    ferrokit::close_window(&a);
    a.setFrameAutosaveName(&NSString::new());
    let b = open(Window::new("Restore B").size(300.0, 200.0).remember_frame("check restore"));
    let got = b.frame();
    ferrokit::close_window(&b);
    check(
        "frame-autosave",
        saved.is_some() && got == target,
        format!("saved {saved:?}; reopened at {:.0},{:.0} {:.0}×{:.0}", got.origin.x, got.origin.y, got.size.width, got.size.height),
    );
    defaults.removeObjectForKey(&frame_key);

    // Split position: a divider moved outside layout (as a drag) is saved; a
    // new split with the same name starts there.
    let split_key = NSString::from_str("ferrokit split check");
    defaults.removeObjectForKey(&split_key);
    let split_window = || Window::new("Split R").size(500.0, 200.0).view(split((text("a"), text("b"))).position(150.0).remember("check"));
    let c = open(split_window());
    let sv = all_views(&c.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSSplitView>().ok()).unwrap();
    let initial = sv.arrangedSubviews().firstObject().unwrap().frame().size.width;
    sv.setPosition_ofDividerAtIndex(230.0, 0);
    let stored_pos = defaults.doubleForKey(&split_key);
    ferrokit::close_window(&c);
    let d = open(split_window());
    let sv = all_views(&d.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSSplitView>().ok()).unwrap();
    let restored = sv.arrangedSubviews().firstObject().unwrap().frame().size.width;
    ferrokit::close_window(&d);
    check(
        "split-remember",
        initial == 150.0 && stored_pos == 230.0 && restored == 230.0,
        format!("first pane {initial} → dragged to 230 → saved {stored_pos} → new split {restored}"),
    );
    defaults.removeObjectForKey(&split_key);

    after_events(move || undo_checks(events.clone()));
}

#[derive(Clone)]
struct UndoState {
    name: Signal<String>,
    own: TextModel,
    shared: TextModel,
    window: Retained<objc2_app_kit::NSWindow>,
}

fn undo_title(w: &objc2_app_kit::NSWindow) -> (String, String) {
    let m = w.undoManager().unwrap();
    (m.undoMenuItemTitle().to_string(), m.redoMenuItemTitle().to_string())
}

/// Runs `f` after the run loop has gone idle once: that's when AppKit closes
/// the undo group of the current event (a `later` block can run in the same
/// loop iteration, inside the same group).
fn after_idle(f: impl Fn() + 'static) {
    spawn(|| std::thread::sleep(std::time::Duration::from_millis(30)), move |()| f());
}

/// Undo checks run one step per idle run loop, as user events would: AppKit
/// groups everything registered in one event into a single undo step.
fn undo_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let name = Signal::new("A".to_string());
    let own = TextModel::new(ViewId(950), "");
    let shared = TextModel::new(ViewId(951), "");
    let window = open(
        Window::new("Undo").size(420.0, 320.0).view(
            vstack((text_field(&name), text_editor(&own), text_editor(&shared).shared_undo())).padding(12.0),
        ),
    );
    let u = UndoState { name, own, shared, window };
    let w = &u.window;
    let m = w.undoManager();
    let editor_w = windows().into_iter().find(|w| w.title().to_string() == "Editor").unwrap();
    let distinct = m.as_ref().zip(editor_w.undoManager()).is_some_and(|(a, b)| !std::ptr::eq(&**a, &*b));
    let stable = m.as_ref().zip(w.undoManager()).is_some_and(|(a, b)| std::ptr::eq(&**a, &*b));
    let field = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSTextField>().ok()).unwrap();
    w.makeFirstResponder(Some(&field));
    // While a field is being edited its field editor has AppKit's private
    // NSCellUndoManager (field typing is undone there, then dropped when
    // editing ends); the field itself answers with the window's.
    let editor = field.currentEditor();
    let cell_undo = editor.as_ref().and_then(|e| e.undoManager()).map(|u| u.class().name().to_string_lossy().to_string());
    let field_undo = field.undoManager();
    let field_shares = m.as_ref().zip(field_undo.as_ref()).is_some_and(|(a, b)| std::ptr::eq(&**a, &**b)) && cell_undo.is_some();
    let own_apart = m.as_ref().is_some_and(|m| !std::ptr::eq(&**m, &*u.own.undo_manager()));
    let shared_in = m.as_ref().is_some_and(|m| std::ptr::eq(&**m, &*u.shared.undo_manager()));
    check(
        "undo-manager-per-window",
        distinct && stable && field_shares && own_apart && shared_in,
        format!("own manager per window: {distinct}, stable: {stable}; text field uses it: {field_shares} (while editing: {cell_undo:?}); default editor apart: {own_apart}; shared_undo editor in it: {shared_in}"),
    );
    w.makeFirstResponder(None);

    // An app-level change: ⌘Z / ⇧⌘Z with the action's name.
    set_undoable("Rename", &u.name, "B".to_string());
    after_idle(move || {
        let w = &u.window;
        let t0 = undo_title(w);
        let undone = shortcut(w, "z", false);
        let after_undo = (u.name.get_untracked(), undo_title(w));
        let redone = shortcut(w, "z", true);
        let after_redo = u.name.get_untracked();
        check(
            "undoable-signal",
            t0.0 == "Undo Rename" && undone && after_undo.0 == "A" && after_undo.1 .1 == "Redo Rename" && redone && after_redo == "B",
            format!("{t0:?}; ⌘Z → {:?} {:?}; ⇧⌘Z → {after_redo:?}", after_undo.0, after_undo.1),
        );
        // The default editor keeps its own history: typing there leaves the window's alone.
        u.own.replace_selection("x");
        let own_ok = u.own.can_undo() && undo_title(w).0 == "Undo Rename";
        check("editor-own-undo", own_ok, format!("editor can undo: {}; window's top: {:?}", u.own.can_undo(), undo_title(w).0));
        let u = u.clone();
        let events = events.clone();
        after_idle(move || undo_stack_checks(u.clone(), events.clone()));
    });
}

/// The shared stack, one explicit undo group per simulated event. (AppKit
/// closes its per-event group when the app handles an event; an unattended
/// run gets none, so its groups stay open across passes.)
fn undo_stack_checks(u: UndoState, events: Rc<RefCell<Vec<AppEvent>>>) {
    let w = &u.window;
    let m = w.undoManager().unwrap();
    m.removeAllActions();
    while m.groupingLevel() > 0 {
        m.endUndoGrouping();
    }
    m.setGroupsByEvent(false);
    let event = |f: &dyn Fn()| {
        m.beginUndoGrouping();
        f();
        m.endUndoGrouping();
    };
    batch(|| u.name.set("B".into()));
    // Typing (as the keyboard does: insertText, named "Typing"), an
    // app-level change, more typing: three steps, undone newest first.
    let tv = u.shared.text_view();
    let typed = |t: &str| unsafe { tv.insertText_replacementRange(&NSString::from_str(t), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
    event(&|| typed("typed"));
    let typing_title = undo_title(w).0;
    event(&|| set_undoable("Rename", &u.name, "C".to_string()));
    event(&|| typed("!"));
    let mut seen = vec![(u.name.get_untracked(), u.shared.text())];
    for _ in 0..3 {
        shortcut(w, "z", false);
        seen.push((u.name.get_untracked(), u.shared.text()));
    }
    let want: Vec<(String, String)> =
        [("C", "typed!"), ("C", "typed"), ("B", "typed"), ("B", "")].iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
    check(
        "editor-shared-undo",
        typing_title == "Undo Typing" && seen == want,
        format!("top after typing: {typing_title:?}; then ⌘Z ×3: {seen:?}"),
    );

    // set_text drops only that editor's steps from the shared stack.
    event(&|| set_undoable("Rename", &u.name, "D".to_string()));
    event(&|| u.shared.replace_selection("more"));
    event(&|| set_undoable("Rename", &u.name, "E".to_string()));
    u.shared.set_text("fresh");
    let top = undo_title(w).0;
    shortcut(w, "z", false);
    let first = (u.name.get_untracked(), u.shared.text());
    shortcut(w, "z", false);
    let second = (u.name.get_untracked(), u.shared.text());
    check(
        "editor-set-text-undo",
        top == "Undo Rename" && first == ("D".into(), "fresh".into()) && second == ("B".into(), "fresh".into()),
        format!("after set_text the top is {top:?}; ⌘Z → {first:?}; ⌘Z → {second:?} (the dropped typing is skipped)"),
    );

    event(&|| set_undoable("Rename", &u.name, "F".to_string()));
    ferrokit::close_window(w);
    check("undo-close", !m.canUndo() && !m.canRedo(), format!("after close: can undo {}, redo {}", m.canUndo(), m.canRedo()));
    after_events(move || posted_event_checks(events.clone()));
}

thread_local! {
    /// Set when a posted key found no key window to make: the app isn't
    /// active (macOS gives focus to the app the user is in), so menu
    /// shortcuts like ⌘Z have no responder chain to go to.
    static NO_KEY_WINDOW: Cell<bool> = const { Cell::new(false) };
}

/// For checks of menu shortcuts through posted keys: `Some(reason)` when
/// the app had no key window, so they can't be judged in this run.
fn keys_unreachable() -> Option<&'static str> {
    NO_KEY_WINDOW.with(Cell::get).then_some("skipped: the app wasn't active (no key window), so ⌘Z had no responder to reach; a person pressing keys always has the app in front")
}

/// On a CI runner (GitHub sets `CI`): shared, slow virtual machines, so
/// timing budgets are reported but don't fail (correctness checks still do).
/// Timing budgets are informational on CI (shared, virtual machines) and
/// in debug builds (run for objc2's checks, not for speed).
fn on_ci() -> bool {
    std::env::var_os("CI").is_some() || cfg!(debug_assertions)
}

/// Appended to a timing check's note where it's informational.
fn ci_note() -> &'static str {
    if on_ci() { "; informational on CI and in debug builds" } else { "" }
}

/// Posts a key press (down and up) to the app's event queue for `w`, as the
/// keyboard does: it goes through the run loop, the menu's key equivalents
/// and the first responder, and AppKit closes its per-event undo group.
fn post_key(w: &objc2_app_kit::NSWindow, chars: &str, flags: NSEventModifierFlags) {
    use objc2_app_kit::{NSEvent, NSEventType};
    // Keys go to the key window's first responder; something else on the
    // machine (a person using it meanwhile) can take key status away.
    if !w.isKeyWindow() {
        let app = NSApplication::sharedApplication(mtm());
        let key = app.keyWindow().map(|k| k.title().to_string());
        w.makeKeyWindow();
        if !w.isKeyWindow() {
            NO_KEY_WINDOW.with(|n| n.set(true));
        }
        eprintln!(
            "[note] {:?} wasn't the key window before {chars:?} (key: {key:?}, app active: {}); made it key: {}",
            w.title().to_string(),
            app.isActive(),
            w.isKeyWindow()
        );
    }
    // US-layout key codes, for input methods that look at them.
    let code = match chars.to_lowercase().as_str() {
        "a" => 0, "s" => 1, "h" => 4, "c" => 8, "b" => 11, "e" => 14, "r" => 15, "i" => 34, "," => 43, "n" => 45, "\u{1b}" => 53, _ => 6,
    };
    for t in [NSEventType::KeyDown, NSEventType::KeyUp] {
        let e = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
            t, objc2_foundation::NSPoint::new(0.0, 0.0), flags, 0.0, w.windowNumber(), None, &NSString::from_str(chars), &NSString::from_str(chars), false, code,
        )
        .unwrap();
        NSApplication::sharedApplication(mtm()).postEvent_atStart(&e, false);
    }
}

/// Runs `steps` one per 150 ms (each posts events), calling `snap` after
/// each has been handled, then `done`.
fn posted_steps(steps: Rc<Vec<Box<dyn Fn()>>>, i: usize, snap: Rc<dyn Fn(usize)>, done: Rc<dyn Fn()>) {
    if i == steps.len() {
        return done();
    }
    steps[i]();
    spawn(|| std::thread::sleep(std::time::Duration::from_millis(150)), move |()| {
        snap(i);
        posted_steps(steps, i + 1, snap, done);
    });
}

/// Real key events posted to the app's queue (the app needn't be active):
/// typing, a menu shortcut and ⌘Z / ⇧⌘Z with AppKit's own per-event undo
/// grouping (the checks above use explicit groups), the custom menus'
/// shortcuts, and a text field's undo.
fn posted_event_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let m = MENU.with(Clone::clone);
    let field_text = Signal::new(String::new());
    let shared = Rc::new(TextModel::new(ViewId(960), ""));
    let w = open(Window::new("Events").size(420.0, 260.0).view(vstack((text_field(&field_text), text_editor(&shared).shared_undo())).padding(12.0)));
    w.makeKeyAndOrderFront(None);
    w.makeFirstResponder(Some(&shared.text_view()));
    let cmd = NSEventModifierFlags::Command;
    let k = |c: &'static str, f: NSEventModifierFlags| {
        let w = w.clone();
        Box::new(move || post_key(&w, c, f)) as Box<dyn Fn()>
    };
    let none = NSEventModifierFlags::empty();
    let steps = Rc::new(vec![
        Box::new({ let w = w.clone(); move || { post_key(&w, "a", none); post_key(&w, "b", none) } }) as Box<dyn Fn()>,
        k("e", cmd | NSEventModifierFlags::Control),
        k("c", none),
        k("z", cmd),
        k("z", cmd),
        k("z", cmd),
        k("Z", cmd | NSEventModifierFlags::Shift),
    ]);
    // (name, editor text, Edit menu's Undo title, open undo groups) after each step.
    type Seen = Vec<(String, String, String, isize)>;
    let seen: Rc<RefCell<Seen>> = Rc::default();
    let snap: Rc<dyn Fn(usize)> = {
        let (seen, m, shared, w) = (seen.clone(), m.clone(), shared.clone(), w.clone());
        Rc::new(move |_| {
            let um = w.undoManager().unwrap();
            seen.borrow_mut().push((m.renamed.get_untracked(), shared.text(), um.undoMenuItemTitle().to_string(), um.groupingLevel()));
        })
    };
    let done: Rc<dyn Fn()> = Rc::new(move || {
        let want: Vec<(String, String, String, isize)> = [
            ("A", "ab", "Undo Typing"),
            ("A+", "ab", "Undo Rename"),
            ("A+", "abc", "Undo Typing"),
            ("A+", "ab", "Undo Rename"),
            ("A", "ab", "Undo Typing"),
            ("A", "", "Undo"),
            ("A", "ab", "Undo Typing"),
        ]
        .iter()
        .map(|(a, b, c)| (a.to_string(), b.to_string(), c.to_string(), 0))
        .collect();
        let got = seen.borrow().clone();
        let skip = keys_unreachable();
        check(
            "posted-undo",
            got == want || skip.is_some(),
            format!("{}type ab, ⌃⌘E Rename, type c, ⌘Z ×3, ⇧⌘Z (name, text, Edit menu, open groups): {got:?}", skip.map(|s| format!("{s}; ")).unwrap_or_default()),
        );
        posted_shortcut_checks(w.clone(), field_text, events.clone());
    });
    posted_steps(steps, 0, snap, done);
}

/// A split divider dragged with posted mouse events (NSSplitView tracks the
/// drag from the event queue): the panes resize and their content relayouts.
fn posted_split_drag(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSEvent, NSEventType, NSSplitView};
    use objc2_foundation::NSPoint;
    let w = open(
        Window::new("Split Drag")
            .size(600.0, 300.0)
            .view(split((vstack((text("Left").fill_width(),)).padding(8.0), vstack((text("Right").fill_width(),)).padding(8.0))).position(160.0)),
    );
    w.makeKeyAndOrderFront(None);
    let sv = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSSplitView>().ok()).unwrap();
    let sv2 = sv.clone();
    let pane = move |i: usize| sv2.arrangedSubviews().objectAtIndex(i).frame().size.width;
    let content = w.contentView().unwrap();
    let label_width = move |title: &str| {
        all_views(&content)
            .into_iter()
            .filter_map(|v| v.downcast::<NSTextField>().ok())
            .find(|t| t.stringValue().to_string() == title)
            .map_or(0.0, |t| t.frame().size.width)
    };
    let before = (pane(0), pane(1), label_width("Left"), label_width("Right"));
    let x = pane(0) + sv.dividerThickness() / 2.0;
    let post = |t: NSEventType, x: f64| {
        let p = sv.convertPoint_toView(NSPoint::new(x, 100.0), None);
        let e = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
            t, p, NSEventModifierFlags::empty(), 0.0, w.windowNumber(), None, 0, 1, 1.0,
        )
        .unwrap();
        NSApplication::sharedApplication(mtm()).postEvent_atStart(&e, false);
    };
    post(NSEventType::LeftMouseDown, x);
    for i in 1..=10 {
        post(NSEventType::LeftMouseDragged, x + 8.0 * i as f64);
    }
    post(NSEventType::LeftMouseUp, x + 80.0);
    let app_active = NSApplication::sharedApplication(mtm()).isActive();
    spawn(|| std::thread::sleep(std::time::Duration::from_millis(300)), move |()| {
        let after = (pane(0), pane(1), label_width("Left"), label_width("Right"));
        // On macOS 26 posted mouse input reaches only the active app (as
        // posted ⌘ shortcuts need a key window): skip when it isn't.
        // Not delivered at all: an inactive app, or the macOS 26 CI runner
        // (where posted drags don't reach even the active app). The divider
        // and relayout themselves are covered by `split-drag` (AppKit's API).
        let skip = (after == before && (!app_active || on_ci())).then_some("skipped: the posted drag wasn't delivered here (inactive app or CI runner); ");
        check(
            "posted-split-drag",
            skip.is_some() || (after.0 - before.0 - 80.0).abs() < 1.0 && (before.1 - after.1 - 80.0).abs() < 1.0 && (after.2 - before.2 - 80.0).abs() < 1.0 && (before.3 - after.3 - 80.0).abs() < 1.0,
            format!("{}divider dragged 80 pt: panes {:.0}/{:.0} → {:.0}/{:.0}; labels {:.0}/{:.0} → {:.0}/{:.0}", skip.unwrap_or(""), before.0, before.1, after.0, after.1, before.2, before.3, after.2, after.3),
        );
        ferrokit::close_window(&w);
        let events = events.clone();
        after_events(move || close_button_checks(events.clone()));
    });
}

/// A window of 200 bound labels and a table (with a toolbar), for close checks.
fn closable_window(title: &str, value: &Signal<u32>) -> Window {
    let labels: Vec<ferrokit::AnyView> = (0..200)
        .map(|i| {
            let v = *value;
            ferrokit::AnyView::new(text(move || format!("{i}: {}", v.get())))
        })
        .collect();
    let model = Rc::new(TableModel::new(ViewId(970), vec![Column::text("n", "N", |n: &u32| n.to_string())]));
    model.set_rows((0..1000).collect());
    Window::new(title)
        .size(420.0, 400.0)
        .toolbar(vec![toolbar_button("add", "Add", "plus", || {})])
        .view(vstack((scroll(vstack(labels)), table(&model))))
}

/// The close button (performClose:, the path a click takes) and ⌘W tear a
/// window down like close_window; Settings is kept.
fn close_button_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let value = Signal::new(0u32);
    let (n0, list0) = (live_nodes(), windows().len());
    let w = open(closable_window("Close Me", &value));
    let built = live_nodes() - n0;
    let weak = objc2::rc::Weak::from_retained(&w);
    w.performClose(None);
    drop(w);
    let v = value;
    after_idle(move || {
        let runs = effect_runs();
        batch(|| v.set(1));
        let ran = effect_runs() - runs;
        let freed = weak.load().is_none();
        check(
            "close-button-teardown",
            built > 200 && live_nodes() == n0 && windows().len() == list0 && ran == 0 && freed,
            format!(
                "{built} nodes built; after the close button: {} left, listed windows {} (was {list0}), effects run on a change {ran}, window freed {freed}",
                live_nodes() - n0,
                windows().len()
            ),
        );
        action_owner_check();
        // Settings is reused: closing it keeps the same window and its views.
        let s1 = ferrokit::open_settings().unwrap();
        let s_nodes = live_nodes();
        s1.performClose(None);
        let s1p = Retained::as_ptr(&s1);
        drop(s1);
        let v = v;
        let events = events.clone();
        after_idle(move || {
            let s2 = ferrokit::open_settings().unwrap();
            let same = Retained::as_ptr(&s2) == s1p && live_nodes() == s_nodes;
            s2.close();
            check("close-settings-kept", same, format!("Settings after closing: same window and views {same}"));
            close_cycles(v, events.clone(), 0, 0.0);
        });
    });
}

/// A button's action runs under its view tree's owner: a signal it makes
/// (as for a sheet's form) is freed with the window, not kept for the app.
fn action_owner_check() {
    use objc2_app_kit::NSButton;
    let made: Rc<Cell<Option<Signal<String>>>> = Rc::default();
    let m = made.clone();
    let w = open(Window::new("Action Owner").size(200.0, 80.0).view(button("Make", move || m.set(Some(Signal::new("form".into()))))));
    let b = w.contentView().unwrap().subviews().iter().find_map(|v| v.downcast::<NSButton>().ok()).unwrap();
    // SAFETY: a nil sender is allowed.
    unsafe { b.performClick(None) };
    let made_alive = made.get().is_some_and(|s| s.is_alive());
    ferrokit::close_window(&w);
    let freed = made.get().is_some_and(|s| !s.is_alive() && s.try_get().is_none());
    check("action-owner", made_alive && freed, format!("signal made by the action: alive while open {made_alive}, freed with the window {freed}"));
}

mod plain_toolbar {
    use objc2::rc::Retained;
    use objc2::runtime::NSObjectProtocol;
    use objc2::{MainThreadMarker, MainThreadOnly, define_class};
    use objc2_app_kit::{NSImage, NSToolbar, NSToolbarDelegate, NSToolbarItem};
    use objc2_foundation::{NSArray, NSObject, NSString};

    define_class!(
        // A plain toolbar's delegate: one "Add" button with an SF Symbol,
        // like the ferrokit test window's.
        #[unsafe(super(NSObject))]
        #[thread_kind = MainThreadOnly]
        #[name = "ChecklistPlainToolbar"]
        pub struct PlainToolbar;

        unsafe impl NSObjectProtocol for PlainToolbar {}

        unsafe impl NSToolbarDelegate for PlainToolbar {
            #[unsafe(method_id(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:))]
            fn item(&self, _toolbar: &NSToolbar, id: &NSString, _insert: bool) -> Option<Retained<NSToolbarItem>> {
                let mtm = MainThreadMarker::new().unwrap();
                let item = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(mtm), id);
                item.setLabel(&NSString::from_str("Add"));
                item.setImage(NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str("plus"), None).as_deref());
                Some(item)
            }

            #[unsafe(method_id(toolbarDefaultItemIdentifiers:))]
            fn defaults(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSString>> {
                NSArray::from_retained_slice(&[NSString::from_str("add")])
            }

            #[unsafe(method_id(toolbarAllowedItemIdentifiers:))]
            fn allowed(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSString>> {
                NSArray::from_retained_slice(&[NSString::from_str("add")])
            }
        }
    );
}
use plain_toolbar::PlainToolbar;

/// A plain AppKit window like `closable_window` (200 labels in a scroll
/// view, a table, a toolbar with one button), opened and closed: AppKit's
/// own cost per cycle, the floor for ours.
fn plain_cycle() {
    use objc2::MainThreadOnly;
    use objc2_app_kit::{NSBackingStoreType, NSScrollView, NSTableColumn, NSTableView, NSWindow, NSWindowStyleMask};
    use objc2_foundation::{NSPoint, NSRect, NSSize};
    let mtm = MainThreadMarker::new().unwrap();
    objc2::rc::autoreleasepool(|_| {
        let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(420.0, 400.0));
        let style = NSWindowStyleMask::Titled | NSWindowStyleMask::Closable | NSWindowStyleMask::Resizable;
        let w = unsafe { NSWindow::initWithContentRect_styleMask_backing_defer(NSWindow::alloc(mtm), rect, style, NSBackingStoreType::Buffered, false) };
        unsafe { w.setReleasedWhenClosed(false) };
        let content = w.contentView().unwrap();
        let doc = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(400.0, 200.0 * 18.0)));
        for i in 0..200 {
            let l = NSTextField::labelWithString(&NSString::from_str(&format!("{i}: 0")), mtm);
            l.setFrame(NSRect::new(NSPoint::new(0.0, i as f64 * 18.0), NSSize::new(200.0, 17.0)));
            doc.addSubview(&l);
        }
        let sv = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::new(0.0, 200.0), NSSize::new(420.0, 200.0)));
        sv.setDocumentView(Some(&doc));
        content.addSubview(&sv);
        let tv = NSTableView::initWithFrame(NSTableView::alloc(mtm), NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(420.0, 200.0)));
        tv.addTableColumn(&NSTableColumn::initWithIdentifier(NSTableColumn::alloc(mtm), &NSString::from_str("n")));
        let tsv = NSScrollView::initWithFrame(NSScrollView::alloc(mtm), NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(420.0, 200.0)));
        tsv.setDocumentView(Some(&tv));
        content.addSubview(&tsv);
        let delegate: Retained<PlainToolbar> = unsafe { objc2::msg_send![PlainToolbar::alloc(mtm), init] };
        let toolbar = objc2_app_kit::NSToolbar::initWithIdentifier(objc2_app_kit::NSToolbar::alloc(mtm), &NSString::from_str("plain"));
        toolbar.setDelegate(Some(objc2::runtime::ProtocolObject::from_ref(&*delegate)));
        w.setToolbar(Some(&toolbar));
        w.makeKeyAndOrderFront(None);
        w.performClose(None);
        toolbar.setDelegate(None);
        drop(delegate);
    });
}

/// Open/close cycles through the close button, against the same number of
/// plain AppKit windows: ours shouldn't cost much more than AppKit's own.
/// AppKit's caches grow over the first few dozen windows of a kind (the
/// toolbar's longest), so 40 cycles warm up before 30 are measured.
fn close_cycles(value: Signal<u32>, events: Rc<RefCell<Vec<AppEvent>>>, round: u32, base: f64) {
    const ROUNDS: u32 = 70;
    const WARM: u32 = 40;
    if round == 0 {
        // The floor: plain AppKit, same warm-up and count, one per idle pass.
        fn plain(round: u32, base: f64, then: Rc<dyn Fn(f64)>) {
            // The baseline settles too (both ends measured alike).
            if round == WARM && base == 0.0 {
                return settled_heap(move |b| plain(round, b, then));
            }
            if round == ROUNDS {
                return settled_heap(move |now| then((now - base) * 1024.0 / (ROUNDS - WARM) as f64));
            }
            plain_cycle();
            let then = then.clone();
            after_idle(move || plain(round + 1, base, then.clone()));
        }
        let (v, e) = (value, events.clone());
        plain(0, 0.0, Rc::new(move |floor| {
            PLAIN_FLOOR_KB.with(|f| f.set(floor));
            close_cycles(v, e.clone(), 1, 0.0);
        }));
        return;
    }
    if round == WARM && base == 0.0 {
        return settled_heap(move |b| close_cycles(value, events, round, b));
    }
    if round == ROUNDS {
        return settled_heap(move |now| close_cycles_report(now, base, events));
    }
    let w = open(closable_window("Cycle", &value));
    w.performClose(None);
    drop(w);
    let v = value;
    after_idle(move || close_cycles(v, events.clone(), round + 1, base));
}

fn close_cycles_report(now: f64, base: f64, events: Rc<RefCell<Vec<AppEvent>>>) {
    const ROUNDS: u32 = 70;
    const WARM: u32 = 40;
    {
        let per = (now - base) * 1024.0 / (ROUNDS - WARM) as f64;
        let floor = PLAIN_FLOOR_KB.with(Cell::get);
        let inconclusive = retaining_note();
        check(
            "close-cycles-memory",
            // Live allocations (not footprint, which the allocator returns late).
            per < floor.max(0.0) + 16.0 || inconclusive.is_some(),
            format!(
                "{}{} cycles through the close button: heap in use {per:+.1} KB per cycle; a plain AppKit window with the same views {floor:+.1} KB (budget: plain + 16)",
                inconclusive.unwrap_or_default(),
                ROUNDS - WARM
            ),
        );
        after_events(move || sheet_cycles(events.clone()));
    }
}

thread_local! {
    static PLAIN_FLOOR_KB: Cell<f64> = const { Cell::new(0.0) };
}

/// Plain AppKit windows keep part of their content after closing in some
/// machine states (seen on 2026-10-29 with an outside accessibility client
/// running: `heap` showed SwiftUI-hosted views, attribute graphs and KVO
/// records of closed windows staying). Then no window can be measured
/// against a budget; the floor tells.
const RETAINING_FLOOR_KB: f64 = 32.0;

/// `Some(note)` when the plain floor shows the machine retaining closed
/// windows' content: memory budgets are inconclusive there.
fn retaining_note() -> Option<String> {
    let floor = PLAIN_FLOOR_KB.with(Cell::get);
    (floor > RETAINING_FLOOR_KB).then(|| format!("inconclusive here: plain AppKit windows keep {floor:.0} KB each after closing on this machine now (AppKit/SwiftUI internals); "))
}

/// Calls `then` with the heap in use once the last closed windows are
/// freed: AppKit finishes deallocating a window on later passes, seconds
/// later on a busy machine. A measure right after the last close counts
/// the windows still pending (on 2026-10-29 that read +70 to +1,130 KB per
/// window, while `heap`'s per-class counts showed nothing accumulating).
/// Samples every 250 ms, keeping the lowest, until it stops falling (less
/// than 32 KB over the last second), for at most 8 s.
fn settled_heap(then: impl FnOnce(f64) + 'static) {
    fn sample(history: Vec<f64>, then: Box<dyn FnOnce(f64)>) {
        let mut history = history;
        history.push(heap_in_use_mb());
        let low = history.iter().copied().fold(f64::MAX, f64::min);
        let n = history.len();
        let settled = n >= 5 && history[n - 5] - low < 32.0 / 1024.0;
        if settled || n >= 32 {
            return then(low);
        }
        spawn(|| std::thread::sleep(std::time::Duration::from_millis(250)), move |()| sample(history, then));
    }
    sample(Vec::new(), Box::new(then));
}


/// Repeats `cycle` (one per idle pass): `WARM` warm-up rounds, then
/// `MEASURED` measured ones; calls `done` with KB per measured cycle.
fn cycles(round: u32, base: f64, cycle: Rc<dyn Fn()>, done: Rc<dyn Fn(f64)>) {
    const WARM: u32 = 40;
    const MEASURED: u32 = 30;
    if round == WARM && base == 0.0 {
        return settled_heap(move |b| cycles(round, b, cycle, done));
    }
    if round == WARM + MEASURED {
        return settled_heap(move |now| done((now - base) * 1024.0 / MEASURED as f64));
    }
    cycle();
    after_idle(move || cycles(round + 1, base, cycle.clone(), done.clone()));
}

/// Sheets with a form, opened and closed on one window: views go, the sheet
/// window is freed, and memory stays flat.
fn sheet_cycles(events: Rc<RefCell<Vec<AppEvent>>>) {
    let parent = open(Window::new("Sheets").size(480.0, 320.0).view(text("Sheet parent")));
    let n0 = live_nodes();
    let freed: Rc<RefCell<Vec<objc2::rc::Weak<objc2_app_kit::NSWindow>>>> = Rc::default();
    let (p, f) = (parent.clone(), freed.clone());
    let cycle: Rc<dyn Fn()> = Rc::new(move || {
        let name = Signal::new("draft".to_string());
        let form = Window::new("Form").size(320.0, 140.0).view(vstack((text_field(&name), checkbox("Remember", &Signal::new(true)), button("Done", || {}))).padding(16.0));
        let h = sheet(&p, form, || {});
        f.borrow_mut().push(objc2::rc::Weak::from_retained(&h.window()));
        h.close();
    });
    let p2 = parent.clone();
    let done: Rc<dyn Fn(f64)> = Rc::new(move |per| {
        let left = live_nodes() - n0;
        let alive = freed.borrow().iter().filter(|w| w.load().is_some()).count();
        // The floor: plain AppKit sheets with the same controls, same counts.
        let (events, parent) = (events.clone(), p2.clone());
        let pp = parent.clone();
        let plain: Rc<dyn Fn()> = Rc::new(move || plain_sheet_cycle(&pp));
        let report: Rc<dyn Fn(f64)> = Rc::new(move |floor| {
            check(
                "sheet-cycles-memory",
                left == 0 && alive == 0 && (per < floor.max(0.0) + 8.0 || retaining_note().is_some()),
                format!("{}70 form sheets opened and closed: heap in use {per:+.1} KB per cycle after warm-up; plain AppKit sheets {floor:+.1} KB (budget: plain + 8); nodes left {left}; sheet windows still alive {alive}", retaining_note().unwrap_or_default()),
            );
            ferrokit::close_window(&parent);
            let events = events.clone();
            after_events(move || deep_widget_cycles(events.clone()));
        });
        cycles(0, 0.0, plain, report);
    });
    cycles(0, 0.0, cycle, done);
}

/// One plain AppKit sheet with a field, a checkbox and a button, shown and
/// ended on `parent`.
fn plain_sheet_cycle(parent: &objc2_app_kit::NSWindow) {
    use objc2::MainThreadOnly;
    use objc2_app_kit::{NSBackingStoreType, NSButton, NSWindow, NSWindowStyleMask};
    use objc2_foundation::{NSPoint, NSRect, NSSize};
    let mtm = MainThreadMarker::new().unwrap();
    objc2::rc::autoreleasepool(|_| {
        let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(320.0, 140.0));
        let sheet = unsafe { NSWindow::initWithContentRect_styleMask_backing_defer(NSWindow::alloc(mtm), rect, NSWindowStyleMask::Titled, NSBackingStoreType::Buffered, false) };
        unsafe { sheet.setReleasedWhenClosed(false) };
        let content = sheet.contentView().unwrap();
        let field = NSTextField::new(mtm);
        field.setStringValue(&NSString::from_str("draft"));
        field.setFrame(NSRect::new(NSPoint::new(16.0, 90.0), NSSize::new(280.0, 24.0)));
        content.addSubview(&field);
        let check_box = unsafe { NSButton::checkboxWithTitle_target_action(&NSString::from_str("Remember"), None, None, mtm) };
        check_box.setFrame(NSRect::new(NSPoint::new(16.0, 56.0), NSSize::new(200.0, 20.0)));
        content.addSubview(&check_box);
        let done = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Done"), None, None, mtm) };
        done.setFrame(NSRect::new(NSPoint::new(220.0, 16.0), NSSize::new(80.0, 28.0)));
        content.addSubview(&done);
        parent.beginSheet_completionHandler(&sheet, None);
        parent.endSheet(&sheet);
        sheet.orderOut(None);
    });
}

/// Windows holding the deep widgets (a 10,000-row table, an outline, a text
/// editor), opened and closed through the close button.
fn deep_widget_cycles(events: Rc<RefCell<Vec<AppEvent>>>) {
    let n0 = live_nodes();
    let freed: Rc<RefCell<Vec<objc2::rc::Weak<objc2_app_kit::NSWindow>>>> = Rc::default();
    let f = freed.clone();
    let cycle: Rc<dyn Fn()> = Rc::new(move || {
        let model = Rc::new(TableModel::new(ViewId(980), vec![Column::text("n", "N", |n: &u32| n.to_string())]));
        model.set_rows((0..10_000).collect());
        let notes = TextModel::new(ViewId(981), "Some notes\nover two lines");
        let tree = || (0..20u32).map(|i| TreeNode { value: place(i, &format!("Group {i}"), None), children: (0..5).map(|j| TreeNode { value: place(1000 + i * 10 + j, "Leaf", None), children: vec![] }).collect() }).collect();
        let w = open(
            Window::new("Deep")
                .size(640.0, 480.0)
                .view(split((
                    outline(tree, |p: &Place| p.name.clone()),
                    vstack((
                        table(&model),
                        text_editor(&notes),
                        ferrokit::collection(|| (0..500u32).map(|i| place(i, "Tile", None)).collect(), |p: &Place| {
                            ferrokit::CollectionItem::new(format!("{} {}", p.name, p.id), ferrokit::ItemImage::Symbol("folder".into()))
                        }),
                    )),
                ))),
        );
        f.borrow_mut().push(objc2::rc::Weak::from_retained(&w));
        w.performClose(None);
    });
    let done: Rc<dyn Fn(f64)> = Rc::new(move |per| {
        let left = live_nodes() - n0;
        let alive = freed.borrow().iter().filter(|w| w.load().is_some()).count();
        check(
            "deep-widget-cycles-memory",
            left == 0 && alive == 0 && (per < 16.0 || retaining_note().is_some()),
            format!("{}70 windows with a 10,000-row table, an outline, an editor and a 500-item grid, closed by the close button: heap in use {per:+.1} KB per cycle after warm-up (budget 16); nodes left {left}; windows still alive {alive}", retaining_note().unwrap_or_default()),
        );
        let events = events.clone();
        after_events(move || accessibility_checks(events.clone()));
    });
    cycles(0, 0.0, cycle, done);
}

/// Names VoiceOver reads: `accessibility_label` on a field, a slider, a
/// pop-up, a stepper and an editor; a toggle's switch; decorative and
/// described images. The audit finds an unnamed field, then nothing.
fn accessibility_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::{ax_audit, ax_elements};
    let (name, vol, pick, days, on) = (Signal::new(String::new()), Signal::new(0.5), Signal::new(1u8), Signal::new(3.0), Signal::new(true));
    let notes = TextModel::new(ViewId(990), "");
    let bare = Signal::new(String::new());
    let w = open(Window::new("Accessibility").size(420.0, 420.0).view(
        vstack((
            hstack((text("Name:"), text_field(&name).accessibility_label("Name"))),
            hstack((image("speaker.fill"), slider(&vol, 0.0, 1.0).accessibility_label("Volume"))),
            picker(&pick, vec![("One", 1u8), ("Two", 2)]).accessibility_label("Count"),
            stepper(&days, 1.0, 9.0, 1.0).accessibility_label("Days"),
            toggle("Sync", &on),
            image("star.fill").description("Favourite"),
            text_editor(&notes).accessibility_label("Notes"),
            text_field(&bare),
            ferrokit::date_picker(&Signal::new(std::time::UNIX_EPOCH)),
        ))
        .padding(12.0),
    ));
    let named = |role: &str, label: &str| ax_elements(&w).iter().any(|e| e.role == role && e.name == label);
    let found = [
        ("AXTextField", "Name"),
        ("AXSlider", "Volume"),
        ("AXPopUpButton", "Count"),
        ("AXIncrementor", "Days"),
        ("AXButton", "Sync"),
        ("AXImage", "Favourite"),
        ("AXTextArea", "Notes"),
    ]
    .iter()
    .filter(|(r, l)| !named(r, l))
    .map(|(r, l)| format!("{r} {l}"))
    .collect::<Vec<_>>();
    let images = ax_elements(&w).iter().filter(|e| e.role == "AXImage").count();
    let problems = ax_audit(&w);
    check(
        "accessibility-labels",
        // An unnamed date picker is reported with its stepper (its parts are
        // skipped only inside a named one).
        found.is_empty() && images == 1 && problems.len() == 3 && problems[0].contains("AXTextField") && problems[1].contains("AXDateTimeArea") && problems[2].contains("AXIncrementor"),
        format!("names missing {found:?}; images exposed {images} (the decorative one hidden); audit finds only the bare field and the bare date picker (with its stepper): {problems:?}"),
    );
    ferrokit::close_window(&w);
    // The form windows of this checklist.
    let mut forms = Vec::new();
    for title in ["Controls", "Controls B"] {
        if let Some(fw) = windows().into_iter().find(|w| w.title().to_string() == title) {
            forms.extend(ax_audit(&fw).into_iter().map(|p| format!("{title}: {p}")));
        }
    }
    check("accessibility-audit-forms", forms.is_empty(), format!("Controls and Controls B: {forms:?}"));
    after_events(move || controls_c_checks(events.clone()));
}

/// The custom menus' shortcuts and Settings (⌘,) from posted key presses,
/// then typing and ⌘Z in a text field.
fn posted_shortcut_checks(w: Retained<objc2_app_kit::NSWindow>, field_text: Signal<String>, events: Rc<RefCell<Vec<AppEvent>>>) {
    let m = MENU.with(Clone::clone);
    let cmd = NSEventModifierFlags::Command;
    let start = (m.items.get_untracked(), m.sidebar.get_untracked(), m.refreshed.get_untracked());
    let combos: Vec<(&'static str, NSEventModifierFlags)> = vec![
        ("n", cmd),
        ("n", cmd),
        ("n", cmd | NSEventModifierFlags::Option),
        ("s", cmd | NSEventModifierFlags::Control),
        ("R", cmd | NSEventModifierFlags::Shift),
        (",", cmd),
    ];
    let steps: Rc<Vec<Box<dyn Fn()>>> = Rc::new(
        combos
            .into_iter()
            .map(|(c, f)| {
                let w = w.clone();
                Box::new(move || post_key(&w, c, f)) as Box<dyn Fn()>
            })
            .collect(),
    );
    let seen: Rc<RefCell<Vec<(i64, bool, u32)>>> = Rc::default();
    let snap: Rc<dyn Fn(usize)> = {
        let (seen, m) = (seen.clone(), m.clone());
        Rc::new(move |_| seen.borrow_mut().push((m.items.get_untracked(), m.sidebar.get_untracked(), m.refreshed.get_untracked())))
    };
    let done: Rc<dyn Fn()> = Rc::new(move || {
        let (i0, s0, r0) = start;
        let got = seen.borrow().clone();
        let settings = NSApplication::sharedApplication(mtm()).windows().iter().find(|w| w.title().to_string() == "Settings" && w.isVisible());
        let want = vec![(i0 + 1, s0, r0), (i0 + 2, s0, r0), (i0 + 1, s0, r0), (i0 + 1, !s0, r0), (i0 + 1, !s0, r0 + 1), (i0 + 1, !s0, r0 + 1)];
        check(
            "posted-shortcuts",
            got == want && settings.is_some(),
            format!("⌘N ⌘N ⌥⌘N ⌃⌘S ⇧⌘R → (items, sidebar, refreshed) {got:?}; ⌘, opened Settings: {}", settings.is_some()),
        );
        if let Some(s) = settings {
            s.close();
        }
        // Typing in a text field, then ⌘Z and ⇧⌘Z: the field and its bound
        // signal. AppKit (plain AppKit too) sends ⇧⌘Z to the window's undo
        // manager when it has a redo pending, not to the field's private
        // one, so the window's history is cleared first, as in a fresh form.
        w.undoManager().unwrap().removeAllActions();
        let field = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSTextField>().ok()).unwrap();
        w.makeFirstResponder(Some(&field));
        let none = NSEventModifierFlags::empty();
        let steps: Rc<Vec<Box<dyn Fn()>>> = Rc::new(vec![
            Box::new({ let w = w.clone(); move || { post_key(&w, "h", none); post_key(&w, "i", none) } }),
            Box::new({ let w = w.clone(); move || post_key(&w, "z", cmd) }),
            Box::new({ let w = w.clone(); move || post_key(&w, "Z", cmd | NSEventModifierFlags::Shift) }),
        ]);
        let seen: Rc<RefCell<Vec<(String, String)>>> = Rc::default();
        let snap: Rc<dyn Fn(usize)> = {
            let (seen, f, field) = (seen.clone(), field_text, field.clone());
            Rc::new(move |_| seen.borrow_mut().push((field.stringValue().to_string(), f.get_untracked())))
        };
        let (w2, events2) = (w.clone(), events.clone());
        let done: Rc<dyn Fn()> = Rc::new(move || {
            let got = seen.borrow().clone();
            let want: Vec<(String, String)> = [("hi", "hi"), ("", ""), ("hi", "hi")].iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
            let skip = keys_unreachable();
            check(
                "posted-field-undo",
                got == want || skip.is_some(),
                format!("{}type hi, ⌘Z, ⇧⌘Z → (field, bound signal): {got:?}", skip.map(|s| format!("{s}; ")).unwrap_or_default()),
            );
            ferrokit::close_window(&w2);
            posted_split_drag(events2.clone());
        });
        posted_steps(steps, 0, snap, done);
    });
    posted_steps(steps, 0, snap, done);
}

#[derive(Clone, Debug, PartialEq)]
struct Item2 {
    name: String,
    n: f64,
}

#[derive(Clone)]
struct TransferState {
    model: Rc<TableModel<Item2>>,
    moves: Signal<Vec<(Vec<usize>, Option<usize>)>>,
    files: Signal<Vec<(Vec<std::path::PathBuf>, Option<usize>)>>,
    urls: Signal<Vec<(Vec<String>, Option<usize>)>>,
    pastes: Signal<u32>,
}

fn names(m: &TableModel<Item2>) -> Vec<String> {
    m.rows().iter().map(|r| r.name.clone()).collect()
}

/// G2 controls: date picker, colour well, segmented control, combo box and
/// search field. Each way: the user's edit (through the control's own
/// action or notification) sets the signal; setting the signal updates
/// the control.
fn controls_c_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Color, color_well, combo_box, combo_box_with, date_picker, search_field, segmented, time_picker};
    use objc2_app_kit::{NSColorWell, NSComboBox, NSDatePicker, NSSearchField, NSSegmentedControl};
    use std::time::{Duration, UNIX_EPOCH};
    let day = |d: u64| UNIX_EPOCH + Duration::from_secs(1_790_000_000 + d * 86_400);
    let date = Signal::new(day(0));
    let colour = Signal::new(Color::rgb(1.0, 0.0, 0.0));
    let view_mode = Signal::new(1u8);
    let city = Signal::new(String::new());
    let query = Signal::new(String::new());
    let submits = Signal::new(0u32);
    let s2 = submits;
    let time = Signal::new((9u32, 30u32));
    let places = Signal::new(vec!["Oslo".to_string()]);
    let place = Signal::new(String::new());
    let w = open(Window::new("Controls C").size(420.0, 380.0).view(
        vstack((
            date_picker(&date).accessibility_label("Due"),
            date_picker(&date).with_time().calendar().range(day(0), day(400)).accessibility_label("Due, calendar"),
            time_picker(&time).accessibility_label("Reminder"),
            color_well(&colour).accessibility_label("Colour"),
            segmented(&view_mode, vec![("List", 1u8), ("Grid", 2), ("Columns", 3)]).accessibility_label("View"),
            combo_box(&city, vec!["Berlin", "Lagos", "Tokyo"]).accessibility_label("City"),
            combo_box_with(&place, move || places.get()).placeholder("Place").accessibility_label("Place"),
            search_field(&query).placeholder("Search orders").on_submit(move || s2.update(|n| *n += 1)).accessibility_label("Search"),
        ))
        .padding(12.0),
    ));
    let all = all_views(&w.contentView().unwrap());
    let mut pickers: Vec<_> = all.iter().filter_map(|v| v.clone().downcast::<NSDatePicker>().ok()).collect();
    let time_p = (pickers.len() == 3).then(|| pickers.remove(2));
    let well = all.iter().find_map(|v| v.clone().downcast::<NSColorWell>().ok()).unwrap();
    let seg = all.iter().find_map(|v| v.clone().downcast::<NSSegmentedControl>().ok()).unwrap();
    let mut combos = all.iter().filter_map(|v| v.clone().downcast::<NSComboBox>().ok());
    let combo = combos.next().unwrap();
    let live_combo = combos.next().unwrap();
    let search = all.iter().find_map(|v| v.clone().downcast::<NSSearchField>().ok()).unwrap();
    let secs = |p: &NSDatePicker| p.dateValue().timeIntervalSince1970() as u64;

    // Date: signal → both pickers; the user's pick → signal.
    batch(|| date.set(day(10)));
    let shown = pickers.iter().all(|p| secs(p) == 1_790_000_000 + 10 * 86_400);
    pickers[0].setDateValue(&objc2_foundation::NSDate::dateWithTimeIntervalSince1970((1_790_000_000 + 20 * 86_400) as f64));
    send_action(&pickers[0]);
    let picked = date.get_untracked() == day(20) && secs(&pickers[1]) == 1_790_000_000 + 20 * 86_400;
    let max_ok = pickers[1].maxDate().is_some_and(|d| d.timeIntervalSince1970() as u64 == 1_790_000_000 + 400 * 86_400);
    check("date-picker", pickers.len() == 2 && shown && picked && max_ok, format!("signal → pickers: {shown}; pick → signal and the other picker: {picked}; calendar range max set: {max_ok}"));

    // Time of day: hour and minute only; signal → picker; the user's pick → signal.
    if let Some(tp) = &time_p {
        use objc2_foundation::{NSCalendar, NSCalendarOptions, NSCalendarUnit};
        let cal = NSCalendar::currentCalendar();
        let hm = |p: &NSDatePicker| (cal.component_fromDate(NSCalendarUnit::Hour, &p.dateValue()), cal.component_fromDate(NSCalendarUnit::Minute, &p.dateValue()));
        let only_time = tp.datePickerElements() == objc2_app_kit::NSDatePickerElementFlags::HourMinute;
        let first = hm(tp) == (9, 30);
        batch(|| time.set((21, 5)));
        let shown = hm(tp) == (21, 5);
        if let Some(d) = cal.dateBySettingHour_minute_second_ofDate_options(7, 45, 0, &tp.dateValue(), NSCalendarOptions::empty()) {
            tp.setDateValue(&d);
        }
        send_action(tp);
        let picked = time.get_untracked();
        check("time-picker", only_time && first && shown && picked == (7, 45), format!("hour and minute only: {only_time}; starts 9:30: {first}; signal 21:05 → picker: {shown}; pick 7:45 → {picked:?}"));
    } else {
        check("time-picker", false, "no time picker".into());
    }

    // Colour: signal → well; the user's colour → signal.
    let srgb = objc2_app_kit::NSColorSpace::sRGBColorSpace();
    let red = well.color().colorUsingColorSpace(&srgb).is_some_and(|c| c.redComponent() > 0.99 && c.greenComponent() < 0.01);
    well.setColor(&objc2_app_kit::NSColor::colorWithSRGBRed_green_blue_alpha(0.0, 0.5, 1.0, 1.0));
    send_action(&well);
    let got = colour.get_untracked();
    let chosen = got.components().is_some_and(|(r, g, b, _)| (g - 0.5).abs() < 0.01 && (b - 1.0).abs() < 0.01 && r < 0.01);
    batch(|| colour.set(Color::rgb(0.2, 0.8, 0.2)));
    let back = well.color().colorUsingColorSpace(&srgb).is_some_and(|c| (c.greenComponent() - 0.8).abs() < 0.01);
    check("color-well", red && chosen && back, format!("starts red: {red}; picked → {got:?}; signal → well: {back}"));

    // Segments: signal → selection; a click → signal.
    let first = seg.selectedSegment() == 0;
    seg.setSelectedSegment(2);
    send_action(&seg);
    let clicked = view_mode.get_untracked() == 3;
    batch(|| view_mode.set(2));
    check("segmented", first && clicked && seg.selectedSegment() == 1, format!("List selected first: {first}; Columns → {}; signal Grid → segment {}", view_mode.get_untracked(), seg.selectedSegment()));

    // Combo box: typing → signal; a suggestion → signal; signal → text.
    post_edit(&combo, "Os");
    let typed = city.get_untracked() == "Os";
    combo.selectItemAtIndex(1);
    let chose = city.get_untracked() == "Lagos";
    batch(|| city.set("Tokyo".into()));
    check("combo-box", typed && chose && combo.stringValue().to_string() == "Tokyo", format!("typed → {typed}; chose Lagos → {chose}; signal → field {:?}", combo.stringValue()));

    // Live suggestions: the list follows its signal and leaves the text
    // alone; the placeholder shows while it's empty.
    let items = |c: &NSComboBox| (0..c.numberOfItems()).filter_map(|i| c.itemObjectValueAtIndex(i).downcast::<NSString>().ok().map(|s| s.to_string())).collect::<Vec<_>>();
    let first = items(&live_combo);
    let hint = live_combo.placeholderString().map(|p| p.to_string());
    post_edit(&live_combo, "Ber");
    batch(|| places.update(|p| p.push("Bergen".into())));
    let grown = items(&live_combo);
    let kept = place.get_untracked() == "Ber" && live_combo.stringValue().to_string() == "Ber";
    check("combo-box-live", first == ["Oslo"] && grown == ["Oslo", "Bergen"] && kept && hint.as_deref() == Some("Place"), format!("items {first:?} → {grown:?}; typed text kept: {kept}; placeholder {hint:?}"));

    // Search: typing → signal; Return → submit; the clear button → empty.
    // (A keystroke sends the field's action too; Return is the command
    // its delegate sees first.)
    post_edit(&search, "1234");
    send_action(&search);
    let typed = query.get_untracked() == "1234" && submits.get_untracked() == 0;
    if let Some(d) = search.delegate() {
        let editor = objc2_app_kit::NSTextView::new(mtm());
        let _: bool = unsafe { objc2::msg_send![&*d, control: &*search, textView: &*editor, doCommandBySelector: objc2::sel!(insertNewline:)] };
    }
    send_action(&search);
    let submitted = submits.get_untracked() == 1;
    search.setStringValue(&NSString::from_str(""));
    send_action(&search);
    let cleared = query.get_untracked().is_empty();
    batch(|| query.set("paris".into()));
    let placeholder = search.placeholderString().map(|p| p.to_string());
    check(
        "search-field",
        typed && submitted && cleared && search.stringValue().to_string() == "paris" && placeholder.as_deref() == Some("Search orders"),
        format!("typed → {typed}; Return → submit {submitted}; clear → empty {cleared}; signal → field {:?}; placeholder {placeholder:?}", search.stringValue()),
    );

    // VoiceOver: every control named; segments read by title.
    let problems = ferrokit::testing::ax_audit(&w);
    let elements = ferrokit::testing::ax_elements(&w);
    let segments: Vec<String> = elements.iter().filter(|e| e.role == "AXRadioButton").map(|e| e.name.clone()).collect();
    check("controls-c-accessibility", problems.is_empty() && segments == ["List", "Grid", "Columns"], format!("unnamed: {problems:?}; segments {segments:?}"));
    ferrokit::close_window(&w);
    after_events(move || button_kind_checks(events.clone()));
}

/// C1: button styles and sizes, a destructive button, the help button, a
/// menu (pull-down) button whose items act, check and disable.
fn button_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{ButtonStyle, ControlSize, button, help_button, menu_button, menu_item, menu_separator};
    use objc2::ClassType;
    use objc2_foundation::NSObjectProtocol;
    use objc2_app_kit::{NSBezelStyle, NSButton, NSControlSize, NSPopUpButton};
    let helped = Signal::new(0u32);
    let exported = Signal::new(String::new());
    let busy = Signal::new(false);
    let (h2, e2, e3) = (helped, exported, exported);
    let w = open(Window::new("Buttons").size(520.0, 220.0).view(
        vstack((
            hstack((
                button("Standard", || {}),
                button("Borderless", || {}).style(ButtonStyle::Borderless),
                button("Inline", || {}).style(ButtonStyle::Inline),
                button("Recessed", || {}).style(ButtonStyle::Recessed),
                button("", || {}).symbol("plus").style(ButtonStyle::Circular).accessibility_label("Add"),
            ))
            .spacing(8.0),
            hstack((
                button("Toolbar", || {}).style(ButtonStyle::Toolbar),
                button("Glass", || {}).style(ButtonStyle::Glass),
                button("Small", || {}).control_size(ControlSize::Small),
                button("Large", || {}).control_size(ControlSize::Large),
                button("Delete", || {}).destructive(),
            ))
            .spacing(8.0),
            hstack((
                menu_button(
                    "Export",
                    vec![
                        menu_item("CSV…", move || e2.set("csv".into())),
                        menu_separator(),
                        menu_item("PDF…", move || e3.set("pdf".into())).disabled(move || busy.get()),
                    ],
                ),
                menu_button("", vec![menu_item("Rename", || {})]).symbol("ellipsis.circle").style(ButtonStyle::Borderless).accessibility_label("More"),
                help_button(move || h2.update(|n| *n += 1)),
            ))
            .spacing(8.0),
        ))
        .spacing(12.0)
        .padding(16.0),
    ));
    let all = all_views(&w.contentView().unwrap());
    let pulls: Vec<Retained<NSPopUpButton>> = all.iter().filter_map(|v| v.clone().downcast::<NSPopUpButton>().ok()).collect();
    let buttons: Vec<Retained<NSButton>> = all.iter().filter_map(|v| v.clone().downcast::<NSButton>().ok()).filter(|b: &Retained<NSButton>| !b.isKindOfClass(NSPopUpButton::class())).collect();
    let by_title = |t: &str| buttons.iter().find(|b| b.title().to_string() == t).cloned();
    let style_of = |t: &str| by_title(t).map(|b| b.bezelStyle());
    let glass = if ferrokit::has_liquid_glass() { NSBezelStyle::Glass } else { NSBezelStyle::Push };
    let styles = style_of("Standard") == Some(NSBezelStyle::Push)
        && by_title("Borderless").is_some_and(|b| !b.isBordered())
        && style_of("Inline") == Some(NSBezelStyle::Badge)
        && style_of("Recessed") == Some(NSBezelStyle::AccessoryBar)
        && style_of("Toolbar") == Some(NSBezelStyle::Toolbar)
        && style_of("Glass") == Some(glass)
        && buttons.iter().any(|b| b.bezelStyle() == NSBezelStyle::Circular);
    let sizes = by_title("Small").map(|b| b.controlSize()) == Some(NSControlSize::Small) && by_title("Large").map(|b| b.controlSize()) == Some(NSControlSize::Large);
    let destructive = by_title("Delete").is_some_and(|b| b.hasDestructiveAction());
    check("button-styles", styles && sizes && destructive, format!("styles {styles}; sizes {sizes}; destructive {destructive}"));

    // Help: AppKit's round "?" button, named, and it acts.
    let help = buttons.iter().find(|b| b.bezelStyle() == NSBezelStyle::HelpButton).cloned();
    if let Some(h) = &help {
        // SAFETY: clicking a button on the main thread.
        unsafe { h.performClick(None) };
    }
    let help_name = help.as_ref().and_then(|h| objc2_app_kit::NSAccessibility::accessibilityLabel(&**h)).map(|l| l.to_string());
    check("help-button", help.is_some() && helped.get_untracked() == 1 && help_name.as_deref() == Some("Help"), format!("found {}; pressed {}; named {help_name:?}", help.is_some(), helped.get_untracked()));

    // Menu button: a pull-down showing its title; an item acts; a disabled
    // condition is read when the menu opens.
    let export = pulls.iter().find(|p| p.titleOfSelectedItem().is_some_and(|t| t.to_string() == "Export") || p.itemTitleAtIndex(0).to_string() == "Export").cloned();
    let titles: Vec<String> = export.as_ref().map(|p| p.itemTitles().iter().map(|t| t.to_string()).collect()).unwrap_or_default();
    let pulls_down = export.as_ref().is_some_and(|p| p.pullsDown());
    if let Some(menu) = export.as_ref().and_then(|p| p.menu()) {
        menu.performActionForItemAtIndex(1);
    }
    let acted = exported.get_untracked() == "csv";
    batch(|| busy.set(true));
    let pdf_enabled_when_busy = export.as_ref().and_then(|p| p.menu()).map(|m| {
        m.update();
        m.itemAtIndex(3).is_some_and(|i| i.isEnabled())
    });
    let n = pulls.len();
    check(
        "menu-button",
        n == 2 && pulls_down && titles.first().map(String::as_str) == Some("Export") && acted && pdf_enabled_when_busy == Some(false),
        format!("{n} pull-downs; pulls down {pulls_down}; items {titles:?}; CSV… acts {acted}; PDF… enabled while busy {pdf_enabled_when_busy:?}"),
    );

    let problems = ferrokit::testing::ax_audit(&w);
    check("buttons-accessibility", problems.is_empty(), format!("{problems:?}"));
    if let Ok(dir) = std::env::var("SNAP") {
        snapshot_windows(&dir);
    }
    ferrokit::close_window(&w);
    after_events(move || slider_kind_checks(events.clone()));
}

/// C2: tick marks, a vertical slider and a dial, a spinner, control sizes.
fn slider_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{ControlSize, progress, slider};
    use objc2_app_kit::{NSControlSize, NSProgressIndicator, NSProgressIndicatorStyle, NSSlider, NSSliderType};
    let level = Signal::new(50.0);
    let volume = Signal::new(0.3);
    let angle = Signal::new(90.0);
    let loading = Signal::new(None::<f64>);
    let w = open(Window::new("Sliders").size(420.0, 220.0).view(
        hstack((
            vstack((
                slider(&level, 0.0, 100.0).ticks(11).snap_to_ticks().accessibility_label("Level"),
                slider(&level, 0.0, 100.0).control_size(ControlSize::Small).accessibility_label("Level, small"),
                hstack((progress(move || loading.get()).spinner().accessibility_label("Loading"), text("Loading…"))).spacing(6.0),
            ))
            .spacing(12.0),
            slider(&volume, 0.0, 1.0).vertical().accessibility_label("Volume"),
            slider(&angle, 0.0, 360.0).circular().accessibility_label("Angle"),
        ))
        .spacing(16.0)
        .padding(16.0),
    ));
    let all = all_views(&w.contentView().unwrap());
    let sliders: Vec<Retained<NSSlider>> = all.iter().filter_map(|v| v.clone().downcast::<NSSlider>().ok()).collect();
    let ticked = sliders.iter().find(|s| s.numberOfTickMarks() == 11).cloned();
    let small = sliders.iter().find(|s| s.controlSize() == NSControlSize::Small).cloned();
    let vertical = sliders.iter().find(|s| s.isVertical()).cloned();
    let dial = sliders.iter().find(|s| s.sliderType() == NSSliderType::Circular).cloned();
    let ticks = ticked.as_ref().is_some_and(|s| s.allowsTickMarkValuesOnly()) && small.is_some();
    // The vertical slider fills the content's height; the dial keeps its size.
    let tall = vertical.as_ref().map(|s| s.frame().size);
    let upright = tall.is_some_and(|f| f.height > 150.0 && f.height > f.width * 3.0);
    let round = dial.as_ref().map(|s| s.frame().size).is_some_and(|f| (f.width - f.height).abs() < 4.0 && f.width < 60.0);
    if let Some(d) = &dial {
        d.setDoubleValue(270.0);
        send_action(d);
    }
    batch(|| volume.set(0.8));
    let both_ways = angle.get_untracked() == 270.0 && vertical.as_ref().is_some_and(|s| (s.doubleValue() - 0.8).abs() < 1e-9);
    check(
        "slider-kinds",
        sliders.len() == 4 && ticks && upright && round && both_ways,
        format!("{} sliders; ticks and snap {ticks}; vertical {tall:?}; dial round {round}; dial → {}, signal → vertical {both_ways}", sliders.len(), angle.get_untracked()),
    );

    // The spinner: spinning while unknown, then a filling circle.
    let spinner = all.iter().find_map(|v| v.clone().downcast::<NSProgressIndicator>().ok());
    let spinning = spinner.as_ref().is_some_and(|p| p.style() == NSProgressIndicatorStyle::Spinning && p.isIndeterminate());
    batch(|| loading.set(Some(0.4)));
    let known = spinner.as_ref().is_some_and(|p| !p.isIndeterminate() && (p.doubleValue() - 0.4).abs() < 1e-9);
    let size = spinner.as_ref().map(|p| p.frame().size);
    check("spinner", spinning && known && size.is_some_and(|s| s.width > 8.0 && s.width < 40.0), format!("spinning while unknown {spinning}; 0.4 shown {known}; size {size:?}"));

    let problems = ferrokit::testing::ax_audit(&w);
    check("sliders-accessibility", problems.is_empty(), format!("{problems:?}"));
    if let Ok(dir) = std::env::var("SNAP") {
        snapshot_windows(&dir);
    }
    ferrokit::close_window(&w);
    after_events(move || symbol_effect_checks(events.clone()));
}

/// C3: SF Symbol effects: one running while a signal is true, one played
/// when a value changes (not when the view is built).
fn symbol_effect_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::symbol_effects;
    use ferrokit::{SymbolEffect, image};
    fn animating(layer: &objc2_quartz_core::CALayer) -> bool {
        // SAFETY: reading a layer's sublayers on the main thread.
        let subs = unsafe { layer.sublayers() };
        layer.animationKeys().is_some_and(|k| k.count() > 0) || subs.is_some_and(|s| s.iter().any(|l| animating(&l)))
    }
    let searching = Signal::new(false);
    let unread = Signal::new(0u32);
    let before = symbol_effects();
    let w = open(Window::new("Symbol effects").size(240.0, 100.0).view(
        hstack((
            image("wifi").symbol_size(28.0).effect(SymbolEffect::VariableColor, move || searching.get()).description("Wi-Fi"),
            image("bell.fill").symbol_size(28.0).effect_on(SymbolEffect::Bounce, move || unread.get()).description("Notifications"),
        ))
        .spacing(20.0)
        .padding(20.0),
    ));
    let supported = objc2::runtime::AnyClass::get(c"NSSymbolBounceEffect").is_some();
    let built = symbol_effects();
    batch(|| searching.set(true));
    let on = symbol_effects();
    let wifi = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSImageView>().ok());
    let layers = wifi.as_ref().and_then(|v| v.layer()).is_some_and(|l| animating(&l));
    batch(|| searching.set(false));
    let off = symbol_effects();
    batch(|| unread.set(3));
    let bounced = symbol_effects();
    check(
        "symbol-effects",
        supported && built == before && on.0 == before.0 + 1 && off.0 == before.0 && bounced.1 == before.1 + 1,
        format!("before {before:?}; built {built:?}; searching {on:?} (layers animating {layers}); stopped {off:?}; after a change {bounced:?}"),
    );
    ferrokit::close_window(&w);
    after_events(move || window_panel_checks(events.clone()));
}

/// C4: floating, utility and HUD panels: NSPanels that float, hide with the
/// app, leave the Window menu alone and take the keyboard only when needed.
fn window_panel_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::PanelStyle;
    use objc2::ClassType;
    use objc2_app_kit::{NSPanel, NSWindow, NSWindowStyleMask};
    use objc2_foundation::NSObjectProtocol;
    let kinds = [(PanelStyle::Floating, "Inspector"), (PanelStyle::Utility, "Tools"), (PanelStyle::Hud, "Adjust")];
    let panels: Vec<Retained<NSWindow>> =
        kinds.iter().map(|(k, t)| open(Window::new(t).size(220.0, 140.0).panel(*k).view(vstack((text(*t), button("OK", || {}))).padding(12.0)))).collect();
    let mut notes = Vec::new();
    let mut ok = true;
    for (w, (kind, _)) in panels.iter().zip(kinds) {
        let is_panel = w.isKindOfClass(NSPanel::class());
        let panel = w.clone().downcast::<NSPanel>().ok();
        let floats = panel.as_ref().is_some_and(|p| p.isFloatingPanel() && p.becomesKeyOnlyIfNeeded()) && w.level() == objc2_app_kit::NSFloatingWindowLevel;
        let behaves = w.hidesOnDeactivate() && w.isExcludedFromWindowsMenu() && !w.styleMask().contains(NSWindowStyleMask::Miniaturizable);
        let mask = w.styleMask();
        let look = match kind {
            PanelStyle::Floating => !mask.contains(NSWindowStyleMask::UtilityWindow),
            PanelStyle::Utility => mask.contains(NSWindowStyleMask::UtilityWindow) && !mask.contains(NSWindowStyleMask::HUDWindow),
            _ => mask.contains(NSWindowStyleMask::HUDWindow),
        };
        ok &= is_panel && floats && behaves && look;
        notes.push(format!("{kind:?}: panel {is_panel}, floats {floats}, hides and stays out of the Window menu {behaves}, look {look}"));
    }
    check("panels", ok, notes.join("; "));
    if let Ok(dir) = std::env::var("SNAP") {
        snapshot_windows(&dir);
    }
    for w in &panels {
        ferrokit::close_window(w);
    }
    after_events(move || hidden_checks(events.clone()));
}

/// L4: `.hidden(..)` hides a view without rebuilding it, and it takes no
/// room; a hidden view inside another waits for it; a `dynamic` replaced
/// while hidden shows its new content.
fn hidden_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let (middle, outer, inner, version) = (Signal::new(true), Signal::new(false), Signal::new(false), Signal::new(1));
    let w = open(
        Window::new("Hidden").size(260.0, 260.0).view(
            vstack((
                text("Top"),
                text("Middle").hidden(move || middle.get()),
                text("Bottom"),
                vstack((text("Outer"), text("Inner").hidden(move || inner.get()), dynamic(move || text(format!("Version {}", version.get())))))
                    .hidden(move || outer.get()),
                spacer(),
            ))
            .padding(12.0),
        ),
    );
    let label = {
        let w = w.clone();
        move |t: &str| w.contentView().unwrap().subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == t)
    };
    let mid_y = |f: &NSTextField| f.frame().origin.y + f.frame().size.height / 2.0;
    after_events(move || {
        let (top, mid, bottom) = (label("Top").unwrap(), label("Middle").unwrap(), label("Bottom").unwrap());
        let gap_hidden = (mid_y(&bottom) - mid_y(&top)).abs();
        let hidden = mid.isHidden() && !top.isHidden() && !bottom.isHidden();
        middle.set(false);
        let (label, events) = (label.clone(), events.clone());
        after_events(move || {
            let (top, bottom, mid2) = (label("Top").unwrap(), label("Bottom").unwrap(), label("Middle").unwrap());
            let gap_shown = (mid_y(&bottom) - mid_y(&top)).abs();
            let kept = std::ptr::eq(&*mid, &*mid2);
            check(
                "hidden-takes-no-room",
                hidden && !mid2.isHidden() && kept && gap_shown > gap_hidden * 1.6,
                format!("hidden {hidden}, shown {}, same view {kept}; Top to Bottom {gap_hidden:.1} hidden, {gap_shown:.1} shown", !mid2.isHidden()),
            );
            // Nested: the inner view shown while the outer is hidden stays
            // hidden until the outer shows; a dynamic replaced while hidden
            // shows its new content.
            batch(|| {
                inner.set(true);
                outer.set(true);
            });
            let (label, events) = (label.clone(), events.clone());
            after_events(move || {
                let all_hidden = ["Outer", "Inner", "Version 1"].iter().all(|t| label(t).is_some_and(|f| f.isHidden()));
                inner.set(false);
                version.set(2);
                let (label, events) = (label.clone(), events.clone());
                after_events(move || {
                    let waits = label("Inner").is_some_and(|f| f.isHidden());
                    outer.set(false);
                    let (label, events) = (label.clone(), events.clone());
                    after_events(move || {
                        let shown = ["Outer", "Inner", "Version 2"].iter().all(|t| label(t).is_some_and(|f| !f.isHidden()));
                        let replaced = label("Version 1").is_none();
                        check("hidden-nested-and-dynamic", all_hidden && waits && shown && replaced, format!("all hidden {all_hidden}, inner waits {waits}, all shown {shown}, old version gone {replaced}"));
                        if let Some(w) = windows().into_iter().find(|w| w.title().to_string() == "Hidden") {
                            ferrokit::close_window(&w);
                        }
                        let events = events.clone();
                        after_events(move || native_checks(events.clone()));
                    });
                });
            });
        });
    });
}

mod swatch {
    //! A view the app draws itself (L3's custom `NSView`): a filled
    //! rectangle that counts its instances and draws, takes the focus, and
    //! reads as an image to VoiceOver.
    use std::cell::Cell;

    use objc2::rc::Retained;
    use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
    use objc2_app_kit::{NSBezierPath, NSColor, NSView};
    use objc2_foundation::{NSCopying, NSRect, NSString};

    thread_local! {
        /// Swatches alive now (made minus deallocated).
        pub static LIVE: Cell<i64> = const { Cell::new(0) };
    }

    pub struct State {
        /// Its height, set by an update and read by its measure.
        pub height: Cell<f64>,
        pub draws: Cell<u32>,
        /// Times it was marked for display.
        pub marked: Cell<u32>,
    }

    impl Drop for State {
        fn drop(&mut self) {
            let _ = LIVE.try_with(|l| l.set(l.get() - 1));
        }
    }

    define_class!(
        #[unsafe(super(NSView))]
        #[thread_kind = MainThreadOnly]
        #[name = "ChecklistSwatch"]
        #[ivars = State]
        pub struct Swatch;

        impl Swatch {
            #[unsafe(method(drawRect:))]
            fn draw_rect(&self, _dirty: NSRect) {
                self.ivars().draws.set(self.ivars().draws.get() + 1);
                NSColor::systemTealColor().setFill();
                NSBezierPath::fillRect(self.bounds());
            }

            #[unsafe(method(setNeedsDisplay:))]
            fn set_needs_display(&self, flag: bool) {
                if flag {
                    self.ivars().marked.set(self.ivars().marked.get() + 1);
                }
                // SAFETY: NSView's own method.
                let () = unsafe { msg_send![super(self), setNeedsDisplay: flag] };
            }

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

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

            #[unsafe(method_id(accessibilityRole))]
            fn accessibility_role(&self) -> Option<Retained<NSString>> {
                // SAFETY: AppKit's constant.
                Some(unsafe { objc2_app_kit::NSAccessibilityImageRole }.copy())
            }
        }
    );

    impl Swatch {
        pub fn new(mtm: MainThreadMarker) -> Retained<Swatch> {
            LIVE.with(|l| l.set(l.get() + 1));
            let this = Swatch::alloc(mtm).set_ivars(State { height: Cell::new(20.0), draws: Cell::new(0), marked: Cell::new(0) });
            // SAFETY: NSView's designated initialiser.
            unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] }
        }
    }
}
use swatch::Swatch;

/// L3: custom native views (`native`): layout, updates, focus,
/// accessibility and teardown, with a view the checklist draws itself.
fn native_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{AnyView, Size, native};
    use objc2::DefinedClass;
    use objc2::rc::Weak;
    type Held = Rc<RefCell<Option<Weak<Swatch>>>>;
    let hold = |h: &Held, s: &Retained<Swatch>| *h.borrow_mut() = Some(Weak::from_retained(s));
    let get = |h: &Held| h.borrow().as_ref().and_then(Weak::load);
    let (measured, focusable, filler): (Held, Held, Held) = Default::default();
    let tall = Signal::new(30.0);
    let (runs, removed) = (Rc::new(Cell::new(0u32)), Rc::new(Cell::new(0u32)));
    let (first, second) = (Signal::new("one".to_string()), Signal::new("two".to_string()));
    let lives_before = swatch::LIVE.with(Cell::get);
    let w = {
        let (m, f, fl, r, rm) = (measured.clone(), focusable.clone(), filler.clone(), runs.clone(), removed.clone());
        open(
            Window::new("Native").size(300.0, 400.0).view(
                vstack((
                    text("Above"),
                    native(move |mtm| {
                        let s = Swatch::new(mtm);
                        hold(&m, &s);
                        s
                    })
                    .update(move |s| {
                        s.ivars().height.set(tall.get());
                        r.set(r.get() + 1);
                    })
                    .measure(|s| Size { w: 80.0, h: s.ivars().height.get() })
                    .flexible(false, false)
                    .on_remove(move |_| rm.set(rm.get() + 1))
                    .accessibility_label("Measured swatch"),
                    text("Below"),
                    hstack((
                        text_field(&first).accessibility_label("First"),
                        native(move |mtm| {
                            let s = Swatch::new(mtm);
                            hold(&f, &s);
                            s
                        })
                        .measure(|_| Size { w: 40.0, h: 20.0 })
                        .flexible(false, false)
                        .accessibility_label("Focusable swatch"),
                        text_field(&second).accessibility_label("Second"),
                    )),
                    // No name: the audit should report it.
                    native(move |mtm| {
                        let s = Swatch::new(mtm);
                        hold(&fl, &s);
                        s
                    })
                    .min_height(50.0),
                ))
                .padding(12.0),
            ),
        )
    };
    let label = {
        let w = w.clone();
        move |t: &str| w.contentView().unwrap().subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == t)
    };
    let mid_y = |v: &NSView| v.frame().origin.y + v.frame().size.height / 2.0;
    after_events(move || {
        let (Some(m), Some(fl)) = (get(&measured), get(&filler)) else {
            check("native-layout", false, "the swatches weren't built".into());
            return;
        };
        let size = m.frame().size;
        let content_w = w.contentView().unwrap().frame().size.width;
        let fills = (fl.frame().size.width - (content_w - 24.0)).abs() < 1.0 && fl.frame().size.height >= 50.0;
        check(
            "native-layout",
            (size.width, size.height) == (80.0, 30.0) && fills,
            format!("measured {}×{} (80×30); the flexible one {}×{} in {content_w} (fills, at least 50 high)", size.width, size.height, fl.frame().size.width, fl.frame().size.height),
        );
        let gap = (mid_y(&label("Below").unwrap()) - mid_y(&label("Above").unwrap())).abs();
        let marked = m.ivars().marked.get();
        tall.set(60.0);
        let (label, measured, focusable, w, runs, removed, events) = (label.clone(), measured.clone(), focusable.clone(), w.clone(), runs.clone(), removed.clone(), events.clone());
        after_events(move || {
            let m = get(&measured).unwrap();
            let gap2 = (mid_y(&label("Below").unwrap()) - mid_y(&label("Above").unwrap())).abs();
            let redrawn = m.ivars().marked.get() > marked;
            check(
                "native-update",
                runs.get() == 2 && m.frame().size.height == 60.0 && (gap2 - gap - 30.0).abs() < 1.0 && redrawn,
                format!("update ran {} times (2); height {} (60); Above to Below {gap:.0} → {gap2:.0}; marked for display {redrawn}", runs.get(), m.frame().size.height),
            );
            let audit = ferrokit::testing::ax_audit(&w);
            let named = ferrokit::testing::ax_elements(&w).iter().any(|e| e.role == "AXImage" && e.name == "Measured swatch");
            check(
                "native-accessibility",
                named && audit.len() == 1 && audit[0].contains("AXImage"),
                format!("named swatch read as an image {named}; audit {audit:?} (only the unnamed one)"),
            );
            // Then teardown: the window closed, and a hundred views through a dynamic.
            let finish = {
                let (w, runs, removed, measured, events) = (w.clone(), runs.clone(), removed.clone(), measured.clone(), events.clone());
                move || {
                    ferrokit::close_window(&w);
                    let (runs, removed, measured, events) = (runs.clone(), removed.clone(), measured.clone(), events.clone());
                    after_events(move || {
                        tall.set(90.0);
                        let after = runs.get();
                        let lives = swatch::LIVE.with(Cell::get);
                        let gone = get(&measured).is_none();
                        // A hundred at a time through a dynamic, three times.
                        let show = Signal::new(false);
                        let removals = Rc::new(Cell::new(0u32));
                        let rm = removals.clone();
                        let w2 = open(Window::new("Native Cycles").size(200.0, 200.0).view(dynamic(move || {
                            if show.get() {
                                let rm = rm.clone();
                                AnyView::new(vstack(
                                    (0..100)
                                        .map(|_| {
                                            let rm = rm.clone();
                                            AnyView::new(native(Swatch::new).flexible(false, false).measure(|_| Size { w: 4.0, h: 1.0 }).on_remove(move |_| rm.set(rm.get() + 1)))
                                        })
                                        .collect::<Vec<_>>(),
                                ))
                            } else {
                                AnyView::new(text("None"))
                            }
                        })));
                        let nodes = live_nodes();
                        let mut peak = 0;
                        for _ in 0..3 {
                            show.set(true);
                            peak = peak.max(swatch::LIVE.with(Cell::get) - lives);
                            show.set(false);
                        }
                        let (events, removals, removed) = (events.clone(), removals.clone(), removed.clone());
                        after_events(move || {
                            let back = swatch::LIVE.with(Cell::get) - lives;
                            let nodes_back = live_nodes() == nodes;
                            check(
                                "native-teardown",
                                lives == lives_before && gone && after == 2 && removed.get() == 1 && peak == 100 && back == 0 && removals.get() == 300 && nodes_back,
                                format!(
                                    "closed window: swatches alive {} (0), update after close {} (none), on_remove {}; a dynamic three times: {peak} built, {back} left, on_remove {} (300), nodes back {nodes_back}",
                                    lives - lives_before,
                                    after - 2,
                                    removed.get(),
                                    removals.get()
                                ),
                            );
                            ferrokit::close_window(&w2);
                            let events = events.clone();
                            after_events(move || table_selection_checks(events.clone()));
                        });
                    });
                }
            };
            // Tab order: First → the swatch → Second (AppKit's key view
            // loop), by real Tab keys when the app can be active, else by
            // AppKit's own entry point.
            let field = |t: &str| label(t).unwrap();
            let (a, b, sw) = (field("one"), field("two"), get(&focusable).unwrap());
            let real = ferrokit::testing::input::ready(&w);
            let tab = {
                let w = w.clone();
                move |from: &NSView| {
                    if real {
                        ferrokit::testing::input::key(&w, ferrokit::testing::input::Key::Tab, &[]);
                    } else {
                        w.selectKeyViewFollowingView(from);
                    }
                }
            };
            let made = w.makeFirstResponder(Some(&a));
            let before = input_state();
            tab(&a);
            // Posted keys arrive in their own time: wait for the focus to move.
            let on_swatch = {
                let (w, sw) = (w.clone(), sw.clone());
                move || w.firstResponder().is_some_and(|r| std::ptr::eq(&*r as *const _ as *const u8, &*sw as *const _ as *const u8))
            };
            let sw2 = sw.clone();
            until(on_swatch.clone(), 2000, move || {
                let into_swatch = on_swatch();
                tab(&sw2);
                let b2 = b.clone();
                until(move || b2.currentEditor().is_some(), 2000, move || {
                    let into_second = b.currentEditor().is_some();
                    let pass = made && into_swatch && into_second;
                    let state = if pass { String::new() } else { format!(" (when the Tab was sent: {before}; now: {})", input_state()) };
                    check(
                        "native-focus",
                        pass,
                        format!("Tab ({}) from the first field reaches the swatch {into_swatch}, then the second field {into_second}{state}", if real { "real keys" } else { "AppKit's key view loop, app not active" }),
                    );
                    finish();
                });
            });
        });
    });
}

/// L4: a table's selection bound to a signal, both ways.
fn table_selection_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let model = Rc::new(TableModel::new(ViewId(960), vec![Column::text("n", "N", |n: &u32| n.to_string())]));
    model.set_rows((0..6).collect());
    let selected = Signal::new(Vec::<usize>::new());
    let pressed = Rc::new(RefCell::new(Vec::new()));
    let (p1, p2) = (pressed.clone(), pressed.clone());
    let w = open(
        Window::new("Bound Selection").size(240.0, 260.0).view(
            table(&model)
                .selection(&selected)
                .on_key(TableKey::Delete, move |rows| p1.borrow_mut().push(format!("delete {rows:?}")))
                .on_key(TableKey::Space, move |rows| p2.borrow_mut().push(format!("space {rows:?}"))),
        ),
    );
    let m = model.clone();
    after_events(move || {
        // The signal selects (any order).
        selected.set(vec![3, 1]);
        let from_signal = m.selection();
        // The user selects: the table tells the signal.
        let set = objc2_foundation::NSIndexSet::indexSetWithIndex(4);
        m.table_view().selectRowIndexes_byExtendingSelection(&set, false);
        let (m, w, events, pressed) = (m.clone(), w.clone(), events.clone(), pressed.clone());
        after_events(move || {
            let from_user = selected.get_untracked();
            // Replacing the rows clears the selection, and the signal follows.
            m.set_rows((10..16).collect());
            let (m, w, events, from_signal, pressed) = (m.clone(), w.clone(), events.clone(), from_signal.clone(), pressed.clone());
            after_events(move || {
                let cleared = selected.get_untracked();
                selected.set(vec![5]);
                let again = m.selection();
                // Bare keys: Delete, Forward Delete and Space reach the app
                // with the selection; with ⌘ they don't.
                let tv = m.table_view();
                let key = |code: u16, chars: &str, flags: NSEventModifierFlags| {
                    let e = objc2_app_kit::NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
                        objc2_app_kit::NSEventType::KeyDown,
                        objc2_foundation::NSPoint::new(0.0, 0.0),
                        flags,
                        0.0,
                        w.windowNumber(),
                        None,
                        &NSString::from_str(chars),
                        &NSString::from_str(chars),
                        false,
                        code,
                    )
                    .unwrap();
                    let _: () = unsafe { objc2::msg_send![&*tv, keyDown: &*e] };
                };
                key(51, "\u{7f}", NSEventModifierFlags::empty());
                key(117, "\u{f728}", NSEventModifierFlags::Function);
                key(49, " ", NSEventModifierFlags::empty());
                key(51, "\u{7f}", NSEventModifierFlags::Command);
                check(
                    "table-selection-bound",
                    from_signal == [1, 3] && from_user == [4] && cleared.is_empty() && again == [5],
                    format!("signal [3, 1] → table {from_signal:?}; user picks 4 → signal {from_user:?}; set_rows → signal {cleared:?}; signal [5] → table {again:?}"),
                );
                // A date column: sorted by date (no date first), shown in
                // the user's format, copied as shown.
                let day = |secs: u64| std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs);
                let dated = Rc::new(TableModel::new(
                    ViewId(961),
                    vec![Column::text("name", "Name", |r: &(&str, Option<std::time::SystemTime>)| r.0.to_string()), Column::date("when", "Date Modified", |r: &(&str, Option<std::time::SystemTime>)| r.1)],
                ));
                dated.set_rows(vec![("now", Some(std::time::SystemTime::now())), ("never", None), ("2020", Some(day(1_600_000_000))), ("2001", Some(day(1_000_000_000)))]);
                dated.set_sort(Some(Sort { column: "when".into(), ascending: true }));
                dated.select(&[0, 1, 2, 3]);
                let copied = dated.selected_text();
                let lines: Vec<&str> = copied.lines().collect();
                let names: Vec<&str> = lines.iter().map(|l| l.split('\t').next().unwrap_or("")).collect();
                let shown_2020 = lines.iter().find(|l| l.starts_with("2020\t")).map(|l| l.split('\t').nth(1).unwrap_or("").to_string()).unwrap_or_default();
                let never_empty = lines.iter().any(|l| *l == "never\t" || *l == "never");
                check(
                    "table-date-column",
                    names == ["never", "2001", "2020", "now"] && shown_2020.contains("2020") && never_empty,
                    format!("sorted {names:?}; 2020 shown as {shown_2020:?}; no date shown empty {never_empty}; copied {copied:?}"),
                );
                let (pressed, w, events) = (pressed.clone(), w.clone(), events.clone());
                after_events(move || {
                    let keys = pressed.borrow().clone();
                    check("table-bare-keys", keys == ["delete [5]", "delete [5]", "space [5]"], format!("{keys:?} (⌘⌫ not among them)"));
                    ferrokit::close_window(&w);
                    let events = events.clone();
                    after_events(move || table_focus_checks(events.clone()));
                });
            });
        });
    });
}

/// Cell focus: ← → move the focused column, the selected row outlines it,
/// a signal holds it both ways, and a click focuses the clicked column.
fn table_focus_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let model = Rc::new(TableModel::new(
        ViewId(962),
        vec![Column::text("a", "A", |n: &u32| format!("a{n}")), Column::text("b", "B", |n: &u32| format!("b{n}")), Column::number("c", "C", |n: &u32| f64::from(*n))],
    ));
    model.set_rows((0..5).collect());
    let focus = Signal::new(None::<String>);
    let w = open(Window::new("Cell Focus").size(360.0, 220.0).view(table(&model).cell_focus(&focus)));
    let m = model.clone();
    after_events(move || {
        m.select(&[1]);
        let tv = m.table_view();
        let key = |code: u16, flags: NSEventModifierFlags| {
            let chars = if code == 123 { "\u{f702}" } else { "\u{f703}" };
            let e = objc2_app_kit::NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
                objc2_app_kit::NSEventType::KeyDown,
                objc2_foundation::NSPoint::new(0.0, 0.0),
                flags | NSEventModifierFlags::Function | NSEventModifierFlags::NumericPad,
                0.0,
                w.windowNumber(),
                None,
                &NSString::from_str(chars),
                &NSString::from_str(chars),
                false,
                code,
            )
            .unwrap();
            let _: () = unsafe { objc2::msg_send![&*tv, keyDown: &*e] };
        };
        // → from nothing focuses the first column; → → reaches the last and
        // stays; ← goes back one; ⇧→ is AppKit's, not a move.
        let mut seen = Vec::new();
        for (code, flags) in [(124, NSEventModifierFlags::empty()), (124, NSEventModifierFlags::empty()), (124, NSEventModifierFlags::empty()), (124, NSEventModifierFlags::empty()), (123, NSEventModifierFlags::empty()), (124, NSEventModifierFlags::Shift)] {
            key(code, flags);
            seen.push(m.focused_column().unwrap_or_default());
        }
        let (m, w, events, tv) = (m.clone(), w.clone(), events.clone(), tv.clone());
        after_events(move || {
            let from_keys = focus.get_untracked();
            tv.displayIfNeeded();
            let ring = m.focus_ring(1);
            let col_b = tv.rectOfColumn(1);
            let ring_on_b = ring.is_some_and(|(x, _, width, _)| (x - col_b.origin.x - 1.5).abs() < 1.0 && (width - (col_b.size.width - 3.0)).abs() < 1.0);
            let no_ring_unselected = m.focus_ring(2).is_none();
            check(
                "table-cell-focus-keys",
                seen == ["a", "b", "c", "c", "b", "b"] && from_keys.as_deref() == Some("b") && ring_on_b && no_ring_unselected,
                format!("after → → → → ← ⇧→: {seen:?}; signal {from_keys:?}; ring {ring:?} on column B ({:.0}, {:.0} wide) {ring_on_b}; unselected row has none {no_ring_unselected}", col_b.origin.x, col_b.size.width),
            );
            // The signal moves the focus; replacing the columns without it clears it.
            focus.set(Some("c".into()));
            let (m, w, events, tv) = (m.clone(), w.clone(), events.clone(), tv.clone());
            after_events(move || {
                let from_signal = m.focused_column();
                m.set_columns(vec![Column::text("a", "A", |n: &u32| format!("a{n}")), Column::text("b", "B", |n: &u32| format!("b{n}"))]);
                let (m, w, events, tv) = (m.clone(), w.clone(), events.clone(), tv.clone());
                after_events(move || {
                    let cleared = (m.focused_column(), focus.get_untracked());
                    check(
                        "table-cell-focus-signal",
                        from_signal.as_deref() == Some("c") && cleared == (None, None),
                        format!("signal c → table {from_signal:?}; after its column is removed: table and signal {cleared:?}"),
                    );
                    // A real click on a cell in column A focuses it (needs the
                    // app in front to take posted clicks; `ready` can take a turn).
                    ferrokit::testing::input::ready(&w);
                    let (m, w, events, tv) = (m.clone(), w.clone(), events.clone(), tv.clone());
                    wait(300, move || {
                        let clicked = ferrokit::testing::input::ready(&w);
                        let before = input_state();
                        if clicked {
                            let r = tv.frameOfCellAtColumn_row(0, 3);
                            let view: &objc2_app_kit::NSView = &tv;
                            ferrokit::testing::input::click_at(view, r.origin.x + 10.0, r.origin.y + r.size.height / 2.0);
                        }
                        // Posted clicks arrive in their own time.
                        let (m, w, events) = (m.clone(), w.clone(), events.clone());
                        wait(300, move || {
                            if clicked {
                                let got = (m.focused_column(), focus.get_untracked(), m.selection());
                                let pass = got == (Some("a".into()), Some("a".into()), vec![3]);
                                let state = if pass { String::new() } else { format!(" (when the click was sent: {before}; now: {})", input_state()) };
                                check("table-cell-focus-click", pass, format!("click on row 3, column A: table, signal, selection {got:?}{state}"));
                            } else {
                                eprintln!("[check] table-cell-focus-click SKIP the app isn't in front, so posted clicks don't arrive");
                            }
                            ferrokit::close_window(&w);
                            let events = events.clone();
                            after_events(move || preview_checks(events.clone()));
                        });
                    });
                });
            });
        });
    });
}

/// Preview mode (`cargo ferrokit preview`): a window keeps its frame across
/// restarts by its title, without `remember_frame`.
fn preview_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_foundation::{NSPoint, NSRect, NSSize, NSUserDefaults};
    let key = NSString::from_str("NSWindow Frame ferrokit preview Preview Frame");
    let defaults = NSUserDefaults::standardUserDefaults();
    defaults.removeObjectForKey(&key);
    ferrokit::testing::set_preview_mode(true);
    let first = open(Window::new("Preview Frame").size(300.0, 160.0).view(text("Where it was")));
    let moved = NSRect::new(NSPoint::new(140.0, 180.0), NSSize::new(420.0, 260.0));
    first.setFrame_display(moved, true);
    let moved = first.frame();
    ferrokit::close_window(&first);
    after_events(move || {
        // The app restarts: the same window opens where it was left.
        let again = open(Window::new("Preview Frame").size(300.0, 160.0).view(text("Where it was")));
        let back = again.frame();
        ferrokit::close_window(&again);
        // Outside a preview, a window without `remember_frame` opens centred at its size.
        ferrokit::testing::set_preview_mode(false);
        let plain = open(Window::new("Preview Frame").size(300.0, 160.0).view(text("Where it was")));
        let plain_size = plain.contentRectForFrameRect(plain.frame()).size;
        ferrokit::close_window(&plain);
        NSUserDefaults::standardUserDefaults().removeObjectForKey(&NSString::from_str("NSWindow Frame ferrokit preview Preview Frame"));
        let same = |a: NSRect, b: NSRect| (a.origin.x - b.origin.x).abs() < 1.0 && (a.origin.y - b.origin.y).abs() < 1.0 && (a.size.width - b.size.width).abs() < 1.0 && (a.size.height - b.size.height).abs() < 1.0;
        check(
            "preview-keeps-window-frames",
            same(moved, back) && (plain_size.width - 300.0).abs() < 1.0,
            format!("moved to {moved:?}; reopened at {back:?}; outside a preview {:.0}×{:.0}", plain_size.width, plain_size.height),
        );
        let events = events.clone();
        after_events(move || tabs_and_dock_checks(events.clone()));
    });
}

/// C5: windows as tabs, no full screen, the Dock badge and the Dock menu.
fn tabs_and_dock_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Tabbing, dock_badge, is_full_screen, open_tab, set_dock_badge};
    use objc2_app_kit::{NSWindowCollectionBehavior, NSWindowTabbingMode};
    let a = open(Window::new("Tab A").size(360.0, 200.0).tabbing(Tabbing::Preferred, Some("checklist-docs")).view(text("A")));
    let b = open_tab(&a, Window::new("Tab B").size(360.0, 200.0).tabbing(Tabbing::Preferred, Some("checklist-docs")).view(text("B")));
    let tabs: Vec<String> = a.tabbedWindows().map(|t| t.iter().map(|w| w.title().to_string()).collect()).unwrap_or_default();
    let grouped = a.tabbingIdentifier().to_string() == "checklist-docs" && a.tabbingMode() == NSWindowTabbingMode::Preferred;
    check("window-tabs", tabs.len() == 2 && tabs.contains(&"Tab B".to_string()) && grouped && b.isVisible(), format!("tabs {tabs:?}; group and mode {grouped}"));
    ferrokit::close_window(&b);
    ferrokit::close_window(&a);

    let palette = open(Window::new("Palette").size(200.0, 120.0).no_full_screen().view(text("Tools")));
    let behaviour = palette.collectionBehavior();
    let normal = open(Window::new("Normal").size(200.0, 120.0).view(text("Doc")));
    let can = !normal.collectionBehavior().contains(NSWindowCollectionBehavior::FullScreenNone);
    check(
        "full-screen-option",
        behaviour.contains(NSWindowCollectionBehavior::FullScreenNone) && !behaviour.contains(NSWindowCollectionBehavior::FullScreenPrimary) && can && !is_full_screen(&normal),
        format!("palette {behaviour:?}; a normal window can go full screen {can}"),
    );
    ferrokit::close_window(&palette);
    ferrokit::close_window(&normal);

    set_dock_badge(Some("3"));
    let shown = dock_badge();
    set_dock_badge(None);
    check("dock-badge", shown.as_deref() == Some("3") && dock_badge().is_none(), format!("set 3 → {shown:?}; cleared → {:?}", dock_badge()));

    // The Dock asks the app's delegate for its menu each time it opens.
    let app = objc2_app_kit::NSApplication::sharedApplication(objc2::MainThreadMarker::new().unwrap());
    let menu: Option<Retained<objc2_app_kit::NSMenu>> = app.delegate().and_then(|d| {
        // SAFETY: Ferrokit's app delegate answers applicationDockMenu:.
        unsafe { objc2::msg_send![&*d, applicationDockMenu: &*app] }
    });
    let items: Vec<String> = menu.map(|m| m.itemArray().iter().map(|i| i.title().to_string()).collect()).unwrap_or_default();
    let fresh = items.get(1).is_some_and(|t| t.ends_with("windows open"));
    check("dock-menu", items.first().map(String::as_str) == Some("New Checklist Window") && fresh, format!("{items:?}"));

    // Links in the app's URL schemes reach App::on_open_url, by the
    // delegate method macOS calls (scripts/check-ferrokit.sh sends a real
    // one to a bundled app); several at once, in order, as macOS gives them.
    let links = ["checklist://open/item%203?from=check", "checklist:settings"];
    let urls: Vec<Retained<objc2_foundation::NSURL>> = links.iter().filter_map(|l| objc2_foundation::NSURL::URLWithString(&NSString::from_str(l))).collect();
    let urls = objc2_foundation::NSArray::from_retained_slice(&urls);
    if let Some(d) = app.delegate() {
        // SAFETY: Ferrokit's app delegate answers application:openURLs:.
        let () = unsafe { objc2::msg_send![&*d, application: &*app, openURLs: &*urls] };
    }
    after_events(move || {
        let got = OPENED_URLS.with_borrow(Clone::clone);
        check("open-url", got == links, format!("sent {links:?}, App::on_open_url got {got:?}"));
        toolbar_kind_checks(events.clone());
    });
}

thread_local! {
    /// The links App::on_open_url got (check `open-url`).
    static OPENED_URLS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

/// C7: toolbar groups, a picker, and a customisable toolbar whose layout is
/// remembered, with an optional item.
fn toolbar_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{toolbar_fixed_space, toolbar_group, toolbar_picker};
    use objc2_app_kit::{NSToolbarItemGroup, NSToolbarItemGroupSelectionMode};
    #[derive(Clone, Copy, PartialEq, Debug)]
    enum Mode {
        List,
        Grid,
    }
    const KEY: &str = "ferrokit.toolbar.checklist-tools";
    let forget = || objc2_foundation::NSUserDefaults::standardUserDefaults().removeObjectForKey(&NSString::from_str(KEY));
    forget();
    let (zoomed, mode, shared) = (Signal::new(0), Signal::new(Mode::List), Signal::new(0));
    let tools = move |title: &str| {
        Window::new(title)
            .size(520.0, 200.0)
            .toolbar(vec![
                toolbar_group("zoom", "Zoom", vec![
                    toolbar_button("out", "Zoom Out", "minus.magnifyingglass", move || zoomed.update(|z| *z -= 1)),
                    toolbar_button("in", "Zoom In", "plus.magnifyingglass", move || zoomed.update(|z| *z += 1)),
                ]),
                toolbar_fixed_space(),
                toolbar_picker("mode", "View", &mode, vec![("List", "list.bullet", Mode::List), ("Grid", "square.grid.2x2", Mode::Grid)]),
                toolbar_space(),
                ferrokit::toolbar_popover("about", "About", "info.circle", || text("Shown from the toolbar").padding(12.0)),
                toolbar_button("share", "Share", "square.and.arrow.up", move || shared.update(|n| *n += 1)).optional(),
            ])
            .customizable_toolbar("checklist-tools")
            .view(text("Tools"))
    };
    let w = open(tools("Tools"));
    let tb = w.toolbar().unwrap();
    let ids = |tb: &objc2_app_kit::NSToolbar| tb.items().iter().map(|i| i.itemIdentifier().to_string()).collect::<Vec<String>>();
    let group = |id: &str| tb.items().iter().find(|i| i.itemIdentifier().to_string() == id).and_then(|i| i.downcast::<NSToolbarItemGroup>().ok());
    let app = NSApplication::sharedApplication(mtm());
    let send = |item: &NSToolbarItemGroup| unsafe { app.sendAction_to_from(item.action().unwrap(), item.target().as_deref(), Some(item)) };

    // A group: one item of two segments; a segment runs its button.
    let zoom = group("zoom").unwrap();
    let labels: Vec<String> = zoom.subitems().iter().map(|i| i.label().to_string()).collect();
    zoom.setSelectedIndex(1);
    let fired_in = send(&zoom);
    let after_in = zoomed.get_untracked();
    zoom.setSelectedIndex(0);
    send(&zoom);
    check(
        "toolbar-group",
        labels == ["Zoom Out", "Zoom In"] && zoom.selectionMode() == NSToolbarItemGroupSelectionMode::Momentary && fired_in && after_in == 1 && zoomed.get_untracked() == 0 && zoom.label().to_string() == "Zoom",
        format!("segments {labels:?}; Zoom In → {after_in}, then Zoom Out → {}", zoomed.get_untracked()),
    );

    // A picker: the segment follows the signal; choosing one sets it.
    let picker = group("mode").unwrap();
    let first = picker.selectedIndex();
    batch(|| mode.set(Mode::Grid));
    let followed = picker.selectedIndex();
    picker.setSelectedIndex(0);
    send(&picker);
    check(
        "toolbar-picker",
        first == 0 && followed == 1 && mode.get_untracked() == Mode::List && picker.selectionMode() == NSToolbarItemGroupSelectionMode::SelectOne,
        format!("shows {first}; Grid → segment {followed}; choosing List → {:?}", mode.get_untracked()),
    );

    // A toolbar popover: pressing the item opens its content in a popover
    // (pointing at the item); pressing again closes it.
    let about = tb.items().iter().find(|i| i.itemIdentifier().to_string() == "about").unwrap();
    let press = |i: &objc2_app_kit::NSToolbarItem| unsafe { app.sendAction_to_from(i.action().unwrap(), i.target().as_deref(), Some(i)) };
    let popover_text = || {
        app.windows().iter().filter(|x| x.isVisible() && x.class().name().to_string_lossy().contains("Popover")).find_map(|x| {
            let cv = x.contentView()?;
            all_views(&cv).into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).map(|f| f.stringValue().to_string()).find(|t| t == "Shown from the toolbar")
        })
    };
    press(&about);
    let opened = popover_text();
    press(&about);
    let closed = popover_text().is_none();
    check("toolbar-popover", opened.is_some() && closed, format!("pressed: {opened:?}; pressed again, closed {closed}"));

    // Customisable: the optional item is offered, not shown; adding it (as
    // the sheet does) makes a live item, and the layout is remembered.
    let delegate = tb.delegate().unwrap();
    // SAFETY: the toolbar's delegate answers this NSToolbarDelegate method.
    let allowed: Retained<objc2_foundation::NSArray<NSString>> = unsafe { objc2::msg_send![&*delegate, toolbarAllowedItemIdentifiers: &*tb] };
    let offered = allowed.iter().any(|i| i.to_string() == "share");
    let before = ids(&tb);
    tb.insertItemWithItemIdentifier_atIndex(&NSString::from_str("share"), tb.items().count() as isize);
    let share = tb.items().iter().find(|i| i.itemIdentifier().to_string() == "share");
    let acts = share.is_some_and(|i| unsafe { app.sendAction_to_from(i.action().unwrap(), i.target().as_deref(), Some(&i)) }) && shared.get_untracked() == 1;
    let customizable = tb.allowsUserCustomization();
    spawn(
        || std::thread::sleep(std::time::Duration::from_millis(150)),
        move |()| {
            let saved: Vec<String> = objc2_foundation::NSUserDefaults::standardUserDefaults().stringArrayForKey(&NSString::from_str(KEY)).map(|l| l.iter().map(|s| s.to_string()).collect()).unwrap_or_default();
            // A new window of the same toolbar starts with the user's layout.
            let again = open(tools("Tools Again"));
            let restored = again.toolbar().map(|t| ids(&t)).unwrap_or_default();
            check(
                "toolbar-customize",
                customizable && offered && !before.contains(&"share".to_string()) && acts && saved.last().map(String::as_str) == Some("share") && restored == saved,
                format!("customisable {customizable}; Share offered {offered}, not shown {:?}; added, it acts {acts}; saved {saved:?}; a new window has {restored:?}", before),
            );
            if let Ok(dir) = std::env::var("SNAP") {
                snapshot_windows(&dir);
            }
            ferrokit::close_window(&again);
            ferrokit::close_window(&w);
            forget();
            after_events({
                let events = events.clone();
                move || form_kind_checks(events.clone())
            });
        },
    );
}

/// C10: a grouped form (rows, lines between them, help and a footer), its
/// controls named by their labels, a titled box, and a disclosure group.
fn form_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{disclosure, form, form_content, form_row, group_box, section};
    use objc2_app_kit::{NSBox, NSStepper, NSSwitch};
    let (name, sync, beta, open_, retries) = (Signal::new("Ada".to_string()), Signal::new(true), Signal::new(false), Signal::new(false), Signal::new(3.0));
    let w = open(
        Window::new("Form").size(480.0, 520.0).view(
            vstack((
                form(vec![
                    section("General", vec![form_row("Name", text_field(&name)), form_row("Sync", toggle("", &sync)).help("Keeps your library the same on every Mac.")]).footer("Changes apply at once."),
                    section("", vec![form_content(checkbox("Try new features", &beta))]),
                ]),
                group_box("Totals", text("3 libraries, 1,204 books")),
                disclosure("Advanced", &open_, move || form(vec![section("", vec![form_row("Retries", stepper(&retries, 0.0, 10.0, 1.0))])])),
            ))
            .spacing(16.0)
            .alignment(Align::Start)
            .padding(20.0),
        ),
    );
    let all = || all_views(&w.contentView().unwrap());
    let label = |t: &str| all().into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == t);
    let switch = all().into_iter().find_map(|v| v.downcast::<NSSwitch>().ok()).unwrap();
    let lines = all().into_iter().filter_map(|v| v.downcast::<NSBox>().ok()).filter(|b| b.boxType() == objc2_app_kit::NSBoxType::Separator).count();
    let in_window = |v: &NSView| v.convertRect_toView(v.bounds(), None);
    let (sync_label, help, footer) = (label("Sync"), label("Keeps your library the same on every Mac."), label("Changes apply at once."));
    let row = sync_label.as_ref().map(|l| in_window(l));
    let control = in_window(&switch);
    // Label on the left, control on the right, help under them.
    let laid_out = row.is_some_and(|r| r.origin.x < 60.0 && control.origin.x > 300.0) && help.as_ref().zip(row).is_some_and(|(h, r)| in_window(h).origin.y < r.origin.y);
    check(
        "form-grouped",
        laid_out && lines == 1 && footer.is_some() && label("General").is_some(),
        format!("Sync label at {:?}, switch at x {:.0}; {lines} line between rows (1); help under the row; footer {}", row.map(|r| r.origin), control.origin.x, footer.is_some()),
    );
    let named = objc2_app_kit::NSAccessibility::accessibilityLabel(&*switch).map(|l| l.to_string());
    let problems = ferrokit::testing::ax_audit(&w);
    check("form-voiceover", named.as_deref() == Some("Sync") && problems.is_empty(), format!("the switch is read as {named:?}; audit {problems:?}"));
    check("group-box", label("Totals").is_some() && label("3 libraries, 1,204 books").is_some(), "title and content shown".into());

    // Disclosure: closed, its content not built; the triangle opens it.
    let triangle = all().into_iter().filter_map(|v| v.downcast::<objc2_app_kit::NSButton>().ok()).find(|b| b.bezelStyle() == objc2_app_kit::NSBezelStyle::Disclosure).unwrap();
    let closed = !all().into_iter().any(|v| v.downcast::<NSStepper>().is_ok());
    unsafe { triangle.performClick(None) };
    let opened = open_.get_untracked();
    let w2 = w.clone();
    after_events(move || {
        let stepper = all_views(&w2.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSStepper>().ok());
        let stepper_named = stepper.as_ref().and_then(|s| objc2_app_kit::NSAccessibility::accessibilityLabel(&**s)).map(|l| l.to_string());
        if let Ok(dir) = std::env::var("SNAP") {
            snapshot_windows(&dir);
        }
        batch(|| open_.set(false));
        let (w3, triangle) = (w2.clone(), triangle.clone());
        let events = events.clone();
        after_events(move || {
            let gone = !all_views(&w3.contentView().unwrap()).into_iter().any(|v| v.downcast::<NSStepper>().is_ok());
            let follows = triangle.state() == objc2_app_kit::NSControlStateValueOff;
            check(
                "disclosure",
                closed && opened && stepper_named.as_deref() == Some("Retries") && gone && follows,
                format!("closed at first {closed}; the triangle opened it {opened}, showing a stepper named {stepper_named:?}; closed from code: gone {gone}, triangle follows {follows}"),
            );
            ferrokit::close_window(&w3);
            filter_kind_checks(events.clone());
        });
    });
}

/// C11: the filter builder shows a filter set from code, with fields by
/// their titles and as tall as its rows; the user's rows set the filter.
fn filter_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{Filter, FilterField, FilterRule, FilterTest, Match, filter_editor};
    use objc2_app_kit::{NSPopUpButton, NSPredicateEditor};
    let filter = Signal::new(Filter::default());
    let w = open(
        Window::new("Filter").size(620.0, 300.0).view(
            vstack((
                filter_editor(&filter, vec![FilterField::text("name", "Name"), FilterField::number("total", "Total"), FilterField::choice("city", "City", &["Oslo", "Bergen"])]),
                text(move || filter.get().to_sql()),
            ))
            .alignment(Align::Start)
            .padding(16.0),
        ),
    );
    let editor = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSPredicateEditor>().ok()).unwrap();
    let empty_rows = editor.numberOfRows();
    batch(|| {
        filter.set(Filter {
            combine: Match::Any,
            rules: vec![
                FilterRule::Field { field: "name".into(), test: FilterTest::Contains("ad".into()) },
                FilterRule::Field { field: "total".into(), test: FilterTest::AtLeast(100.0) },
                FilterRule::Field { field: "city".into(), test: FilterTest::Is("Bergen".into()) },
            ],
        })
    });
    let w2 = w.clone();
    after_events(move || {
        let format = editor.predicate().map(|p| p.predicateFormat().to_string()).unwrap_or_default();
        let rows = editor.numberOfRows();
        let tall = (editor.frame().size.height - rows as f64 * editor.rowHeight()).abs() < 1.0;
        let titles: Vec<String> = all_views(&editor).into_iter().filter_map(|v| v.downcast::<NSPopUpButton>().ok()).filter_map(|p| p.titleOfSelectedItem()).map(|t| t.to_string()).collect();
        let named = ["Name", "Total", "City"].iter().all(|t| titles.iter().any(|s| s == t));
        check(
            "filter-editor-shows",
            empty_rows == 2 && rows == 4 && format == r#"name CONTAINS[c] "ad" OR total >= 100 OR city == "Bergen""# && tall && named,
            format!("empty: {empty_rows} rows (the line and one rule); set: {rows} rows, {format:?}; as tall as its rows {tall}; fields by title {named} {titles:?}"),
        );
        // The user removes a row, then adds one: the filter follows.
        let app = NSApplication::sharedApplication(mtm());
        let send = |e: &NSPredicateEditor| unsafe { app.sendAction_to_from(e.action().unwrap(), e.target().as_deref(), Some(e)) };
        editor.removeRowAtIndex(2);
        send(&editor);
        let after_remove = filter.get_untracked();
        unsafe { editor.addRow(None) };
        send(&editor);
        let after_add = filter.get_untracked();
        let sql = after_remove.to_sql();
        let (w3, editor) = (w2.clone(), editor.clone());
        let events = events.clone();
        after_events(move || {
            let grew = (editor.frame().size.height - editor.numberOfRows() as f64 * editor.rowHeight()).abs() < 1.0;
            check(
                "filter-editor-edits",
                after_remove.combine == Match::Any && after_remove.rules.len() == 2 && sql == r#"("name" LIKE '%ad%' ESCAPE '\' OR "city" = 'Bergen')"# && after_add.rules.len() == 3 && grew,
                format!("removed the total row: {} rules, SQL {sql}; added a row: {} rules; grew with it {grew}", after_remove.rules.len(), after_add.rules.len()),
            );
            if let Ok(dir) = std::env::var("SNAP") {
                snapshot_windows(&dir);
            }
            let problems = ferrokit::testing::ax_audit(&w3);
            check("filter-editor-voiceover", problems.is_empty(), format!("{problems:?}"));
            ferrokit::close_window(&w3);
            browser_kind_checks(events.clone());
        });
    });
}

#[derive(Clone)]
struct Spot(&'static str, &'static str);

impl Identifiable for Spot {
    type Id = &'static str;
    fn id(&self) -> &'static str {
        self.0
    }
}

/// C13: the column browser opens the columns down to a path set in code,
/// a click sets the path, the tree updates under it keeping the path, and
/// a double-click activates an item.
fn browser_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::column_browser;
    use objc2_app_kit::NSBrowser;
    let leaf = |n, i| TreeNode::leaf(Spot(n, i));
    let tree = move |finland: bool| {
        let mut roots = vec![
            TreeNode::branch(Spot("Norway", "flag"), vec![
                TreeNode::branch(Spot("Lofoten", "mountain.2"), vec![leaf("Reine", "house"), leaf("Å", "house")]),
                TreeNode::branch(Spot("Nordland", "map"), vec![leaf("Bodø", "house")]),
            ]),
            TreeNode::branch(Spot("Sweden", "flag"), vec![leaf("Kiruna", "house")]),
        ];
        if finland {
            roots.push(leaf("Finland", "flag"));
        }
        roots
    };
    let (finland, path, opened) = (Signal::new(false), Signal::new(Vec::<&'static str>::new()), Signal::new(None::<&'static str>));
    let w = open(
        Window::new("Browser").size(720.0, 320.0).view(
            column_browser(move || tree(finland.get()), |p: &Spot| p.0.to_string())
                .icon(|p| Some(p.1.to_string()))
                .selection(&path)
                .on_activate(move |p| opened.set(Some(p.0)))
                .accessibility_label("Places")
                .padding(12.0),
        ),
    );
    let b = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSBrowser>().ok()).unwrap();
    let rows = |b: &NSBrowser| b.selectionIndexPath().map(|p| (0..p.length()).map(|i| p.indexAtPosition(i)).collect::<Vec<_>>()).unwrap_or_default();
    let first = (b.lastColumn(), rows(&b));
    batch(|| path.set(vec!["Norway", "Lofoten", "Å"]));
    let w2 = w.clone();
    after_events(move || {
        let opened_to = rows(&b);
        let columns = b.lastColumn();
        // A cell's symbol, from the delegate as the row is shown.
        // (Text cells on macOS 27: the symbol is an attachment before the title.)
        let cell: Option<Retained<objc2_app_kit::NSCell>> = unsafe { objc2::msg_send![&*b, loadedCellAtRow: 0isize, column: 0isize] };
        let icon = cell.as_ref().is_some_and(|c| c.attributedStringValue().string().to_string().starts_with('\u{FFFC}'));
        check(
            "browser-columns",
            first == (0, vec![]) && opened_to == [0, 0, 1] && columns >= 2 && icon,
            format!("at first: last column {}, selection {:?}; set to Norway › Lofoten › Å: rows {opened_to:?}, {columns} as last column; icons {icon}", first.0, first.1),
        );
        // A click on Sweden in the first column sets the path.
        let app = NSApplication::sharedApplication(mtm());
        b.selectRow_inColumn(1, 0);
        unsafe { app.sendAction_to_from(b.action().unwrap(), b.target().as_deref(), Some(&b)) };
        let clicked = path.get_untracked();
        // The tree changes: the path stays.
        batch(|| finland.set(true));
        let w3 = w2.clone();
        let events = events.clone();
        let b = b.clone();
        after_events(move || {
            let kept = rows(&b);
            check("browser-click", clicked == ["Sweden"] && kept == [1] && path.get_untracked() == ["Sweden"], format!("click on Sweden → {clicked:?}; after Finland was added, still {kept:?}"));
            // A double-click on Bodø activates it.
            batch(|| path.set(vec!["Norway", "Nordland", "Bodø"]));
            let (b2, w3, events) = (b.clone(), w3.clone(), events.clone());
            after_events(move || {
                let app = NSApplication::sharedApplication(mtm());
                unsafe { app.sendAction_to_from(b2.doubleAction().unwrap(), b2.target().as_deref(), Some(&b2)) };
                let problems = ferrokit::testing::ax_audit(&w3);
                let role = objc2_app_kit::NSAccessibility::accessibilityRole(&*b2).map(|r| r.to_string());
                check(
                    "browser-activate",
                    opened.get_untracked() == Some("Bodø") && rows(&b2) == [0, 1, 0] && problems.is_empty() && role.as_deref() == Some("AXBrowser"),
                    format!("double-click → {:?}; rows {:?}; VoiceOver role {role:?}, audit {problems:?}", opened.get_untracked(), rows(&b2)),
                );
                if let Ok(dir) = std::env::var("SNAP") {
                    snapshot_windows(&dir);
                }
                ferrokit::close_window(&w3);
                shell_kind_checks(events.clone());
            });
        });
    });
}

/// A window with C15's shell: a sidebar, the content, an inspector, a
/// toolbar with one button.
fn shell_window(title: &str, sidebar_hidden: Signal<bool>, inspector_hidden: Signal<bool>) -> Window {
    Window::new(title)
        .size(900.0, 420.0)
        .toolbar(vec![toolbar_button("add", "Add", "plus", || {})])
        .sidebar(vstack((text("Library"), text("Recent"), text_field(&Signal::new(String::new())).accessibility_label("Find in library"))).padding(12.0))
        .sidebar_hidden(&sidebar_hidden)
        .view(vstack((text("Shell content"), text("Rows go here"))).padding(12.0))
        .inspector(vstack((text("Inspector"), text_field(&Signal::new(String::new())).accessibility_label("Note"))).padding(12.0))
        .inspector_hidden(&inspector_hidden)
        .on_command(SHELL_ADD, || SHELL_ADDS.set(SHELL_ADDS.get() + 1))
}

/// C15: the shell is AppKit's split view controller (a sidebar item, the
/// content, an inspector item); the hidden signals and AppKit's toggles
/// follow each other; and a closed shell window leaves no more behind than
/// a plain AppKit one built the same way.
fn shell_kind_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSSplitViewController, NSSplitViewItemBehavior};
    let (side, insp) = (Signal::new(false), Signal::new(false));
    let w = open(shell_window("Shell", side, insp));
    let controller = w.contentViewController().and_then(|c| c.downcast::<NSSplitViewController>().ok());
    let behaviours: Vec<NSSplitViewItemBehavior> = controller.as_ref().map(|c| c.splitViewItems().iter().map(|i| i.behavior()).collect()).unwrap_or_default();
    let ids: Vec<String> = w.toolbar().map(|t| t.items().iter().map(|i| i.itemIdentifier().to_string()).collect()).unwrap_or_default();
    let w2 = w.clone();
    after_events(move || {
        // The content sits below the title bar and toolbar, the sidebar's
        // list too (they run up under it).
        let label = |t: &str| all_views(&w2.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == t);
        let layout_top = { let r = w2.contentLayoutRect(); r.origin.y + r.size.height };
        let below = |t: &str| label(t).and_then(|l| unsafe { l.superview() }.map(|s| s.convertRect_toView(l.frame(), None))).is_some_and(|r| r.origin.y + r.size.height <= layout_top + 0.5);
        check(
            "shell-layout",
            behaviours == [NSSplitViewItemBehavior::Sidebar, NSSplitViewItemBehavior::Default, NSSplitViewItemBehavior::Inspector]
                && ids.first().map(String::as_str) == Some("NSToolbarToggleSidebarItem")
                && ids.get(1).map(String::as_str) == Some("NSToolbarSidebarTrackingSeparatorItemIdentifier")
                && ids.last().map(String::as_str) == Some("NSToolbarToggleInspectorItem")
                && below("Shell content") && below("Library") && below("Inspector"),
            format!("items {behaviours:?}; toolbar {ids:?}; below the title bar: content {}, sidebar {}, inspector {}", below("Shell content"), below("Library"), below("Inspector")),
        );
        // The window's commands reach it from the sidebar's and the
        // inspector's focus too (each pane is its own tree).
        // (The editable fields: the sidebar's, then the inspector's.)
        let fields: Vec<_> = all_views(&w2.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).filter(|f| f.isEditable()).collect();
        let mut reached = Vec::new();
        for f in &fields {
            let focused = w2.makeFirstResponder(Some(f));
            reached.push((focused, ferrokit::can_perform_in(Some(&w2), SHELL_ADD), ferrokit::perform_in(Some(&w2), SHELL_ADD)));
        }
        check(
            "shell-commands",
            reached.len() == 2 && reached.iter().all(|&(f, can, ran)| f && can && ran) && SHELL_ADDS.get() == 2,
            format!("(focused, can, ran) from sidebar and inspector {reached:?}; handler ran {}", SHELL_ADDS.get()),
        );
        if let Ok(dir) = std::env::var("SNAP") {
            snapshot_windows(&dir);
        }
        // The signals hide the panes; AppKit's own toggle sets them back.
        batch(|| {
            side.set(true);
            insp.set(true);
        });
        let (w3, events) = (w2.clone(), events.clone());
        spawn(|| std::thread::sleep(std::time::Duration::from_millis(900)), move |()| {
            let c = w3.contentViewController().and_then(|c| c.downcast::<NSSplitViewController>().ok()).unwrap();
            let items = c.splitViewItems();
            let hidden = items.objectAtIndex(0).isCollapsed() && items.objectAtIndex(2).isCollapsed();
            unsafe { c.toggleSidebar(None) };
            let w4 = w3.clone();
            spawn(|| std::thread::sleep(std::time::Duration::from_millis(900)), move |()| {
                let shown = !c.splitViewItems().objectAtIndex(0).isCollapsed();
                check(
                    "shell-hide",
                    hidden && shown && !side.get_untracked() && insp.get_untracked(),
                    format!("signals hid both {hidden}; Toggle Sidebar showed it {shown}, signal now {}; inspector still hidden {}", side.get_untracked(), insp.get_untracked()),
                );
                ferrokit::close_window(&w4);
                shell_memory(events.clone());
            });
        });
    });
}

/// Runs `cycle` 40 times to warm AppKit's caches, then 30 more, and calls
/// `then` with the heap kept per cycle (KB), once closed windows are freed.
fn measure_cycles(cycle: Rc<dyn Fn()>, then: Rc<dyn Fn(f64)>) {
    const WARM: u32 = 40;
    const ROUNDS: u32 = 70;
    fn step(round: u32, base: f64, cycle: Rc<dyn Fn()>, then: Rc<dyn Fn(f64)>) {
        if round == WARM && base == 0.0 {
            return settled_heap(move |b| step(round, b, cycle, then));
        }
        if round == ROUNDS {
            return settled_heap(move |now| then((now - base) * 1024.0 / (ROUNDS - WARM) as f64));
        }
        cycle();
        after_idle(move || step(round + 1, base, cycle.clone(), then.clone()));
    }
    step(0, 0.0, cycle, then);
}

/// The memory a closed shell window keeps, against a plain AppKit window
/// with a split view controller of the same three panes and a toolbar with
/// the same tracking separators (in round 2 of the hands-on checks, an
/// earlier shell kept 0.6 to 1.1 MB per window).
fn shell_memory(events: Rc<RefCell<Vec<AppEvent>>>) {
    let plain: Rc<dyn Fn()> = Rc::new(plain_shell_cycle);
    measure_cycles(plain, Rc::new(move |floor| {
        let (side, insp) = (Signal::new(false), Signal::new(false));
        let ours: Rc<dyn Fn()> = Rc::new(move || {
            let w = open(shell_window("Shell cycle", side, insp));
            w.performClose(None);
        });
        let events = events.clone();
        measure_cycles(ours, Rc::new(move |per| {
            check(
                "shell-close-memory",
                per < floor.max(0.0) + 16.0,
                format!("30 shell windows closed: heap kept {per:+.1} KB each; a plain AppKit split view controller window {floor:+.1} KB (budget: plain + 16)"),
            );
            // On the next pass, outside this batch: as a click would be.
            let events = events.clone();
            after_events(move || failure_checks(events.clone()));
        }));
    }));
}

/// A plain AppKit window like `shell_window`: a split view controller with
/// a sidebar, content and inspector item (labels in each), a toolbar with
/// the sidebar's and inspector's toggles and tracking separators.
fn plain_shell_cycle() {
    use objc2::MainThreadOnly;
    use objc2_app_kit::{NSBackingStoreType, NSSplitViewController, NSSplitViewItem, NSViewController, NSWindow, NSWindowStyleMask};
    use objc2_foundation::{NSPoint, NSRect, NSSize};
    let mtm = MainThreadMarker::new().unwrap();
    objc2::rc::autoreleasepool(|_| {
        let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(900.0, 420.0));
        let style = NSWindowStyleMask::Titled | NSWindowStyleMask::Closable | NSWindowStyleMask::Resizable | NSWindowStyleMask::FullSizeContentView;
        let w = unsafe { NSWindow::initWithContentRect_styleMask_backing_defer(NSWindow::alloc(mtm), rect, style, NSBackingStoreType::Buffered, false) };
        unsafe { w.setReleasedWhenClosed(false) };
        let pane = |title: &str| {
            let vc = NSViewController::new(mtm);
            let v = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, NSSize::new(300.0, 420.0)));
            v.addSubview(&NSTextField::labelWithString(&NSString::from_str(title), mtm));
            vc.setView(&v);
            vc
        };
        let c = NSSplitViewController::new(mtm);
        c.addSplitViewItem(&NSSplitViewItem::sidebarWithViewController(&pane("Library")));
        c.addSplitViewItem(&NSSplitViewItem::splitViewItemWithViewController(&pane("Content")));
        c.addSplitViewItem(&NSSplitViewItem::inspectorWithViewController(&pane("Inspector")));
        w.setContentViewController(Some(&c));
        let delegate: Retained<ShellToolbar> = unsafe { objc2::msg_send![ShellToolbar::alloc(mtm), init] };
        let toolbar = objc2_app_kit::NSToolbar::initWithIdentifier(objc2_app_kit::NSToolbar::alloc(mtm), &NSString::from_str("plain-shell"));
        toolbar.setDelegate(Some(objc2::runtime::ProtocolObject::from_ref(&*delegate)));
        w.setToolbar(Some(&toolbar));
        w.makeKeyAndOrderFront(None);
        w.performClose(None);
        toolbar.setDelegate(None);
        w.setContentViewController(None);
        drop(delegate);
    });
}

mod shell_toolbar {
    use objc2::rc::Retained;
    use objc2::runtime::NSObjectProtocol;
    use objc2::{MainThreadMarker, MainThreadOnly, define_class};
    use objc2_app_kit::{NSImage, NSToolbar, NSToolbarDelegate, NSToolbarItem};
    use objc2_foundation::{NSArray, NSObject, NSString};

    fn ids() -> Retained<NSArray<NSString>> {
        let names = ["NSToolbarToggleSidebarItem", "NSToolbarSidebarTrackingSeparatorItemIdentifier", "add", "NSToolbarInspectorTrackingSeparatorItemIdentifier", "NSToolbarFlexibleSpaceItem", "NSToolbarToggleInspectorItem"];
        NSArray::from_retained_slice(&names.map(NSString::from_str))
    }

    define_class!(
        // The plain shell window's toolbar: the shell's standard items and
        // an "Add" button.
        #[unsafe(super(NSObject))]
        #[thread_kind = MainThreadOnly]
        #[name = "ChecklistShellToolbar"]
        pub struct ShellToolbar;

        unsafe impl NSObjectProtocol for ShellToolbar {}

        unsafe impl NSToolbarDelegate for ShellToolbar {
            #[unsafe(method_id(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:))]
            fn item(&self, _toolbar: &NSToolbar, id: &NSString, _insert: bool) -> Option<Retained<NSToolbarItem>> {
                // AppKit makes its own items; only "add" is ours.
                (id.to_string() == "add").then(|| {
                    let mtm = MainThreadMarker::new().unwrap();
                    let item = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(mtm), id);
                    item.setLabel(&NSString::from_str("Add"));
                    item.setImage(NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str("plus"), None).as_deref());
                    item
                })
            }

            #[unsafe(method_id(toolbarDefaultItemIdentifiers:))]
            fn defaults(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSString>> {
                ids()
            }

            #[unsafe(method_id(toolbarAllowedItemIdentifiers:))]
            fn allowed(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSString>> {
                ids()
            }
        }
    );
}
use shell_toolbar::ShellToolbar;

thread_local! {
    /// Failures `App::on_error` was told about.
    static HOOKED: Cell<u32> = const { Cell::new(0) };
}

/// R2: an exception or a panic in an action, or a panic in an effect, is
/// caught where AppKit called in, reported, and the app goes on: later
/// changes still take effect.
fn failure_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::failures;
    let (count, poison) = (Signal::new(0), Signal::new(false));
    let w = open(
        Window::new("Failures").size(360.0, 160.0).view(
            vstack((
                button("Throw", || {
                    // An Objective-C exception from AppKit's side: past the end of an array.
                    let empty = objc2_foundation::NSArray::<NSString>::new();
                    let _: *mut objc2::runtime::AnyObject = unsafe { objc2::msg_send![&*empty, objectAtIndex: 3usize] };
                }),
                button("Panic", || panic!("a deliberate panic, for the check")),
                button("Poison", move || poison.set(true)),
                button("Count", move || count.update(|n| *n += 1)),
                // An effect that panics while the signal is set.
                ferrokit::watch(move || {
                    if poison.get() {
                        panic!("a deliberate panic in an effect");
                    }
                }),
                text(move || format!("count {}", count.get())),
            ))
            .padding(12.0),
        ),
    );
    let button_named = |t: &str| all_views(&w.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<objc2_app_kit::NSButton>().ok()).find(|b| b.title().to_string() == t).unwrap();
    let label_now = || all_views(&w.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string().starts_with("count")).map(|f| f.stringValue().to_string()).unwrap_or_default();
    let before = failures().len();
    send_action(&button_named("Throw"));
    send_action(&button_named("Panic"));
    send_action(&button_named("Poison"));
    let caught: Vec<ferrokit::Failure> = failures().into_iter().skip(before).collect();
    // The app goes on: a later change still updates the screen.
    send_action(&button_named("Count"));
    send_action(&button_named("Count"));
    let shown = label_now();
    let exception = caught.iter().any(|f| f.exception && f.place == "a control's action" && f.message.contains("NSRangeException"));
    let panics = caught.iter().filter(|f| !f.exception && f.message.contains("deliberate panic")).count();
    check(
        "failures-caught",
        exception && panics == 2 && shown == "count 2" && HOOKED.with(Cell::get) as usize >= caught.len() && caught.len() == 3,
        format!("caught {:?}; after them the label reads {shown:?}; on_error told {} time(s)", caught.iter().map(|f| f.to_string()).collect::<Vec<_>>(), HOOKED.with(Cell::get)),
    );
    ferrokit::close_window(&w);
    crash_report_check();
    after_events(move || failure_boundary_checks(events.clone()));
}

/// Failures are caught wherever AppKit calls in, not only in actions: a
/// table asking for a cell, typing in a text field, a background task.
fn failure_boundary_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::failures;
    use ferrokit::{Cancel, Resource};
    let poisoned = Rc::new(Cell::new(false));
    let p = poisoned.clone();
    let model = Rc::new(TableModel::new(
        ViewId(9300),
        vec![Column::text("name", "Name", move |s: &String| {
            if p.get() {
                panic!("a deliberate panic in a column");
            }
            s.clone()
        })],
    ));
    model.set_rows(vec!["one".to_string(), "two".to_string()]);
    let (typed, count) = (Signal::new(String::new()), Signal::new(0));
    let progress = Signal::new(None);
    let load = Resource::new(|| (), |(): (), _: &Cancel| -> Result<i64, &'static str> { panic!("a deliberate panic in a load") });
    let w = open(
        Window::new("Boundary").size(360.0, 220.0).view(
            vstack((
                table(&model).height(80.0),
                text_field(&typed),
                ferrokit::watch(move || {
                    if typed.get() == "boom" {
                        panic!("a deliberate panic after typing");
                    }
                }),
                button("Count", move || count.update(|n| *n += 1)),
                text(move || format!("count {}", count.get())),
            ))
            .padding(12.0),
        ),
    );
    let before = failures().len();
    // The table asks for a cell: the column's closure panics.
    poisoned.set(true);
    let tv = model.table_view();
    tv.reloadData();
    let cell = tv.viewAtColumn_row_makeIfNecessary(0, 0, true);
    poisoned.set(false);
    // Typing: an effect that reads the field's signal panics.
    let field = all_views(&w.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.isEditable()).unwrap();
    ferrokit::testing::post_edit(&field, "boom");
    // A background task that panics: its progress ends, `then` never runs.
    let ran = Rc::new(Cell::new(false));
    let r = ran.clone();
    ferrokit::spawn_with_progress(&progress, |_| -> i64 { panic!("a deliberate panic in a task") }, move |_| r.set(true));
    let w2 = w.clone();
    until(
        move || progress.get_untracked().is_none() && !load.loading(),
        3000,
        move || {
            // After this task's batch: the button's action below runs in a
            // batch of its own, as a click's does.
            let (w2, cell_made) = (w2.clone(), cell.is_some());
            let (ran, events) = (ran.clone(), events.clone());
            after_events(move || {
                let caught: Vec<ferrokit::Failure> = failures().into_iter().skip(before).collect();
                let places: Vec<&str> = caught.iter().map(|f| f.place).collect();
                let button = all_views(&w2.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<objc2_app_kit::NSButton>().ok()).find(|b| b.title().to_string() == "Count").unwrap();
                send_action(&button);
                let shown = all_views(&w2.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSTextField>().ok()).any(|f| f.stringValue().to_string() == "count 1");
                let error = load.error();
                check(
                    "failures-caught-everywhere",
                    places.iter().any(|p| p.starts_with("a table")) && places.iter().any(|p| p.starts_with("a control")) && places.iter().filter(|p| **p == "a background task").count() == 2 && !cell_made && !ran.get() && progress.get_untracked().is_none() && error.as_deref().is_some_and(|e| e.contains("panicked")) && shown,
                    format!("caught in {places:?}; the cell {}; the task's then ran {}; its progress {:?}; the load's error {error:?}; the app goes on {shown}", if cell_made { "was made" } else { "wasn't made" }, ran.get(), progress.get_untracked()),
                );
                ferrokit::close_window(&w2);
                rtl_checks(events.clone());
            });
        },
    );
}

/// L5: a panic Ferrokit doesn't catch writes a crash report; one it
/// catches doesn't. A child run of this app crashes on purpose.
fn crash_report_check() {
    let dir = std::env::temp_dir().join(format!("ferrokit-crashes-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let status = std::process::Command::new(std::env::current_exe().unwrap())
        .env("CRASH_TEST", "1")
        .env("FERROKIT_CRASH_DIR", &dir)
        .env_remove("CHECK")
        .stderr(std::process::Stdio::null())
        .status();
    let crashed = status.as_ref().is_ok_and(|s| !s.success());
    let reports = ferrokit::testing::pending_crash_reports(&dir);
    let text = reports.first().map(|r| r.text.clone()).unwrap_or_default();
    let complete = ["App: Crash Test", "macOS:", "Thread: the main thread", "Panic: a deliberate crash, for the check", "ui_checklist.rs:", "Backtrace:"].iter().all(|t| text.contains(t));
    let not_caught = !text.contains("a caught panic");
    // The next launch hands the report to the app.
    let launched = std::process::Command::new(std::env::current_exe().unwrap())
        .env("CRASH_TEST", "deliver")
        .env("FERROKIT_CRASH_DIR", &dir)
        .env_remove("CHECK")
        .stderr(std::process::Stdio::null())
        .status();
    let delivered = std::fs::read_to_string(dir.join("delivered")).unwrap_or_default();
    let handed = launched.as_ref().is_ok_and(|s| s.success()) && reports.first().is_some_and(|r| delivered == r.path.display().to_string());
    let sent = reports.first().is_some_and(|r| r.mark_sent().is_ok()) && ferrokit::testing::pending_crash_reports(&dir).is_empty() && dir.join("Sent").read_dir().is_ok_and(|d| d.count() == 1);
    let _ = std::fs::remove_dir_all(&dir);
    check(
        "crash-report",
        crashed && reports.len() == 1 && complete && not_caught && handed && sent,
        format!("child ended with {status:?}; {} report(s); complete {complete}; the caught panic left out {not_caught}; handed over at the next launch {handed}; marked sent {sent}; first lines {:?}", reports.len(), text.lines().take(5).collect::<Vec<_>>()),
    );
}

/// The child run of [`crash_report_check`]: crash reports on, a panic
/// Ferrokit catches, then one it doesn't.
fn crash_test() {
    if std::env::var("CRASH_TEST").is_ok_and(|v| v == "deliver") {
        // The next launch: the report reaches the handler, which notes it.
        let dir = std::path::PathBuf::from(std::env::var_os("FERROKIT_CRASH_DIR").unwrap());
        spawn(|| std::thread::sleep(std::time::Duration::from_secs(5)), |()| std::process::exit(1));
        return App::new("Crash Test")
            .crash_reports(move |report| {
                let _ = std::fs::write(dir.join("delivered"), report.path.display().to_string());
                std::process::exit(0);
            })
            .run();
    }
    let _app = App::new("Crash Test").crash_reports(|_| {});
    ferrokit::testing::catching(|| panic!("a caught panic"));
    panic!("a deliberate crash, for the check");
}

/// R5: right to left, a row's first item is on the right and its last on
/// the left, padding and spacing mirror, and a form's labels move to the
/// right of their controls; left to right again, they go back.
fn rtl_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::testing::set_right_to_left;
    let name = Signal::new(String::new());
    let make = move || {
        Window::new("Mirror").size(420.0, 200.0).view(
            vstack((
                hstack((text("First"), spacer(), text("Last"))),
                ferrokit::form(vec![ferrokit::section("", vec![ferrokit::form_row("Name", text_field(&name))])]).style(ferrokit::FormStyle::Columns),
            ))
            .padding_xy(30.0, 12.0),
        )
    };
    let frames = |w: &objc2_app_kit::NSWindow| {
        let views = all_views(&w.contentView().unwrap());
        let x = |t: &str| views.iter().filter_map(|v| v.clone().downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == t).map(|f| (f.frame().origin.x, f.frame().origin.x + f.frame().size.width));
        let field = views.iter().filter_map(|v| v.clone().downcast::<NSTextField>().ok()).find(|f| f.isEditable()).map(|f| (f.frame().origin.x, f.frame().origin.x + f.frame().size.width));
        (x("First"), x("Last"), x("Name:"), field)
    };
    let ltr_w = open(make());
    let ltr = frames(&ltr_w);
    ferrokit::close_window(&ltr_w);
    set_right_to_left(Some(true));
    let rtl_w = open(make());
    let rtl = frames(&rtl_w);
    if let Ok(dir) = std::env::var("SNAP") {
        snapshot_windows(&dir);
    }
    // Wider: First stays at the right edge (its rectangle is the same
    // left to right, so it was skipped and kept the old width's mirror).
    rtl_w.setContentSize(objc2_foundation::NSSize::new(520.0, 200.0));
    let wide = frames(&rtl_w);
    check(
        "right-to-left-resize",
        wide.0.is_some_and(|first| (first.1 - 490.0).abs() < 1.0) && wide.1.is_some_and(|last| (last.0 - 30.0).abs() < 1.0),
        format!("100 points wider: First {:?} (ends at 490), Last {:?} (starts at 30)", wide.0, wide.1),
    );
    ferrokit::close_window(&rtl_w);
    set_right_to_left(None);
    // Mirrored in the 420-point window: x becomes 420 − (x + width).
    let mirror = |a: Option<(f64, f64)>| a.map(|(x0, x1)| (420.0 - x1, 420.0 - x0));
    let near = |a: Option<(f64, f64)>, b: Option<(f64, f64)>| a.zip(b).is_some_and(|(a, b)| (a.0 - b.0).abs() < 1.0 && (a.1 - b.1).abs() < 1.0);
    let ok = near(rtl.0, mirror(ltr.0)) && near(rtl.1, mirror(ltr.1)) && near(rtl.2, mirror(ltr.2)) && near(rtl.3, mirror(ltr.3))
        && rtl.0.zip(rtl.1).is_some_and(|(first, last)| first.0 > last.1)
        && rtl.2.zip(rtl.3).is_some_and(|(label, field)| label.0 > field.1);
    check(
        "right-to-left",
        ok,
        format!("left to right: First {:?}, Last {:?}, label {:?}, field {:?}; right to left: First {:?}, Last {:?}, label {:?}, field {:?}", ltr.0, ltr.1, ltr.2, ltr.3, rtl.0, rtl.1, rtl.2, rtl.3),
    );
    after_events(move || builder_owner_checks(events.clone()));
}

/// R4 (found by the habits soak): signals a sheet's or window's builder
/// makes are freed when it closes (`sheet_with`, `open_with`), where ones
/// made in an action would live as long as the app.
fn builder_owner_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::{live_signals, open_with, sheet_with};
    let parent = open(Window::new("Owner parent").size(360.0, 200.0).view(text("Parent")));
    let before = live_signals();
    let build = || {
        let (a, b, c) = (Signal::new(String::new()), Signal::new(0usize), Signal::new(false));
        Window::new("Built").size(300.0, 120.0).view(vstack((text_field(&a), text(move || format!("{} {}", b.get(), c.get())))).padding(12.0))
    };
    let handle = sheet_with(&parent, build, || {});
    let during = live_signals();
    handle.close();
    let p2 = parent.clone();
    after_events(move || {
        let after_sheet = live_signals();
        let w = open_with(build);
        let window_during = live_signals();
        ferrokit::close_window(&w);
        let p3 = p2.clone();
        let events = events.clone();
        after_events(move || {
            let after_window = live_signals();
            check(
                "builder-owns-signals",
                during >= before + 3 && after_sheet == before && window_during >= before + 3 && after_window == before,
                format!("live signals {before}; with the sheet open {during}, closed {after_sheet}; with the window open {window_during}, closed {after_window}"),
            );
            ferrokit::close_window(&p3);
            rich_table_checks(events.clone());
        });
    });
}

#[derive(Clone)]
struct Task {
    name: String,
    group: String,
    done: f64,
    size: f64,
}

/// G4: group rows, icon cells, progress cells, a fitted column; indices in
/// events stay model indices.
fn rich_table_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::CellImage;
    use objc2_app_kit::{NSEvent, NSProgressIndicator, NSTableCellView};
    let groups = ["Today", "Yesterday", "Last Week"];
    let tasks: Vec<Task> = (0..300)
        .map(|i| Task { name: format!("Task {i}"), group: groups[i % 3].into(), done: (i % 10) as f64 / 10.0, size: ((i * 37) % 500) as f64 })
        .chain(std::iter::once(Task { name: "A much longer task name than the others".into(), group: "Today".into(), done: 1.0, size: 1.0 }))
        .collect();
    let model = Rc::new(TableModel::new(
        ViewId(995),
        vec![
            Column::text("name", "Name", |t: &Task| t.name.clone()).icon(|t: &Task| Some(CellImage::Symbol(if t.done >= 1.0 { "checkmark.circle".into() } else { "circle".into() }))).fit(),
            Column::progress("done", "Done", |t: &Task| t.done),
            Column::number("size", "Size", |t: &Task| t.size),
        ],
    ));
    model.set_rows(tasks.clone());
    model.set_group_by(Some(Box::new(|t: &Task| t.group.clone())));
    let activated = Signal::new(None::<usize>);
    let selected = Signal::new(Vec::<usize>::new());
    let (a2, s2) = (activated, selected);
    let w = open(Window::new("Rich Table").size(560.0, 420.0).view(
        table(&model).on_activate(move |r| a2.set(Some(r))).on_select(move |r| s2.set(r)).accessibility_label("Tasks"),
    ));
    let tv = model.table_view();
    tv.layoutSubtreeIfNeeded();

    // Groups: a header before each run; headers aren't rows.
    let n = tasks.len();
    let headers: Vec<usize> = (0..model.shown_rows()).filter(|&r| model.row_at(r).is_none()).collect();
    let first_group = (1..headers[1]).filter_map(|r| model.row_at(r)).all(|m| tasks[m].group == "Today");
    let styled = {
        // SAFETY: NSTableView's row view lookup and NSTableRowView's style flag.
        let row_view: Option<Retained<objc2::runtime::AnyObject>> = unsafe { objc2::msg_send![&*tv, rowViewAtRow: 0isize, makeIfNecessary: true] };
        row_view.is_some_and(|v| unsafe { objc2::msg_send![&*v, isGroupRowStyle] })
    };
    check(
        "table-groups",
        model.groups() == groups && model.shown_rows() == n + 3 && headers.len() == 3 && headers[0] == 0 && first_group && styled,
        format!("groups {:?}; {} rows shown for {n} rows; headers at {headers:?}; first group all Today: {first_group}; header row styled as a group: {styled}", model.groups(), model.shown_rows()),
    );

    // Sorting sorts within each group; groups keep their order.
    let desc = objc2_foundation::NSSortDescriptor::sortDescriptorWithKey_ascending(Some(&NSString::from_str("size")), false);
    tv.setSortDescriptors(&objc2_foundation::NSArray::from_retained_slice(&[desc]));
    let mut ok = true;
    let mut last_group = String::new();
    let mut prev = f64::MAX;
    for r in 0..model.shown_rows() {
        match model.row_at(r) {
            None => prev = f64::MAX,
            Some(m) => {
                if tasks[m].group != last_group && prev != f64::MAX {
                    ok = false;
                }
                ok &= tasks[m].size <= prev;
                prev = tasks[m].size;
                last_group = tasks[m].group.clone();
            }
        }
    }
    let still = model.groups() == groups;
    check("table-groups-sorted", ok && still, format!("sorted by Size, descending, within each group: {ok}; groups in order: {still}"));

    // Selection and activation report model indices; headers can't be selected.
    model.select(&[headers[1] - 1]);
    let picked = model.selection();
    let header_selectable = unsafe { tv.delegate() }.is_some_and(|d| {
        let ok: bool = unsafe { objc2::msg_send![&*d, tableView: &*tv, shouldSelectRow: 0isize] };
        ok
    });
    let row = tv.selectedRow();
    let e = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
        objc2_app_kit::NSEventType::KeyDown, objc2_foundation::NSPoint::new(0.0, 0.0), NSEventModifierFlags::empty(), 0.0, w.windowNumber(), None, &NSString::from_str("\r"), &NSString::from_str("\r"), false, 36,
    ).unwrap();
    tv.keyDown(&e);
    let model2 = model.clone();
    let (activated2, w2, events2) = (activated, w.clone(), events.clone());
    after_idle(move || {
        let act = activated2.get_untracked();
        check(
            "table-groups-indices",
            // `row` is where the selected model row is shown (headers count as rows).
            !header_selectable && picked.len() == 1 && act == picked.first().copied() && model2.row_at(row as usize) == picked.first().copied(),
            format!("header row selectable: {header_selectable}; selected model row {picked:?} at view row {row}; Return → Activate({act:?})"),
        );

        // Icon, progress and fitted cells.
        let tv = model2.table_view();
        let view_row = 1;
        let m = model2.row_at(view_row).unwrap();
        let cell = tv.viewAtColumn_row_makeIfNecessary(0, view_row as isize, true).and_then(|v| v.downcast::<NSTableCellView>().ok());
        let (has_image, text) = cell.as_ref().map_or((false, String::new()), |c| unsafe { (c.imageView().is_some_and(|i| i.image().is_some()), c.textField().map(|t| t.stringValue().to_string()).unwrap_or_default()) });
        // The icon is decoration (the text names the row), hidden from VoiceOver.
        let icon_hidden = cell.as_ref().and_then(|c| unsafe { c.imageView() }).is_some_and(|i| ax_hidden(&i));
        let bar = tv.viewAtColumn_row_makeIfNecessary(1, view_row as isize, true).and_then(|v| v.subviews().iter().find_map(|s| s.downcast::<NSProgressIndicator>().ok()));
        let tasks_now = model2.rows().clone();
        let bar_ok = bar.as_ref().is_some_and(|b| (b.doubleValue() - tasks_now[m].done).abs() < 1e-9 && !b.isIndeterminate());
        let name_width = tv.tableColumnWithIdentifier(&NSString::from_str("name")).map_or(0.0, |c| c.width());
        // The text and the bar end inside their cells (they once grew a
        // column's width past them, putting right-aligned numbers in the
        // next column).
        // SAFETY: the cell's view hierarchy, on the main thread.
        let overhang = |sub: Option<Retained<NSView>>| sub.and_then(|v| unsafe { v.superview() }.map(|c| v.frame().origin.x + v.frame().size.width - c.frame().size.width)).unwrap_or(f64::MAX);
        let text_over = overhang(cell.as_ref().and_then(|c| unsafe { c.textField() }).map(Retained::into_super).map(Retained::into_super));
        let bar_over = overhang(bar.clone().map(Retained::into_super));
        // And the icon cell's text shares its row's baseline: its top is a
        // plain cell's (the Size column's) top.
        let top = |v: Option<Retained<NSView>>| v.map_or(f64::MAX, |v| v.convertRect_toView(v.bounds(), Some(&tv)).origin.y);
        let icon_text = top(cell.as_ref().and_then(|c| unsafe { c.textField() }).map(Retained::into_super).map(Retained::into_super));
        let plain_text = top(tv.viewAtColumn_row_makeIfNecessary(2, view_row as isize, true));
        let baseline_off = (icon_text - plain_text).abs();
        check(
            "table-cell-kinds",
            has_image && icon_hidden && text == tasks_now[m].name && bar_ok && name_width > 250.0 && name_width < 420.0 && text_over <= 0.5 && bar_over <= 0.5 && baseline_off <= 0.5,
            format!("icon cell: image {has_image} (hidden from VoiceOver {icon_hidden}), text {text:?} ending {text_over:.0} pt past the cell, {baseline_off:.1} pt off its row's baseline; progress cell at {:?}, ending {bar_over:.0} pt past it; fitted Name column {name_width:.0} pt (longest name)", bar.as_ref().map(|b| b.doubleValue())),
        );

        // Copying the selection: rows only, never headers.
        let pb = ferrokit_core::testing::private_pasteboard();
        model2.select(&[tasks_now.iter().position(|t| t.group == "Yesterday").unwrap()]);
        let copied = model2.copy_to(&pb) && ferrokit_core::testing::pasteboard_text(&pb).is_some_and(|t| !t.contains("Yesterday") && t.starts_with("Task "));
        ferrokit_core::testing::release_pasteboard(&pb);

        // Appending with groups regroups; ungrouping restores plain rows.
        model2.append(vec![Task { name: "New".into(), group: "Tomorrow".into(), done: 0.0, size: 1.0 }]);
        let regrouped = model2.groups().last().map(String::as_str) == Some("Tomorrow") && model2.shown_rows() == tasks_now.len() + 1 + 4;
        model2.set_group_by(None);
        let plain = model2.groups().is_empty() && model2.shown_rows() == tasks_now.len() + 1 && model2.row_at(0).is_some();
        let problems = ferrokit::testing::ax_audit(&w2);
        check(
            "table-groups-edit",
            copied && regrouped && plain && problems.is_empty(),
            format!("copy has rows only: {copied}; append adds a group: {regrouped}; ungrouped: {plain}; unnamed: {problems:?}"),
        );
        ferrokit::close_window(&w2);
        let events = events2.clone();
        after_events(move || transfer_checks(events.clone()));
    });
}

/// Drag and drop, copy and paste on a small table. Only private pasteboards
/// are used (never the clipboard), and drops go through the table's own
/// data-source methods (no mouse).
fn transfer_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit_core::testing::{drag_rows, drop_on_table, files_pasteboard, urls_pasteboard, pasteboard_text, private_pasteboard, release_pasteboard, set_pasteboard_text};
    let model = Rc::new(TableModel::new(
        ViewId(960),
        vec![Column::text("name", "Name", |r: &Item2| r.name.clone()), Column::number("n", "N", |r: &Item2| r.n), Column::check("big", "Big", |r: &Item2| r.n >= 5.0)],
    ));
    model.set_rows((0..10).map(|i| Item2 { name: format!("Item {i}"), n: i as f64 }).collect());
    let s = TransferState { model: model.clone(), moves: Signal::new(vec![]), files: Signal::new(vec![]), urls: Signal::new(vec![]), pastes: Signal::new(0) };
    let (m1, m2, m3) = (s.clone(), s.clone(), s.clone());
    let _ = open(
        Window::new("Transfer").size(420.0, 360.0).view(
            vstack((table(&model)
                .reorderable(move |rows, before| {
                    m1.moves.update(|v| v.push((rows.clone(), before)));
                    m1.model.move_rows(&rows, before);
                })
                .on_files_dropped(&["csv"], move |paths, before| m2.files.update(|v| v.push((paths, before))))
                .on_urls_dropped(move |urls, before| m2.urls.update(|v| v.push((urls, before))))
                .on_paste(move |text| {
                    m3.pastes.update(|n| *n += 1);
                    for line in text.lines() {
                        let mut cells = line.split('\t');
                        let name = cells.next().unwrap_or_default().to_string();
                        let n = cells.next().and_then(|c| c.parse().ok()).unwrap_or(0.0);
                        m3.model.push(Item2 { name, n });
                    }
                }),))
            .padding(12.0),
        ),
    );
    let tv = model.table_view();
    let main_table = TABLE.with(|t| t.model.clone());

    // ⌘C: the selected rows as tab-separated text, columns in their shown order.
    model.select(&[1, 3]);
    let pb = private_pasteboard();
    let copied = model.copy_to(&pb);
    let text = pasteboard_text(&pb);
    let tsv = text.as_deref() == Some("Item 1\t1\tNo\nItem 3\t3\tNo") && model.selected_text() == text.clone().unwrap_or_default();
    use objc2::runtime::NSObjectProtocol as _;
    let responds = tv.respondsToSelector(objc2::sel!(copy:)) && tv.respondsToSelector(objc2::sel!(paste:));
    check("table-copy", copied && tsv && responds, format!("copied: {copied}; text {text:?}; responds to copy:/paste: {responds}"));

    // ⌘V: the app gets the text; here it parses lines into rows.
    set_pasteboard_text(&pb, "New A\t7\nNew B\t8");
    let pasted = model.paste_from(&pb);
    let refused = !main_table.paste_from(&pb);
    release_pasteboard(&pb);
    let s2 = s.clone();
    after_events(move || {
        let s = &s2;
        let m = &s.model;
        let tail: Vec<Item2> = m.rows()[10..].to_vec();
        check(
            "table-paste",
            pasted && refused && s.pastes.get_untracked() == 1 && tail == [Item2 { name: "New A".into(), n: 7.0 }, Item2 { name: "New B".into(), n: 8.0 }],
            format!("pasted: {pasted}; a table without on_paste refuses: {refused}; rows added {tail:?}"),
        );

        // Dragging rows out: each carries its cells as text.
        let out = drag_rows(&m.table_view(), &[2]);
        let out_text = out.as_ref().and_then(|p| pasteboard_text(p));
        let main_off = drag_rows(&TABLE.with(|t| t.model.table_view()), &[0]).is_none();
        check(
            "table-drag-out",
            out_text.as_deref() == Some("Item 2\t2\tNo") && main_off,
            format!("row 2 drags as {out_text:?}; a table without row drag gives none: {main_off}"),
        );
        if let Some(p) = &out {
            release_pasteboard(p);
        }

        // Reorder: rows 0 and 1 dropped above row 5.
        let pb = drag_rows(&m.table_view(), &[0, 1]).unwrap();
        let accepted = drop_on_table(&m.table_view(), &pb, 5, true);
        let s3 = s.clone();
        let events = events.clone();
        after_events(move || {
            let s = &s3;
            let m = &s.model;
            let order = names(m);
            let moves = s.moves.get_untracked();
            let selected = m.selection();
            // Sorted, the same drop is refused.
            m.set_sort(Some(Sort { column: "n".into(), ascending: false }));
            let sorted_refused = !drop_on_table(&m.table_view(), &pb, 2, true);
            m.set_sort(None);
            release_pasteboard(&pb);
            // move_rows against a plain reference, for awkward cases.
            let reference = |v: &[String], rows: &[usize], before: Option<usize>| -> Vec<String> {
                let mut rows = rows.to_vec();
                rows.sort_unstable();
                let moved: Vec<String> = rows.iter().map(|&r| v[r].clone()).collect();
                let end = before.unwrap_or(v.len());
                let mut out: Vec<String> = Vec::new();
                for (i, x) in v.iter().enumerate() {
                    if i == end {
                        out.extend(moved.iter().cloned());
                    }
                    if !rows.contains(&i) {
                        out.push(x.clone());
                    }
                }
                if end >= v.len() {
                    out.extend(moved.iter().cloned());
                }
                out
            };
            let cases: [(&[usize], Option<usize>); 4] = [(&[9, 2, 7], Some(4)), (&[0], None), (&[3, 4], Some(4)), (&[11], Some(0))];
            let mut move_ok = true;
            for (rows, before) in cases {
                let want = reference(&names(m), rows, before);
                m.move_rows(rows, before);
                move_ok &= names(m) == want;
            }
            check(
                "table-reorder",
                accepted
                    && moves == [(vec![0, 1], Some(5))]
                    && order[..6] == ["Item 2", "Item 3", "Item 4", "Item 0", "Item 1", "Item 5"]
                    && selected == [3, 4]
                    && sorted_refused
                    && move_ok,
                format!("accepted: {accepted}; event {moves:?}; order {:?}; selected {selected:?}; refused while sorted: {sorted_refused}; move_rows matches a reference in 4 more cases: {move_ok}", &order[..6]),
            );

            // Files from the Finder: .csv accepted above the shown row; .txt refused.
            let dir = std::env::temp_dir();
            let (a, b, t) = (dir.join("a.csv"), dir.join("b.csv"), dir.join("notes.txt"));
            let csvs = files_pasteboard(&[&a, &b]);
            let dropped = drop_on_table(&m.table_view(), &csvs, 1, false);
            let txt = files_pasteboard(&[&t]);
            let txt_refused = !drop_on_table(&m.table_view(), &txt, 1, false);
            // Rows from another table aren't a reorder here.
            let foreign = !drop_on_table(&m.table_view(), &drag_rows(&m.table_view(), &[0]).unwrap(), 1, false);
            // A link dragged from a browser: its address, above the row; a
            // file drop still goes to the files.
            let link = urls_pasteboard(&["https://example.com/report"]);
            let url_dropped = drop_on_table(&m.table_view(), &link, 2, false);
            [csvs, txt, link].iter().for_each(|p| release_pasteboard(p));
            let s4 = s.clone();
            let events = events.clone();
            after_events(move || {
                let files = s4.files.get_untracked();
                let want = vec![(vec![a.clone(), b.clone()], s4.model.row_at(1))];
                check(
                    "table-file-drop",
                    dropped && txt_refused && foreign && files == want,
                    format!("csv drop: {dropped} → {files:?}; .txt refused: {txt_refused}; rows without the table as source refused: {foreign}"),
                );
                let urls = s4.urls.get_untracked();
                check(
                    "table-url-drop",
                    url_dropped && urls == vec![(vec!["https://example.com/report".to_string()], s4.model.row_at(2))] && files.len() == 1,
                    format!("link drop: {url_dropped} → {urls:?}; files still {}", files.len()),
                );
                let w = windows().into_iter().find(|w| w.title().to_string() == "Transfer").unwrap();
                ferrokit::close_window(&w);
                let events = events.clone();
                after_events(move || frame_check(events.clone()));
            });
        });
    });
}

/// on_frame: calls come (from display frames, or the stand-in timer while
/// the display isn't drawing), run in a batch, and stop when the loop is dropped.
fn frame_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    let w = windows().into_iter().find(|w| w.title().to_string() == "Views").unwrap();
    let calls = Rc::new(Cell::new(0u32));
    let c = calls.clone();
    let lp = ferrokit::on_frame(&w, move |_| c.set(c.get() + 1));
    spawn(
        || std::thread::sleep(std::time::Duration::from_millis(500)),
        move |()| {
            let (display, fallback) = lp.counts();
            let seen = calls.get();
            drop(lp);
            let calls2 = calls.clone();
            spawn(
                || std::thread::sleep(std::time::Duration::from_millis(300)),
                move |()| {
                    let after = calls2.get();
                    check(
                        "frame-loop",
                        seen >= 3 && u64::from(seen) == display + fallback && after == seen,
                        format!("{seen} calls in 0.5 s ({display} from display frames, {fallback} from the stand-in timer); none after drop: {}", after == seen),
                    );
                    let events = events.clone();
                    after_events(move || appearance_check(events.clone()));
                },
            );
        },
    );
}

fn all_views(v: &NSView) -> Vec<Retained<NSView>> {
    let mut out = Vec::new();
    for s in v.subviews().iter() {
        out.extend(all_views(&s));
        out.push(s);
    }
    out
}

fn appearance_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    // Appearance: switching NSApp's appearance reaches the app as an event.
    let before = ferrokit::is_dark();
    ferrokit_core::testing::set_app_appearance(Some(!before));
    later(move || {
        let after = ferrokit::is_dark();
        let got = events.borrow().iter().filter(|e| **e == AppEvent::AppearanceChanged).count();
        check("appearance", after != before && got >= 1, format!("dark {before} → {after}, {got} event(s)"));
        // The native views themselves follow (they inherit NSApp's appearance).
        let controls = windows().into_iter().find(|w| w.title().to_string() == "Controls").unwrap();
        let views = controls.contentView().unwrap().subviews().to_vec();
        let names = unsafe {
            objc2_foundation::NSArray::from_slice(&[objc2_app_kit::NSAppearanceNameAqua, objc2_app_kit::NSAppearanceNameDarkAqua])
        };
        let dark_views = views
            .iter()
            .filter(|v| v.effectiveAppearance().bestMatchFromAppearancesWithNames(&names).is_some_and(|n: Retained<NSString>| n.to_string().contains("Dark")))
            .count();
        let want = if after { views.len() } else { 0 };
        check("dark-mode-views", dark_views == want, format!("{dark_views} of {} native views resolve to {}", views.len(), if after { "Dark Aqua" } else { "Aqua" }));
        ferrokit_core::testing::set_app_appearance(None);
        // See `main`: password AutoFill stays out of these runs.
        let autofill = objc2::runtime::AnyClass::get(c"SPSafariPlatformSupport").is_some();
        let major = objc2_foundation::NSProcessInfo::processInfo().operatingSystemVersion().majorVersion;
        if major < 26 {
            // macOS 15 loads it whatever the setting (seen on GitHub's runner).
            eprintln!("[check] autofill-off SKIP macOS {major} loads AutoFill regardless (loaded: {autofill})");
        } else {
            check("autofill-off", !autofill, format!("Safari's password AutoFill loaded: {autofill}"));
        }
        let failed = FAILED.with(Cell::get);
        eprintln!("[check] done, {failed} failed");
        std::process::exit(if failed == 0 { 0 } else { 1 });
    });
}

#[derive(Clone)]
struct Item {
    id: u32,
    name: String,
}

impl Identifiable for Item {
    type Id = u32;
    fn id(&self) -> u32 {
        self.id
    }
}

fn item(id: u32) -> Item {
    Item { id, name: format!("item{id}") }
}

#[derive(Clone)]
struct ViewState {
    items: Signal<Vec<Item>>,
    flag: Signal<bool>,
    inner: Signal<u32>,
    tab: Signal<u32>,
}

thread_local! {
    static STATE: ViewState = ViewState {
        items: Signal::new(vec![item(1), item(2), item(3)]),
        flag: Signal::new(true),
        inner: Signal::new(0),
        tab: Signal::new(0),
    };
}

fn state() -> ViewState {
    STATE.with(Clone::clone)
}

fn views_window() -> impl View {
    let st = state();
    let (items, flag, inner, tab) = (st.items, st.flag, st.inner, st.tab);
    vstack((
        text(move || format!("{} items", st.items.with(Vec::len))),
        for_each(move || items.get(), |it: Item| text(move || it.name.clone())),
        dynamic(move || {
            if flag.get() {
                let inner = inner;
                vstack((text("on"), text(move || format!("inner {}", inner.get())))).id("on")
            } else {
                text("off").id("off")
            }
        }),
        dynamic(move || {
            let t = tab.get();
            // Tabs 0 and 1 share an id: switching between them keeps the node.
            text(format!("tab {t}")).id(t / 2)
        }),
        spacer(),
    ))
    .padding(12.0)
}

/// The window's labels: (text, view).
fn labels() -> Vec<(String, Retained<NSTextField>)> {
    let w = windows().into_iter().find(|w| w.title().to_string() == "Views").unwrap();
    w.contentView()
        .unwrap()
        .subviews()
        .iter()
        .filter_map(|v| v.downcast::<NSTextField>().ok())
        .map(|f| (f.stringValue().to_string(), f))
        .collect()
}

fn find_label(text: &str) -> Option<Retained<NSTextField>> {
    labels().into_iter().find(|(t, _)| t == text).map(|(_, v)| v)
}


fn view_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let st = state();
    // Build: the tree's leaves are subviews of the window's root view.
    let names: Vec<String> = labels().into_iter().map(|(t, _)| t).collect();
    check(
        "views-build",
        ["3 items", "item1", "item2", "item3", "on", "inner 0", "tab 0"].iter().all(|t| names.iter().any(|n| n == t)),
        format!("{names:?}"),
    );

    // for_each: reorder + insert + remove keeps the surviving items' native views.
    let (v1, v2, v3) = (find_label("item1").unwrap(), find_label("item2").unwrap(), find_label("item3").unwrap());
    let weak2 = objc2::rc::Weak::from_retained(&v2);
    drop(v2);
    batch(|| st.items.set(vec![item(3), item(1), item(4)]));
    let (n1, n3, n4) = (find_label("item1").unwrap(), find_label("item3").unwrap(), find_label("item4").unwrap());
    let same = std::ptr::eq(&*v1, &*n1) && std::ptr::eq(&*v3, &*n3);
    let order = n3.frame().origin.y < n1.frame().origin.y && n1.frame().origin.y < n4.frame().origin.y;
    check(
        "for-each-identity",
        same && order && find_label("item2").is_none() && find_label("3 items").is_some(),
        format!("kept item1/item3 views: {same}; laid out 3,1,4: {order}"),
    );

    // dynamic: switching tears the old subtree down and stops its effects.
    let nodes_on = live_nodes();
    batch(|| st.flag.set(false));
    let runs = effect_runs();
    batch(|| st.inner.set(5));
    let stopped = effect_runs() == runs;
    check(
        "dynamic-teardown",
        find_label("off").is_some() && find_label("on").is_none() && find_label("inner 0").is_none() && stopped,
        format!("nodes {nodes_on} → {}; removed subtree's effect ran after removal: {}", live_nodes(), !stopped),
    );
    batch(|| st.flag.set(true));
    check("dynamic-rebuild", find_label("inner 5").is_some(), "rebuilt subtree reads the current value".into());

    // .id: same id keeps the node (and its text); a new id rebuilds.
    let t0 = find_label("tab 0").unwrap();
    batch(|| st.tab.set(1));
    let kept = find_label("tab 0").is_some_and(|v| std::ptr::eq(&*v, &*t0));
    batch(|| st.tab.set(2));
    let rebuilt = find_label("tab 2").is_some_and(|v| !std::ptr::eq(&*v, &*t0));
    check("id-identity", kept && rebuilt, format!("tab 0→1 kept the node: {kept}; 1→2 rebuilt: {rebuilt}"));

    // Teardown: churn 1,000 × 10 items; nodes and subviews return to baseline.
    let base_nodes = live_nodes();
    let base_views = labels().len();
    // Warm-up: one full churn (first-time AppKit and allocator growth), then
    // measure a second one. A leak shows as growth; a one-off peak doesn't.
    for round in 0..1000u32 {
        batch(|| st.items.set((0..10).map(|i| item(50_000 + round * 10 + i)).collect()));
        batch(|| st.items.set(vec![]));
    }
    let rss0 = footprint_mb();
    let t = std::time::Instant::now();
    for round in 0..1000u32 {
        batch(|| st.items.set((0..10).map(|i| item(10_000 + round * 10 + i)).collect()));
        batch(|| st.items.set(vec![]));
    }
    let ms = t.elapsed().as_secs_f64() * 1e3;
    batch(|| st.items.set(vec![item(3), item(1), item(4)]));
    later(move || {
        let removed_gone = weak2.load().is_none();
        let rss1 = footprint_mb();
        check(
            "teardown-churn",
            // AppKit keeps about 0.64 KB per view ever shown; budget 0.9 KB.
            live_nodes() == base_nodes && labels().len() == base_views && removed_gone && rss1 - rss0 < 9.0,
            format!(
                "10,000 rows built and removed in {ms:.0} ms; nodes {base_nodes} → {}; views {base_views} → {}; removed view deallocated: {removed_gone}; footprint {rss0:.0} → {rss1:.0} MB = {:.2} KB per view (AppKit's floor ≈ 0.64; budget 0.9)",
                live_nodes(),
                labels().len(),
                (rss1 - rss0) * 1024.0 / 10_000.0
            ),
        );
        layout_checks(events.clone());
    });
}

thread_local! {
    static WIDE: Signal<String> = Signal::new("short".into());
}

fn layout_window() -> impl View {
    let wide = WIDE.with(Clone::clone);
    vstack((
        vstack((text("A wide label for alignment"), text("mid"))).alignment(Align::Center),
        vstack((text("A wide label for alignment"), text("end"))).alignment(Align::End),
        hstack((text("tall\nlabel\nhere"), text("bottom"))).alignment(Align::End),
        grid([
            (text("Name"), text("Alice"), text("x")),
            (text("A much longer key"), text("Bob"), text("y")),
        ]),
        hstack((text("left"), spacer(), text("right"))),
        text("filled").fill_width(),
        text("framed").frame(121.0, 41.0),
        hstack((text(move || wide.get()), text("after"))),
    ))
    .padding(13.0)
}

fn frame_of(window: &str, text: &str) -> objc2_foundation::NSRect {
    let w = windows().into_iter().find(|w| w.title().to_string() == window).unwrap();
    w.contentView()
        .unwrap()
        .subviews()
        .iter()
        .filter_map(|v| v.downcast::<NSTextField>().ok())
        .filter(|f| f.stringValue().to_string() == text)
        .map(|f| f.frame())
        .last()
        .unwrap()
}

fn layout_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let f = |t: &str| frame_of("Layout", t);
    let mid_x = |r: objc2_foundation::NSRect| r.origin.x + r.size.width / 2.0;
    let max_x = |r: objc2_foundation::NSRect| r.origin.x + r.size.width;
    let max_y = |r: objc2_foundation::NSRect| r.origin.y + r.size.height;
    let wides: Vec<_> = {
        let w = windows().into_iter().find(|w| w.title().to_string() == "Layout").unwrap();
        w.contentView().unwrap().subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok()).filter(|t| t.stringValue().to_string() == "A wide label for alignment").map(|t| t.frame()).collect()
    };
    let (mid, end) = (f("mid"), f("end"));
    check(
        "align-center-end",
        (mid_x(mid) - mid_x(wides[0])).abs() <= 0.5 && (max_x(end) - max_x(wides[1])).abs() <= 0.5,
        format!("centre {:.1} vs {:.1}; trailing {:.1} vs {:.1}", mid_x(mid), mid_x(wides[0]), max_x(end), max_x(wides[1])),
    );
    let (tall, bottom) = (f("tall\nlabel\nhere"), f("bottom"));
    check("align-bottom", (max_y(tall) - max_y(bottom)).abs() <= 0.5, format!("bottoms {:.1} / {:.1}", max_y(tall), max_y(bottom)));
    let (alice, bob, key) = (f("Alice"), f("Bob"), f("A much longer key"));
    check(
        "grid-columns",
        alice.origin.x == bob.origin.x && bob.origin.x >= max_x(key) + 8.0 - 0.5 && f("x").origin.x == f("y").origin.x,
        format!("column 2 at {:.1} / {:.1}; longest key ends at {:.1}", alice.origin.x, bob.origin.x, max_x(key)),
    );
    let content_w = windows().into_iter().find(|w| w.title().to_string() == "Layout").unwrap().contentView().unwrap().bounds().size.width;
    let (left, right) = (f("left"), f("right"));
    check(
        "spacer",
        left.origin.x == 13.0 && (max_x(right) - (content_w - 13.0)).abs() <= 0.5,
        format!("left at {:.1}, right ends at {:.1} of {:.1}", left.origin.x, max_x(right), content_w - 13.0),
    );
    let (filled, framed) = (f("filled"), f("framed"));
    check(
        "fill-and-frame",
        (filled.size.width - (content_w - 26.0)).abs() <= 0.5 && framed.size.width == 121.0 && framed.size.height == 41.0,
        format!("filled {:.1} wide (of {:.1}); framed {:.1}×{:.1}", filled.size.width, content_w - 26.0, framed.size.width, framed.size.height),
    );
    let all: Vec<_> = {
        let w = windows().into_iter().find(|w| w.title().to_string() == "Layout").unwrap();
        w.contentView().unwrap().subviews().iter().map(|v| v.frame()).collect()
    };
    let snapped = all.iter().all(|r| [r.origin.x, r.origin.y, r.size.width, r.size.height].iter().all(|v| (v * 2.0).fract() == 0.0));
    check("pixel-snapping", snapped, format!("{} frames on the 0.5 pt grid (2x)", all.len()));

    // A label that changes width moves its sibling; the rest of the window is skipped.
    let wide = WIDE.with(Clone::clone);
    let before = f("after").origin.x;
    let (p0, s0, _) = layout_stats();
    batch(|| wide.set("a considerably longer text".into()));
    let (p1, s1, _) = layout_stats();
    let after = f("after").origin.x;
    check(
        "subtree-relayout",
        after > before && p1 - p0 <= 6,
        format!("sibling moved {before:.1} → {after:.1}; {} nodes placed, {} subtrees skipped", p1 - p0, s1 - s0),
    );
    layout_bench(events);
}

/// 1,000 native views (250 stretching rows × label, label, button, label): resize layout
/// and the cost of a label update.
fn layout_bench(events: Rc<RefCell<Vec<AppEvent>>>) {
    let counter = Signal::new(0u64);
    let c = counter;
    let rows: Vec<_> = (0..250)
        .map(|i| {
            hstack((
                if i == 0 { ferrokit::AnyView::new(text(move || format!("Counter {}", c.get()))) } else { ferrokit::AnyView::new(text(format!("Row {i}"))) },
                text("Some label"),
                spacer(), // rows stretch: every row re-lays out on resize
                button("Go", || {}),
                text("tail"),
            ))
        })
        .map(ferrokit::AnyView::new)
        .collect();
    let t = std::time::Instant::now();
    let w = open(Window::new("Bench").size(700.0, 700.0).view(vstack(rows).padding(12.0)));
    let build_ms = t.elapsed().as_secs_f64() * 1e3;
    let views = w.contentView().unwrap().subviews().len();
    let n0 = layout_passes();
    for k in 0..200 {
        w.setContentSize(objc2_foundation::NSSize::new(600.0 + (k % 40) as f64 * 10.0, 700.0));
    }
    let times = layout_times_us();
    let new = ((layout_passes() - n0) as usize).min(times.len());
    let mut resize: Vec<f64> = times[times.len() - new..].to_vec();
    resize.sort_by(|a, b| a.total_cmp(b));
    let mut upd = Vec::new();
    let (p0, _, _) = layout_stats();
    for _ in 0..500 {
        let t = std::time::Instant::now();
        batch(|| counter.update(|v| *v += 1));
        upd.push(t.elapsed().as_secs_f64() * 1e6);
    }
    let (p1, _, _) = layout_stats();
    upd.sort_by(|a, b| a.total_cmp(b));
    let p = |v: &[f64], q: usize| v[(v.len() - 1) * q / 100];
    check(
        "layout-bench",
        views == 1000 && ((p(&resize, 50) < 2000.0 && p(&upd, 50) < 72.0) || on_ci()),
        format!(
            "{views} views built in {build_ms:.0} ms; resize layout p50 {:.2} ms, p95 {:.2} ms; label update p50 {:.1} µs, p95 {:.1} µs, {:.1} nodes placed per update (P0: 0.75 ms, 72 µs)",
            p(&resize, 50) / 1000.0, p(&resize, 95) / 1000.0, p(&upd, 50), p(&upd, 95), (p1 - p0) as f64 / 500.0
        ),
    );
    controls_checks(events);
}

#[derive(Clone)]
struct Ctrl {
    name: Signal<String>,
    pw: Signal<String>,
    wifi: Signal<bool>,
    remember: Signal<bool>,
    submits: Signal<u32>,
    saves: Signal<u32>,
}

thread_local! {
    static CTRL: Ctrl = Ctrl {
        name: Signal::new(String::new()),
        pw: Signal::new(String::new()),
        wifi: Signal::new(false),
        remember: Signal::new(false),
        submits: Signal::new(0),
        saves: Signal::new(0),
    };
}

fn controls_window() -> impl View {
    let c = CTRL.with(Clone::clone);
    let (submits, saves, name) = (c.submits, c.saves, c.name);
    let summary = c.clone();
    vstack((
        text_field(&c.name).placeholder("Your name").on_submit(move || submits.update(|n| *n += 1)),
        secure_field(&c.pw).placeholder("Password"),
        toggle("Wi-Fi", &c.wifi),
        checkbox("Remember me", &c.remember),
        button("Save", move || saves.update(|n| *n += 1)).disabled(move || name.with(String::is_empty)).default_action(),
        text(move || {
            format!(
                "{} / {} chars / wifi {} / remember {}",
                summary.name.get(),
                summary.pw.with(String::len),
                summary.wifi.get(),
                summary.remember.get()
            )
        }),
    ))
    .padding(16.0)
}




fn controls_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSButton, NSSecureTextField, NSSwitch};
    let c = CTRL.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Controls").unwrap();
    let subs: Vec<Retained<NSView>> = w.contentView().unwrap().subviews().to_vec();
    let secure = subs.iter().find_map(|v| v.clone().downcast::<NSSecureTextField>().ok()).unwrap();
    let field = subs
        .iter()
        .filter_map(|v| v.clone().downcast::<NSTextField>().ok())
        .find(|f| f.isEditable() && !std::ptr::eq(&**f, &**secure as &NSTextField))
        .unwrap();
    let switch = subs.iter().find_map(|v| v.clone().downcast::<NSSwitch>().ok()).unwrap();
    let buttons: Vec<Retained<NSButton>> = subs.iter().filter_map(|v| v.clone().downcast::<NSButton>().ok()).collect();
    let check_box = buttons.iter().find(|b| b.title().to_string() == "Remember me").unwrap().clone();
    let save = buttons.iter().find(|b| b.title().to_string() == "Save").unwrap().clone();
    let summary = || {
        subs.iter()
            .filter_map(|v| v.clone().downcast::<NSTextField>().ok())
            .map(|f| f.stringValue().to_string())
            .find(|s| s.contains("chars"))
            .unwrap_or_default()
    };

    // AppKit gives a default button its Return key equivalent only while
    // its window is key (the bench window took key status before this).
    w.makeKeyAndOrderFront(None);
    // Text field: placeholder; user edits → signal → label and the Save button.
    let was_disabled = !save.isEnabled();
    post_edit(&field, "Ada");
    check(
        "text-field-edit",
        c.name.get_untracked() == "Ada" && summary().starts_with("Ada /") && was_disabled && save.isEnabled()
            && field.placeholderString().map(|p| p.to_string()) == Some("Your name".into()),
        format!("signal {:?}; Save enabled {} → {}; summary {:?}", c.name.get_untracked(), !was_disabled, save.isEnabled(), summary()),
    );
    batch(|| c.name.set("Grace".into()));
    check("text-field-signal", field.stringValue().to_string() == "Grace", format!("field shows {:?}", field.stringValue().to_string()));
    let sent = unsafe { field.sendAction_to(field.action(), field.target().as_deref()) };
    check("text-field-submit", sent && c.submits.get_untracked() == 1, format!("Return action sent: {sent}, submits {}", c.submits.get_untracked()));

    // Secure field.
    post_edit(&secure, "hunter2");
    check(
        "secure-field",
        c.pw.get_untracked() == "hunter2" && summary().contains("7 chars") && has_ax(&ax_tree(&w), "AXTextField", "AXSecureTextField", ""),
        format!("signal len {}, AXSecureTextField in the AX tree: {}", c.pw.get_untracked().len(), has_ax(&ax_tree(&w), "AXTextField", "AXSecureTextField", "")),
    );

    // Switch and checkbox: clicks → signal; signal → control.
    unsafe { switch.performClick(None) };
    let on = c.wifi.get_untracked();
    batch(|| c.wifi.set(false));
    check(
        "toggle",
        on && switch.state() == objc2_app_kit::NSControlStateValueOff && ax_tree(&w).iter().any(|(_, s, _)| s == "AXSwitch"),
        format!("click → {on}; signal false → state {}; AXSwitch in the AX tree: {}", switch.state(), ax_tree(&w).iter().any(|(_, s, _)| s == "AXSwitch")),
    );
    unsafe { check_box.performClick(None) };
    let on = c.remember.get_untracked();
    batch(|| c.remember.set(false));
    check(
        "checkbox",
        on && check_box.state() == objc2_app_kit::NSControlStateValueOff && has_ax(&ax_tree(&w), "AXCheckBox", "", "Remember me"),
        format!("click → {on}; signal false → state {}; AXCheckBox \"Remember me\" in the AX tree: {}", check_box.state(), has_ax(&ax_tree(&w), "AXCheckBox", "", "Remember me")),
    );

    // Default button: Return key equivalent; click runs the action; disabled follows the signal.
    unsafe { save.performClick(None) };
    let saved = c.saves.get_untracked();
    batch(|| c.name.set(String::new()));
    check(
        "button-default-disabled",
        save.keyEquivalent().to_string() == "\r" && saved == 1 && !save.isEnabled(),
        format!("key equivalent {:?}; saves {saved}; enabled after clearing the name: {}", save.keyEquivalent().to_string(), save.isEnabled()),
    );

    // Tab: from the name field to the password field (key view loop by position).
    // A Tab key press reaches the field editor as insertTab:, which moves
    // to the next key view (AppKit's loop, recalculated from positions).
    // Focus leaving the password field can raise an NSRangeException inside
    // Safari's password AutoFill (SafariPlatformSupport, when its list is
    // up); the run loop swallowed it and ended this chain of checks.
    let raised = objc2::exception::catch(std::panic::AssertUnwindSafe(|| {
        w.makeFirstResponder(Some(&field));
        if let Some(editor) = field.currentEditor() {
            let _: () = unsafe { objc2::msg_send![&*editor, insertTab: Option::<&objc2::runtime::AnyObject>::None] };
        }
    }))
    .err()
    .map(|e| format!("; AppKit raised {:?} (password AutoFill) on the way", e.map(|e| e.to_string())));
    check(
        "tab-order",
        secure.currentEditor().is_some() || raised.is_some(),
        format!("Tab moves from the name field to the password field{}", raised.unwrap_or_default()),
    );

    controls_b_checks(events);
}

#[derive(Clone)]
struct CtrlB {
    size: Signal<u32>,
    volume: Signal<f64>,
    count: Signal<f64>,
    progress: Signal<Option<f64>>,
    lines: Signal<Vec<Item>>,
}

thread_local! {
    static CTRL_B: CtrlB = CtrlB {
        size: Signal::new(2),
        volume: Signal::new(0.5),
        count: Signal::new(3.0),
        progress: Signal::new(Some(0.4)),
        lines: Signal::new((1..=60).map(item).collect()),
    };
}

fn controls_b_window() -> impl View {
    let c = CTRL_B.with(Clone::clone);
    let (count, prog, lines) = (c.count, c.progress, c.lines);
    vstack((
        picker(&c.size, vec![("Small", 1), ("Medium", 2), ("Large", 3)]).accessibility_label("Size"),
        hstack((slider(&c.volume, 0.0, 1.0).accessibility_label("Volume"), stepper(&c.count, 0.0, 10.0, 1.0).accessibility_label("Count"), text(move || format!("count {}", count.get())))),
        progress(move || prog.get()),
        hstack((image("star.fill").description("Favourite"), text("starred"))),
        divider(),
        scroll(vstack((for_each(move || lines.get(), |it: Item| text(move || it.name.clone())),))),
    ))
    .padding(16.0)
}




fn controls_field() -> (Retained<objc2_app_kit::NSWindow>, Retained<NSTextField>, Retained<objc2_app_kit::NSSecureTextField>) {
    let w = windows().into_iter().find(|w| w.title().to_string() == "Controls").unwrap();
    let subs: Vec<Retained<NSView>> = w.contentView().unwrap().subviews().to_vec();
    let secure = subs.iter().find_map(|v| v.clone().downcast::<objc2_app_kit::NSSecureTextField>().ok()).unwrap();
    let field = subs
        .iter()
        .filter_map(|v| v.clone().downcast::<NSTextField>().ok())
        .find(|f| f.isEditable() && !std::ptr::eq(&**f, &**secure as &NSTextField))
        .unwrap();
    (w, field, secure)
}

fn editor_of(field: &NSTextField) -> Retained<objc2_app_kit::NSTextView> {
    field.currentEditor().unwrap().downcast::<objc2_app_kit::NSTextView>().unwrap()
}

/// Ported Phase 1 checks: Shift-Tab, edit shortcuts through the menu,
/// Japanese input composition and the candidate window position.
fn keyboard_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let c = CTRL.with(Clone::clone);
    let (w, field, secure) = controls_field();
    w.makeKeyAndOrderFront(None);

    // Shift-Tab: from the password field back to the name field.
    w.makeFirstResponder(Some(&secure));
    if let Some(editor) = secure.currentEditor() {
        let _: () = unsafe { objc2::msg_send![&*editor, insertBacktab: Option::<&objc2::runtime::AnyObject>::None] };
    }
    check("shift-tab", field.currentEditor().is_some(), "Shift-Tab moves from the password field to the name field".into());

    // Shortcuts: type, ⌘A selects all, ⌘Z undoes the typing, ⇧⌘Z redoes it;
    // each goes through the menu bar's key equivalents to the focused field.
    batch(|| c.name.set(String::new()));
    w.makeFirstResponder(Some(&field));
    let ed = editor_of(&field);
    unsafe { ed.insertText_replacementRange(&NSString::from_str("Hello"), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
    let typed = c.name.get_untracked();
    later(move || {
        let (w, field, _) = controls_field();
        let ed = editor_of(&field);
        let sel_all = shortcut(&w, "a", false) && ed.selectedRange().length == 5;
        let undo_sent = shortcut(&w, "z", false);
        let (c, typed, events) = (c.clone(), typed.clone(), events.clone());
        // The field reports the undone text on the next pass.
        later(move || {
            let (w, field, _) = controls_field();
            // With the app active, the binding follows undo/redo. When another
            // app is in front, AppKit doesn't send the field's change
            // notification for an undo (no key window), so check the field.
            let active = NSApplication::sharedApplication(mtm()).isActive();
            let read = |f: &NSTextField| if active { c.name.get_untracked() } else { f.stringValue().to_string() };
            let after_undo = read(&field);
            let redo_sent = shortcut(&w, "z", true);
            let (c, typed, events, after_undo) = (c.clone(), typed.clone(), events.clone(), after_undo.clone());
            later(move || {
                let after_redo = if active { c.name.get_untracked() } else { field.stringValue().to_string() };
                check(
                    "shortcuts",
                    typed == "Hello" && sel_all && undo_sent && after_undo.is_empty() && redo_sent && after_redo == "Hello",
                    format!(
                        "typed {typed:?}; ⌘A selected all: {sel_all}; ⌘Z → {after_undo:?}; ⇧⌘Z → {after_redo:?} ({})",
                        if active { "app active: checked the binding" } else { "app inactive: checked the field" }
                    ),
                );
                ime_checks(events.clone());
            });
        });
    });
}

fn has_input_context(ed: &objc2_app_kit::NSTextView) -> bool {
    let ctx: Option<Retained<objc2::runtime::AnyObject>> = unsafe { objc2::msg_send![ed, inputContext] };
    ctx.is_some()
}

fn ime_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::NSTextInputClient;
    let c = CTRL.with(Clone::clone);
    let (w, field, _) = controls_field();
    batch(|| c.name.set(String::new()));
    w.makeFirstResponder(Some(&field));
    // No field editor (the field couldn't become first responder, e.g. in
    // an inactive app on a CI runner): nothing to compose into.
    let Some(ed) = field.currentEditor().and_then(|e| e.downcast::<objc2_app_kit::NSTextView>().ok()) else {
        let why = "skipped: the field has no editor here (it couldn't become first responder)".to_string();
        check("ime-composition", true, why.clone());
        check("ime-candidate-rect", true, why);
        return teardown_checks(events);
    };
    let not_found = objc2_foundation::NSRange::new(usize::MAX >> 1, 0);
    eprintln!("[step] ime: composing in {:?}", ed.class().name());
    // Composition: "toukyou" as marked text, then commit 東京.
    unsafe {
        ed.setMarkedText_selectedRange_replacementRange(
            &NSString::from_str("とうきょう"),
            objc2_foundation::NSRange::new(5, 0),
            not_found,
        )
    };
    let marked = ed.hasMarkedText();
    let during = c.name.get_untracked();
    // The candidate window goes where the input method asks: the caret's
    // screen rectangle, which must lie on the field.
    let rect = unsafe { ed.firstRectForCharacterRange_actualRange(objc2_foundation::NSRange::new(0, 5), std::ptr::null_mut()) };
    let field_screen = w.convertRectToScreen(field.convertRect_toView(field.bounds(), None));
    let on_field = rect.origin.x >= field_screen.origin.x - 1.0
        && rect.origin.x < field_screen.origin.x + field_screen.size.width
        && rect.origin.y >= field_screen.origin.y - 1.0
        && rect.origin.y + rect.size.height <= field_screen.origin.y + field_screen.size.height + 1.0;
    unsafe { ed.insertText_replacementRange(&NSString::from_str("東京"), not_found) };
    let committed = c.name.get_untracked();
    check(
        "ime-composition",
        marked && !ed.hasMarkedText() && committed == "東京" && has_input_context(&ed),
        format!("marked while composing: {marked} (signal meanwhile {during:?}); committed → {committed:?}"),
    );
    check(
        "ime-candidate-rect",
        on_field && rect.size.height > 0.0,
        format!(
            "marked-text rect ({:.0}, {:.0}, {:.0}×{:.0}) on the field at ({:.0}, {:.0}, {:.0}×{:.0})",
            rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
            field_screen.origin.x, field_screen.origin.y, field_screen.size.width, field_screen.size.height
        ),
    );
    teardown_checks(events);
}

thread_local! {
    static FORM: Signal<bool> = Signal::new(true);
}

fn teardown_window() -> impl View {
    let show = FORM.with(Clone::clone);
    dynamic(move || {
        if show.get() {
            let (t, b, n, f) = (Signal::new(String::new()), Signal::new(false), Signal::new(0.5), Signal::new(1u32));
            ferrokit::AnyView::new(
                vstack((
                    text_field(&t).placeholder("name"),
                    secure_field(&t),
                    toggle("switch", &b),
                    checkbox("check", &b),
                    picker(&f, vec![("one", 1), ("two", 2)]),
                    hstack((slider(&n, 0.0, 1.0), stepper(&n, 0.0, 1.0, 0.1))),
                    progress(move || Some(n.get())),
                    vstack((image("star"), button("go", || {}), divider(), scroll(vstack((text("a"), text("b")))))),
                ))
                .padding(12.0),
            )
            .id(1)
        } else {
            ferrokit::AnyView::new(text("off")).id(0)
        }
    })
}

/// Every control type built and torn down 300 times (after a warm-up):
/// nodes, subviews and footprint return to baseline; controls deallocate.
fn teardown_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let show = FORM.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Teardown").unwrap();
    let switch = w.contentView().unwrap().subviews().iter().find_map(|v| v.downcast::<objc2_app_kit::NSSwitch>().ok()).unwrap();
    let weak = objc2::rc::Weak::from_retained(&switch);
    drop(switch);
    for _ in 0..100 {
        batch(|| show.set(false));
        batch(|| show.set(true));
    }
    fn count(v: &NSView) -> usize {
        1 + v.subviews().iter().map(|c| count(&c)).sum::<usize>()
    }
    // Every view in the form, AppKit's internal subviews included.
    let per_form = count(&w.contentView().unwrap()) - 1;
    let (n0, v0, f0, s0) = (live_nodes(), w.contentView().unwrap().subviews().len(), footprint_mb(), ferrokit::live_signals());
    let t = std::time::Instant::now();
    let cycles = || {
        for _ in 0..300 {
            batch(|| show.set(false));
            batch(|| show.set(true));
        }
    };
    cycles();
    let ms = t.elapsed().as_secs_f64() * 1e3;
    // Two batches, the smaller growth counted: the first can be refilling
    // memory the allocator kept free from earlier checks (the baseline
    // moves with them), while a cost per view shows in both.
    let f_mid = footprint_mb();
    cycles();
    later(move || {
        let w = windows().into_iter().find(|w| w.title().to_string() == "Teardown").unwrap();
        let (n1, v1, f1, s1) = (live_nodes(), w.contentView().unwrap().subviews().len(), footprint_mb(), ferrokit::live_signals());
        let gone = weak.load().is_none();
        // AppKit keeps ~1 KB per view ever measured and added to a window
        // (plain AppKit, same form: 7.5 MB per 300 cycles); more is ours.
        let per = |mb: f64| mb * 1024.0 / (300.0 * per_form as f64);
        let kb_per_view = per(f_mid - f0).min(per(f1 - f_mid));
        check(
            "controls-teardown",
            n1 == n0 && v1 == v0 && s1 == s0 && gone && kb_per_view < 1.5,
            format!("2 × 300 × a 15-control form ({per_form} views), the first in {ms:.0} ms; nodes {n0} → {n1}; subviews {v0} → {v1}; signals {s0} → {s1}; first switch deallocated: {gone}; footprint {f0:.0} → {f_mid:.0} → {f1:.0} MB = {:.2} then {:.2} KB per view created, {kb_per_view:.2} counted (AppKit's floor ≈ 1)", per(f_mid - f0), per(f1 - f_mid)),
        );
        table_checks(events.clone());
    });
}

#[derive(Clone)]
struct Order {
    name: String,
    qty: f64,
    done: bool,
}

#[derive(Clone)]
struct TableState {
    model: Rc<TableModel<Order>>,
    selected: Signal<Vec<usize>>,
    activated: Signal<Option<usize>>,
    sorted: Signal<Option<Sort>>,
    edits: Signal<u32>,
    show: Signal<bool>,
}

thread_local! {
    static TABLE: TableState = {
        let model = Rc::new(TableModel::new(
            ViewId(500),
            vec![
                Column::text("name", "Name", |o: &Order| o.name.clone()).width(180.0).editable(true),
                Column::number("qty", "Qty", |o: &Order| o.qty).editable(true).style(|o: &Order| ferrokit::CellStyle {
                    // Done orders struck through; the largest tinted.
                    strikethrough: o.done,
                    color: o.done.then_some(ferrokit::Color::Secondary),
                    background: (o.qty >= 49.0).then_some(ferrokit::Color::Rgba(1.0, 0.6, 0.0, 0.3)),
                    italic: false,
                }),
                Column::check("done", "Done", |o: &Order| o.done),
            ],
        ));
        let t = std::time::Instant::now();
        model.set_rows((0..200_000).map(|i| Order { name: format!("Order {i:06}"), qty: (i % 50) as f64, done: i % 3 == 0 }).collect());
        eprintln!("[time] 200k rows into the model: {:.0} ms", t.elapsed().as_secs_f64() * 1e3);
        TableState {
            model,
            selected: Signal::new(vec![]),
            activated: Signal::new(None),
            sorted: Signal::new(None),
            edits: Signal::new(0),
            show: Signal::new(true),
        }
    };
}

fn table_window() -> impl View {
    let t = TABLE.with(Clone::clone);
    let (t1, t2, t3, t4, t5, t6) = (t.clone(), t.clone(), t.clone(), t.clone(), t.clone(), t.clone());
    vstack((
        text(move || format!("{} selected", t1.selected.with(Vec::len))),
        dynamic(move || {
            if t2.show.get() {
                let (t3, t4, t5, t6) = (t3.clone(), t4.clone(), t5.clone(), t6.clone());
                ferrokit::AnyView::new(
                    table(&t3.model.clone())
                        .on_select(move |rows| t3.selected.set(rows))
                        .on_activate(move |row| t4.activated.set(Some(row)))
                        .on_sort(move |sort| t5.sorted.set(Some(sort)))
                        .on_toggle({
                            let t = t6.clone();
                            move |row, _, value| {
                                let mut o = t.model.rows()[row].clone();
                                o.done = value;
                                t.model.update_row(row, o);
                            }
                        })
                        .on_edit(move |row, column, value| {
                            let mut o = t6.model.rows()[row].clone();
                            match column.as_str() {
                                "name" => o.name = value,
                                _ => o.qty = value.parse().unwrap_or(o.qty),
                            }
                            t6.model.update_row(row, o);
                            t6.edits.update(|n| *n += 1);
                        }),
                )
                .id(1)
            } else {
                ferrokit::AnyView::new(text("no table")).id(0)
            }
        }),
    ))
    .padding(12.0)
}

/// Runs `f` after two run-loop passes (model events are delivered on the
/// pass after AppKit's callback).
fn after_events(f: impl Fn() + 'static) {
    after_events_dyn(Rc::new(f));
}

// Not generic, so the long chains of checks don't nest `later`'s closure
// types past the compiler's recursion limit (debug builds hit it).
fn after_events_dyn(f: Rc<dyn Fn()>) {
    later(move || {
        let f = f.clone();
        later(move || f())
    });
}

fn table_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSButton, NSTableView};
    let t = TABLE.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Table").unwrap();
    w.makeKeyAndOrderFront(None);
    let tv: Retained<NSTableView> = t.model.table_view();
    let sv = t.model.scroll_view();
    let fills = sv.frame().size.height > 300.0 && sv.frame().size.width > 500.0;
    check(
        "table-placed",
        tv.numberOfRows() == 200_000 && fills,
        format!("{} rows; scroll view {:.0}×{:.0} in a 560×420 window", tv.numberOfRows(), sv.frame().size.width, sv.frame().size.height),
    );

    // Selection through NSTableView → on_select (after the event pass).
    tv.selectRowIndexes_byExtendingSelection(&objc2_foundation::NSIndexSet::indexSetWithIndex(5), false);
    let t2 = t.clone();
    let events2 = events.clone();
    after_events(move || {
        let t = t2.clone();
        let tv = t.model.table_view();
        let w = windows().into_iter().find(|w| w.title().to_string() == "Table").unwrap();
        check("table-select", t.selected.get_untracked() == vec![5], format!("on_select got {:?}", t.selected.get_untracked()));

        // Return on the selected row → on_activate.
        let ev = objc2_app_kit::NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
            objc2_app_kit::NSEventType::KeyDown, objc2_foundation::NSPoint::new(0.0, 0.0), objc2_app_kit::NSEventModifierFlags::empty(), 0.0,
            w.windowNumber(), None, &NSString::from_str("\r"), &NSString::from_str("\r"), false, 36,
        ).unwrap();
        tv.keyDown(&ev);

        // Sort by quantity, descending, as a header click does.
        let desc = objc2_foundation::NSSortDescriptor::sortDescriptorWithKey_ascending(Some(&NSString::from_str("qty")), false);
        tv.setSortDescriptors(&objc2_foundation::NSArray::from_retained_slice(&[desc]));

        // Toggle a checkbox cell (row 1 shows a not-done order before sorting… use the visible row 0).
        let check_col = tv.columnWithIdentifier(&NSString::from_str("done"));
        let cell = tv.viewAtColumn_row_makeIfNecessary(check_col, 0, true).and_then(|v| v.downcast::<NSButton>().ok()).unwrap();
        let model_row = t.model.row_at(0).unwrap();
        let before = t.model.rows()[model_row].done;
        unsafe { cell.performClick(None) };

        // Edit the name of visible row 1 the way a user does: start editing, type, Return.
        let name_col = tv.columnWithIdentifier(&NSString::from_str("name"));
        let edit_row = t.model.row_at(1).unwrap();
        tv.editColumn_row_withEvent_select(name_col, 1, None, true);
        // View-based tables edit in the cell's own text field (its field
        // editor), not in the table.
        let name_cell = tv.viewAtColumn_row_makeIfNecessary(name_col, 1, true).and_then(|v| v.downcast::<NSTextField>().ok()).unwrap();
        let editing = name_cell.currentEditor().is_some();
        if let Some(ed) = name_cell.currentEditor().and_then(|e| e.downcast::<objc2_app_kit::NSTextView>().ok()) {
            unsafe { ed.selectAll(None) };
            unsafe { ed.insertText_replacementRange(&NSString::from_str("Renamed"), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
            let _: () = unsafe { objc2::msg_send![&*ed, insertNewline: Option::<&objc2::runtime::AnyObject>::None] };
        }
        let t3 = t.clone();
        let events3 = events2.clone();
        after_events(move || {
            let t = t3.clone();
            check("table-activate", t.activated.get_untracked() == Some(5), format!("Return activated {:?}", t.activated.get_untracked()));
            let first = t.model.row_at(0).map(|r| t.model.rows()[r].qty);
            check(
                "table-sort",
                t.sorted.get_untracked() == Some(Sort { column: "qty".into(), ascending: false }) && first == Some(49.0),
                format!("on_sort {:?}; first row qty {first:?}", t.sorted.get_untracked()),
            );
            let after = t.model.rows()[model_row].done;
            check("table-toggle", after != before, format!("row {model_row} done {before} → {after} (on_toggle → update_row)"));
            // Cell styles: each visible row's qty cell as its row says,
            // reused cells reset (a not-done row after a done one isn't struck).
            let tv = t.model.table_view();
            let qty_col = tv.columnWithIdentifier(&NSString::from_str("qty"));
            let styled: Vec<(bool, bool, bool, bool)> = (4..12)
                .filter_map(|pos| {
                    let row = t.model.row_at(pos)?;
                    let o = t.model.rows()[row].clone();
                    let f = tv.viewAtColumn_row_makeIfNecessary(qty_col, pos as isize, true)?.downcast::<NSTextField>().ok()?;
                    let text = f.attributedStringValue();
                    // SAFETY: an attribute lookup within the string's length.
                    let struck = text.length() > 0 && unsafe { text.attribute_atIndex_effectiveRange(objc2_app_kit::NSStrikethroughStyleAttributeName, 0, std::ptr::null_mut()) }.is_some();
                    Some((o.done, struck, o.qty >= 49.0, f.drawsBackground()))
                })
                .collect();
            let right = styled.iter().all(|(done, struck, big, tinted)| done == struck && big == tinted);
            let mixed = styled.iter().any(|s| s.0) && styled.iter().any(|s| !s.0) && styled.iter().any(|s| s.2);
            check("table-cell-style", styled.len() == 8 && right && mixed, format!("(done, struck, qty 49, tinted) per row: {styled:?}"));
            let name = t.model.rows()[edit_row].name.clone();
            let shown = t
                .model
                .table_view()
                .viewAtColumn_row_makeIfNecessary(t.model.table_view().columnWithIdentifier(&NSString::from_str("name")), 1, true)
                .and_then(|v| v.downcast::<NSTextField>().ok())
                .map(|f| f.stringValue().to_string());
            check(
                "table-edit",
                editing && name == "Renamed" && shown.as_deref() == Some("Renamed") && t.edits.get_untracked() == 1,
                format!("editor opened: {editing}; row {edit_row} name {name:?}; cell shows {shown:?}"),
            );
            // An edit the focus leaves (a click elsewhere) is kept; one
            // cancelled with Escape isn't an edit.
            let tv = t.model.table_view();
            let name_col = tv.columnWithIdentifier(&NSString::from_str("name"));
            let type_into = |view_row: isize, text: &str| {
                tv.editColumn_row_withEvent_select(name_col, view_row, None, true);
                let cell = tv.viewAtColumn_row_makeIfNecessary(name_col, view_row, true).and_then(|v| v.downcast::<NSTextField>().ok()).unwrap();
                let ed = cell.currentEditor().and_then(|e| e.downcast::<objc2_app_kit::NSTextView>().ok());
                if let Some(ed) = &ed {
                    unsafe { ed.selectAll(None) };
                    unsafe { ed.insertText_replacementRange(&NSString::from_str(text), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
                }
                ed
            };
            let (left_row, cancel_row) = (t.model.row_at(2).unwrap(), t.model.row_at(3).unwrap());
            let cancel_name = t.model.rows()[cancel_row].name.clone();
            let window = tv.window().unwrap();
            let left = type_into(2, "Clicked away").is_some();
            window.makeFirstResponder(Some(&tv));
            let cancelled = type_into(3, "Not kept");
            if let Some(ed) = &cancelled {
                // What Escape does: the field editor's cancelOperation: command.
                let _: () = unsafe { objc2::msg_send![&**ed, doCommandBySelector: objc2::sel!(cancelOperation:)] };
            }
            window.makeFirstResponder(Some(&tv));
            let t4 = t.clone();
            let events4 = events3.clone();
            after_events(move || {
                let t = t4.clone();
                let (kept, unchanged) = (t.model.rows()[left_row].name.clone(), t.model.rows()[cancel_row].name.clone());
                check(
                    "table-edit-focus",
                    left && cancelled.is_some() && kept == "Clicked away" && unchanged == cancel_name && t.edits.get_untracked() == 2,
                    format!("focus left: row {left_row} {kept:?}; Escape: row {cancel_row} {unchanged:?} (was {cancel_name:?}); edits {}", t.edits.get_untracked()),
                );
                field_commit_checks(events4.clone());
            });
        });
    });
}

/// A text field's `on_commit` runs when editing ends without Return (Tab,
/// or a click elsewhere), so an edit isn't lost by leaving the field.
fn field_commit_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let (value, commits) = (Signal::new(String::new()), Signal::new(Vec::<String>::new()));
    let w = open(Window::new("Commit").size(300.0, 80.0).view(
        vstack((text_field(&value).on_commit(move || commits.update(|c| c.push(value.get_untracked()))).accessibility_label("Field"),)).padding(12.0),
    ));
    w.makeKeyAndOrderFront(None);
    let field = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<NSTextField>().ok()).unwrap();
    w.makeFirstResponder(Some(&field));
    if let Some(ed) = field.currentEditor().and_then(|e| e.downcast::<objc2_app_kit::NSTextView>().ok()) {
        unsafe { ed.insertText_replacementRange(&NSString::from_str("left by a click"), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
    }
    // Focus leaves the field (as a click elsewhere does): editing ends.
    w.makeFirstResponder(None);
    after_events(move || {
        let got = commits.get_untracked();
        // (Focusing the field twice ends an empty edit first: a commit of
        // the unchanged value, which on_commit's docs allow.)
        check("field-commit", got.last().map(String::as_str) == Some("left by a click"), format!("on_commit saw {got:?}"));
        ferrokit::close_window(&w);
        live_segments_checks(events.clone());
    });
}

/// `segmented_with`: segments added, retitled and removed in place (the
/// same control), a click choosing the value; and values kept in user
/// defaults without a signal (`write_stored`, `read_stored`).
fn live_segments_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let tabs = Signal::new(vec![(1u64, "One".to_string())]);
    let chosen = Signal::new(1u64);
    let w = open(Window::new("Segments").size(360.0, 80.0).view(
        vstack((segmented_with(&chosen, move || tabs.get().into_iter().map(|(id, title)| (title, id)).collect()).accessibility_label("Tabs"),)).padding(12.0),
    ));
    fn control(w: &objc2_app_kit::NSWindow) -> Retained<objc2_app_kit::NSSegmentedControl> {
        all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSSegmentedControl>().ok()).unwrap()
    }
    let first = control(&w);
    let width = first.frame().size.width;
    batch(|| {
        tabs.set(vec![(1, "One".into()), (2, "Two".into()), (3, "Three".into())]);
        chosen.set(3);
    });
    after_events(move || {
        let c = control(&w);
        let labels = |c: &objc2_app_kit::NSSegmentedControl| (0..c.segmentCount()).map(|i| c.labelForSegment(i).map(|l| l.to_string()).unwrap_or_default()).collect::<Vec<_>>();
        let grown = labels(&c);
        let same = Retained::as_ptr(&c) == Retained::as_ptr(&first);
        let wider = c.frame().size.width > width + 20.0;
        let selected = c.selectedSegment();
        // A click on the second segment chooses its value.
        c.setSelectedSegment(1);
        unsafe { c.sendAction_to(c.action(), c.target().as_deref()) };
        let clicked = chosen.get_untracked();
        batch(|| tabs.update(|t| {
            t.remove(0);
            t[0].1 = "Second".into();
        }));
        let (w, events) = (w.clone(), events.clone());
        after_events(move || {
            let c = control(&w);
            let shrunk = labels(&c);
            write_stored("check.stored.direct", &"kept".to_string());
            let read: Option<String> = read_stored("check.stored.direct");
            remove_stored("check.stored.direct");
            let gone: Option<String> = read_stored("check.stored.direct");
            check(
                "live-segments",
                grown == ["One", "Two", "Three"] && same && wider && selected == 2 && clicked == 2 && shrunk == ["Second", "Three"] && c.selectedSegment() == 0,
                format!("grown {grown:?} (same control {same}, wider {wider}, selected {selected}); click chose {clicked}; shrunk {shrunk:?}, selected {}", c.selectedSegment()),
            );
            check("stored-direct", read.as_deref() == Some("kept") && gone.is_none(), format!("read {read:?}; after removing {gone:?}"));
            ferrokit::close_window(&w);
            completion_checks(events.clone());
        });
    });
}

/// A key-down for the text view (Return, Escape…), sent to it directly.
fn key_down(view: &objc2_app_kit::NSTextView, chars: &str, code: u16) {
    let w = view.window().unwrap();
    let e = objc2_app_kit::NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
        objc2_app_kit::NSEventType::KeyDown,
        objc2_foundation::NSPoint::new(0.0, 0.0),
        NSEventModifierFlags::empty(),
        0.0,
        w.windowNumber(),
        None,
        &NSString::from_str(chars),
        &NSString::from_str(chars),
        false,
        code,
    )
    .unwrap();
    view.keyDown(&e);
}

/// `TextModel::set_completer`: typing opens AppKit's completion list with
/// the completer's words, typing on filters them, Escape keeps what was
/// typed, Return puts the word in.
fn completion_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let model = TextModel::new(ViewId(9100), "");
    const WORDS: [&str; 4] = ["select", "serial", "set", "update"];
    model.set_completer(Some(|text: &str, caret: usize| {
        let start = text[..caret].rfind(|c: char| !c.is_alphanumeric()).map_or(0, |i| i + 1);
        let word = &text[start..caret];
        let items: Vec<String> = WORDS.iter().filter(|w| !word.is_empty() && w.starts_with(word) && **w != word).map(|w| w.to_string()).collect();
        Some(ferrokit::Completion { range: start..caret, items })
    }));
    let w = open(Window::new("Completion").size(360.0, 160.0).view(text_editor(&model).accessibility_label("Code")));
    w.makeKeyAndOrderFront(None);
    let tv = model.text_view();
    w.makeFirstResponder(Some(&tv));
    let typed = |t: &str| unsafe { tv.insertText_replacementRange(&NSString::from_str(t), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
    typed("s");
    typed("e");
    // The list opens in its own time (from a timer): wait for its words.
    let (m, w2) = (model.clone(), w.clone());
    let opened = model.clone();
    until(move || !opened.offered_completions().is_empty(), 3000, move || {
        let first = m.offered_completions();
        // The list may still be up, running its own event loop (on an idle
        // Mac nothing else ends it): close it as the user would, with an
        // Escape it reads, before typing on opens the next one.
        let was_open = completion_list_open();
        if was_open {
            post_key(&w2, "\u{1b}", NSEventModifierFlags::empty());
        }
        let (m, w2, first) = (m.clone(), w2.clone(), first.clone());
        let events = events.clone();
        until(|| !completion_list_open(), 3000, move || {
        let tv = m.text_view();
        unsafe { tv.insertText_replacementRange(&NSString::from_str("r"), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
        let (narrowed, before) = (m.clone(), first.clone());
        until(move || narrowed.offered_completions() != before, 3000, move || {
            let filtered = m.offered_completions();
            let tv = m.text_view();
            // Escape: the list goes, the text stays as typed.
            key_down(&tv, "\u{1b}", 53);
            let kept = m.text();
            // What AppKit's list sends (an inactive window's list takes no
            // keys in unattended runs): moving through it and typing on
            // leave the text as typed; Return puts the word in.
            let word = NSString::from_str("serial");
            let partial = objc2_foundation::NSRange::new(0, 3);
            tv.insertCompletion_forPartialWordRange_movement_isFinal(&word, partial, 0x10, false);
            tv.insertCompletion_forPartialWordRange_movement_isFinal(&word, partial, 0, true);
            let moving = m.text();
            tv.insertCompletion_forPartialWordRange_movement_isFinal(&word, partial, 0x10, true);
            let (m, w2, first, filtered) = (m.clone(), w2.clone(), first.clone(), filtered.clone());
            let events = events.clone();
            after_events(move || {
                let chosen = m.text();
                check(
                    "text-completion",
                    first == ["select", "serial", "set"] && filtered == ["serial"] && kept == "ser" && moving == "ser" && chosen == "serial",
                    format!("offered {first:?}, then after r {filtered:?}; Escape kept {kept:?}; moving and typing on kept {moving:?}; Return gave {chosen:?}"),
                );
                ferrokit::close_window(&w2);
                outline_expanded_checks(events.clone());
            });
        });
        });
    });
}

/// Whether this code runs inside AppKit's completion list: the list runs
/// its own event loop, in the event-tracking mode, while it's up.
fn completion_list_open() -> bool {
    objc2_foundation::NSRunLoop::currentRunLoop().currentMode().is_some_and(|m| m.to_string() == "NSEventTrackingRunLoopMode")
}

/// A `dynamic` inside a hidden view, rebuilt while hidden: its new views
/// stay hidden (they showed through), and show when the view does. The
/// same for a row a `for_each` adds there (found by an app on 0.5.0).
fn dynamic_hidden_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let (hide, which) = (Signal::new(true), Signal::new(1));
    let rows = Signal::new(vec![place(1, "Row 1", None)]);
    let w = open(Window::new("Hidden").size(300.0, 160.0).view(
        vstack((
            dynamic(move || button(format!("Branch {}", which.get()), || {})).hidden(move || hide.get()),
            vstack((text("Rows"), for_each(move || rows.get(), |p: Place| button(&p.name, || {})))).hidden(move || hide.get()),
            text("Always"),
        ))
        .padding(12.0),
    ));
    let all_buttons = |w: &objc2_app_kit::NSWindow| all_views(&w.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<objc2_app_kit::NSButton>().ok()).collect::<Vec<_>>();
    let buttons = move |w: &objc2_app_kit::NSWindow| all_buttons(w).into_iter().filter(|b| b.title().to_string().starts_with("Branch")).collect::<Vec<_>>();
    let row_buttons = move |w: &objc2_app_kit::NSWindow| all_buttons(w).into_iter().filter(|b| b.title().to_string().starts_with("Row")).map(|b| (b.title().to_string(), b.isHiddenOrHasHiddenAncestor())).collect::<Vec<_>>();
    batch(|| {
        which.set(2);
        rows.update(|r| r.push(place(2, "Row 2", None)));
    });
    let w2 = w.clone();
    after_events(move || {
        let rebuilt: Vec<(String, bool)> = buttons(&w2).iter().map(|b| (b.title().to_string(), b.isHiddenOrHasHiddenAncestor())).collect();
        let rows_hidden = row_buttons(&w2);
        batch(|| hide.set(false));
        let (w3, rebuilt) = (w2.clone(), rebuilt.clone());
        let events = events.clone();
        after_events(move || {
            let shown: Vec<(String, bool)> = buttons(&w3).iter().map(|b| (b.title().to_string(), b.isHiddenOrHasHiddenAncestor())).collect();
            check(
                "dynamic-hidden",
                rebuilt == [("Branch 2".to_string(), true)] && shown == [("Branch 2".to_string(), false)],
                format!("rebuilt while hidden {rebuilt:?}; shown {shown:?}"),
            );
            let rows_shown = row_buttons(&w3);
            let pair = |a: bool, b: bool| vec![("Row 1".to_string(), a), ("Row 2".to_string(), b)];
            check("foreach-hidden", rows_hidden == pair(true, true) && rows_shown == pair(false, false), format!("added while hidden {rows_hidden:?}; shown {rows_shown:?}"));
            ferrokit::close_window(&w3);
            tree_state_checks(events.clone());
        });
    });
}

/// Hidden and disabled come from the tree as it is now: nested hidden
/// views compose whatever order they change in, a hidden region doesn't
/// keep the views it replaced, a disabled view's later branches and rows
/// are disabled too, and a `for_each` row's signals go with the row.
fn tree_state_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use ferrokit::live_signals;
    use objc2_app_kit::NSButton;
    // Rows that change under a cell edit: what was typed is never written
    // to another row, and the table keeps the keyboard.
    {
        use objc2_app_kit::NSTextField;
        type Case = (&'static str, bool, String);
        let results: Rc<RefCell<Vec<Case>>> = Rc::default();
        for case in ["set_rows", "remove", "insert", "update_row"] {
            let m = Rc::new(TableModel::new(ViewId(9320), vec![Column::text("name", "Name", |s: &String| s.clone()).editable(true)]));
            m.set_rows(vec!["a".to_string(), "b".to_string(), "c".to_string()]);
            let edits: Rc<RefCell<Vec<(usize, String)>>> = Rc::default();
            let e2 = edits.clone();
            let ew = open(Window::new("Edit").size(240.0, 160.0).view(table(&m).on_edit(move |row, _, value| e2.borrow_mut().push((row, value)))));
            let tv = m.table_view();
            tv.editColumn_row_withEvent_select(0, 1, None, true);
            let cell = tv.viewAtColumn_row_makeIfNecessary(0, 1, true).and_then(|v| v.downcast::<NSTextField>().ok()).unwrap();
            let ed = cell.currentEditor().and_then(|e| e.downcast::<objc2_app_kit::NSTextView>().ok());
            if let Some(ed) = &ed {
                unsafe { ed.selectAll(None) };
                unsafe { ed.insertText_replacementRange(&NSString::from_str("typed"), objc2_foundation::NSRange::new(usize::MAX >> 1, 0)) };
            }
            match case {
                "set_rows" => m.set_rows(vec!["x".to_string(), "y".to_string(), "z".to_string()]),
                "remove" => drop(m.remove(0)),
                "insert" => m.insert(0, "new".to_string()),
                _ => m.update_row(1, "B".to_string()),
            }
            let (editing, results) = (ed.is_some(), results.clone());
            after_events(move || {
                let on_table = ew.firstResponder().is_some_and(|r| r.downcast::<objc2_app_kit::NSTableView>().is_ok());
                let edits = edits.borrow().clone();
                // The edited row itself updated: the edit is that row's.
                let right = if case == "update_row" { edits == [(1, "typed".to_string())] } else { edits.is_empty() };
                results.borrow_mut().push((case, editing && right && on_table, format!("{case}: edits {edits:?}, the table has the keyboard {on_table}")));
                ferrokit::close_window(&ew);
                if results.borrow().len() == 4 {
                    let r = results.borrow();
                    check("table-edit-under-reload", r.iter().all(|c| c.1), r.iter().map(|c| c.2.clone()).collect::<Vec<_>>().join("; "));
                }
            });
        }
    }
    // A bound editor edited more than once in a turn keeps every edit (the
    // signal's older value went back over the later ones); and Edit ▸ Find
    // is there, with ⌘F showing the editor's find bar and the app's own
    // Edit items after it.
    {
        const EDIT_A: ferrokit::Command = ferrokit::Command::new("check-edit-a");
        const EDIT_B: ferrokit::Command = ferrokit::Command::new("check-edit-b");
        let text = Signal::new(String::from("one"));
        let m = TextModel::new(ViewId(9330), "one");
        let (m1, m2) = (m.clone(), m.clone());
        let bw = open(Window::new("Bound").size(260.0, 140.0).view(
            text_editor(&m).bind(&text).on_command(EDIT_A, move || m1.replace_selection("A")).on_command(EDIT_B, move || m2.replace_selection("B")),
        ));
        bw.makeFirstResponder(Some(&m.text_view()));
        m.set_selection(3..3);
        batch(|| {
            ferrokit::perform_in(Some(&bw), EDIT_A);
            ferrokit::perform_in(Some(&bw), EDIT_B);
            ferrokit::perform_in(Some(&bw), EDIT_A);
        });
        let m = m.clone();
        after_events(move || {
            let (shown, bound) = (m.text(), text.get_untracked());
            check("editor-edits-in-one-turn", shown == "oneABA" && bound == shown, format!("three edits in one turn: the editor has {shown:?}, its signal {bound:?}"));
            let edit = NSApplication::sharedApplication(mtm()).mainMenu().and_then(|bar| bar.itemWithTitle(&NSString::from_str("Edit"))).and_then(|i| i.submenu());
            let find = edit.as_ref().and_then(|e| e.itemWithTitle(&NSString::from_str("Find"))).and_then(|i| i.submenu());
            let tags: Vec<isize> = find.iter().flat_map(|f| f.itemArray().iter().map(|i| i.tag()).collect::<Vec<_>>()).collect();
            // (AppKit adds its own items, Emoji & Symbols, after the app's.)
            let titles: Vec<String> = edit.iter().flat_map(|e| e.itemArray().iter().map(|i| i.title().to_string()).collect::<Vec<_>>()).collect();
            let own = titles.iter().position(|t| t == "Checklist Edit") > titles.iter().position(|t| t == "Find");
            let pressed = ferrokit::testing::shortcut(&bw, "f", false);
            let (m, bw) = (m.clone(), bw.clone());
            after_events(move || {
                let bar = m.is_find_visible();
                check(
                    "edit-menu-find",
                    tags == [1, 12, 2, 3, 7] && own && pressed && bar,
                    format!("Edit ▸ Find's items by action {tags:?}; the app's Edit item after Find: {own} in {titles:?}; ⌘F in the editor taken {pressed}, the find bar shows {bar}"),
                );
                // Lines that don't wrap run past the editor's width; wrapping
                // again brings the text back to it.
                let width = m.scroll_view().contentSize().width;
                m.set_text(&"a long line of text that goes on ".repeat(30));
                m.set_wraps(false);
                // (The text view lays its text out when it's asked to show
                // it: showing the end lays out the whole line.)
                let end = objc2_foundation::NSRange::new(m.text_view().string().length(), 0);
                m.text_view().scrollRangeToVisible(end);
                let (m, bw) = (m.clone(), bw.clone());
                let m0 = m.clone();
                until(move || m0.text_view().frame().size.width > width * 2.0, 3000, move || {
                    let tv = m.text_view();
                    let (long, scroller) = (tv.frame().size.width, m.scroll_view().hasHorizontalScroller());
                    m.set_wraps(true);
                    tv.scrollRangeToVisible(end);
                    let (m, bw) = (m.clone(), bw.clone());
                    let m0 = m.clone();
                    until(move || (m0.text_view().frame().size.width - width).abs() < 1.0, 3000, move || {
                        let back = m.text_view().frame().size.width;
                        check("editor-wraps", long > width * 2.0 && scroller && !m.scroll_view().hasHorizontalScroller() && (back - width).abs() < 1.0 && m.wraps(), format!("an editor {width} wide: not wrapping, the text is {long} wide with a scroller {scroller}; wrapping again, {back}"));
                        ferrokit::close_window(&bw);
                    });
                });
            });
        });
    }
    // Two radio groups in one window: a click in one leaves the other's
    // choice showing.
    {
        let (size, colour) = (Signal::new("m"), Signal::new("red"));
        let rw = open(
            Window::new("Radios").size(260.0, 160.0).view(vstack((ferrokit::radio_group(&size, vec![("Small", "s"), ("Medium", "m")]), ferrokit::radio_group(&colour, vec![("Red", "red"), ("Blue", "blue")]))).padding(12.0)),
        );
        let buttons = move |w: &objc2_app_kit::NSWindow| all_views(&w.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSButton>().ok()).collect::<Vec<_>>();
        let on = move |w: &objc2_app_kit::NSWindow| buttons(w).iter().filter(|b| b.state() == objc2_app_kit::NSControlStateValueOn).map(|b| b.title().to_string()).collect::<Vec<_>>();
        if let Some(blue) = buttons(&rw).into_iter().find(|b| b.title().to_string() == "Blue") {
            unsafe { blue.performClick(None) };
        }
        after_events(move || {
            let shown = on(&rw);
            check("radio-groups-apart", shown == ["Medium", "Blue"] && size.get_untracked() == "m" && colour.get_untracked() == "blue", format!("Medium chosen, then Blue clicked in the other group: on {shown:?}; values {} and {}", size.get_untracked(), colour.get_untracked()));
            ferrokit::close_window(&rw);
        });
    }
    let (outer, inner, which, off, own_off) = (Signal::new(true), Signal::new(false), Signal::new(0), Signal::new(true), Signal::new(true));
    let rows = Signal::new(vec![place(1, "Line 1", None)]);
    let before = live_signals();
    let w = open(Window::new("Tree State").size(320.0, 220.0).view(
        vstack((
            vstack((text("Outer"), button("Nested", || {}).hidden(move || inner.get()))).hidden(move || outer.get()),
            dynamic(move || button(format!("Swap {}", which.get()), || {})).hidden(move || outer.get()),
            vstack((
                dynamic(move || button(format!("Form {}", which.get()), || {})),
                for_each(
                    move || rows.get(),
                    |p: Place| {
                        // A row's own state: freed with the row.
                        let open = Signal::new(false);
                        button(&p.name, move || open.set(true))
                    },
                ),
                button("Own", || {}).disabled(move || own_off.get()),
            ))
            .disabled(move || off.get()),
        ))
        .padding(12.0),
    ));
    let find = |w: &objc2_app_kit::NSWindow, prefix: &str| -> Vec<Retained<NSButton>> {
        all_views(&w.contentView().unwrap()).into_iter().filter_map(|v| v.downcast::<NSButton>().ok()).filter(|b| b.title().to_string().starts_with(prefix)).collect()
    };
    let hidden = |w: &objc2_app_kit::NSWindow, prefix: &str| find(w, prefix).iter().map(|b| b.isHidden()).collect::<Vec<_>>();
    let enabled = |w: &objc2_app_kit::NSWindow, prefix: &str| find(w, prefix).iter().map(|b| b.isEnabled()).collect::<Vec<_>>();
    // A table sorted outside keeps the app's order; a changed row regroups.
    {
        let m = TableModel::new(ViewId(9310), vec![Column::text("name", "Name", |s: &String| s.clone())]);
        m.set_sorts_in_place(false);
        m.set_sort(Some(ferrokit::Sort { column: "name".into(), ascending: true }));
        m.set_rows(vec!["b".to_string(), "a".to_string(), "c".to_string()]);
        m.select(&[0]);
        let at = m.table_view().selectedRow();
        check("table-sorted-outside", at == 0 && m.sort().is_some(), format!("rows b, a, c with built-in sorting off: b is shown at row {at}; the header's sort is kept {}", m.sort().is_some()));
        let g = TableModel::new(ViewId(9311), vec![Column::text("name", "Name", |s: &String| s.clone())]);
        g.set_group_by(Some(Box::new(|s: &String| s[..1].to_string())));
        g.set_rows(vec!["a1".to_string(), "b1".to_string()]);
        let before = g.groups();
        g.update_row(1, "a2".to_string());
        let after = g.groups();
        check("table-update-regroups", before == ["a", "b"] && after == ["a"], format!("groups {before:?}; after b1 became a2: {after:?}"));
    }
    // A picker whose options share a title keeps them all, in order.
    {
        let choice = Signal::new(2);
        let pw = open(Window::new("Picker").size(240.0, 80.0).view(vstack((picker(&choice, vec![("None", 0), ("Custom", 1), ("None", 2)]), image("no.such.symbol.anywhere"))).padding(12.0)));
        let popup = all_views(&pw.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSPopUpButton>().ok()).unwrap();
        let (items, selected) = (popup.numberOfItems(), popup.indexOfSelectedItem());
        check("picker-same-titles", items == 3 && selected == 2, format!("None, Custom, None: {items} items, the third selected: index {selected}"));
        let reported = ferrokit::testing::failures().iter().any(|f| f.place == "an image" && f.message.contains("no.such.symbol.anywhere"));
        let shown = all_views(&pw.contentView().unwrap()).into_iter().any(|v| v.downcast::<objc2_app_kit::NSImageView>().is_ok());
        check("image-unknown-symbol", reported && shown, format!("an unknown SF Symbol: reported {reported}, a placeholder shown {shown}"));
        ferrokit::close_window(&pw);
    }
    // A font, a colour, an opacity and a tooltip reach a branch and a row
    // built after the view they're set on.
    {
        use ferrokit::{Color, Font};
        let (step, warm) = (Signal::new(0), Signal::new(false));
        let lines = Signal::new(vec![place(1, "Look row 1", None)]);
        let lw = open(Window::new("Look").size(260.0, 140.0).view(
            vstack((dynamic(move || text(format!("Look branch {}", step.get()))), for_each(move || lines.get(), |p: Place| text(&p.name))))
                .font(Font::headline())
                .color(move || if warm.get() { Color::Orange } else { Color::Blue })
                .opacity(0.5)
                .tooltip("Look tip")
                .padding(12.0),
        ));
        batch(|| {
            step.set(1);
            lines.update(|l| l.push(place(2, "Look row 2", None)));
        });
        batch(|| warm.set(true));
        let looks: Vec<(String, bool, Option<Color>, f64, String)> = all_views(&lw.contentView().unwrap())
            .into_iter()
            .filter_map(|v| v.downcast::<NSTextField>().ok())
            .filter(|f| f.stringValue().to_string().starts_with("Look"))
            .map(|f| {
                let bold = f.font().is_some_and(|font| font.fontDescriptor().symbolicTraits().contains(objc2_app_kit::NSFontDescriptorSymbolicTraits::TraitBold));
                (f.stringValue().to_string(), bold, f.textColor().and_then(|c| Color::from_ns(&c)), f.alphaValue(), f.toolTip().map(|t| t.to_string()).unwrap_or_default())
            })
            .collect();
        // (In the order the views were added, not the order shown.)
        let mut names: Vec<&str> = looks.iter().map(|l| l.0.as_str()).collect();
        names.sort_unstable();
        check(
            "modifiers-reach-new-branches",
            names == ["Look branch 1", "Look row 1", "Look row 2"] && looks.iter().all(|(_, bold, color, alpha, tip)| *bold && *color == Some(Color::Orange) && (*alpha - 0.5).abs() < 0.01 && tip == "Look tip"),
            format!("(text, bold, colour, opacity, tooltip) after a rebuilt branch, an added row and a colour change: {looks:?}"),
        );
        ferrokit::close_window(&lw);
    }
    // The inner view is hidden while the outer one already is; showing the
    // outer one mustn't show it.
    batch(|| inner.set(true));
    batch(|| outer.set(false));
    let nested = hidden(&w, "Nested");
    batch(|| inner.set(false));
    let nested_shown = hidden(&w, "Nested");
    check("hidden-nested", nested == [true] && nested_shown == [false], format!("inner hidden under a hidden outer, outer shown: hidden {nested:?}; inner shown: {nested_shown:?}"));
    // Replaced while hidden: the old views go.
    batch(|| outer.set(true));
    let first = objc2::rc::Weak::from_retained(&find(&w, "Swap")[0]);
    for i in 1..=50 {
        batch(|| which.set(i));
    }
    // Disabled: the replaced branch and a new row are disabled too.
    batch(|| rows.update(|r| r.push(place(2, "Line 2", None))));
    let (form, lines, own) = (enabled(&w, "Form"), enabled(&w, "Line"), enabled(&w, "Own"));
    batch(|| off.set(false));
    let (form_on, lines_on, own_still) = (enabled(&w, "Form"), enabled(&w, "Line"), enabled(&w, "Own"));
    batch(|| own_off.set(false));
    let own_on = enabled(&w, "Own");
    check(
        "disabled-inherited",
        form == [false] && lines == [false, false] && own == [false] && form_on == [true] && lines_on == [true, true] && own_still == [false] && own_on == [true],
        format!("disabled: branch {form:?}, rows {lines:?}, own {own:?}; enabled: branch {form_on:?}, rows {lines_on:?}, a view disabled itself {own_still:?}, then {own_on:?}"),
    );
    // Rows that go take their signals.
    let with_rows = live_signals();
    for i in 3..=40 {
        batch(|| rows.set(vec![place(i, &format!("Line {i}"), None)]));
    }
    let after_rows = live_signals();
    check("foreach-row-signals", after_rows < with_rows && after_rows <= before + 16, format!("signals: {before} before the window, {with_rows} with two rows, {after_rows} after 38 replacements of the rows"));
    let w2 = w.clone();
    after_events(move || {
        let kept = first.load().is_some();
        let now = find(&w2, "Swap").iter().map(|b| b.title().to_string()).collect::<Vec<_>>();
        check("hidden-rebuild-frees", !kept && now == ["Swap 50"], format!("after 50 replacements while hidden: the first view kept {kept}; now {now:?}"));
        ferrokit::close_window(&w2);
        about_help_checks(events.clone());
    });
}

/// An empty editable table cell is named after its column, so VoiceOver
/// can read it (ax_audit finds nothing unnamed).
fn empty_cell_ax_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let model = Rc::new(TableModel::new(ViewId(9200), vec![Column::text("note", "Note", |s: &String| s.clone()).editable(true)]));
    model.set_rows(vec![String::new(), "kept".to_string()]);
    let w = open(Window::new("Empty Cells").size(300.0, 160.0).view(table(&model).alternating_rows(false).column_lines().animated().accessibility_label("Notes")));
    let w2 = w.clone();
    let tv = model.table_view();
    after_events(move || {
        // A plain table: no stripes, hairlines between the columns.
        let striped = tv.usesAlternatingRowBackgroundColors();
        let lines = tv.gridStyleMask();
        check(
            "table-plain-style",
            !striped && lines == objc2_app_kit::NSTableViewGridLineStyle::SolidVerticalGridLineMask,
            format!("alternating rows {striped}; grid {lines:?}"),
        );
        // Animated: a row inserted and removed one at a time slides in and
        // out; the row above keeps its cell (no reload).
        let first = |tv: &objc2_app_kit::NSTableView, make: bool| tv.viewAtColumn_row_makeIfNecessary(0, 0, make).map(|v| Retained::as_ptr(&v) as usize);
        // (Drawn first, so the first row has its cell.)
        w2.displayIfNeeded();
        let before = first(&tv, false);
        model.insert(1, "added".to_string());
        let (inserted, kept_in) = (tv.numberOfRows(), first(&tv, false) == before);
        model.remove(1);
        let (removed, kept_out) = (tv.numberOfRows(), first(&tv, false) == before);
        check(
            "table-row-animation",
            before.is_some() && inserted == 3 && removed == 2 && kept_in && kept_out,
            format!("rows 2 → {inserted} → {removed}; the first row's cell kept: {kept_in}, {kept_out}"),
        );
        let problems = ferrokit::testing::ax_audit(&w2);
        // The elements, when it fails, to see what went unnamed.
        let note = if problems.is_empty() {
            "the empty field reads as its column".to_string()
        } else {
            let elements: Vec<String> = ferrokit::testing::ax_elements(&w2).iter().map(|e| format!("{}{} {:?}", " ".repeat(e.depth), e.role, e.name)).collect();
            format!("{problems:?} in {elements:?}")
        };
        check("table-empty-cell-ax", problems.is_empty(), note);
        ferrokit::close_window(&w2);
        table_teardown(events.clone());
    });
}

/// `App::about`: About {app} shows the credits; a "Help" menu fills the
/// standard Help menu (one Help menu, with the app's item).
fn about_help_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let app = NSApplication::sharedApplication(objc2::MainThreadMarker::new().unwrap());
    let bar = app.mainMenu().unwrap();
    let titles: Vec<String> = bar.itemArray().iter().map(|i| i.title().to_string()).collect();
    let helps = titles.iter().filter(|t| *t == "Help").count();
    let help = app.helpMenu().map(|m| m.itemArray().iter().map(|i| i.title().to_string()).collect::<Vec<_>>()).unwrap_or_default();
    let before = ferrokit::testing::about_shown();
    let about = bar.itemAtIndex(0).and_then(|i| i.submenu()).and_then(|m| m.itemAtIndex(0)).unwrap();
    let menu = bar.itemAtIndex(0).and_then(|i| i.submenu()).unwrap();
    menu.performActionForItemAtIndex(menu.indexOfItem(&about));
    let events = events.clone();
    after_events(move || {
        let shown = ferrokit::testing::about_shown() - before;
        // The panel, with the credits in it.
        let panel = ferrokit::windows().into_iter().chain(NSApplication::sharedApplication(objc2::MainThreadMarker::new().unwrap()).windows().iter()).find(|w| {
            all_views(&w.contentView().unwrap()).iter().any(|v| v.downcast_ref::<objc2_app_kit::NSTextView>().is_some_and(|t| t.string().to_string().contains("Made with Ferrokit.")))
        });
        check(
            "about-help",
            helps == 1 && help.contains(&"Checklist Help".to_string()) && shown == 1 && panel.is_some(),
            format!("Help menus {helps}, items {help:?}; About shown {shown} time, its credits on screen {}", panel.is_some()),
        );
        if let Some(p) = panel {
            p.close();
        }
        empty_cell_ax_checks(events.clone());
    });
}

#[derive(Clone)]
struct Step(String);

impl Identifiable for Step {
    type Id = String;
    fn id(&self) -> String {
        self.0.clone()
    }
}

/// `Outline::expanded`: every level open, and again when the tree changes.
fn outline_expanded_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let deep = Signal::new(false);
    let tree = move || {
        let leaf = |s: &str| TreeNode::leaf(Step(s.into()));
        let mut inner = vec![leaf("c1"), leaf("c2")];
        if deep.get() {
            inner.push(TreeNode::branch(Step("c3".into()), vec![leaf("d1")]));
        }
        vec![TreeNode::branch(Step("a".into()), vec![TreeNode::branch(Step("b".into()), inner)]), leaf("e")]
    };
    let w = open(Window::new("Plan").size(300.0, 300.0).view(outline(tree, |s: &Step| s.0.clone()).expanded().accessibility_label("Plan")));
    let ov = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSOutlineView>().ok()).unwrap();
    let rows = ov.numberOfRows();
    batch(|| deep.set(true));
    after_events(move || {
        let after = ov.numberOfRows();
        check("outline-expanded", rows == 5 && after == 7, format!("{rows} rows shown of 5; after the tree grew {after} of 7"));
        ferrokit::close_window(&w);
        outline_lazy_checks(events.clone());
    });
}

/// `Outline::lazy_children` and `Outline::column`: a folder whose
/// children load when it's expanded (and it stays expanded when they
/// arrive), and a Size column beside the tree, as the Finder's list view.
fn outline_lazy_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let (loaded, kids) = (Signal::new(Vec::<String>::new()), Signal::new(Vec::<String>::new()));
    let tree = move || {
        let inside = kids.get().into_iter().map(|k| TreeNode::leaf(Step(k))).collect();
        vec![TreeNode::branch(Step("Folder".into()), inside), TreeNode::leaf(Step("notes.txt".into()))]
    };
    let size = |s: &Step| if s.0 == "notes.txt" { "12 KB".to_string() } else { "--".to_string() };
    let files = outline(tree, |s: &Step| s.0.clone())
        .number_column("Size", 80.0, size)
        .lazy_children(|s: &Step| s.0 == "Folder", move |id: String| {
            loaded.update(|l| l.push(id));
            kids.set(vec!["a.txt".into(), "b.txt".into()]);
        })
        .accessibility_label("Files");
    let w = open(Window::new("Files").size(360.0, 240.0).view(files));
    let ov = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSOutlineView>().ok()).unwrap();
    let header = ov.headerView().is_some() && ov.tableColumns().count() == 2;
    let text_at = |ov: &objc2_app_kit::NSOutlineView, col: isize, row: isize| {
        ov.viewAtColumn_row_makeIfNecessary(col, row, true).and_then(|v| v.downcast::<objc2_app_kit::NSTableCellView>().ok()).and_then(|c| unsafe { c.textField() }).map(|f| f.stringValue().to_string())
    };
    let size_cell = text_at(&ov, 1, 1);
    let folder = ov.itemAtRow(0).unwrap();
    let expandable = unsafe { ov.isExpandable(Some(&folder)) };
    let rows_before = ov.numberOfRows();
    unsafe { ov.expandItem(Some(&folder)) };
    // The load runs on the next pass, then the tree is rebuilt.
    after_events(move || {
        let (ov, w, size_cell, events) = (ov.clone(), w.clone(), size_cell.clone(), events.clone());
        after_events(move || {
            let folder = ov.itemAtRow(0).unwrap();
            let open_ = unsafe { ov.isItemExpanded(Some(&folder)) };
            let names: Vec<String> = (0..ov.numberOfRows()).filter_map(|r| text_at(&ov, 0, r)).collect();
            check(
                "outline-columns",
                header && size_cell.as_deref() == Some("12 KB"),
                format!("header with 2 columns: {header}; notes.txt's Size {size_cell:?}"),
            );
            check(
                "outline-lazy-children",
                expandable && rows_before == 2 && loaded.get_untracked() == ["Folder"] && open_ && names == ["Folder", "a.txt", "b.txt", "notes.txt"],
                format!("Folder expandable with no children: {expandable}; expanding loaded {:?}; still open {open_}; rows {names:?}", loaded.get_untracked()),
            );
            ferrokit::close_window(&w);
            progress_job_checks(events.clone());
        });
    });
}

/// `spawn_with_progress`: a background job's fractions reach a signal on
/// the main thread as it goes, then it reads `None` and the result arrives.
fn progress_job_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let progress = Signal::new(None::<f64>);
    let seen: Rc<RefCell<Vec<Option<f64>>>> = Rc::default();
    let s2 = seen.clone();
    let watch = Effect::new(move || s2.borrow_mut().push(progress.get()));
    ferrokit::spawn_with_progress(
        &progress,
        |r| {
            for i in 1..=10 {
                std::thread::sleep(std::time::Duration::from_millis(30));
                r.report(i as f64 / 10.0);
            }
            "done"
        },
        move |answer| {
            let seen = seen.borrow().clone();
            let between = seen.iter().flatten().filter(|f| **f > 0.0 && **f < 1.0).count();
            let rising = seen.iter().flatten().collect::<Vec<_>>().windows(2).all(|w| w[0] <= w[1]);
            check(
                "progress-job",
                answer == "done" && seen.first() == Some(&None) && seen.get(1) == Some(&Some(0.0)) && between >= 2 && rising && progress.get_untracked().is_none(),
                format!("seen {seen:?}; then {answer:?}, progress {:?}", progress.get_untracked()),
            );
            drop(watch);
            dynamic_hidden_checks(events.clone());
        },
    );
}

fn table_teardown(events: Rc<RefCell<Vec<AppEvent>>>) {
    let t = TABLE.with(Clone::clone);
    let sv = t.model.scroll_view();
    batch(|| t.show.set(false));
    let removed = unsafe { sv.superview() }.is_none();
    // Events from a table that's no longer in the tree aren't delivered.
    let before = t.selected.get_untracked();
    t.model.table_view().selectRowIndexes_byExtendingSelection(&objc2_foundation::NSIndexSet::indexSetWithIndex(9), false);
    let t2 = t.clone();
    after_events(move || {
        let t = t2.clone();
        let quiet = t.selected.get_untracked() == before;
        batch(|| t.show.set(true));
        let back = unsafe { t.model.scroll_view().superview() }.is_some();
        check("table-teardown", removed && quiet && back, format!("removed from window: {removed}; no callback after removal: {quiet}; re-added: {back}"));
        table_bench(events.clone());
    });
}

fn table_bench(events: Rc<RefCell<Vec<AppEvent>>>) {
    let t = TABLE.with(Clone::clone);
    let tv = t.model.table_view();
    let cells0 = t.model.cells_created();
    let start = std::time::Instant::now();
    let mut worst = 0.0f64;
    for row in (0..200_000).step_by(2_000) {
        let s = std::time::Instant::now();
        tv.scrollRowToVisible(row);
        tv.displayIfNeeded();
        worst = worst.max(s.elapsed().as_secs_f64() * 1e3);
    }
    let total = start.elapsed().as_secs_f64() * 1e3;
    let created = t.model.cells_created() - cells0;
    check(
        "table-bench",
        (worst < 16.7 || on_ci()) && created < 200,
        format!("100 jumps across 200k rows (scroll + display): total {total:.0} ms, worst {worst:.1} ms; {created} new cell views (reuse)"),
    );
    outline_checks(events);
}

#[derive(Clone)]
struct Place {
    id: u32,
    name: String,
    symbol: Option<&'static str>,
}

impl Identifiable for Place {
    type Id = u32;
    fn id(&self) -> u32 {
        self.id
    }
}

fn place(id: u32, name: &str, symbol: Option<&'static str>) -> Place {
    Place { id, name: name.into(), symbol }
}

#[derive(Clone)]
struct OutlineState {
    sections: Signal<Vec<TreeNode<Place>>>,
    tree: Signal<Vec<TreeNode<Place>>>,
    place: Signal<Option<u32>>,
    node: Signal<Option<u32>>,
    show: Signal<bool>,
}

fn project(id: u32, files: u32) -> TreeNode<Place> {
    TreeNode::branch(
        place(id, &format!("Project {id}"), Some("folder")),
        (0..files).map(|f| TreeNode::leaf(place(id * 1000 + f, &format!("file{f}.rs"), Some("doc")))).collect(),
    )
}

thread_local! {
    static OUTLINE: OutlineState = OutlineState {
        sections: Signal::new(vec![
            TreeNode::branch(place(1, "Favourites", None), vec![
                TreeNode::leaf(place(11, "Documents", Some("doc.text"))),
                TreeNode::leaf(place(12, "Downloads", Some("arrow.down.circle"))),
            ]),
            TreeNode::branch(place(2, "Locations", None), vec![
                TreeNode::leaf(place(21, "Mac", Some("desktopcomputer"))),
                TreeNode::leaf(place(22, "Network", Some("network"))),
            ]),
        ]),
        tree: Signal::new((1..=3).map(|p| project(p, 3)).collect()),
        place: Signal::new(None),
        node: Signal::new(None),
        show: Signal::new(true),
    };
}

fn outline_window() -> impl View {
    let o = OUTLINE.with(Clone::clone);
    let (sections, o2) = (o.sections, o.clone());
    hstack((
        sidebar(move || sections.get(), |p: &Place| p.name.clone())
            .icon(|p: &Place| p.symbol.map(String::from))
            .badge(|p: &Place| (p.id == 12).then(|| "3".to_string()))
            .selection(&o.place)
            .width(180.0),
        dynamic(move || {
            if o2.show.get() {
                let tree = o2.tree;
                ferrokit::AnyView::new(
                    outline(move || tree.get(), |p: &Place| p.name.clone())
                        .icon(|p: &Place| p.symbol.map(String::from))
                        .selection(&o2.node)
                        .fill_width()
                        .fill_height(),
                )
                .id(1)
            } else {
                ferrokit::AnyView::new(text("no outline")).id(0)
            }
        }),
    ))
}

fn outline_views() -> (Retained<objc2_app_kit::NSOutlineView>, Option<Retained<objc2_app_kit::NSOutlineView>>) {
    let w = windows().into_iter().find(|w| w.title().to_string() == "Outline").unwrap();
    let mut outlines: Vec<(f64, Retained<objc2_app_kit::NSOutlineView>)> = w
        .contentView()
        .unwrap()
        .subviews()
        .iter()
        .filter_map(|v| v.downcast::<objc2_app_kit::NSScrollView>().ok())
        .filter_map(|sv| {
            let x = sv.frame().origin.x;
            sv.documentView().and_then(|d| d.downcast::<objc2_app_kit::NSOutlineView>().ok()).map(|o| (x, o))
        })
        .collect();
    outlines.sort_by(|a, b| a.0.total_cmp(&b.0));
    let mut it = outlines.into_iter().map(|(_, o)| o);
    (it.next().unwrap(), it.next())
}

fn outline_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let o = OUTLINE.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Outline").unwrap();
    w.makeKeyAndOrderFront(None);
    let (side, tree) = outline_views();
    let tree = tree.unwrap();

    // Sidebar: source-list style; sections expanded as group rows; icons.
    let item0 = side.itemAtRow(0);
    let group = item0.as_ref().is_some_and(|i| unsafe { side.isExpandable(Some(i)) } && unsafe { side.isItemExpanded(Some(i)) });
    let icon = side
        .viewAtColumn_row_makeIfNecessary(0, 1, true)
        .and_then(|v| v.downcast::<objc2_app_kit::NSTableCellView>().ok())
        .and_then(|c| unsafe { c.imageView() });
    // The icon is decoration (the title names the row), hidden from VoiceOver.
    let icon_hidden = icon.as_ref().is_some_and(|iv| ax_hidden(iv));
    let icon = icon.is_some_and(|iv| iv.image().is_some());
    check(
        "sidebar-style",
        side.style() == objc2_app_kit::NSTableViewStyle::SourceList && side.numberOfRows() == 6 && group && icon && icon_hidden,
        format!("style source list: {}; {} rows (2 sections + 4 items); section expanded: {group}; icon: {icon} (hidden from VoiceOver {icon_hidden})", side.style() == objc2_app_kit::NSTableViewStyle::SourceList, side.numberOfRows()),
    );

    // A badge at the end of Downloads' row, none on Documents'; the title
    // stops short of it, and the badge inside the row.
    let badge_of = |row: isize| {
        side.viewAtColumn_row_makeIfNecessary(0, row, true).and_then(|c| {
            let badge = c.viewWithTag(0x0bad6e).and_then(|b| b.downcast::<objc2_app_kit::NSTextField>().ok())?;
            let title = c.downcast_ref::<objc2_app_kit::NSTableCellView>().and_then(|c| unsafe { c.textField() })?;
            c.layoutSubtreeIfNeeded();
            Some((badge.isHidden(), badge.stringValue().to_string(), title.frame(), badge.frame(), c.frame().size.width))
        })
    };
    let (docs, downloads) = (badge_of(1), badge_of(2));
    let shown = downloads.as_ref().is_some_and(|(hidden, text, title, badge, width)| {
        !hidden && text == "3" && title.origin.x + title.size.width <= badge.origin.x && badge.origin.x + badge.size.width <= *width
    });
    let none = docs.as_ref().is_some_and(|(hidden, ..)| *hidden);
    check("sidebar-badge", shown && none, format!("Downloads {downloads:?}; Documents {docs:?}"));

    // Sidebar selection both ways.
    side.selectRowIndexes_byExtendingSelection(&objc2_foundation::NSIndexSet::indexSetWithIndex(2), false);
    let picked = o.place.get_untracked();
    batch(|| o.place.set(Some(22)));
    let row_of_network = side.selectedRow();
    check("sidebar-selection", picked == Some(12) && row_of_network == 5, format!("row 2 → {picked:?}; Network → row {row_of_network}"));
    // VoiceOver reads a sidebar row by its text (the static text's value).
    let names: Vec<String> = ferrokit::testing::ax_elements(&w).into_iter().filter(|e| e.role == "AXStaticText").map(|e| e.name).collect();
    check("sidebar-ax-names", ["Favourites", "Documents", "Network"].iter().all(|n| names.iter().any(|m| m == n)), format!("static text read: {names:?}"));

    // Outline: collapsed at first; expanding a project shows its files.
    let rows0 = tree.numberOfRows();
    let first = tree.itemAtRow(0);
    unsafe { tree.expandItem(first.as_deref()) };
    let rows1 = tree.numberOfRows();
    check(
        "outline-expand",
        rows0 == 3 && rows1 == 6 && has_ax(&ax_tree(&w), "AXOutline", "", ""),
        format!("{rows0} rows collapsed → {rows1} after expanding Project 1; AXOutline in the tree"),
    );

    // Update: add a file to the expanded project; expansion and selection survive.
    tree.selectRowIndexes_byExtendingSelection(&objc2_foundation::NSIndexSet::indexSetWithIndex(2), false);
    let sel_before = o.node.get_untracked();
    batch(|| {
        o.tree.update(|t| {
            t[0].children.push(TreeNode::leaf(place(1999, "new.rs", Some("doc"))));
            t.push(project(4, 2));
        })
    });
    let rows2 = tree.numberOfRows();
    let still_expanded = tree.itemAtRow(0).is_some_and(|i| unsafe { tree.isItemExpanded(Some(&i)) });
    let sel_after = o.node.get_untracked();
    let row_after = tree.selectedRow();
    check(
        "outline-update",
        sel_before == Some(1001) && rows2 == 8 && still_expanded && sel_after == sel_before && row_after == 2,
        format!("selected {sel_before:?}; after adding a file and a project: {rows2} rows, Project 1 expanded {still_expanded}, selection {sel_after:?} at row {row_after}"),
    );

    // Teardown: the outline's item objects go with it.
    let weak_item = tree.itemAtRow(0).map(|i| objc2::rc::Weak::from_retained(&i));
    drop(tree);
    batch(|| o.show.set(false));
    let o2 = o.clone();
    // AppKit releases a removed outline's items a little later.
    spawn(|| std::thread::sleep(std::time::Duration::from_millis(300)), move |_| {
        let gone = weak_item.as_ref().is_some_and(|w| w.load().is_none());
        let none_left = outline_views().1.is_none();
        check("outline-teardown", gone && none_left, format!("outline removed: {none_left}; its item objects deallocated: {gone}"));
        batch(|| o2.show.set(true));
        // spawn's continuation is itself a batch: the outline comes back when
        // it ends, so measure on the next pass.
        let (o3, events) = (o2.clone(), events.clone());
        later(move || outline_bench(o3.clone(), events.clone()));
    });
}

fn outline_bench(o: OutlineState, events: Rc<RefCell<Vec<AppEvent>>>) {
    // 100 projects × 100 files: rebuild from the signal, then expand everything.
    let t = std::time::Instant::now();
    batch(|| o.tree.set((1..=100).map(|p| project(p, 100)).collect()));
    let build_ms = t.elapsed().as_secs_f64() * 1e3;
    let (_, tree) = outline_views();
    let tree = tree.unwrap();
    let t = std::time::Instant::now();
    unsafe { tree.expandItem_expandChildren(None, true) };
    tree.displayIfNeeded();
    let expand_ms = t.elapsed().as_secs_f64() * 1e3;
    let t = std::time::Instant::now();
    batch(|| o.tree.update(|tr| tr[50].children.push(TreeNode::leaf(place(999_999, "late.rs", None)))));
    let update_ms = t.elapsed().as_secs_f64() * 1e3;
    check(
        "outline-bench",
        tree.numberOfRows() == 10_101 && ((build_ms < 100.0 && update_ms < 100.0) || on_ci()),
        format!("10,100 items: rebuild {build_ms:.1} ms; expand all + display {expand_ms:.1} ms; one added item (expansion kept) {update_ms:.1} ms; {} rows", tree.numberOfRows()),
    );
    editor_checks(events);
}

const NOTES: &str = "This sentense has a speling error.";

#[derive(Clone)]
struct EditorState {
    model: TextModel,
    notes: Signal<String>,
    changes: Signal<u32>,
    compositions: Signal<Vec<Option<String>>>,
    show: Signal<bool>,
}

thread_local! {
    static EDITOR: EditorState = EditorState {
        model: TextModel::new(ViewId(900), NOTES),
        notes: Signal::new(NOTES.to_string()),
        changes: Signal::new(0),
        compositions: Signal::new(vec![]),
        show: Signal::new(true),
    };
}

fn editor_window() -> impl View {
    let e = EDITOR.with(Clone::clone);
    let (e1, e2) = (e.clone(), e.clone());
    vstack((
        text(move || format!("{} characters", e1.notes.with(|t| t.chars().count()))),
        dynamic(move || {
            if e2.show.get() {
                let (c, k) = (e2.changes, e2.compositions);
                ferrokit::AnyView::new(
                    text_editor(&e2.model)
                        .bind(&e2.notes)
                        .on_change(move |_| c.update(|n| *n += 1))
                        .on_composition(move |m| k.update(|v| v.push(m))),
                )
                .id(1)
            } else {
                ferrokit::AnyView::new(text("no editor")).id(0)
            }
        }),
    ))
    .padding(12.0)
}

fn editor_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let e = EDITOR.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Editor").unwrap();
    w.makeKeyAndOrderFront(None);
    let tv = e.model.text_view();
    let sv = e.model.scroll_view();
    check(
        "editor-placed",
        sv.frame().size.height > 200.0 && tv.string().to_string() == NOTES && has_ax(&ax_tree(&w), "AXTextArea", "", ""),
        format!("scroll view {:.0}×{:.0}; text {:?}; AXTextArea in the tree", sv.frame().size.width, sv.frame().size.height, tv.string().to_string()),
    );

    // Typing at the end → binding, on_change, and the label.
    w.makeFirstResponder(Some(&tv));
    let end = tv.string().length();
    tv.setSelectedRange(objc2_foundation::NSRange::new(end, 0));
    let not_found = objc2_foundation::NSRange::new(usize::MAX >> 1, 0);
    unsafe { tv.insertText_replacementRange(&NSString::from_str(" More."), not_found) };
    let e2 = e.clone();
    after_events(move || {
        let e = e2.clone();
        let w = windows().into_iter().find(|w| w.title().to_string() == "Editor").unwrap();
        let bound = e.notes.get_untracked();
        let label_ok = w.contentView().unwrap().subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok())
            .any(|f| f.stringValue().to_string() == format!("{} characters", bound.chars().count()));
        check("editor-typing", bound.ends_with("error. More.") && e.changes.get_untracked() >= 1 && label_ok, format!("binding {bound:?}; on_change ×{}; label follows: {label_ok}", e.changes.get_untracked()));

        // Signal → editor: replaces the text and clears undo.
        batch(|| e.notes.set("Replaced".into()));
        let tv = e.model.text_view();
        check("editor-bind", tv.string().to_string() == "Replaced" && !e.model.can_undo(), format!("editor shows {:?}; can undo: {}", tv.string().to_string(), e.model.can_undo()));

        // Japanese input: no change while composing; one change on commit.
        let changes0 = e.changes.get_untracked();
        let end = tv.string().length();
        tv.setSelectedRange(objc2_foundation::NSRange::new(end, 0));
        let not_found = objc2_foundation::NSRange::new(usize::MAX >> 1, 0);
        unsafe { tv.setMarkedText_selectedRange_replacementRange(&NSString::from_str("とうきょう"), objc2_foundation::NSRange::new(5, 0), not_found) };
        let e3 = e.clone();
        let events = events.clone();
        after_events(move || {
            let e = e3.clone();
            let tv = e.model.text_view();
            let mid_changes = e.changes.get_untracked() - changes0;
            let mid_bound = e.notes.get_untracked();
            let not_found = objc2_foundation::NSRange::new(usize::MAX >> 1, 0);
            unsafe { tv.insertText_replacementRange(&NSString::from_str("東京"), not_found) };
            let e4 = e.clone();
            let events = events.clone();
            after_events(move || {
                let e = e4.clone();
                let comps = e.compositions.get_untracked();
                check(
                    "editor-ime",
                    mid_changes == 0 && mid_bound == "Replaced" && e.notes.get_untracked() == "Replaced東京"
                        && comps.first() == Some(&Some("とうきょう".to_string())) && comps.last() == Some(&None),
                    format!("while composing: {mid_changes} changes, binding {mid_bound:?}; committed → {:?}; compositions {comps:?}", e.notes.get_untracked()),
                );
                editor_undo_and_spelling(events.clone());
            });
        });
    });
}

fn editor_undo_and_spelling(events: Rc<RefCell<Vec<AppEvent>>>) {
    let e = EDITOR.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Editor").unwrap();
    let tv = e.model.text_view();
    w.makeFirstResponder(Some(&tv));
    // Undo through the Edit menu's ⌘Z (the editor's own undo manager).
    let before = e.notes.get_untracked();
    let undone = shortcut(&w, "z", false);
    let e2 = e.clone();
    after_events(move || {
        let e = e2.clone();
        let after = e.notes.get_untracked();
        check(
            "editor-undo",
            undone && after == "Replaced" && e.model.text() == "Replaced",
            format!("⌘Z sent: {undone}; {before:?} → binding {after:?}, editor {:?}", e.model.text()),
        );
        // Spell check (Phase 1's T11): continuous checking flags the words
        // (asynchronously), and the context menu offers suggestions.
        batch(|| e.notes.set(NOTES.to_string()));
        let e3 = e.clone();
        let events = events.clone();
        spawn(|| std::thread::sleep(std::time::Duration::from_millis(1500)), move |_| {
            let e = e3.clone();
            let tv = e.model.text_view();
            let flagged = ["sentense", "speling"].map(is_misspelled);
            let menu = context_menu_for_word(&tv, "speling");
            let suggests = menu.iter().any(|t| t == "spelling");
            let grammar = menu.iter().any(|t| t.starts_with("Spelling and Grammar"));
            check(
                "editor-spell-check",
                tv.isContinuousSpellCheckingEnabled() && flagged == [true, true] && suggests && grammar,
                format!("continuous checking {}; flagged {flagged:?}; right-click 'speling' → first items {:?}", tv.isContinuousSpellCheckingEnabled(), &menu[..menu.len().min(3)]),
            );
            let events = events.clone();
            later(move || editor_teardown(events.clone()));
        });
    });
}

fn editor_teardown(events: Rc<RefCell<Vec<AppEvent>>>) {
    let e = EDITOR.with(Clone::clone);
    let sv = e.model.scroll_view();
    batch(|| e.show.set(false));
    let removed = unsafe { sv.superview() }.is_none();
    let changes = e.changes.get_untracked();
    e.model.replace_selection("ignored");
    let e2 = e.clone();
    after_events(move || {
        let e = e2.clone();
        let quiet = e.changes.get_untracked() == changes;
        batch(|| e.show.set(true));
        let back = unsafe { e.model.scroll_view().superview() }.is_some();
        check("editor-teardown", removed && quiet && back, format!("removed: {removed}; no callback after removal: {quiet}; re-added: {back}"));
        chrome_checks(events.clone());
    });
}


#[derive(Clone)]
struct ChromeState {
    adds: Signal<u32>,
    locked: Signal<bool>,
    query: Signal<String>,
    renames: Signal<u32>,
    archivable: Signal<bool>,
    deleted: Signal<Option<usize>>,
    model: Rc<TableModel<Order>>,
}

thread_local! {
    static CHROME: ChromeState = {
        let model = Rc::new(TableModel::new(ViewId(950), vec![Column::text("name", "Name", |o: &Order| o.name.clone())]));
        model.set_rows((0..50).map(|i| Order { name: format!("Row {i}"), qty: 0.0, done: false }).collect());
        ChromeState {
            adds: Signal::new(0),
            locked: Signal::new(false),
            query: Signal::new(String::new()),
            renames: Signal::new(0),
            archivable: Signal::new(false),
            deleted: Signal::new(None),
            model,
        }
    };
}

fn chrome_window() -> Window {
    let c = CHROME.with(Clone::clone);
    let (adds, locked, renames, archivable, deleted) = (c.adds, c.locked, c.renames, c.archivable, c.deleted);
    Window::new("Chrome")
        .size(620.0, 400.0)
        .toolbar(vec![
            toolbar_button("add", "Add", "plus", move || adds.update(|n| *n += 1)).disabled(move || locked.get()),
            toolbar_space(),
            toolbar_search("search", &c.query),
        ])
        .view(
            split((
                vstack((text("Sidebar pane").fill_width(),)).padding(8.0),
                vstack((
                    text("Content pane").fill_width(),
                    table(&c.model).row_menu("Delete Row", move |row| deleted.set(Some(row))),
                    text("Right-click me").context_menu(vec![
                        menu_item("Rename", move || renames.update(|n| *n += 1)),
                        menu_separator(),
                        menu_item("Archive", || {}).disabled(move || !(archivable.get_untracked())),
                    ]),
                ))
                .padding(8.0),
            ))
            .position(160.0),
        )
}

fn chrome_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSSearchToolbarItem, NSSplitView};
    let c = CHROME.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Chrome").unwrap();
    w.makeKeyAndOrderFront(None);
    let sv = w.contentView().unwrap().subviews().iter().find_map(|v| v.downcast::<NSSplitView>().ok()).unwrap();
    // The panes, in order (a window's top-level split is managed by a split
    // view controller, which wraps each pane in a view of its own).
    fn pane_in(v: Retained<NSView>) -> Option<Retained<NSView>> {
        if v.class().name().to_str() == Ok("FerrokitSplitPane") {
            return Some(v);
        }
        v.subviews().iter().find_map(pane_in)
    }
    let panes: Vec<Retained<NSView>> = sv.arrangedSubviews().iter().filter_map(pane_in).collect();
    let label = |text: &str| {
        panes.iter().flat_map(|p| p.subviews().to_vec()).filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == text).unwrap()
    };
    let (left, right) = (panes[0].frame().size.width, panes[1].frame().size.width);
    let content = label("Content pane");
    let fits = (content.frame().size.width - (right - 16.0)).abs() < 1.0;
    check(
        "split-panes",
        panes.len() == 2 && (left - 160.0).abs() < 1.0 && fits && has_ax(&ax_tree(&w), "AXSplitGroup", "", ""),
        format!("panes {left:.0} + {right:.0}; content label {:.0} wide in its pane; AXSplitGroup in the tree", content.frame().size.width),
    );

    // Window resize: the first pane keeps its width; the second takes the change.
    w.setContentSize(objc2_foundation::NSSize::new(720.0, 400.0));
    let (l2, r2) = (panes[0].frame().size.width, panes[1].frame().size.width);
    let follows = (label("Content pane").frame().size.width - (r2 - 16.0)).abs() < 1.0;
    check("split-resize", (l2 - left).abs() < 1.0 && (r2 - right - 100.0).abs() < 1.0 && follows, format!("after +100 pt: panes {l2:.0} + {r2:.0}; content follows: {follows}"));

    // Divider drag (as the user does): the pane's content re-lays out at once.
    sv.setPosition_ofDividerAtIndex(240.0, 0);
    let (l3, r3) = (panes[0].frame().size.width, panes[1].frame().size.width);
    let follows = (label("Content pane").frame().size.width - (r3 - 16.0)).abs() < 1.0
        && (label("Sidebar pane").frame().size.width - (l3 - 16.0)).abs() < 1.0;
    check("split-drag", (l3 - 240.0).abs() < 1.0 && follows, format!("divider at 240: panes {l3:.0} + {r3:.0}; both panes' content follows: {follows}"));

    // Toolbar: items in order; the button's action and its disabled state.
    let tb = w.toolbar().unwrap();
    let items = tb.items();
    let ids: Vec<String> = items.iter().map(|i| i.itemIdentifier().to_string()).collect();
    let add = items.iter().find(|i| i.itemIdentifier().to_string() == "add").unwrap();
    let app = NSApplication::sharedApplication(mtm());
    let fired = unsafe { app.sendAction_to_from(add.action().unwrap(), add.target().as_deref(), Some(&add)) };
    let enabled_before = add.isEnabled();
    batch(|| c.locked.set(true));
    let enabled_after = add.isEnabled();
    check(
        "toolbar-button",
        // (First the space that keeps the title beside the sidebar.)
        ids.len() == 4 && ids[0] == "ferrokit.sidebar-spacer" && ids[1] == "add" && ids[3] == "search" && fired && c.adds.get_untracked() == 1 && enabled_before && !enabled_after,
        format!("items {ids:?}; Add → {} add(s); disabled when locked: {}", c.adds.get_untracked(), !enabled_after),
    );

    // Toolbar search: both ways.
    let search = items.iter().find_map(|i| i.downcast::<NSSearchToolbarItem>().ok()).unwrap();
    let field = search.searchField();
    post_edit(&field, "invoice");
    let typed = c.query.get_untracked();
    batch(|| c.query.set("receipt".into()));
    check("toolbar-search", typed == "invoice" && field.stringValue().to_string() == "receipt", format!("typed → {typed:?}; signal → field {:?}", field.stringValue().to_string()));

    // Context menu: items, action, validation when the menu opens.
    let target = label("Right-click me");
    let menu = target.menu().unwrap();
    let titles: Vec<String> = (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).map(|i| i.title().to_string()).collect();
    menu.performActionForItemAtIndex(0);
    menu.update();
    let archive_off = !menu.itemAtIndex(2).unwrap().isEnabled();
    batch(|| c.archivable.set(true));
    menu.update();
    let archive_on = menu.itemAtIndex(2).unwrap().isEnabled();
    check(
        "context-menu",
        titles == ["Rename", "", "Archive"] && c.renames.get_untracked() == 1 && archive_off && archive_on,
        format!("{titles:?}; Rename ran: {}; Archive disabled then enabled: {archive_off}/{archive_on}", c.renames.get_untracked() == 1),
    );

    // Table row menu: acts on the clicked row, or the selected one.
    let tv = c.model.table_view();
    tv.selectRowIndexes_byExtendingSelection(&objc2_foundation::NSIndexSet::indexSetWithIndex(3), false);
    let row_menu = tv.menu().unwrap();
    row_menu.performActionForItemAtIndex(0);
    check(
        "table-row-menu",
        row_menu.itemAtIndex(0).is_some_and(|i| i.title().to_string() == "Delete Row") && c.deleted.get_untracked() == c.model.row_at(3),
        format!("Delete Row on the selected row → model row {:?}", c.deleted.get_untracked()),
    );
    dialog_checks(events);
}


fn dialogs_window() -> Retained<objc2_app_kit::NSWindow> {
    windows().into_iter().find(|w| w.title().to_string() == "Dialogs").unwrap()
}

fn buttons_in(w: &objc2_app_kit::NSWindow) -> Vec<Retained<objc2_app_kit::NSButton>> {
    fn walk(v: &NSView, out: &mut Vec<Retained<objc2_app_kit::NSButton>>) {
        for c in v.subviews().iter() {
            if let Ok(b) = c.clone().downcast::<objc2_app_kit::NSButton>() {
                out.push(b);
            }
            walk(&c, out);
        }
    }
    let mut out = Vec::new();
    if let Some(v) = w.contentView() {
        walk(&v, &mut out);
    }
    out
}

fn dialog_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let w = dialogs_window();
    w.makeKeyAndOrderFront(None);
    // Alert sheet: destructive button, the chosen button's index, closes.
    let chosen = Signal::new(None::<usize>);
    let ch = chosen;
    alert(&w, Alert::new("Delete “report.csv”?", "This can't be undone.").button("Delete").button("Cancel").destructive(0).warning(), move |i| ch.set(Some(i)));
    let sheet_win = w.attachedSheet();
    let buttons = sheet_win.as_ref().map(|s| buttons_in(s)).unwrap_or_default();
    let delete = buttons.iter().find(|b| b.title().to_string() == "Delete");
    let destructive = delete.is_some_and(|b| b.hasDestructiveAction());
    if let Some(cancel) = buttons.iter().find(|b| b.title().to_string() == "Cancel") {
        unsafe { cancel.performClick(None) };
    }
    after_events(move || {
        let w = dialogs_window();
        check(
            "alert-sheet",
            destructive && chosen.get_untracked() == Some(1) && w.attachedSheet().is_none(),
            format!("Delete shown destructive: {destructive}; Cancel → {:?}; sheet closed: {}", chosen.get_untracked(), w.attachedSheet().is_none()),
        );
        view_sheet_check(events.clone());
    });
}

fn view_sheet_check(events: Rc<RefCell<Vec<AppEvent>>>) {
    let w = dialogs_window();
    let nodes0 = live_nodes();
    let name = Signal::new("draft".to_string());
    let closed = Signal::new(false);
    let handle: Rc<RefCell<Option<SheetHandle>>> = Rc::default();
    let h2 = handle.clone();
    let content = Window::new("Rename").size(320.0, 110.0).view(
        vstack((text_field(&name), hstack((spacer(), button("Done", move || {
            if let Some(h) = h2.borrow().as_ref() {
                h.close();
            }
        }).default_action()))))
        .padding(16.0),
    );
    let c2 = closed;
    *handle.borrow_mut() = Some(sheet(&w, content, move || c2.set(true)));
    let sheet_win = w.attachedSheet().unwrap();
    let field = sheet_win.contentView().unwrap().subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.isEditable()).unwrap();
    let shown = field.stringValue().to_string();
    let nodes_open = live_nodes();
    post_edit(&field, "final.csv");
    let typed = name.get_untracked();
    let done = buttons_in(&sheet_win).into_iter().find(|b| b.title().to_string() == "Done").unwrap();
    unsafe { done.performClick(None) };
    after_events(move || {
        let w = dialogs_window();
        check(
            "view-sheet",
            shown == "draft" && typed == "final.csv" && closed.get_untracked() && w.attachedSheet().is_none() && live_nodes() == nodes0 && nodes_open > nodes0,
            format!(
                "field showed {shown:?}; typed → {typed:?}; Done closed it: {}; nodes {nodes0} → {nodes_open} open → {} after",
                closed.get_untracked(),
                live_nodes()
            ),
        );
        // Escape presses a sheet's cancel button.
        let cancelled = Signal::new(false);
        let handle: Rc<RefCell<Option<SheetHandle>>> = Rc::default();
        let h2 = handle.clone();
        let content = Window::new("Ask").size(300.0, 90.0).view(
            hstack((spacer(), button("Cancel", move || {
                cancelled.set(true);
                if let Some(h) = h2.borrow().as_ref() {
                    h.close();
                }
            }).cancel_action(), button("OK", || {}).default_action()))
            .padding(16.0),
        );
        *handle.borrow_mut() = Some(sheet(&w, content, || {}));
        let sheet_win = w.attachedSheet().unwrap();
        let escape = objc2_app_kit::NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
            objc2_app_kit::NSEventType::KeyDown, objc2_foundation::NSPoint::new(0.0, 0.0), NSEventModifierFlags::empty(), 0.0, sheet_win.windowNumber(), None, &NSString::from_str("\u{1b}"), &NSString::from_str("\u{1b}"), false, 53,
        ).unwrap();
        let handled = sheet_win.performKeyEquivalent(&escape);
        let events = events.clone();
        after_events(move || {
            let w = dialogs_window();
            check(
                "sheet-escape",
                handled && cancelled.get_untracked() && w.attachedSheet().is_none(),
                format!("Escape handled {handled}; Cancel pressed {}; sheet closed {}", cancelled.get_untracked(), w.attachedSheet().is_none()),
            );
            panel_checks(events.clone());
        });
    });
}

fn panel_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    let w = dialogs_window();
    // Open panel: configuration, then Cancel → None.
    let result = Signal::new(Some(None::<Vec<std::path::PathBuf>>));
    let r2 = result;
    open_panel(&w, OpenOptions { extensions: vec!["csv".into(), "txt".into()], multiple: true, directories: false }, move |p| r2.set(Some(p)));
    let panel = w.attachedSheet().and_then(|s| s.downcast::<objc2_app_kit::NSOpenPanel>().ok());
    let types = panel.as_ref().map_or(0, |p| p.allowedContentTypes().count());
    let multiple = panel.as_ref().is_some_and(|p| p.allowsMultipleSelection());
    if let Some(p) = &panel {
        unsafe { p.cancel(None) };
    }
    after_events(move || {
        let w = dialogs_window();
        check(
            "open-panel",
            panel.is_some() && types == 2 && multiple && result.get_untracked() == Some(None) && w.attachedSheet().is_none(),
            format!("NSOpenPanel sheet: {}; {types} allowed types; multiple: {multiple}; Cancel → {:?}", panel.is_some(), result.get_untracked()),
        );
        // Save panel: proposed name and folder; Cancel → None. (The panel runs
        // out of process; a programmatic OK isn't reliable, so choosing a
        // path is a hands-on check.)
        let dir = std::env::temp_dir().join("ferrokit-check");
        let _ = std::fs::create_dir_all(&dir);
        let saved = Signal::new(None::<Option<std::path::PathBuf>>);
        let s2 = saved;
        save_panel(&w, "export.csv", Some(&dir), move |p| s2.set(Some(p)));
        let panel = w.attachedSheet().and_then(|s| s.downcast::<objc2_app_kit::NSSavePanel>().ok());
        let name = panel.as_ref().map(|p| p.nameFieldStringValue().to_string());
        let folder = panel.as_ref().and_then(|p| p.directoryURL()).and_then(|u| u.path()).map(|p| p.to_string());
        let want = dir.canonicalize().unwrap_or(dir.clone()).to_string_lossy().to_string();
        let folder_ok = folder.as_deref().is_some_and(|f| std::path::Path::new(f).canonicalize().map(|c| c.to_string_lossy().to_string()).unwrap_or_default() == want);
        if let Some(p) = &panel {
            unsafe { p.cancel(None) };
        }
        let events = events.clone();
        after_events(move || {
            let w = dialogs_window();
            let got = saved.get_untracked();
            check(
                "save-panel",
                name.as_deref() == Some("export.csv") && folder_ok && got == Some(None) && w.attachedSheet().is_none(),
                format!("proposed {name:?} in {folder:?} (expected folder: {folder_ok}); Cancel → {got:?}"),
            );
            let events = events.clone();
            after_events(move || menu_checks(events.clone()));
        });
    });
}

fn controls_b_checks(events: Rc<RefCell<Vec<AppEvent>>>) {
    use objc2_app_kit::{NSBox, NSImageView, NSPopUpButton, NSProgressIndicator, NSScrollView, NSSlider, NSStepper};
    let c = CTRL_B.with(Clone::clone);
    let w = windows().into_iter().find(|w| w.title().to_string() == "Controls B").unwrap();
    w.makeKeyAndOrderFront(None);
    let subs: Vec<Retained<NSView>> = w.contentView().unwrap().subviews().to_vec();
    let find = |f: &dyn Fn(&Retained<NSView>) -> bool| subs.iter().find(|v| f(v)).cloned().unwrap();
    let popup = find(&|v| v.clone().downcast::<NSPopUpButton>().is_ok()).downcast::<NSPopUpButton>().unwrap();
    let slider_v = find(&|v| v.clone().downcast::<NSSlider>().is_ok()).downcast::<NSSlider>().unwrap();
    let stepper_v = find(&|v| v.clone().downcast::<NSStepper>().is_ok()).downcast::<NSStepper>().unwrap();
    let bar = find(&|v| v.clone().downcast::<NSProgressIndicator>().is_ok()).downcast::<NSProgressIndicator>().unwrap();
    let img = find(&|v| v.clone().downcast::<NSImageView>().is_ok()).downcast::<NSImageView>().unwrap();
    let line = find(&|v| v.clone().downcast::<NSBox>().is_ok());
    let sv = find(&|v| v.clone().downcast::<NSScrollView>().is_ok()).downcast::<NSScrollView>().unwrap();
    let content_w = w.contentView().unwrap().bounds().size.width;

    // Picker: starts on the signal's value; user choice → signal; signal → menu.
    let initial = popup.indexOfSelectedItem();
    popup.selectItemAtIndex(2);
    send_action(&popup);
    let chosen = c.size.get_untracked();
    batch(|| c.size.set(1));
    check(
        "picker",
        initial == 1 && chosen == 3 && popup.indexOfSelectedItem() == 0 && has_ax(&ax_tree(&w), "AXPopUpButton", "", ""),
        format!("initial index {initial}; chose Large → {chosen}; signal 1 → index {}", popup.indexOfSelectedItem()),
    );

    // Slider and stepper.
    slider_v.setDoubleValue(0.75);
    send_action(&slider_v);
    let from_user = c.volume.get_untracked();
    batch(|| c.volume.set(0.25));
    check("slider", from_user == 0.75 && slider_v.doubleValue() == 0.25, format!("user 0.75 → {from_user}; signal 0.25 → {}", slider_v.doubleValue()));
    stepper_v.setDoubleValue(4.0);
    send_action(&stepper_v);
    let stepped = c.count.get_untracked();
    batch(|| c.count.set(9.0));
    let shown = stepper_v.doubleValue();
    check(
        "stepper",
        stepped == 4.0 && shown == 9.0 && stepper_v.maxValue() == 10.0 && stepper_v.increment() == 1.0,
        format!("user 4 → {stepped}; signal 9 → {shown}; range 0–{} step {}", stepper_v.maxValue(), stepper_v.increment()),
    );

    // Progress: determinate value, then indeterminate.
    let det = !bar.isIndeterminate() && (bar.doubleValue() - 0.4).abs() < 1e-9;
    batch(|| c.progress.set(None));
    let indet = bar.isIndeterminate();
    batch(|| c.progress.set(Some(1.0)));
    check("progress", det && indet && bar.doubleValue() == 1.0, format!("0.4 shown: {det}; None → indeterminate: {indet}; then {}", bar.doubleValue()));

    // SF Symbol with an accessibility description.
    check(
        "image-symbol",
        img.image().is_some() && has_ax(&ax_tree(&w), "AXImage", "", "Favourite"),
        format!("image set: {}; AXImage \"Favourite\" in the AX tree: {}", img.image().is_some(), has_ax(&ax_tree(&w), "AXImage", "", "Favourite")),
    );

    // Divider: spans the stack's width, one point tall.
    let d = line.frame();
    check("divider", (d.size.width - (content_w - 32.0)).abs() <= 0.5 && d.size.height <= 1.5, format!("{:.1} × {:.1} (inner width {:.1})", d.size.width, d.size.height, content_w - 32.0));

    // Scroll view: content at the visible width, taller than the viewport; scrolls to the end; grows with new rows.
    let doc = sv.documentView().unwrap();
    let visible = sv.contentSize();
    let tall = doc.frame().size.height > visible.height && (doc.frame().size.width - visible.width).abs() < 0.5;
    let last = doc.subviews().iter().filter_map(|v| v.downcast::<NSTextField>().ok()).find(|f| f.stringValue().to_string() == "item60").unwrap();
    doc.scrollRectToVisible(last.frame());
    let shown = sv.documentVisibleRect();
    let lf = last.frame();
    let at_end = lf.origin.y >= shown.origin.y && lf.origin.y + lf.size.height <= shown.origin.y + shown.size.height + 0.5;
    let h0 = doc.frame().size.height;
    batch(|| c.lines.update(|l| l.extend((61..=80).map(item))));
    let grew = doc.frame().size.height > h0;
    check(
        "scroll-view",
        tall && at_end && grew,
        format!(
            "content {:.2}×{:.0} in a {:.2}×{:.0} viewport ({} scroll bars, vertical shown: {}); item60 visible after scrolling: {at_end}; 20 more rows grew it {h0:.0} → {:.0}",
            doc.frame().size.width,
            h0,
            visible.width,
            visible.height,
            if sv.scrollerStyle() == objc2_app_kit::NSScrollerStyle::Legacy { "classic" } else { "overlay" },
            sv.verticalScroller().is_some_and(|s| !s.isHidden()),
            doc.frame().size.height
        ),
    );

    // Classic scroll bars (a Mac with a mouse, or "always show"): they take
    // width when they appear, mid-layout; the content must still fit.
    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Legacy);
    batch(|| c.lines.set((1..=2).map(item).collect()));
    let short = (doc.frame().size.width, sv.contentSize().width);
    batch(|| c.lines.set((1..=80).map(item).collect()));
    let (dw, vw) = (doc.frame().size.width, sv.contentSize().width);
    let bar = sv.verticalScroller().is_some_and(|s| !s.isHidden());
    check(
        "scroll-classic-scrollbars",
        bar && (dw - vw).abs() < 0.5 && vw < short.1,
        format!("2 rows: content {:.1} in {:.1}; 80 rows (bar shown {bar}): content {dw:.1} in {vw:.1}", short.0, short.1),
    );
    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);

    if let Ok(dir) = std::env::var("SNAP") {
        snapshot_windows(&dir);
    }
    keyboard_checks(events);
}

/// Window restoration across launches: `RESTORE=save` moves a remembered
/// window and split, then quits (⌘Q's path, which flushes user defaults);
/// `RESTORE=verify`, in a second launch, checks both came back and cleans up.
fn restore_run(step: String) {
    use objc2_foundation::{NSPoint, NSRect, NSSize, NSUserDefaults};
    let target = NSRect::new(NSPoint::new(180.0, 140.0), NSSize::new(520.0, 300.0));
    App::new("Checklist")
        .window(Window::new("Restore").size(400.0, 240.0).remember_frame("two-launch").view(split((text("a"), text("b"))).position(120.0).remember("two-launch")))
        .on_launch(move || {
            let w = windows().remove(0);
            let sv = all_views(&w.contentView().unwrap()).into_iter().find_map(|v| v.downcast::<objc2_app_kit::NSSplitView>().ok()).unwrap();
            let pane = || sv.arrangedSubviews().firstObject().unwrap().frame().size.width;
            if step == "save" {
                w.setFrame_display(target, true);
                sv.setPosition_ofDividerAtIndex(210.0, 0);
                eprintln!("[restore] saved frame {:?} pane {}", w.frame(), pane());
                ferrokit::quit();
            } else {
                let (frame, width) = (w.frame(), pane());
                check("restore-across-launches", frame == target && width == 210.0, format!("frame {frame:?}; pane {width}"));
                let d = NSUserDefaults::standardUserDefaults();
                d.removeObjectForKey(&NSString::from_str("NSWindow Frame two-launch"));
                d.removeObjectForKey(&NSString::from_str("ferrokit split two-launch"));
                std::process::exit(FAILED.with(Cell::get) as i32);
            }
        })
        .run();
}

fn main() {
    if std::env::var("CRASH_TEST").is_ok() {
        return crash_test();
    }
    if let Ok(step) = std::env::var("RESTORE") {
        return restore_run(step);
    }
    let events: Rc<RefCell<Vec<AppEvent>>> = Rc::default();
    let checks = std::env::var("CHECK").is_ok_and(|v| v == "all");
    if checks {
        // Password AutoFill answers a focused password field later, from
        // another process; when the field's window has gone by then (these
        // checks swap a form with one 300 times), AppKit's remote view
        // raises and crashes the app on purpose (`NSRemoteView`, exit 133).
        // No person closes windows that fast, so the checks turn it off
        // (for this run only: the registration domain isn't saved).
        let off = objc2_foundation::NSNumber::new_bool(false);
        let defaults = objc2_foundation::NSDictionary::from_slices(&[&*NSString::from_str("NSAutoFillHeuristicsEnabled")], &[&*off as &objc2::runtime::AnyObject]);
        unsafe { objc2_foundation::NSUserDefaults::standardUserDefaults().registerDefaults(&defaults) };
    }
    let e2 = events.clone();
    App::new("Checklist")
        // Tables for the l10n checks (the checklist itself stays in the
        // system's language: these don't include English Macs' "en").
        .translations(&[
            ("de", "\"Rename Item\" = \"Objekt umbenennen\";\n\"Save\" = \"Speichern (App)\";\n\"{n} file\" = \"{n} Datei\";\n\"{n} files\" = \"{n} Dateien\";"),
            ("ru", "\"{n} files#one\" = \"{n} файл\";\n\"{n} files#few\" = \"{n} файла\";\n\"{n} files#many\" = \"{n} файлов\";"),
        ])
        // About credits and the app's own Help items.
        .about("Made with Ferrokit.", Some(("ferrokit.dev", "https://github.com/lhassa8/ferrokit")))
        .menu("Help", vec![ferrokit::menu_item("Checklist Help", || {})])
        .menu("Edit", vec![ferrokit::menu_item("Checklist Edit", || {})])
        // C5: the Dock icon's menu, read when it opens.
        .dock_menu(|| vec![ferrokit::menu_item("New Checklist Window", || {}), ferrokit::menu_item(format!("{} windows open", ferrokit::windows().len()), || {})])
        // Links in the app's URL schemes.
        .on_open_url(|url| OPENED_URLS.with_borrow_mut(|u| u.push(url.to_string())))
        .window(Window::new("First").size(480.0, 200.0).content(|| field("hello world")))
        .window(Window::new("Second").size(360.0, 160.0))
        .window(Window::new("Views").size(320.0, 420.0).view(views_window()))
        .window(Window::new("Layout").size(420.0, 480.0).view(layout_window()))
        .window(Window::new("Controls").size(360.0, 300.0).view(controls_window()))
        .window(Window::new("Controls B").size(380.0, 460.0).view(controls_b_window()))
        .window(Window::new("Teardown").size(380.0, 520.0).view(teardown_window()))
        .window(Window::new("Table").size(560.0, 420.0).view(table_window()))
        .window(Window::new("Outline").size(560.0, 360.0).view(outline_window()))
        .window(Window::new("Editor").size(480.0, 320.0).view(editor_window()))
        .window(chrome_window())
        .window(Window::new("Dialogs").size(420.0, 260.0).view(vstack((text("Dialogs"),)).padding(12.0)))
        .menu("File", file_menu())
        .menu("View", view_menu())
        .settings(settings_window())
        .on_command(SHOW_HELP, || HELP_SHOWN.set(HELP_SHOWN.get() + 1))
        .on_event(move |e| e2.borrow_mut().push(e))
        .on_error(|_| HOOKED.with(|h| h.set(h.get() + 1)))
        .on_launch(move || {
            if checks {
                run_checks(events);
            }
        })
        .run();
}

/// How many characters a text view's TextKit 2 layout covers, after laying
/// it all out.
fn laid_out_length(tv: &objc2_app_kit::NSTextView) -> Option<usize> {
    use objc2::rc::Retained;
    use objc2::runtime::AnyObject;
    use objc2::msg_send;
    // SAFETY: TextKit 2 objects of a text view, read on the main thread.
    unsafe {
        let tlm: Option<Retained<AnyObject>> = msg_send![tv, textLayoutManager];
        let tlm = tlm?;
        let cm: Retained<AnyObject> = msg_send![&*tlm, textContentManager];
        let doc: Retained<AnyObject> = msg_send![&*tlm, documentRange];
        let _: () = msg_send![&*tlm, ensureLayoutForRange: &*doc];
        let start: Retained<AnyObject> = msg_send![&*doc, location];
        let end: Retained<AnyObject> = msg_send![&*doc, endLocation];
        let n: isize = msg_send![&*cm, offsetFromLocation: &*start, toLocation: &*end];
        usize::try_from(n).ok()
    }
}