quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! Frame-level rendering: declarative surface list + unified hit-test.
//!
//! Apps build a [`ScreenLayout`] by pushing [`Surface`] entries in
//! back-to-front z-order, then call [`ScreenLayout::draw`] to render
//! everything and get back a [`FrameHitMap`] for click dispatch.
//!
//! Apps that already paint each surface at its natural call site
//! can instead push the same [`Surface`] entries into a `ScreenLayout`
//! purely for hit-testing and call [`ScreenLayout::hit_map`], which
//! registers every zone without invoking any `backend.draw_*()` call.
//!
//! `ScreenLayout::tab_stops` derives Tab order from the same pushed
//! surfaces, and `ScreenLayout::tree_frame` (see its own doc) is an
//! in-progress, not-yet-consumed handle-based alternative to
//! re-walking every pushed `Surface::Tree` each frame.
//!
//! ## `Surface` vs. calling `Backend::draw_*` directly
//!
//! `ScreenLayout` + [`Surface`] is the **canonical path for a consumer
//! assembling a top-level screen out of multiple primitives**: pushing
//! `Surface` entries and calling [`ScreenLayout::draw`] routes both
//! backends through the same call site, so they cannot each paint the
//! identical primitive a different way. `Backend::draw_<name>` remains
//! public, low-level API — `ScreenLayout::draw` calls it internally,
//! and rasteriser tests / compose helpers call it directly by design.
//! See `quadraui/docs/decisions/DECISIONS.md` D-006 for the full
//! decision and `quadraui/docs/PRIMITIVE_RULES.md` "One primitive,
//! one canonical paint path" for the authoring rule this implies for
//! new primitives.
//!
//! ## `Surface` coverage
//!
//! Every primitive that has a `Backend::draw_*` method has a matching
//! [`Surface`] variant (`Board`, `CommandCenter`, `DiffView`,
//! `DropOverlay`, `Image`, `MessageList`, `Minimap`, `PipelineView`,
//! `Progress`, `SidebarPanel`, `Spinner`, `SplitTree`, `TextInput`,
//! `Toolbar` included). `Backend::draw_<name>` stays reachable directly
//! for the reasons above; there is no primitive that is categorically
//! unreachable through the declarative path.
//!
//! ## `FrameHitMap` is serializable; [`OwnedFrame`] is the owned `Frame`
//!
//! [`Surface`] owns every primitive it paints, so it carries no
//! lifetime and a [`ScreenLayout`] can be built in one place and drawn
//! in another. What a `Surface` is not is *serializable*: it
//! implements no `serde` traits, so it cannot by itself serve the
//! cases that need a frame description to leave the process — an
//! accessibility tree snapshot (AccessKit), a web backend serializing
//! a frame description across a WASM/JS boundary, or a record/replay
//! harness persisting what was on screen at a given tick.
//! [`FrameHitMap`] — already returned by
//! [`ScreenLayout::draw`]/[`ScreenLayout::hit_map`] — is that shape's
//! owned, lifetime-free counterpart for hit-testing purposes: it stores
//! `(Rect, FrameZone)` pairs by value. Both halves of that pair —
//! [`Rect`] and [`FrameZone`] — implement `serde::{Serialize,
//! Deserialize}`, so [`FrameHitMap`] itself does, and
//! [`FrameHitMap::zones`] / [`FrameHitMap::from_zones`] make the owned
//! data readable and round-trippable instead of only probeable via
//! [`FrameHitMap::hit_test`].
//!
//! A `FrameZone` alone is a bare tag (e.g. `FrameZone::Tree { idx: 3
//! }`) plus a frame-local surface index: it carries no primitive
//! content, no accessibility role, no label, no value, and cannot by
//! itself feed an AccessKit `TreeUpdate` node, be re-painted by a web
//! backend, or replay a frame. [`OwnedFrame`] is the `serde`-capable
//! counterpart that closes that gap: [`OwnedFrame::from_layout`] clones
//! every primitive a [`ScreenLayout`] holds into an
//! [`OwnedNode`] (rect, optional [`crate::types::WidgetId`], optional
//! [`crate::a11y::A11yInfo`], and the primitive itself as [`OwnedContent`]),
//! so the resulting [`OwnedFrame`] can be serialized, sent across a
//! process/wire boundary, or inspected entirely independently of the
//! `ScreenLayout` that produced it. [`OwnedFrame::draw`] repaints it
//! through the same `Backend` calls [`ScreenLayout::draw`] would have
//! made, and [`OwnedFrame::hit_map`] derives a [`FrameHitMap`] without a
//! backend at all — both are lock-step with the original push order
//! because the index each [`OwnedNode`] carries is captured once, at
//! `from_layout` time.
//!
//! That `serde` capability is the whole reason both types exist:
//! [`Surface`] is owned-but-not-serde and takes any primitive quadraui
//! can paint, while [`OwnedFrame`] is the serializable snapshot and is
//! therefore limited to primitives that are themselves `serde`-capable.
//! [`DropOverlay`] and [`FindReplacePanel`] are not, which is why
//! [`OwnedContent`] has the contentless
//! [`OwnedContent::DropOverlay`]/[`OwnedContent::FindReplace`]
//! fallbacks (and [`OwnedContent::Opaque`] as the generic one). Reach
//! for `Surface`/`ScreenLayout` to describe and paint a frame; reach
//! for `OwnedFrame` when that description has to be serialized.

//! ## Presence gating + the paint/hit-test order invariant
//!
//! `Surface`/`ScreenLayout` above answer "what does a frame look
//! like" for the primitives quadraui already knows about. They don't
//! answer a question every non-trivial app also has: "which of *my*
//! app-specific rungs (an editor pane, a bottom panel, an overlay
//! stack) exist this frame, and in what back-to-front order do they
//! have to be visited — identically — whether you're painting them or
//! resolving a click?"
//!
//! Left unanswered, that question gets reinvented per app, per
//! backend, as two independently-maintained lists that are supposed
//! to agree: vimcode's `FRAME_Z_ORDER` (paint) and
//! `MOUSE_ARBITRATION_ORDER` (hit-test) drifted exactly once —
//! And the fix was a `debug_assert!` comparing the
//! two lists after the fact, not a structural guarantee.
//!
//! [`FrameRung`] + [`FramePresence`] + [`check_frame_order`] make that
//! drift impossible instead of merely detectable:
//!
//! - An app defines one small `enum` for its rungs and implements
//!   [`FrameRung::z_order`] **once** — the single source of truth for
//!   "what's on top of what."
//! - [`FramePresence::from_fn`] evaluates a presence predicate against
//!   every rung **once per frame**, so "is the palette even open right
//!   now" is computed a single time and consulted by both painting and
//!   hit-testing, rather than re-derived (and potentially
//!   re-diverging) at each call site.
//! - [`compose_frame`] walks present rungs in canonical order with a
//!   single non-branching callback — no `match` over paint-operation
//!   variants, because the order comes from `z_order()`, not from the
//!   shape of the walk.
//! - [`check_frame_order`] asserts that some *other*, independently
//!   produced sequence (e.g. a hit-test walk, or a legacy per-backend
//!   paint routine mid-migration to [`compose_frame`]) is consistent
//!   with `z_order()`. This is the guard that would have caught
//!   vimcode#587/#592 as a compile-time-adjacent test failure instead
//!   of a months-later bug report.
//!
//! This machinery is deliberately independent of [`Surface`]/
//! [`ScreenLayout`]: the rungs it orders are app-defined (an app's own
//! enum), not quadraui's primitive set, so it composes with either the
//! `Surface` path or a bespoke per-backend paint routine equally well.
//!
//! ```
//! use quadraui::frame::{check_frame_order, compose_frame, FramePresence, FrameRung};
//!
//! #[derive(Debug, Clone, Copy, PartialEq, Eq)]
//! enum Rung {
//!     Editor,
//!     BottomPanel,
//!     Palette,
//! }
//!
//! impl FrameRung for Rung {
//!     fn z_order() -> &'static [Self] {
//!         // Back-to-front: Editor paints first, Palette paints (and
//!         // hit-tests) last, i.e. "on top".
//!         &[Rung::Editor, Rung::BottomPanel, Rung::Palette]
//!     }
//! }
//!
//! // Computed once: bottom panel is closed, palette is open.
//! let presence = FramePresence::from_fn(|r| !matches!(r, Rung::BottomPanel));
//!
//! let mut painted = Vec::new();
//! compose_frame(&presence, |r| painted.push(r));
//! assert_eq!(painted, vec![Rung::Editor, Rung::Palette]);
//!
//! // A hit-test walk built the same order independently — still valid.
//! assert!(check_frame_order(&[Rung::Editor, Rung::Palette]).is_ok());
//!
//! // A hit-test walk that regressed to checking the palette before the
//! // editor is caught immediately, not months later.
//! assert!(check_frame_order(&[Rung::Palette, Rung::Editor]).is_err());
//! ```

use std::collections::{HashMap, HashSet};

use crate::descriptor_store::{DescriptorStore, Handle};
use crate::event::Rect;
use crate::primitives::activity_bar::ActivityBar;
use crate::primitives::board::BoardModel;
use crate::primitives::canvas::Canvas;
use crate::primitives::chart::Chart;
use crate::primitives::command_center::CommandCenter;
use crate::primitives::command_line::CommandLine;
use crate::primitives::completions::{Completions, CompletionsLayout};
use crate::primitives::context_menu::{ContextMenu, ContextMenuLayout};
use crate::primitives::data_table::DataTable;
use crate::primitives::dialog::{Dialog, DialogLayout};
use crate::primitives::diff_view::DiffView;
use crate::primitives::drop_zone::DropOverlay;
use crate::primitives::editor::Editor;
use crate::primitives::find_replace::FindReplacePanel;
use crate::primitives::float::{Float, FloatLayout};
use crate::primitives::form::Form;
use crate::primitives::image::Image;
use crate::primitives::list::ListView;
use crate::primitives::menu_bar::MenuBar;
use crate::primitives::message_list::MessageList;
use crate::primitives::minimap::Minimap;
use crate::primitives::multi_section_view::MultiSectionView;
use crate::primitives::palette::Palette;
use crate::primitives::panel::Panel;
use crate::primitives::pipeline_view::PipelineView;
use crate::primitives::progress::ProgressBar;
use crate::primitives::rich_text_popup::{RichTextPopup, RichTextPopupLayout};
use crate::primitives::scrollbar::Scrollbar;
use crate::primitives::sidebar_panel::SidebarPanel;
use crate::primitives::spinner::Spinner;
use crate::primitives::split::Split;
use crate::primitives::split_tree::SplitTree;
use crate::primitives::status_bar::StatusBar;
use crate::primitives::tab_bar::TabBar;
use crate::primitives::terminal::Terminal;
use crate::primitives::text_display::TextDisplay;
use crate::primitives::text_input::TextInput;
use crate::primitives::toast::ToastOverlay;
use crate::primitives::toolbar::Toolbar;
use crate::primitives::tooltip::{Tooltip, TooltipLayout};
use crate::primitives::tree::TreeView;
use crate::types::WidgetId;
use crate::Backend;

/// A surface to render in a single frame. Entries are pushed in
/// back-to-front z-order; [`ScreenLayout::draw`] renders them
/// sequentially and the resulting [`FrameHitMap`] checks the
/// highest-z surface first.
///
/// `#[non_exhaustive]`: a new primitive adds a new variant here, and
/// per CLAUDE.md's *Downstream consumers* rule 2, a variant addition
/// should be additive rather than a potential downstream `E0004`.
/// Verified safe to add today: neither `coord-tui` nor `vimcode`
/// exhaustively matches `Surface` without a wildcard arm (grep in the
/// PR body).
#[allow(clippy::large_enum_variant)]
#[non_exhaustive]
pub enum Surface {
    Editor {
        rect: Rect,
        editor: Editor,
    },
    TabBar {
        rect: Rect,
        bar: TabBar,
        hovered_close: Option<usize>,
    },
    StatusBar {
        rect: Rect,
        bar: StatusBar,
        hovered: Option<WidgetId>,
        pressed: Option<WidgetId>,
    },
    ActivityBar {
        rect: Rect,
        bar: ActivityBar,
        hovered: Option<usize>,
    },
    CommandLine {
        rect: Rect,
        cmd: CommandLine,
    },
    Terminal {
        rect: Rect,
        term: Terminal,
    },
    TextDisplay {
        rect: Rect,
        td: TextDisplay,
    },
    MultiSectionView {
        rect: Rect,
        view: MultiSectionView,
    },
    Tree {
        rect: Rect,
        tree: TreeView,
    },
    List {
        rect: Rect,
        list: ListView,
    },
    Form {
        rect: Rect,
        form: Form,
    },
    MenuBar {
        rect: Rect,
        bar: MenuBar,
    },
    Split {
        rect: Rect,
        split: Split,
    },
    Panel {
        rect: Rect,
        panel: Panel,
    },
    Scrollbar {
        rect: Rect,
        sb: Scrollbar,
    },
    Palette {
        rect: Rect,
        palette: Palette,
    },
    Tooltip {
        tooltip: Tooltip,
        layout: TooltipLayout,
    },
    ContextMenu {
        menu: ContextMenu,
        layout: ContextMenuLayout,
    },
    Dialog {
        dialog: Dialog,
        layout: DialogLayout,
    },
    /// Like `Tooltip`/`ContextMenu`/`Dialog` above, carries its own
    /// resolved `layout` rather than a plain `rect` — `Float`
    /// is an overlay-with-caller-anchor primitive, so there's no bare
    /// `rect` the host would otherwise have on hand.
    Float {
        float: Float,
        layout: FloatLayout,
    },
    Completions {
        completions: Completions,
        layout: CompletionsLayout,
    },
    FindReplace {
        rect: Rect,
        panel: FindReplacePanel,
    },
    RichTextPopup {
        popup: RichTextPopup,
        layout: RichTextPopupLayout,
    },
    Toast {
        rect: Rect,
        stack: ToastOverlay,
    },
    DataTable {
        rect: Rect,
        table: DataTable,
        hovered: Option<usize>,
    },
    Chart {
        rect: Rect,
        chart: Chart,
        hovered_point: Option<(usize, usize)>,
        crosshair_x: Option<f64>,
    },
    /// App-defined escape-hatch drawing: a declarative list of
    /// [`crate::primitives::canvas::DrawOp`]s painted in order. See
    /// [`Canvas`]'s module doc for the coordinate frame and the
    /// per-backend degrade table.
    Canvas {
        rect: Rect,
        canvas: Canvas,
    },
    Board {
        rect: Rect,
        model: BoardModel,
    },
    CommandCenter {
        rect: Rect,
        cc: CommandCenter,
    },
    DiffView {
        rect: Rect,
        view: DiffView,
    },
    /// Tab-drag highlight overlay. Unlike every other
    /// transient-overlay variant above (`Tooltip`, `ContextMenu`,
    /// `Dialog`, `Completions`, `RichTextPopup`), there is no `rect`
    /// or `*Layout.bounds` to carry — [`DropOverlay::bounds`] derives
    /// the zone rect from `overlay` itself.
    DropOverlay {
        overlay: DropOverlay,
    },
    Image {
        rect: Rect,
        image: Image,
    },
    MessageList {
        rect: Rect,
        list: MessageList,
    },
    Minimap {
        rect: Rect,
        minimap: Minimap,
    },
    PipelineView {
        rect: Rect,
        view: PipelineView,
    },
    Progress {
        rect: Rect,
        bar: ProgressBar,
    },
    /// Mirrors [`Surface::StatusBar`]'s `hovered`/`pressed` shape: a
    /// `Surface` carries the two optional ids rather than a whole
    /// [`crate::interaction::InteractionState`], and
    /// [`ScreenLayout::draw`] builds the `WidgetId`-keyed store from
    /// them at the call boundary.
    SidebarPanel {
        rect: Rect,
        panel: SidebarPanel,
        hovered: Option<WidgetId>,
        pressed: Option<WidgetId>,
    },
    Spinner {
        rect: Rect,
        spinner: Spinner,
    },
    /// Structural chrome, like [`Surface::Split`] — a divider set with
    /// no independent focusable identity, so excluded from
    /// [`ScreenLayout::tab_stops`].
    SplitTree {
        rect: Rect,
        tree: SplitTree,
    },
    TextInput {
        rect: Rect,
        ti: TextInput,
    },
    /// See [`Surface::SidebarPanel`]'s doc for why `hovered`/`pressed`
    /// are a pair of optional ids rather than an `InteractionState`.
    Toolbar {
        rect: Rect,
        bar: Toolbar,
        hovered: Option<WidgetId>,
        pressed: Option<WidgetId>,
    },
}

/// Identifies which surface zone a point landed in.
///
/// Implements `Serialize`/`Deserialize` so this type — and, with
/// [`Rect`] (already serializable), [`FrameHitMap`] as a whole — can
/// be persisted or sent across a process/wire boundary. See the module
/// doc's "`FrameHitMap` is serializable" section.
///
/// Every variant's `idx` is a **frame-local surface index**: its
/// meaning depends entirely on the push order of the
/// [`ScreenLayout`] that produced it, not on any stable identity (see
/// vimcode's `click.rs:323-327`, which documents the same sharp edge —
/// "global surface index, NOT a per-tab-bar position"). Serializing a
/// `FrameZone` and handing it to a different process is only
/// meaningful if that process reproduces the exact same push order;
/// [`FrameHitMap::from_zones`] does not and cannot validate that an
/// `idx` it is handed actually corresponds to anything on the
/// receiving end.
///
/// `#[non_exhaustive]` for the same reason as [`Surface`]: a new
/// `Surface` variant implies a new `FrameZone` twin, and that pairing
/// should stay additive downstream. Verified safe today: neither
/// `coord-tui` nor `vimcode` exhaustively matches `FrameZone` without
/// a wildcard arm (vimcode's one match, `click.rs:331-355`, ends in
/// `_ => {}`; grep in the PR body).
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub enum FrameZone {
    Editor { idx: usize },
    TabBar { idx: usize },
    StatusBar { idx: usize },
    ActivityBar { idx: usize },
    CommandLine { idx: usize },
    Terminal { idx: usize },
    TextDisplay { idx: usize },
    MultiSectionView { idx: usize },
    Tree { idx: usize },
    List { idx: usize },
    Form { idx: usize },
    MenuBar { idx: usize },
    Split { idx: usize },
    Panel { idx: usize },
    Scrollbar { idx: usize },
    Palette { idx: usize },
    Tooltip { idx: usize },
    ContextMenu { idx: usize },
    Dialog { idx: usize },
    Float { idx: usize },
    Completions { idx: usize },
    FindReplace { idx: usize },
    RichTextPopup { idx: usize },
    Toast { idx: usize },
    DataTable { idx: usize },
    Chart { idx: usize },
    Canvas { idx: usize },
    Board { idx: usize },
    CommandCenter { idx: usize },
    DiffView { idx: usize },
    DropOverlay { idx: usize },
    Image { idx: usize },
    MessageList { idx: usize },
    Minimap { idx: usize },
    PipelineView { idx: usize },
    Progress { idx: usize },
    SidebarPanel { idx: usize },
    Spinner { idx: usize },
    SplitTree { idx: usize },
    TextInput { idx: usize },
    Toolbar { idx: usize },
    Empty,
}

/// Hit regions collected during [`ScreenLayout::draw`]. Resolves
/// absolute coordinates to the highest-z surface that contains them.
///
/// Every `(Rect, FrameZone)` pair is stored by value, so a
/// `FrameHitMap` carries no lifetime and can outlive the frame it was
/// built from. `Rect` and `FrameZone` both implement
/// `serde::{Serialize, Deserialize}`, so this struct derives them too
/// — it can be persisted or sent across a process/wire boundary.
/// **This is a step toward an owned `Frame`, not the owned frame
/// itself**: a `FrameZone` carries no primitive content, role, label
/// or value, only a bare tag and a frame-local index — see the module
/// doc's "`FrameHitMap` is serializable" section for what that means
/// for a receiver on the other end of a wire, and for what is still
/// missing.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrameHitMap {
    zones: Vec<(Rect, FrameZone)>,
}

impl FrameHitMap {
    fn new() -> Self {
        Self::default()
    }

    fn push(&mut self, rect: Rect, zone: FrameZone) {
        self.zones.push((rect, zone));
    }

    /// Build a [`FrameHitMap`] directly from owned `(Rect, FrameZone)`
    /// pairs — the inverse of [`Self::zones`]. Lets a
    /// consumer that deserialized a frame shape (or otherwise built one
    /// independently of [`ScreenLayout::draw`]/[`ScreenLayout::hit_map`])
    /// hand it back in for [`Self::hit_test`] to resolve clicks against,
    /// in the same back-to-front z-order `ScreenLayout` would have
    /// produced (last entry wins ties, matching [`Self::hit_test`]'s
    /// "highest-z match" contract). Does **not** validate that each
    /// `FrameZone`'s `idx` corresponds to anything meaningful — see
    /// [`FrameZone`]'s doc for why that index is push-order-dependent
    /// and cannot be checked for provenance here.
    pub fn from_zones(zones: Vec<(Rect, FrameZone)>) -> Self {
        Self { zones }
    }

    /// The owned `(Rect, FrameZone)` pairs this hit map was built from,
    /// in the same back-to-front order they were pushed — the read
    /// half of the owned/serializable contract described in the module
    /// doc. A consumer that wants more than point
    /// containment (enumerate every zone to build an accessibility
    /// tree, serialize the whole frame, diff two frames for
    /// record/replay) reads this directly instead of probing
    /// [`Self::hit_test`] pixel by pixel.
    pub fn zones(&self) -> &[(Rect, FrameZone)] {
        &self.zones
    }

    /// Find which zone contains `(x, y)`. Returns the highest-z match
    /// (last-drawn surface wins). Returns `FrameZone::Empty` when no
    /// surface contains the point.
    pub fn hit_test(&self, x: f32, y: f32) -> FrameZone {
        for (rect, zone) in self.zones.iter().rev() {
            if x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height {
                return zone.clone();
            }
        }
        FrameZone::Empty
    }

    /// Number of registered zones.
    pub fn len(&self) -> usize {
        self.zones.len()
    }

    /// Whether the hit map is empty.
    pub fn is_empty(&self) -> bool {
        self.zones.is_empty()
    }
}

/// Declarative frame description. Push surfaces in back-to-front
/// z-order, then call [`Self::draw`] to render and get a hit map.
pub struct ScreenLayout {
    surfaces: Vec<Surface>,
    tree_store: DescriptorStore<TreeView>,
    tree_handles: HashMap<WidgetId, Handle<TreeView>>,
}

impl ScreenLayout {
    pub fn new() -> Self {
        Self {
            surfaces: Vec::new(),
            tree_store: DescriptorStore::new(),
            tree_handles: HashMap::new(),
        }
    }

    pub fn push(&mut self, surface: Surface) {
        self.surfaces.push(surface);
    }

    /// The pushed surfaces, in z-order.
    pub fn surfaces(&self) -> &[Surface] {
        &self.surfaces
    }

    /// The pushed surfaces, mutably — for a caller that keeps a layout
    /// across frames and edits a surface in place instead of rebuilding
    /// the whole screen. Surfaces can be replaced, not added or
    /// removed, so each surface's index (and therefore the `idx` its
    /// [`FrameZone`] carries) is stable.
    pub fn surfaces_mut(&mut self) -> &mut [Surface] {
        &mut self.surfaces
    }

    /// Geometry for every pushed [`Surface::Tree`] as `(Handle, Rect)`
    /// pairs instead of cloning each tree's rows into the returned
    /// `Vec`.
    ///
    /// Each tree is kept in an internal [`DescriptorStore`] keyed by its
    /// [`WidgetId`]. A tree whose id was already seen — e.g. the same
    /// logical tree replaced in place via [`Self::surfaces_mut`] on a
    /// *retained* `ScreenLayout` — reuses its existing [`Handle`] and
    /// store slot rather than being removed and re-inserted. An id that
    /// stops being pushed (the surface was replaced with a different
    /// id, or dropped) has its handle and store slot evicted by this
    /// same call, so a retained layout's store stays bounded by the
    /// number of tree ids pushed *this* frame, not by how many have
    /// ever been pushed.
    ///
    /// This only pays off for a `ScreenLayout` an app keeps across
    /// frames and mutates via [`Self::surfaces_mut`]; a fresh
    /// `ScreenLayout::new()` built every frame (every in-repo example
    /// and the `templates/app` scaffold do this today) still inserts —
    /// and clones — every tree from an empty store each call. And even
    /// on a retained layout, this still compares the *whole* tree
    /// (`PartialEq` over every row) to decide whether to skip the
    /// clone, so a changed tree costs a full compare-then-clone rather
    /// than the zero-diff in-place [`DescriptorStore::update`] the
    /// store is designed around — a caller that wants that property
    /// has to mutate through the returned [`Handle`] itself instead of
    /// calling this on a freshly diffed `Surface::Tree`.
    ///
    /// Pushing two [`Surface::Tree`] entries with the same
    /// [`WidgetId`] is not rejected, but only the last one survives in
    /// the store: both resolve to the same [`Handle`], so the earlier
    /// tree's content is overwritten by the later one before either is
    /// returned.
    ///
    /// This leaves [`Self::draw`], [`Self::hit_map`] and
    /// [`Self::tab_stops`] untouched; they still paint and hit-test
    /// directly off [`Self::surfaces`]. No in-crate caller consumes
    /// this yet — `draw`/`hit_map`/`tab_stops`/[`OwnedFrame`] still
    /// read [`Self::surfaces`] directly — so treat this as an early,
    /// additive building block rather than a finished migration.
    pub fn tree_frame(&mut self) -> Vec<(Handle<TreeView>, Rect)> {
        let mut frame = Vec::new();
        let mut seen = HashSet::new();
        for surface in &self.surfaces {
            if let Surface::Tree { rect, tree } = surface {
                seen.insert(tree.id);
                let handle = match self.tree_handles.get(&tree.id) {
                    Some(&handle) => {
                        if self.tree_store.get(handle) != Some(tree) {
                            self.tree_store.update(handle, |slot| *slot = tree.clone());
                        }
                        handle
                    }
                    None => {
                        let handle = self.tree_store.insert(tree.clone());
                        self.tree_handles.insert(tree.id, handle);
                        handle
                    }
                };
                frame.push((handle, *rect));
            }
        }

        // Evict any id that was tracked before but wasn't pushed this
        // call, so a replaced or removed `Surface::Tree` doesn't keep
        // its old slot (and clone) alive forever.
        let stale: Vec<WidgetId> = self
            .tree_handles
            .keys()
            .filter(|id| !seen.contains(*id))
            .copied()
            .collect();
        for id in stale {
            if let Some(handle) = self.tree_handles.remove(&id) {
                self.tree_store.remove(handle);
            }
        }

        frame
    }

    /// Render all surfaces via `backend` in z-order and return a
    /// [`FrameHitMap`] for unified click dispatch. Each surface's
    /// bounding rect is registered as a hit zone; apps then use
    /// per-surface `hit_test()` methods for fine-grained resolution.
    ///
    /// If you're accumulating surfaces that are painted elsewhere
    /// (e.g. at their natural call sites across an existing paint
    /// pass) purely to recover a hit map, use [`Self::hit_map`]
    /// instead — it skips every `backend.draw_*()` call.
    pub fn draw(&self, backend: &mut dyn Backend) -> FrameHitMap {
        let mut hit_map = FrameHitMap::new();

        for (idx, surface) in self.surfaces.iter().enumerate() {
            match surface {
                Surface::Editor { rect, editor } => {
                    backend.draw_editor(*rect, editor);
                }
                Surface::TabBar {
                    rect,
                    bar,
                    hovered_close,
                } => {
                    backend.draw_tab_bar(*rect, bar, *hovered_close);
                }
                Surface::StatusBar {
                    rect,
                    bar,
                    hovered,
                    pressed,
                } => {
                    // `Surface::StatusBar` carries the two optional
                    // ids; the trait wants the `WidgetId`-keyed
                    // hover/pressed store, so build one from them here
                    // at the call boundary.
                    let interaction =
                        crate::interaction::InteractionState::from_parts(*hovered, *pressed);
                    backend.draw_status_bar_interactive(*rect, bar, &interaction);
                }
                Surface::ActivityBar { rect, bar, hovered } => {
                    backend.draw_activity_bar(*rect, bar, *hovered);
                }
                Surface::CommandLine { rect, cmd } => {
                    backend.draw_command_line(*rect, cmd);
                }
                Surface::Terminal { rect, term } => {
                    backend.draw_terminal(*rect, term);
                }
                Surface::TextDisplay { rect, td } => {
                    backend.draw_text_display(*rect, td);
                }
                Surface::MultiSectionView { rect, view } => {
                    backend.draw_multi_section_view(*rect, view);
                }
                Surface::Tree { rect, tree } => {
                    backend.draw_tree(*rect, tree);
                }
                Surface::List { rect, list } => {
                    backend.draw_list(*rect, list);
                }
                Surface::Form { rect, form } => {
                    backend.draw_form(*rect, form);
                }
                Surface::MenuBar { rect, bar } => {
                    backend.draw_menu_bar(*rect, bar);
                }
                Surface::Split { rect, split } => {
                    backend.draw_split(*rect, split);
                }
                Surface::Panel { rect, panel } => {
                    backend.draw_panel(*rect, panel);
                }
                Surface::Scrollbar { rect, sb } => {
                    backend.draw_scrollbar(*rect, sb);
                }
                Surface::Palette { rect, palette } => {
                    backend.draw_palette(*rect, palette);
                }
                Surface::Tooltip { tooltip, layout } => {
                    backend.draw_tooltip(tooltip, layout);
                }
                Surface::ContextMenu { menu, layout } => {
                    backend.draw_context_menu(menu, layout);
                }
                Surface::Dialog { dialog, layout } => {
                    backend.draw_dialog(dialog, layout);
                }
                Surface::Float { float, layout } => {
                    backend.draw_float(float, layout);
                }
                Surface::Completions {
                    completions,
                    layout,
                } => {
                    backend.draw_completions(completions, layout);
                }
                Surface::FindReplace { rect, panel } => {
                    backend.draw_find_replace(*rect, panel);
                }
                Surface::RichTextPopup { popup, layout } => {
                    backend.draw_rich_text_popup(popup, layout);
                }
                Surface::Toast { rect, stack } => {
                    backend.draw_toast_overlay(*rect, stack);
                }
                Surface::DataTable {
                    rect,
                    table,
                    hovered,
                } => {
                    backend.draw_data_table(*rect, table, *hovered);
                }
                Surface::Chart {
                    rect,
                    chart,
                    hovered_point,
                    crosshair_x,
                } => {
                    backend.draw_chart(*rect, chart, *hovered_point, *crosshair_x);
                }
                Surface::Canvas { rect, canvas } => {
                    backend.draw_canvas(*rect, canvas);
                }
                Surface::Board { rect, model } => {
                    backend.draw_board(*rect, model);
                }
                Surface::CommandCenter { rect, cc } => {
                    backend.draw_command_center(*rect, cc);
                }
                Surface::DiffView { rect, view } => {
                    backend.draw_diff_view(*rect, view);
                }
                Surface::DropOverlay { overlay } => {
                    backend.draw_drop_overlay(overlay);
                }
                Surface::Image { rect, image } => {
                    backend.draw_image(*rect, image);
                }
                Surface::MessageList { rect, list } => {
                    backend.draw_message_list(*rect, list);
                }
                Surface::Minimap { rect, minimap } => {
                    backend.draw_minimap(*rect, minimap);
                }
                Surface::PipelineView { rect, view } => {
                    backend.draw_pipeline_view(*rect, view);
                }
                Surface::Progress { rect, bar } => {
                    backend.draw_progress(*rect, bar);
                }
                Surface::SidebarPanel {
                    rect,
                    panel,
                    hovered,
                    pressed,
                } => {
                    let interaction =
                        crate::interaction::InteractionState::from_parts(*hovered, *pressed);
                    backend.draw_sidebar_panel_interactive(*rect, panel, &interaction);
                }
                Surface::Spinner { rect, spinner } => {
                    backend.draw_spinner(*rect, spinner);
                }
                Surface::SplitTree { rect, tree } => {
                    backend.draw_split_tree(*rect, tree);
                }
                Surface::TextInput { rect, ti } => {
                    backend.draw_text_input(*rect, ti);
                }
                Surface::Toolbar {
                    rect,
                    bar,
                    hovered,
                    pressed,
                } => {
                    let interaction =
                        crate::interaction::InteractionState::from_parts(*hovered, *pressed);
                    backend.draw_toolbar_interactive(*rect, bar, &interaction);
                }
            }

            let (rect, zone) = Self::zone_for(idx, surface);
            hit_map.push(rect, zone);
        }

        hit_map
    }

    /// Return the [`FrameHitMap`] that [`Self::draw`] would produce,
    /// without invoking any `backend.draw_*()` call. For apps that
    /// already painted these same surfaces elsewhere in the frame and
    /// only need the hit-test result — pushing surfaces here re-invokes
    /// no rendering, so it's safe to build this after (or interleaved
    /// with) the app's real paint sequencing.
    pub fn hit_map(&self) -> FrameHitMap {
        let mut hit_map = FrameHitMap::new();

        for (idx, surface) in self.surfaces.iter().enumerate() {
            let (rect, zone) = Self::zone_for(idx, surface);
            hit_map.push(rect, zone);
        }

        hit_map
    }

    /// Tab order for this frame, as `(WidgetId, Rect)` pairs in reading
    /// order (top-to-bottom, then left-to-right by rect origin) — the
    /// shared source of truth [`crate::focus::FocusManager::sync_tab_order`]
    /// cycles through. An app that builds its screen via
    /// `ScreenLayout` hands this straight to
    /// [`crate::runner::AppLogic::tab_stops`]; see that method's doc for
    /// the opt-in contract.
    ///
    /// Only surfaces that carry both a plain `rect` and an owning
    /// [`WidgetId`] participate. Excluded, deliberately:
    /// - Transient overlays (`Tooltip`, `ContextMenu`, `Dialog`,
    ///   `Float`, `Completions`, `RichTextPopup`, `FindReplace`,
    ///   `Toast`, `DropOverlay`) — these already own their own internal
    ///   focus/dismiss handling while open, and being modal, nothing
    ///   behind them should be Tab-reachable anyway. `Float` in
    ///   particular already has its own, finer-grained focus story —
    ///   [`crate::ModalStack::top_focusable`] — rather than
    ///   participating in `Tab`/`Shift+Tab` cycling.
    /// - Structural chrome (`Split`, `Scrollbar`, `SplitTree`) —
    ///   containers/controls with no independent focusable identity of
    ///   their own.
    /// - `Image`, `Spinner` and `Canvas` — purely decorative, never
    ///   focusable, regardless of the "carries a `rect` plus an owning
    ///   `WidgetId`" rule: a consumer that adopts them would otherwise
    ///   get dead stops in its Tab order. `Canvas`'s own hit-test
    ///   ([`crate::primitives::canvas::CanvasHit`]) only ever answers
    ///   "inside"/"outside" of its bounds — it has no activation
    ///   affordance to reach by keyboard.
    /// - `Progress` **unless** `ProgressBar::cancellable` is set — a
    ///   bare progress readout has nothing to activate, but a
    ///   cancellable one has a real affordance ([`ProgressBarHit::Cancel`])
    ///   worth reaching by keyboard. `Minimap` stays included even
    ///   though it is also mostly visual, because it is click-to-scroll
    ///   and so has a real interaction to land on.
    pub fn tab_stops(&self) -> Vec<(WidgetId, Rect)> {
        let mut stops: Vec<(WidgetId, Rect)> = self
            .surfaces
            .iter()
            .filter_map(|s| match s {
                Surface::Editor { rect, editor } => Some((editor.id, *rect)),
                Surface::TabBar { rect, bar, .. } => Some((bar.id, *rect)),
                Surface::StatusBar { rect, bar, .. } => Some((bar.id, *rect)),
                Surface::ActivityBar { rect, bar, .. } => Some((bar.id, *rect)),
                Surface::CommandLine { rect, cmd } => Some((cmd.id, *rect)),
                Surface::Terminal { rect, term } => Some((term.id, *rect)),
                Surface::TextDisplay { rect, td } => Some((td.id, *rect)),
                Surface::MultiSectionView { rect, view } => Some((view.id, *rect)),
                Surface::Tree { rect, tree } => Some((tree.id, *rect)),
                Surface::List { rect, list } => Some((list.id, *rect)),
                Surface::Form { rect, form } => Some((form.id, *rect)),
                Surface::MenuBar { rect, bar } => Some((bar.id, *rect)),
                Surface::Panel { rect, panel } => Some((panel.id, *rect)),
                Surface::Palette { rect, palette } => Some((palette.id, *rect)),
                Surface::DataTable { rect, table, .. } => Some((table.id, *rect)),
                Surface::Chart { rect, chart, .. } => Some((chart.id, *rect)),
                Surface::Board { rect, model } => Some((model.id, *rect)),
                Surface::CommandCenter { rect, cc } => Some((cc.id, *rect)),
                Surface::DiffView { rect, view } => Some((view.id, *rect)),
                Surface::MessageList { rect, list } => Some((list.id, *rect)),
                Surface::Minimap { rect, minimap } => Some((minimap.id, *rect)),
                Surface::PipelineView { rect, view } => Some((view.id, *rect)),
                Surface::Progress { rect, bar } if bar.cancellable => Some((bar.id, *rect)),
                Surface::SidebarPanel { rect, panel, .. } => Some((panel.id, *rect)),
                Surface::TextInput { rect, ti } => Some((ti.id, *rect)),
                Surface::Toolbar { rect, bar, .. } => Some((bar.id, *rect)),
                Surface::Image { .. }
                | Surface::Spinner { .. }
                | Surface::Canvas { .. }
                | Surface::Progress { .. }
                | Surface::Split { .. }
                | Surface::Scrollbar { .. }
                | Surface::Tooltip { .. }
                | Surface::ContextMenu { .. }
                | Surface::Dialog { .. }
                | Surface::Float { .. }
                | Surface::Completions { .. }
                | Surface::FindReplace { .. }
                | Surface::RichTextPopup { .. }
                | Surface::DropOverlay { .. }
                | Surface::SplitTree { .. }
                | Surface::Toast { .. } => None,
            })
            .collect();
        stops.sort_by(|(_, a), (_, b)| {
            a.y.partial_cmp(&b.y)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(a.x.partial_cmp(&b.x).unwrap_or(std::cmp::Ordering::Equal))
        });
        stops
    }

    /// Compute the hit-test rect/zone for a single surface at index `idx`.
    /// Shared by [`Self::draw`] and [`Self::hit_map`] so the two stay in
    /// lock-step by construction.
    fn zone_for(idx: usize, surface: &Surface) -> (Rect, FrameZone) {
        match surface {
            Surface::Editor { rect, .. } => (*rect, FrameZone::Editor { idx }),
            Surface::TabBar { rect, .. } => (*rect, FrameZone::TabBar { idx }),
            Surface::StatusBar { rect, .. } => (*rect, FrameZone::StatusBar { idx }),
            Surface::ActivityBar { rect, .. } => (*rect, FrameZone::ActivityBar { idx }),
            Surface::CommandLine { rect, .. } => (*rect, FrameZone::CommandLine { idx }),
            Surface::Terminal { rect, .. } => (*rect, FrameZone::Terminal { idx }),
            Surface::TextDisplay { rect, .. } => (*rect, FrameZone::TextDisplay { idx }),
            Surface::MultiSectionView { rect, .. } => (*rect, FrameZone::MultiSectionView { idx }),
            Surface::Tree { rect, .. } => (*rect, FrameZone::Tree { idx }),
            Surface::List { rect, .. } => (*rect, FrameZone::List { idx }),
            Surface::Form { rect, .. } => (*rect, FrameZone::Form { idx }),
            Surface::MenuBar { rect, .. } => (*rect, FrameZone::MenuBar { idx }),
            Surface::Split { rect, .. } => (*rect, FrameZone::Split { idx }),
            Surface::Panel { rect, .. } => (*rect, FrameZone::Panel { idx }),
            Surface::Scrollbar { rect, .. } => (*rect, FrameZone::Scrollbar { idx }),
            Surface::Palette { rect, .. } => (*rect, FrameZone::Palette { idx }),
            Surface::Tooltip { layout, .. } => (layout.bounds, FrameZone::Tooltip { idx }),
            Surface::ContextMenu { layout, .. } => (layout.bounds, FrameZone::ContextMenu { idx }),
            Surface::Dialog { layout, .. } => (layout.bounds, FrameZone::Dialog { idx }),
            Surface::Float { layout, .. } => (layout.bounds, FrameZone::Float { idx }),
            Surface::Completions { layout, .. } => (layout.bounds, FrameZone::Completions { idx }),
            Surface::FindReplace { rect, .. } => (*rect, FrameZone::FindReplace { idx }),
            Surface::RichTextPopup { layout, .. } => {
                (layout.bounds, FrameZone::RichTextPopup { idx })
            }
            Surface::Toast { rect, .. } => (*rect, FrameZone::Toast { idx }),
            Surface::DataTable { rect, .. } => (*rect, FrameZone::DataTable { idx }),
            Surface::Chart { rect, .. } => (*rect, FrameZone::Chart { idx }),
            Surface::Canvas { rect, .. } => (*rect, FrameZone::Canvas { idx }),
            Surface::Board { rect, .. } => (*rect, FrameZone::Board { idx }),
            Surface::CommandCenter { rect, .. } => (*rect, FrameZone::CommandCenter { idx }),
            Surface::DiffView { rect, .. } => (*rect, FrameZone::DiffView { idx }),
            Surface::DropOverlay { overlay } => (overlay.bounds(), FrameZone::DropOverlay { idx }),
            Surface::Image { rect, .. } => (*rect, FrameZone::Image { idx }),
            Surface::MessageList { rect, .. } => (*rect, FrameZone::MessageList { idx }),
            Surface::Minimap { rect, .. } => (*rect, FrameZone::Minimap { idx }),
            Surface::PipelineView { rect, .. } => (*rect, FrameZone::PipelineView { idx }),
            Surface::Progress { rect, .. } => (*rect, FrameZone::Progress { idx }),
            Surface::SidebarPanel { rect, .. } => (*rect, FrameZone::SidebarPanel { idx }),
            Surface::Spinner { rect, .. } => (*rect, FrameZone::Spinner { idx }),
            Surface::SplitTree { rect, .. } => (*rect, FrameZone::SplitTree { idx }),
            Surface::TextInput { rect, .. } => (*rect, FrameZone::TextInput { idx }),
            Surface::Toolbar { rect, .. } => (*rect, FrameZone::Toolbar { idx }),
        }
    }
}

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

/// A single primitive's content, owned rather than borrowed — the
/// payload half of an [`OwnedNode`]. One variant per [`Surface`]
/// variant that carries a `serde`-serializable primitive.
///
/// `#[non_exhaustive]` for the same reason as [`Surface`] and
/// [`FrameZone`]: a new primitive adds a new variant here additively.
///
/// [`Self::DropOverlay`] and [`Self::FindReplace`] are the fallbacks for
/// the two [`Surface`] variants whose primitive does not (yet) implement
/// `serde::{Serialize, Deserialize}` ([`DropOverlay`], [`FindReplacePanel`]
/// respectively) — the node still gets a rect and its own distinct
/// [`FrameZone`] tag via [`OwnedFrame::hit_map`], but carries no content
/// to redraw or inspect. [`Self::Opaque`] is the generic fallback for any
/// future primitive that likewise can't be captured yet.
#[non_exhaustive]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum OwnedContent {
    Editor(Editor),
    TabBar(TabBar),
    StatusBar(StatusBar),
    ActivityBar(ActivityBar),
    CommandLine(CommandLine),
    Terminal(Terminal),
    TextDisplay(TextDisplay),
    MultiSectionView(MultiSectionView),
    Tree(TreeView),
    List(ListView),
    Form(Form),
    MenuBar(MenuBar),
    Split(Split),
    Panel(Panel),
    Scrollbar(Scrollbar),
    Palette(Palette),
    Tooltip(Tooltip),
    ContextMenu(ContextMenu),
    Dialog(Dialog),
    Float(Float),
    Completions(Completions),
    RichTextPopup(RichTextPopup),
    Toast(ToastOverlay),
    DataTable(DataTable),
    Chart(Chart),
    Canvas(Canvas),
    Board(BoardModel),
    CommandCenter(CommandCenter),
    DiffView(DiffView),
    Image(Image),
    MessageList(MessageList),
    Minimap(Minimap),
    PipelineView(PipelineView),
    Progress(ProgressBar),
    SidebarPanel(SidebarPanel),
    Spinner(Spinner),
    SplitTree(SplitTree),
    TextInput(TextInput),
    Toolbar(Toolbar),
    /// No content captured — the source [`Surface`] was [`Surface::DropOverlay`].
    DropOverlay,
    /// No content captured — the source [`Surface`] was [`Surface::FindReplace`].
    FindReplace,
    /// No content captured — a generic fallback for any future
    /// non-serializable primitive. See this enum's doc for which
    /// [`Surface`] variants use the more specific fallbacks instead.
    Opaque,
}

impl OwnedContent {
    /// Repaint this content through the matching `Backend::draw_*`
    /// call, mirroring [`ScreenLayout::draw`]'s match arm for the
    /// [`Surface`] variant this content was captured from. Transient,
    /// per-frame interaction state (hover/press ids, hovered row
    /// indices) is not captured by [`OwnedFrame::from_layout`], so
    /// every such parameter is passed as `None`/absent here.
    ///
    /// The six overlay variants that need a non-serializable `*Layout`
    /// companion to redraw (`Tooltip`, `ContextMenu`, `Dialog`, `Float`,
    /// `Completions`, `RichTextPopup`), plus [`Self::DropOverlay`],
    /// [`Self::FindReplace`] and [`Self::Opaque`], are no-ops: their
    /// hit-test zone still round-trips, but repainting them needs either
    /// a layout or primitive content this owned snapshot does not keep.
    fn draw(&self, rect: Rect, backend: &mut dyn Backend) {
        match self {
            OwnedContent::Editor(editor) => {
                backend.draw_editor(rect, editor);
            }
            OwnedContent::TabBar(bar) => {
                backend.draw_tab_bar(rect, bar, None);
            }
            OwnedContent::StatusBar(bar) => {
                let interaction = crate::interaction::InteractionState::from_parts(None, None);
                backend.draw_status_bar_interactive(rect, bar, &interaction);
            }
            OwnedContent::ActivityBar(bar) => {
                backend.draw_activity_bar(rect, bar, None);
            }
            OwnedContent::CommandLine(cmd) => backend.draw_command_line(rect, cmd),
            OwnedContent::Terminal(term) => backend.draw_terminal(rect, term),
            OwnedContent::TextDisplay(td) => backend.draw_text_display(rect, td),
            OwnedContent::MultiSectionView(view) => backend.draw_multi_section_view(rect, view),
            OwnedContent::Tree(tree) => backend.draw_tree(rect, tree),
            OwnedContent::List(list) => backend.draw_list(rect, list),
            OwnedContent::Form(form) => backend.draw_form(rect, form),
            OwnedContent::MenuBar(bar) => {
                backend.draw_menu_bar(rect, bar);
            }
            OwnedContent::Split(split) => {
                backend.draw_split(rect, split);
            }
            OwnedContent::Panel(panel) => {
                backend.draw_panel(rect, panel);
            }
            OwnedContent::Scrollbar(sb) => backend.draw_scrollbar(rect, sb),
            OwnedContent::Palette(palette) => backend.draw_palette(rect, palette),
            OwnedContent::Toast(stack) => {
                backend.draw_toast_overlay(rect, stack);
            }
            OwnedContent::DataTable(table) => {
                backend.draw_data_table(rect, table, None);
            }
            OwnedContent::Chart(chart) => {
                backend.draw_chart(rect, chart, None, None);
            }
            OwnedContent::Canvas(canvas) => {
                backend.draw_canvas(rect, canvas);
            }
            OwnedContent::Board(model) => {
                backend.draw_board(rect, model);
            }
            OwnedContent::CommandCenter(cc) => {
                backend.draw_command_center(rect, cc);
            }
            OwnedContent::DiffView(view) => {
                backend.draw_diff_view(rect, view);
            }
            OwnedContent::Image(image) => {
                backend.draw_image(rect, image);
            }
            OwnedContent::MessageList(list) => backend.draw_message_list(rect, list),
            OwnedContent::Minimap(minimap) => {
                backend.draw_minimap(rect, minimap);
            }
            OwnedContent::PipelineView(view) => {
                backend.draw_pipeline_view(rect, view);
            }
            OwnedContent::Progress(bar) => {
                backend.draw_progress(rect, bar);
            }
            OwnedContent::SidebarPanel(panel) => {
                let interaction = crate::interaction::InteractionState::from_parts(None, None);
                backend.draw_sidebar_panel_interactive(rect, panel, &interaction);
            }
            OwnedContent::Spinner(spinner) => {
                backend.draw_spinner(rect, spinner);
            }
            OwnedContent::SplitTree(tree) => {
                backend.draw_split_tree(rect, tree);
            }
            OwnedContent::TextInput(ti) => {
                backend.draw_text_input(rect, ti);
            }
            OwnedContent::Toolbar(bar) => {
                let interaction = crate::interaction::InteractionState::from_parts(None, None);
                backend.draw_toolbar_interactive(rect, bar, &interaction);
            }
            OwnedContent::Tooltip(_)
            | OwnedContent::ContextMenu(_)
            | OwnedContent::Dialog(_)
            | OwnedContent::Float(_)
            | OwnedContent::Completions(_)
            | OwnedContent::RichTextPopup(_)
            | OwnedContent::DropOverlay
            | OwnedContent::FindReplace
            | OwnedContent::Opaque => {}
        }
    }

    /// The [`FrameZone`] this content contributes at frame-local index
    /// `idx`, mirroring [`ScreenLayout::zone_for`]'s tag-per-variant
    /// mapping so a `ScreenLayout` and the [`OwnedFrame`] captured from
    /// it produce identical zones.
    fn zone(&self, idx: usize) -> FrameZone {
        match self {
            OwnedContent::Editor(_) => FrameZone::Editor { idx },
            OwnedContent::TabBar(_) => FrameZone::TabBar { idx },
            OwnedContent::StatusBar(_) => FrameZone::StatusBar { idx },
            OwnedContent::ActivityBar(_) => FrameZone::ActivityBar { idx },
            OwnedContent::CommandLine(_) => FrameZone::CommandLine { idx },
            OwnedContent::Terminal(_) => FrameZone::Terminal { idx },
            OwnedContent::TextDisplay(_) => FrameZone::TextDisplay { idx },
            OwnedContent::MultiSectionView(_) => FrameZone::MultiSectionView { idx },
            OwnedContent::Tree(_) => FrameZone::Tree { idx },
            OwnedContent::List(_) => FrameZone::List { idx },
            OwnedContent::Form(_) => FrameZone::Form { idx },
            OwnedContent::MenuBar(_) => FrameZone::MenuBar { idx },
            OwnedContent::Split(_) => FrameZone::Split { idx },
            OwnedContent::Panel(_) => FrameZone::Panel { idx },
            OwnedContent::Scrollbar(_) => FrameZone::Scrollbar { idx },
            OwnedContent::Palette(_) => FrameZone::Palette { idx },
            OwnedContent::Tooltip(_) => FrameZone::Tooltip { idx },
            OwnedContent::ContextMenu(_) => FrameZone::ContextMenu { idx },
            OwnedContent::Dialog(_) => FrameZone::Dialog { idx },
            OwnedContent::Float(_) => FrameZone::Float { idx },
            OwnedContent::Completions(_) => FrameZone::Completions { idx },
            OwnedContent::RichTextPopup(_) => FrameZone::RichTextPopup { idx },
            OwnedContent::Toast(_) => FrameZone::Toast { idx },
            OwnedContent::DataTable(_) => FrameZone::DataTable { idx },
            OwnedContent::Chart(_) => FrameZone::Chart { idx },
            OwnedContent::Canvas(_) => FrameZone::Canvas { idx },
            OwnedContent::Board(_) => FrameZone::Board { idx },
            OwnedContent::CommandCenter(_) => FrameZone::CommandCenter { idx },
            OwnedContent::DiffView(_) => FrameZone::DiffView { idx },
            OwnedContent::Image(_) => FrameZone::Image { idx },
            OwnedContent::MessageList(_) => FrameZone::MessageList { idx },
            OwnedContent::Minimap(_) => FrameZone::Minimap { idx },
            OwnedContent::PipelineView(_) => FrameZone::PipelineView { idx },
            OwnedContent::Progress(_) => FrameZone::Progress { idx },
            OwnedContent::SidebarPanel(_) => FrameZone::SidebarPanel { idx },
            OwnedContent::Spinner(_) => FrameZone::Spinner { idx },
            OwnedContent::SplitTree(_) => FrameZone::SplitTree { idx },
            OwnedContent::TextInput(_) => FrameZone::TextInput { idx },
            OwnedContent::Toolbar(_) => FrameZone::Toolbar { idx },
            OwnedContent::DropOverlay => FrameZone::DropOverlay { idx },
            OwnedContent::FindReplace => FrameZone::FindReplace { idx },
            OwnedContent::Opaque => FrameZone::Empty,
        }
    }
}

/// One captured surface in an [`OwnedFrame`]: the owned counterpart of
/// a single [`Surface`] entry. Every field is owned and `serde`-capable,
/// so an `OwnedNode` outlives the `ScreenLayout` it was captured from.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OwnedNode {
    /// Frame-local surface index, matching [`FrameZone`]'s `idx` —
    /// see that type's doc for the push-order-dependent caveat.
    pub idx: usize,
    /// Bounding rect this node paints/hit-tests at — the same rect
    /// [`ScreenLayout::zone_for`] would have used for the source
    /// [`Surface`] (plain `rect` for most variants, `layout.bounds` for
    /// the overlay variants that carry one, [`DropOverlay::bounds`] for
    /// [`Surface::DropOverlay`]).
    pub rect: Rect,
    /// This node's owning widget, when the source [`Surface`] variant
    /// carries one — mirrors [`ScreenLayout::tab_stops`]'s inclusion
    /// list exactly (structural chrome, transient overlays, and purely
    /// decorative primitives have no widget id here, matching that
    /// method's exclusions).
    pub widget_id: Option<WidgetId>,
    /// Accessibility sidecar data for this node. Always `None` when
    /// produced by [`OwnedFrame::from_layout`] — no primitive today
    /// carries [`crate::a11y::A11yInfo`] to capture — but present on the
    /// type so a consumer can attach it after the fact.
    pub a11y: Option<crate::a11y::A11yInfo>,
    /// The captured primitive content.
    pub content: OwnedContent,
}

/// An owned, lifetime-free frame tree: the serializable counterpart of
/// a [`ScreenLayout`]. Build one with [`Self::from_layout`], then call
/// [`Self::draw`] to repaint it or [`Self::hit_map`] to derive a
/// [`FrameHitMap`] without a backend. See the module doc's "`FrameHitMap`
/// is serializable; `OwnedFrame` is the owned `Frame`" section for the
/// full rationale.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct OwnedFrame {
    nodes: Vec<OwnedNode>,
}

impl OwnedFrame {
    /// An empty `OwnedFrame`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Capture every surface in `layout` into a serializable
    /// [`OwnedFrame`]. Clones each primitive out of `layout`, so the
    /// result is independent of it and can be serialized, persisted, or
    /// sent across a process/wire boundary.
    pub fn from_layout(layout: &ScreenLayout) -> Self {
        let nodes = layout
            .surfaces
            .iter()
            .enumerate()
            .map(|(idx, surface)| {
                let (rect, widget_id, content) = capture_surface(surface);
                OwnedNode {
                    idx,
                    rect,
                    widget_id,
                    a11y: None,
                    content,
                }
            })
            .collect();
        Self { nodes }
    }

    /// The captured nodes, in the same back-to-front order they were
    /// pushed into the source [`ScreenLayout`].
    pub fn nodes(&self) -> &[OwnedNode] {
        &self.nodes
    }

    /// The captured nodes, mutably — the seam a consumer uses to attach
    /// per-surface [`OwnedNode::a11y`] overrides to a frame it has
    /// already captured. The node set itself is fixed by the capture:
    /// nodes can be edited in place, not added or removed, so `idx`
    /// stays in step with the source [`ScreenLayout`] and the
    /// [`FrameZone`]s [`Self::draw`] registers.
    pub fn nodes_mut(&mut self) -> &mut [OwnedNode] {
        &mut self.nodes
    }

    /// Repaint every node through `backend` and return the resulting
    /// [`FrameHitMap`] — the owned-data counterpart of
    /// [`ScreenLayout::draw`]. See [`OwnedContent::draw`] for which
    /// variants are no-ops here (they still register a hit zone).
    pub fn draw(&self, backend: &mut dyn Backend) -> FrameHitMap {
        let mut hit_map = FrameHitMap::new();
        for node in &self.nodes {
            node.content.draw(node.rect, backend);
            hit_map.push(node.rect, node.content.zone(node.idx));
        }
        hit_map
    }

    /// Derive the [`FrameHitMap`] this frame would produce, without
    /// invoking any `backend.draw_*()` call — the owned-data counterpart
    /// of [`ScreenLayout::hit_map`].
    pub fn hit_map(&self) -> FrameHitMap {
        let mut hit_map = FrameHitMap::new();
        for node in &self.nodes {
            hit_map.push(node.rect, node.content.zone(node.idx));
        }
        hit_map
    }
}

/// Clone one [`Surface`]'s primitive into the `(rect, widget_id,
/// content)` parts an [`OwnedNode`] holds. The widget-id rule mirrors
/// [`ScreenLayout::tab_stops`]'s inclusion list exactly; the rect rule
/// mirrors [`ScreenLayout::zone_for`]'s exactly. [`Surface::DropOverlay`]
/// falls back to [`OwnedContent::DropOverlay`] and [`Surface::FindReplace`]
/// falls back to [`OwnedContent::FindReplace`], because [`DropOverlay`]
/// and [`FindReplacePanel`] do not implement `serde::{Serialize,
/// Deserialize}` — both still keep their own distinct [`FrameZone`] tag.
fn capture_surface(surface: &Surface) -> (Rect, Option<WidgetId>, OwnedContent) {
    match surface {
        Surface::Editor { rect, editor } => {
            (*rect, Some(editor.id), OwnedContent::Editor(editor.clone()))
        }
        Surface::TabBar { rect, bar, .. } => {
            (*rect, Some(bar.id), OwnedContent::TabBar(bar.clone()))
        }
        Surface::StatusBar { rect, bar, .. } => {
            (*rect, Some(bar.id), OwnedContent::StatusBar(bar.clone()))
        }
        Surface::ActivityBar { rect, bar, .. } => {
            (*rect, Some(bar.id), OwnedContent::ActivityBar(bar.clone()))
        }
        Surface::CommandLine { rect, cmd } => {
            (*rect, Some(cmd.id), OwnedContent::CommandLine(cmd.clone()))
        }
        Surface::Terminal { rect, term } => {
            (*rect, Some(term.id), OwnedContent::Terminal(term.clone()))
        }
        Surface::TextDisplay { rect, td } => {
            (*rect, Some(td.id), OwnedContent::TextDisplay(td.clone()))
        }
        Surface::MultiSectionView { rect, view } => (
            *rect,
            Some(view.id),
            OwnedContent::MultiSectionView(view.clone()),
        ),
        Surface::Tree { rect, tree } => (*rect, Some(tree.id), OwnedContent::Tree(tree.clone())),
        Surface::List { rect, list } => (*rect, Some(list.id), OwnedContent::List(list.clone())),
        Surface::Form { rect, form } => (*rect, Some(form.id), OwnedContent::Form(form.clone())),
        Surface::MenuBar { rect, bar } => (*rect, Some(bar.id), OwnedContent::MenuBar(bar.clone())),
        Surface::Split { rect, split } => (*rect, None, OwnedContent::Split(split.clone())),
        Surface::Panel { rect, panel } => {
            (*rect, Some(panel.id), OwnedContent::Panel(panel.clone()))
        }
        Surface::Scrollbar { rect, sb } => (*rect, None, OwnedContent::Scrollbar(sb.clone())),
        Surface::Palette { rect, palette } => (
            *rect,
            Some(palette.id),
            OwnedContent::Palette(palette.clone()),
        ),
        Surface::Tooltip { tooltip, layout } => {
            (layout.bounds, None, OwnedContent::Tooltip(tooltip.clone()))
        }
        Surface::ContextMenu { menu, layout } => {
            (layout.bounds, None, OwnedContent::ContextMenu(menu.clone()))
        }
        Surface::Dialog { dialog, layout } => {
            (layout.bounds, None, OwnedContent::Dialog(dialog.clone()))
        }
        Surface::Float { float, layout } => {
            (layout.bounds, None, OwnedContent::Float(float.clone()))
        }
        Surface::Completions {
            completions,
            layout,
        } => (
            layout.bounds,
            None,
            OwnedContent::Completions(completions.clone()),
        ),
        Surface::FindReplace { rect, .. } => (*rect, None, OwnedContent::FindReplace),
        Surface::RichTextPopup { popup, layout } => (
            layout.bounds,
            None,
            OwnedContent::RichTextPopup(popup.clone()),
        ),
        Surface::Toast { rect, stack } => (*rect, None, OwnedContent::Toast(stack.clone())),
        Surface::DataTable { rect, table, .. } => (
            *rect,
            Some(table.id),
            OwnedContent::DataTable(table.clone()),
        ),
        Surface::Chart { rect, chart, .. } => {
            (*rect, Some(chart.id), OwnedContent::Chart(chart.clone()))
        }
        Surface::Canvas { rect, canvas } => (*rect, None, OwnedContent::Canvas(canvas.clone())),
        Surface::Board { rect, model } => {
            (*rect, Some(model.id), OwnedContent::Board(model.clone()))
        }
        Surface::CommandCenter { rect, cc } => {
            (*rect, Some(cc.id), OwnedContent::CommandCenter(cc.clone()))
        }
        Surface::DiffView { rect, view } => {
            (*rect, Some(view.id), OwnedContent::DiffView(view.clone()))
        }
        Surface::DropOverlay { overlay } => (overlay.bounds(), None, OwnedContent::DropOverlay),
        Surface::Image { rect, image } => (*rect, None, OwnedContent::Image(image.clone())),
        Surface::MessageList { rect, list } => (
            *rect,
            Some(list.id),
            OwnedContent::MessageList(list.clone()),
        ),
        Surface::Minimap { rect, minimap } => (
            *rect,
            Some(minimap.id),
            OwnedContent::Minimap(minimap.clone()),
        ),
        Surface::PipelineView { rect, view } => (
            *rect,
            Some(view.id),
            OwnedContent::PipelineView(view.clone()),
        ),
        Surface::Progress { rect, bar } => (
            *rect,
            if bar.cancellable { Some(bar.id) } else { None },
            OwnedContent::Progress(bar.clone()),
        ),
        Surface::SidebarPanel { rect, panel, .. } => (
            *rect,
            Some(panel.id),
            OwnedContent::SidebarPanel(panel.clone()),
        ),
        Surface::Spinner { rect, spinner } => (*rect, None, OwnedContent::Spinner(spinner.clone())),
        Surface::SplitTree { rect, tree } => (*rect, None, OwnedContent::SplitTree(tree.clone())),
        Surface::TextInput { rect, ti } => {
            (*rect, Some(ti.id), OwnedContent::TextInput(ti.clone()))
        }
        Surface::Toolbar { rect, bar, .. } => {
            (*rect, Some(bar.id), OwnedContent::Toolbar(bar.clone()))
        }
    }
}

/// A typed, app-defined z-order rung. Implement this once
/// per app-specific "what can appear in a frame" enum (an editor pane,
/// a bottom panel, an overlay stack, ...) to get a single declared
/// back-to-front order that both painting ([`compose_frame`]) and
/// hit-testing can consult.
pub trait FrameRung: Copy + Eq + std::fmt::Debug + 'static {
    /// Every variant, back-to-front (bottom of the stack first, i.e.
    /// painted first / hit-tested last). The single source of truth —
    /// define it once, consult it from both paint and hit-test code.
    fn z_order() -> &'static [Self]
    where
        Self: Sized;

    /// This rung's position in [`Self::z_order`]. Panics if the rung
    /// is missing from `z_order()` — that is always a programmer
    /// error (an unlisted variant), not a runtime condition to handle.
    fn rank(&self) -> usize
    where
        Self: Sized,
    {
        Self::z_order()
            .iter()
            .position(|r| r == self)
            .unwrap_or_else(|| panic!("{self:?} is missing from FrameRung::z_order()"))
    }
}

/// Presence gate for a frame: which rungs of `R` exist right now,
/// evaluated once and reused by both the paint walk ([`compose_frame`])
/// and hit-testing, so "is this even open" can't be answered two
/// different ways in the same frame.
pub struct FramePresence<R> {
    present: Vec<(R, bool)>,
}

impl<R: FrameRung> FramePresence<R> {
    /// Evaluate `predicate` once per rung in [`FrameRung::z_order`].
    pub fn from_fn(predicate: impl Fn(R) -> bool) -> Self {
        let present = R::z_order().iter().map(|&r| (r, predicate(r))).collect();
        Self { present }
    }

    /// Whether `rung` is present this frame. Rungs not covered by
    /// [`Self::from_fn`]'s `z_order()` scan (impossible in practice,
    /// since it's derived from `z_order()` itself) are absent.
    pub fn is_present(&self, rung: R) -> bool {
        self.present
            .iter()
            .any(|(r, present)| *r == rung && *present)
    }

    /// Rungs that are present this frame, in canonical [`FrameRung::z_order`] order.
    pub fn present_rungs(&self) -> impl Iterator<Item = R> + '_ {
        self.present.iter().filter(|(_, p)| *p).map(|(r, _)| *r)
    }
}

/// Walk every present rung of `R`, back-to-front, invoking `paint`
/// once per rung. This is the non-branching frame composer: an app
/// supplies `presence` (from [`FramePresence::from_fn`]) and a
/// callback keyed by rung — no `match` over paint-operation variants,
/// and the walk order is [`FrameRung::z_order`] by construction, so it
/// cannot drift from what a `z_order()`-derived hit-test walk expects.
///
/// Returns the visited rungs in the order `paint` was called, e.g. to
/// feed to [`check_frame_order`] when composing the same order a
/// second time via an independent path (see module docs).
pub fn compose_frame<R: FrameRung>(
    presence: &FramePresence<R>,
    mut paint: impl FnMut(R),
) -> Vec<R> {
    let mut visited = Vec::new();
    for rung in presence.present_rungs() {
        paint(rung);
        visited.push(rung);
    }
    visited
}

/// Two rungs visited out of the order [`FrameRung::z_order`] declares:
/// `after` was visited following `before`, despite ranking lower (i.e.
/// further from "on top") in the canonical order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameOrderViolation<R> {
    pub before: R,
    pub after: R,
}

/// Assert that `visited` — some sequence of rungs actually painted or
/// hit-tested, produced however the caller likes — is consistent with
/// [`FrameRung::z_order`]: no rung may appear after a rung that ranks
/// higher has already appeared. Duplicates and gaps (rungs absent this
/// frame) are fine; the invariant is purely the *relative* order among
/// whatever was visited.
///
/// This is the guard that turns a `FRAME_Z_ORDER` vs.
/// `MOUSE_ARBITRATION_ORDER`-style drift into a
/// failing assertion instead of a silent, months-later bug.
pub fn check_frame_order<R: FrameRung>(visited: &[R]) -> Result<(), FrameOrderViolation<R>> {
    let mut last: Option<(R, usize)> = None;
    for &rung in visited {
        let rank = rung.rank();
        if let Some((before, before_rank)) = last {
            if rank < before_rank {
                return Err(FrameOrderViolation {
                    before,
                    after: rung,
                });
            }
        }
        last = Some((rung, rank));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::tree::TreeRow;
    use crate::types::{SelectionMode, StyledText, TreeStyle};

    #[test]
    fn hit_test_returns_highest_z_surface() {
        let mut map = FrameHitMap::new();
        // Background surface covers entire area.
        map.push(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            FrameZone::Editor { idx: 0 },
        );
        // Overlay covers top-left quadrant.
        map.push(
            Rect::new(0.0, 0.0, 50.0, 50.0),
            FrameZone::Palette { idx: 1 },
        );

        // Point in the overlay → highest-z wins.
        assert_eq!(map.hit_test(25.0, 25.0), FrameZone::Palette { idx: 1 });
        // Point outside the overlay but inside editor.
        assert_eq!(map.hit_test(75.0, 75.0), FrameZone::Editor { idx: 0 });
        // Point outside everything.
        assert_eq!(map.hit_test(150.0, 150.0), FrameZone::Empty);
    }

    #[test]
    fn hit_test_empty_map() {
        let map = FrameHitMap::new();
        assert_eq!(map.hit_test(10.0, 10.0), FrameZone::Empty);
        assert!(map.is_empty());
    }

    #[test]
    fn multiple_overlapping_zones_last_wins() {
        let mut map = FrameHitMap::new();
        map.push(
            Rect::new(0.0, 0.0, 80.0, 24.0),
            FrameZone::Editor { idx: 0 },
        );
        map.push(Rect::new(0.0, 0.0, 80.0, 1.0), FrameZone::TabBar { idx: 1 });
        map.push(
            Rect::new(0.0, 23.0, 80.0, 1.0),
            FrameZone::StatusBar { idx: 2 },
        );

        assert_eq!(map.hit_test(40.0, 0.5), FrameZone::TabBar { idx: 1 });
        assert_eq!(map.hit_test(40.0, 12.0), FrameZone::Editor { idx: 0 });
        assert_eq!(map.hit_test(40.0, 23.5), FrameZone::StatusBar { idx: 2 });
    }

    #[test]
    fn screen_layout_default_is_empty() {
        let layout = ScreenLayout::default();
        assert_eq!(layout.surfaces.len(), 0);
    }

    fn sample_tree(id: &str, scroll_offset: usize) -> TreeView {
        TreeView {
            id: WidgetId::new(id),
            rows: vec![TreeRow {
                path: vec![0],
                indent: 0,
                icon: None,
                text: StyledText::plain("src/"),
                badge: None,
                is_expanded: Some(true),
                decoration: Default::default(),
                edit: None,
            }],
            selection_mode: SelectionMode::Single,
            selected_path: Some(vec![0]),
            scroll_offset,
            style: TreeStyle::default(),
            has_focus: false,
        }
    }

    #[test]
    fn tree_frame_carries_handles_with_matching_rects() {
        let mut layout = ScreenLayout::new();
        layout.push(Surface::Tree {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            tree: sample_tree("tree:explorer", 0),
        });

        let frame = layout.tree_frame();

        assert_eq!(frame.len(), 1);
        let (handle, rect) = frame[0];
        assert_eq!(rect, Rect::new(0.0, 0.0, 40.0, 10.0));
        assert_eq!(
            layout.tree_store.get(handle).map(|t| &t.id),
            Some(&WidgetId::new("tree:explorer"))
        );
    }

    #[test]
    fn tree_frame_reuses_the_same_handle_across_frames_without_rebuilding() {
        let mut layout = ScreenLayout::new();
        layout.push(Surface::Tree {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            tree: sample_tree("tree:explorer", 0),
        });

        let first = layout.tree_frame();
        let first_handle = first[0].0;
        assert_eq!(layout.tree_store.len(), 1);

        // Simulate a retained layout's next frame: the same logical tree,
        // unchanged, is still at the same surface index.
        let second = layout.tree_frame();
        assert_eq!(second[0].0, first_handle);
        assert_eq!(layout.tree_store.len(), 1);

        // Replace the surface in place (same `WidgetId`, different scroll
        // state) the way a retained `ScreenLayout` caller would via
        // `surfaces_mut`, and confirm the identity-keyed slot is updated
        // rather than inserted as a new entry.
        layout.surfaces_mut()[0] = Surface::Tree {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            tree: sample_tree("tree:explorer", 5),
        };
        let third = layout.tree_frame();
        assert_eq!(third[0].0, first_handle);
        assert_eq!(layout.tree_store.len(), 1);
        assert_eq!(
            layout.tree_store.get(third[0].0).map(|t| t.scroll_offset),
            Some(5)
        );

        // A genuinely new tree id grows the store by exactly one slot.
        layout.push(Surface::Tree {
            rect: Rect::new(0.0, 10.0, 40.0, 10.0),
            tree: sample_tree("tree:outline", 0),
        });
        let fourth = layout.tree_frame();
        assert_eq!(fourth.len(), 2);
        assert_eq!(layout.tree_store.len(), 2);
    }

    #[test]
    fn tree_frame_evicts_handles_for_ids_no_longer_pushed() {
        let mut layout = ScreenLayout::new();
        layout.push(Surface::Tree {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            tree: sample_tree("tree:explorer", 0),
        });

        let first = layout.tree_frame();
        let stale_handle = first[0].0;
        assert_eq!(layout.tree_store.len(), 1);

        // Swap the surface in place for a *different* tree id — the
        // pattern `surfaces_mut`'s doc calls out (a per-tab explorer, a
        // closed panel reused for a new one). Without eviction this
        // would leave the old id's slot occupied forever.
        layout.surfaces_mut()[0] = Surface::Tree {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            tree: sample_tree("tree:outline", 0),
        };
        let second = layout.tree_frame();

        assert_eq!(layout.tree_store.len(), 1);
        assert!(layout.tree_store.get(stale_handle).is_none());
        assert_eq!(
            layout.tree_store.get(second[0].0).map(|t| &t.id),
            Some(&WidgetId::new("tree:outline"))
        );

        // Dropping the surface entirely (no `Surface::Tree` pushed at
        // all) evicts the last tracked id too, instead of leaving an
        // orphaned slot with nothing in `surfaces` to ever revisit it.
        let mut empty_layout = ScreenLayout::new();
        empty_layout.push(Surface::Tree {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            tree: sample_tree("tree:explorer", 0),
        });
        empty_layout.tree_frame();
        assert_eq!(empty_layout.tree_store.len(), 1);
        empty_layout.surfaces_mut()[0] = Surface::Editor {
            rect: Rect::new(0.0, 0.0, 40.0, 10.0),
            editor: Editor {
                id: "ed".into(),
                rect: Rect::new(0.0, 0.0, 40.0, 10.0),
                lines: Vec::new(),
                cursor: None,
                extra_cursors: Vec::new(),
                selection: None,
                extra_selections: Vec::new(),
                yank_highlight: None,
                scroll_top: 0,
                scroll_left: 0,
                total_lines: 0,
                max_col: 0,
                gutter_char_width: 0,
                is_active: true,
                show_active_bg: false,
                has_git_diff: false,
                has_breakpoints: false,
                diagnostic_gutter: std::collections::HashMap::new(),
                code_action_lines: std::collections::HashSet::new(),
                bracket_match_positions: Vec::new(),
                active_indent_col: None,
                tabstop: 4,
                cursorline: false,
                lightbulb_glyph: '\0',
            },
        };
        empty_layout.tree_frame();
        assert_eq!(empty_layout.tree_store.len(), 0);
    }

    #[test]
    fn hit_map_registers_zones_without_a_backend() {
        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 100.0, 100.0),
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        };
        let palette = Palette {
            id: "pal".into(),
            title: String::new(),
            query: String::new(),
            query_cursor: 0,
            items: Vec::new(),
            selected_idx: 0,
            scroll_offset: 0,
            total_count: 0,
            has_focus: false,
            show_query: true,
            create_label: None,
            preview: None,
            mode: crate::primitives::palette::PaletteMode::List,
        };

        let mut layout = ScreenLayout::new();
        layout.push(Surface::Editor {
            rect: Rect::new(0.0, 0.0, 100.0, 100.0),
            editor,
        });
        layout.push(Surface::Palette {
            rect: Rect::new(0.0, 0.0, 50.0, 50.0),
            palette,
        });

        // No `&mut dyn Backend` in scope anywhere in this test — proves
        // `hit_map()` needs no backend to recover the same zones `draw()`
        // would have registered.
        let hit_map = layout.hit_map();

        assert_eq!(hit_map.len(), 2);
        // Point in the overlay → highest-z (last-pushed) wins.
        assert_eq!(hit_map.hit_test(25.0, 25.0), FrameZone::Palette { idx: 1 });
        // Point outside the overlay but inside the editor.
        assert_eq!(hit_map.hit_test(75.0, 75.0), FrameZone::Editor { idx: 0 });
        // Point outside everything.
        assert_eq!(hit_map.hit_test(150.0, 150.0), FrameZone::Empty);
    }

    /// A [`Surface`] owns the primitive it paints, so the primitive's
    /// original binding can go out of scope while the `Surface` lives
    /// on and still describes a complete frame.
    #[test]
    fn surface_owns_its_primitive_and_outlives_the_source() {
        let rect = Rect::new(2.0, 3.0, 20.0, 8.0);

        let surface = {
            let list = MessageList {
                id: "ml".into(),
                rows: Vec::new(),
                scroll_top: 0,
            };
            Surface::MessageList { rect, list }
            // `list`'s binding dies here; the `Surface` keeps the value.
        };

        let mut layout = ScreenLayout::new();
        layout.push(surface);

        let hit_map = layout.hit_map();
        assert_eq!(hit_map.len(), 1);
        assert_eq!(hit_map.zones()[0].0, rect);
        assert_eq!(
            hit_map.hit_test(3.0, 4.0),
            FrameZone::MessageList { idx: 0 }
        );
        assert_eq!(hit_map.hit_test(100.0, 100.0), FrameZone::Empty);
    }

    /// A [`ScreenLayout`] carries no lifetime, so it is a plain return
    /// value: a helper can build a whole frame description and hand it
    /// back, and the caller can both draw it and hit-map it.
    #[test]
    fn screen_layout_returned_from_a_function_draws_and_hit_maps() {
        use crate::testing::RecordingBackend;

        fn build() -> ScreenLayout {
            let list = MessageList {
                id: "ml".into(),
                rows: Vec::new(),
                scroll_top: 0,
            };
            let mut layout = ScreenLayout::new();
            layout.push(Surface::MessageList {
                rect: Rect::new(0.0, 0.0, 40.0, 10.0),
                list,
            });
            layout
        }

        let layout = build();

        let mut backend = RecordingBackend::new();
        let drawn = layout.draw(&mut backend);
        assert!(backend.calls.contains(&"draw_message_list"));

        assert_eq!(drawn, layout.hit_map());
        assert_eq!(drawn.hit_test(1.0, 1.0), FrameZone::MessageList { idx: 0 });
    }

    /// `tab_stops` derives Tab order from geometry (reading order),
    /// not push order — the whole point of deriving it from
    /// `ScreenLayout` rather than an app hand-maintaining a list.
    #[test]
    fn tab_stops_sorts_by_reading_order_not_push_order() {
        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 10.0, 100.0, 20.0),
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        };
        let palette = Palette {
            id: "pal".into(),
            title: String::new(),
            query: String::new(),
            query_cursor: 0,
            items: Vec::new(),
            selected_idx: 0,
            scroll_offset: 0,
            total_count: 0,
            has_focus: false,
            show_query: true,
            create_label: None,
            preview: None,
            mode: crate::primitives::palette::PaletteMode::List,
        };
        let split = crate::primitives::split::Split {
            id: "split".into(),
            direction: crate::primitives::split::SplitDirection::Horizontal,
            ratio: 0.5,
            first_min: 0.0,
            second_min: 0.0,
        };

        let mut layout = ScreenLayout::new();
        // Pushed in the "wrong" (bottom-to-top) order — `tab_stops` must
        // still resolve reading order (top-to-bottom) from the rects.
        layout.push(Surface::Editor {
            rect: editor.rect,
            editor,
        });
        layout.push(Surface::Palette {
            rect: Rect::new(0.0, 0.0, 50.0, 5.0),
            palette,
        });
        // Structural chrome: must not appear in tab order at all.
        layout.push(Surface::Split {
            rect: Rect::new(0.0, 30.0, 100.0, 1.0),
            split,
        });

        let stops = layout.tab_stops();

        assert_eq!(
            stops.iter().map(|(id, _)| id.as_str()).collect::<Vec<_>>(),
            vec!["pal", "ed"],
            "palette (y=0) must sort before the editor (y=10), regardless of push order"
        );
        assert!(
            !stops.iter().any(|(id, _)| id.as_str() == "split"),
            "Split is structural chrome, not a tab stop"
        );
    }

    /// Every primitive with a `Backend::draw_*` method has a matching
    /// `Surface` variant. Builds one of each variant, pushes them all,
    /// and checks `hit_map()` registers every one under the right
    /// `FrameZone` tag.
    #[test]
    fn surface_gap_closed_for_all_fourteen_primitives() {
        let board = crate::primitives::board::BoardModel {
            id: "board".into(),
            columns: Vec::new(),
            selected_card_id: None,
            col_scroll_offset: 0,
        };
        let cc = CommandCenter {
            id: "cc".into(),
            back_enabled: false,
            forward_enabled: false,
            search_label: String::new(),
        };
        let diff = DiffView {
            id: "diff".into(),
            left: String::new(),
            right: String::new(),
            left_label: None,
            right_label: None,
            hunks: Vec::new(),
            mode: Default::default(),
            editability: Default::default(),
            scroll_offset: 0,
            focused_pane: Default::default(),
            has_focus: false,
        };
        let overlay = DropOverlay {
            highlight: Some(Rect::new(1.0, 1.0, 2.0, 2.0)),
            insertion_bar: None,
            ghost_position: None,
        };
        let image = Image {
            id: "img".into(),
            source: crate::primitives::image::ImageSource::Path(std::path::PathBuf::new()),
            intrinsic_size: None,
            fit: Default::default(),
            fallback_text: String::new(),
        };
        let message_list = MessageList {
            id: "ml".into(),
            rows: Vec::new(),
            scroll_top: 0,
        };
        let minimap = Minimap {
            id: "mm".into(),
            lines: Vec::new(),
            syntax_spans: Vec::new(),
            visible_row_start: 0,
            visible_row_count: 0,
            total_buffer_lines: 0,
        };
        let pipeline = PipelineView {
            id: "pv".into(),
            stages: Vec::new(),
            focused_stage: None,
        };
        let progress = ProgressBar {
            id: "pb".into(),
            label: String::new(),
            value: None,
            frame_idx: 0,
            cancellable: false,
            accent: None,
        };
        let sidebar = SidebarPanel {
            id: "sp".into(),
            toolbar: None,
            toolbar_height: None,
        };
        let spinner = Spinner {
            id: "sn".into(),
            label: String::new(),
            frame_idx: 0,
            accent: None,
        };
        let split_tree = SplitTree::Leaf("leaf".into());
        let text_input = TextInput {
            id: "ti".into(),
            lines: vec![String::new()],
            cursor_line: 0,
            cursor_col: 0,
            placeholder: None,
            scroll_offset: 0,
            scroll_col: 0,
            has_focus: false,
        };
        let toolbar = Toolbar {
            id: "tb".into(),
            buttons: Vec::new(),
            bg: None,
            focused_index: None,
        };

        let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
        let mut layout = ScreenLayout::new();
        layout.push(Surface::Board { rect, model: board });
        layout.push(Surface::CommandCenter { rect, cc });
        layout.push(Surface::DiffView { rect, view: diff });
        layout.push(Surface::DropOverlay {
            overlay: overlay.clone(),
        });
        layout.push(Surface::Image { rect, image });
        layout.push(Surface::MessageList {
            rect,
            list: message_list,
        });
        layout.push(Surface::Minimap { rect, minimap });
        layout.push(Surface::PipelineView {
            rect,
            view: pipeline,
        });
        layout.push(Surface::Progress {
            rect,
            bar: progress,
        });
        layout.push(Surface::SidebarPanel {
            rect,
            panel: sidebar,
            hovered: None,
            pressed: None,
        });
        layout.push(Surface::Spinner { rect, spinner });
        layout.push(Surface::SplitTree {
            rect,
            tree: split_tree,
        });
        layout.push(Surface::TextInput {
            rect,
            ti: text_input,
        });
        layout.push(Surface::Toolbar {
            rect,
            bar: toolbar,
            hovered: None,
            pressed: None,
        });

        let hit_map = layout.hit_map();
        assert_eq!(hit_map.len(), 14);

        let zones: Vec<&FrameZone> = hit_map.zones().iter().map(|(_, z)| z).collect();
        assert_eq!(zones[0], &FrameZone::Board { idx: 0 });
        assert_eq!(zones[1], &FrameZone::CommandCenter { idx: 1 });
        assert_eq!(zones[2], &FrameZone::DiffView { idx: 2 });
        assert_eq!(zones[3], &FrameZone::DropOverlay { idx: 3 });
        assert_eq!(zones[4], &FrameZone::Image { idx: 4 });
        assert_eq!(zones[5], &FrameZone::MessageList { idx: 5 });
        assert_eq!(zones[6], &FrameZone::Minimap { idx: 6 });
        assert_eq!(zones[7], &FrameZone::PipelineView { idx: 7 });
        assert_eq!(zones[8], &FrameZone::Progress { idx: 8 });
        assert_eq!(zones[9], &FrameZone::SidebarPanel { idx: 9 });
        assert_eq!(zones[10], &FrameZone::Spinner { idx: 10 });
        assert_eq!(zones[11], &FrameZone::SplitTree { idx: 11 });
        assert_eq!(zones[12], &FrameZone::TextInput { idx: 12 });
        assert_eq!(zones[13], &FrameZone::Toolbar { idx: 13 });

        // `DropOverlay`'s zone rect comes from `DropOverlay::bounds()`,
        // not a `rect` field it doesn't have.
        assert_eq!(hit_map.zones()[3].0, overlay.bounds());

        // Tab order: `DropOverlay` (transient overlay) and `SplitTree`
        // (structural chrome, like `Split`) don't participate, and
        // neither do the purely-decorative `Image`/`Spinner` or this
        // non-cancellable `Progress` (no activatable affordance).
        let stops = layout.tab_stops();
        let stop_ids: Vec<&str> = stops.iter().map(|(id, _)| id.as_str()).collect();
        for id in ["board", "cc", "diff", "ml", "mm", "pv", "sp", "ti", "tb"] {
            assert!(stop_ids.contains(&id), "{id} should be a tab stop");
        }
        for id in ["img", "sn", "pb", "leaf"] {
            assert!(!stop_ids.contains(&id), "{id} should not be a tab stop");
        }
        assert_eq!(stop_ids.len(), 9);
    }

    /// A cancellable `Progress` bar *does* get a tab stop — the cancel
    /// affordance (`ProgressBarHit::Cancel`) is a real interaction, unlike
    /// a bare progress readout.
    #[test]
    fn cancellable_progress_is_a_tab_stop() {
        let progress = ProgressBar {
            id: "pb".into(),
            label: String::new(),
            value: None,
            frame_idx: 0,
            cancellable: true,
            accent: None,
        };
        let rect = Rect::new(0.0, 0.0, 10.0, 10.0);
        let mut layout = ScreenLayout::new();
        layout.push(Surface::Progress {
            rect,
            bar: progress,
        });
        let stops = layout.tab_stops();
        assert_eq!(stops.len(), 1);
        assert_eq!(stops[0].0.as_str(), "pb");
    }

    /// `Surface::Float` dispatches to `Backend::draw_float` and is
    /// excluded from Tab order — same transient-overlay treatment as
    /// `Tooltip`/`ContextMenu`/`Dialog` (see this module's
    /// `tab_stops` doc).
    #[test]
    fn surface_float_dispatches_to_draw_float_and_is_excluded_from_tab_stops() {
        use crate::layout::{Anchor, Side};
        use crate::testing::RecordingBackend;
        use crate::{Float, FloatMeasure};

        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 100.0, 100.0),
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        };
        let float = Float::new(
            WidgetId::new("f"),
            Anchor::new(Rect::new(0.0, 0.0, 5.0, 1.0), Side::Bottom),
        );
        let float_layout = float.layout(
            Rect::new(0.0, 0.0, 80.0, 24.0),
            FloatMeasure::new(10.0, 4.0),
        );

        let mut layout = ScreenLayout::new();
        layout.push(Surface::Editor {
            rect: Rect::new(0.0, 0.0, 100.0, 100.0),
            editor,
        });
        layout.push(Surface::Float {
            float,
            layout: float_layout,
        });

        let mut backend = RecordingBackend::new();
        layout.draw(&mut backend);
        assert!(backend.calls.contains(&"draw_float"));

        let stops = layout.tab_stops();
        assert_eq!(
            stops.len(),
            1,
            "the Float surface must not become a Tab stop — it owns its \
             own focus story via ModalStack::top_focusable"
        );
        assert_eq!(stops[0].0.as_str(), "ed");
    }

    /// `FrameHitMap` is serializable: round-trips through JSON
    /// (exercising the new `FrameZone` variants too) and reconstructs
    /// via `from_zones`/`zones`.
    #[test]
    fn frame_hit_map_serde_round_trip() {
        let mut map = FrameHitMap::new();
        map.push(Rect::new(0.0, 0.0, 10.0, 10.0), FrameZone::Board { idx: 0 });
        map.push(Rect::new(0.0, 0.0, 5.0, 5.0), FrameZone::Toolbar { idx: 1 });

        let json = serde_json::to_string(&map).expect("FrameHitMap serializes");
        let restored: FrameHitMap = serde_json::from_str(&json).expect("FrameHitMap deserializes");
        assert_eq!(restored, map);
        assert_eq!(restored.hit_test(1.0, 1.0), FrameZone::Toolbar { idx: 1 });

        // `from_zones` is the inverse of `zones()` — a map rebuilt from
        // its own owned data behaves identically.
        let rebuilt = FrameHitMap::from_zones(map.zones().to_vec());
        assert_eq!(rebuilt, map);
    }

    /// [`OwnedFrame`] round-trips through JSON with no backend in
    /// scope, and [`OwnedFrame::hit_map`] on the deserialized copy
    /// matches what the original [`ScreenLayout`] would have produced.
    #[test]
    fn owned_frame_serde_round_trip_preserves_hit_map() {
        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 100.0, 100.0),
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        };
        let palette = Palette {
            id: "pal".into(),
            title: String::new(),
            query: String::new(),
            query_cursor: 0,
            items: Vec::new(),
            selected_idx: 0,
            scroll_offset: 0,
            total_count: 0,
            has_focus: false,
            show_query: true,
            create_label: None,
            preview: None,
            mode: crate::primitives::palette::PaletteMode::List,
        };

        let mut layout = ScreenLayout::new();
        layout.push(Surface::Editor {
            rect: Rect::new(0.0, 0.0, 100.0, 100.0),
            editor,
        });
        layout.push(Surface::Palette {
            rect: Rect::new(0.0, 0.0, 50.0, 50.0),
            palette,
        });

        let captured = OwnedFrame::from_layout(&layout);
        assert_eq!(captured.nodes().len(), 2);

        let json = serde_json::to_string(&captured).expect("OwnedFrame serializes");
        let restored: OwnedFrame = serde_json::from_str(&json).expect("OwnedFrame deserializes");

        let hit_map = restored.hit_map();
        assert!(!hit_map.is_empty());
        assert_eq!(hit_map.len(), 2);
        // Point in the overlay → highest-z (last-pushed) wins, same as
        // `ScreenLayout::hit_map` would have reported for the source.
        assert_eq!(hit_map.hit_test(25.0, 25.0), FrameZone::Palette { idx: 1 });
        // Point outside the overlay but inside the editor.
        assert_eq!(hit_map.hit_test(75.0, 75.0), FrameZone::Editor { idx: 0 });
        // Point outside everything.
        assert_eq!(hit_map.hit_test(150.0, 150.0), FrameZone::Empty);
    }

    /// The literal acceptance shape: build a frame, serialize it,
    /// deserialize it, `draw()` the deserialized copy through a real
    /// [`crate::tui::TuiBackend`] (the production `Backend` call path,
    /// not just `hit_map()`'s backend-free shortcut), and check the
    /// result is non-empty and correct.
    #[cfg(feature = "tui")]
    #[test]
    fn owned_frame_serde_round_trip_draws_through_tui_backend() {
        use crate::runner::{AppLogic, Reaction};
        use crate::tui::testing::TuiDriver;
        use std::cell::RefCell;

        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 20.0, 5.0),
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        };

        let mut layout = ScreenLayout::new();
        layout.push(Surface::Editor {
            rect: Rect::new(0.0, 0.0, 20.0, 5.0),
            editor,
        });

        let captured = OwnedFrame::from_layout(&layout);
        let json = serde_json::to_string(&captured).expect("OwnedFrame serializes");
        let restored: OwnedFrame = serde_json::from_str(&json).expect("OwnedFrame deserializes");

        /// Drives the deserialized `OwnedFrame` through the real
        /// `Backend` trait on every render, exactly as a long-running
        /// app's render hook would, and stashes the resulting
        /// `FrameHitMap` for the test to inspect afterward.
        struct DrawRestoredFrame(OwnedFrame, RefCell<Option<FrameHitMap>>);
        impl AppLogic for DrawRestoredFrame {
            type AreaId = ();
            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                let hit_map = self.0.draw(backend);
                *self.1.borrow_mut() = Some(hit_map);
            }
            fn handle(&mut self, _event: crate::UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        let app = DrawRestoredFrame(restored, RefCell::new(None));
        let driver = TuiDriver::new(app, 20, 5);
        let hit_map = driver
            .app()
            .1
            .borrow()
            .clone()
            .expect("render ran at least once during TuiDriver::new");

        assert!(!hit_map.is_empty());
        assert_eq!(hit_map.hit_test(1.0, 1.0), FrameZone::Editor { idx: 0 });
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum TestRung {
        Editor,
        BottomPanel,
        StatusBar,
        Palette,
    }

    impl FrameRung for TestRung {
        fn z_order() -> &'static [Self] {
            &[
                TestRung::Editor,
                TestRung::BottomPanel,
                TestRung::StatusBar,
                TestRung::Palette,
            ]
        }
    }

    #[test]
    fn frame_rung_rank_matches_z_order_position() {
        assert_eq!(TestRung::Editor.rank(), 0);
        assert_eq!(TestRung::BottomPanel.rank(), 1);
        assert_eq!(TestRung::StatusBar.rank(), 2);
        assert_eq!(TestRung::Palette.rank(), 3);
    }

    #[test]
    #[should_panic(expected = "missing from FrameRung::z_order()")]
    fn frame_rung_rank_panics_for_unlisted_variant() {
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        struct Rogue;
        impl FrameRung for Rogue {
            fn z_order() -> &'static [Self] {
                &[]
            }
        }
        Rogue.rank();
    }

    #[test]
    fn frame_presence_gates_rungs_computed_once() {
        let presence = FramePresence::from_fn(|r| r != TestRung::BottomPanel);

        assert!(presence.is_present(TestRung::Editor));
        assert!(!presence.is_present(TestRung::BottomPanel));
        assert!(presence.is_present(TestRung::StatusBar));
        assert!(presence.is_present(TestRung::Palette));

        assert_eq!(
            presence.present_rungs().collect::<Vec<_>>(),
            vec![TestRung::Editor, TestRung::StatusBar, TestRung::Palette]
        );
    }

    #[test]
    fn compose_frame_visits_only_present_rungs_in_z_order() {
        let presence = FramePresence::<TestRung>::from_fn(|r| r != TestRung::Palette);

        let mut painted = Vec::new();
        let visited = compose_frame(&presence, |r| painted.push(r));

        let expected = vec![TestRung::Editor, TestRung::BottomPanel, TestRung::StatusBar];
        assert_eq!(painted, expected);
        assert_eq!(visited, expected);
    }

    #[test]
    fn check_frame_order_accepts_canonical_and_gapped_sequences() {
        // Exact canonical order.
        assert!(check_frame_order(&[
            TestRung::Editor,
            TestRung::BottomPanel,
            TestRung::StatusBar,
            TestRung::Palette,
        ])
        .is_ok());

        // A rung absent this frame just leaves a gap — still fine.
        assert!(check_frame_order(&[TestRung::Editor, TestRung::Palette]).is_ok());

        // Repeated visits to the same rung don't violate order.
        assert!(
            check_frame_order(&[TestRung::Editor, TestRung::Editor, TestRung::StatusBar]).is_ok()
        );

        // Empty and single-element sequences are trivially ordered.
        assert!(check_frame_order::<TestRung>(&[]).is_ok());
        assert!(check_frame_order(&[TestRung::Palette]).is_ok());
    }

    #[test]
    fn check_frame_order_rejects_out_of_order_visits() {
        // This is the vimcode#587/#592-shaped bug: a hit-test walk
        // (or a paint routine mid-migration to `compose_frame`) that
        // visits the palette before the editor, when `z_order()` says
        // the palette is on top.
        let err = check_frame_order(&[TestRung::Palette, TestRung::Editor]).unwrap_err();
        assert_eq!(
            err,
            FrameOrderViolation {
                before: TestRung::Palette,
                after: TestRung::Editor,
            }
        );
    }

    #[test]
    fn compose_frame_output_always_satisfies_check_frame_order() {
        // By construction: compose_frame walks z_order() directly, so
        // whatever it visits must already be in-order. This is the
        // structural half of the #774 guarantee — the assertion in
        // `check_frame_order` is the guard for code paths that don't
        // go through `compose_frame`.
        let presence = FramePresence::<TestRung>::from_fn(|r| r != TestRung::StatusBar);
        let visited = compose_frame(&presence, |_| {});
        assert!(check_frame_order(&visited).is_ok());
    }
}