teksilo-core 0.13.1

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

use super::*;

impl WidgetTree {
    /// Process dirty state bindings: mark bound widgets for repaint, relayout,
    /// or rebuild. Called automatically at the start of layout().
    pub(super) fn process_state_changes(&mut self, ops: &mut dyn crate::window::WindowOps) {
        // Refresh the node-resident `effective_enabled_signal`s FIRST, so a
        // widget bound to one is dirty-marked in time for the binding flush
        // immediately below to drain it in this same pass, rather than a frame
        // late. This is also where a signal seeded during `build()` — when the
        // widget's parent was not yet wired, so the seed could only see its own
        // `enabled` prop — is corrected against the now-complete tree.
        self.flush_effective_enabled_signals();

        // One unified flush: both visual buckets and the a11y flag
        // are drained from the same walk, so a signal bound at both
        // a visual level and `AccessibilityOnly` (e.g. a Button's
        // `label` re-registers the same Signal at RepaintOnly
        // *and* AccessibilityOnly) flips both. Two separate flushes
        // would each advance this registry's last-seen generation for
        // that source, so the second would find nothing to report.
        let (dirty_widgets, a11y_binding_dirty) = self.binding_registry.flush_all_dirty();
        for (id, level) in &dirty_widgets {
            match level {
                crate::binding::BindingLevel::RepaintOnly => {
                    self.arena.mark_needs_paint(*id);
                }
                crate::binding::BindingLevel::SubtreeRepaint => {
                    // Used by `enabled_when` so the leaves in the
                    // disabled subtree re-resolve their role colors
                    // via the paint walker's `effective_enabled`.
                    // No layout work — geometry is unchanged.
                    self.arena.mark_subtree_needs_paint(*id);
                }
                crate::binding::BindingLevel::Relayout => {
                    self.arena.mark_needs_layout(*id);
                    self.arena.mark_ancestors_need_layout(*id);
                }
                crate::binding::BindingLevel::Rebuild => {
                    self.arena.mark_needs_rebuild(*id);
                    self.arena.mark_ancestors_need_layout(*id);
                }
                crate::binding::BindingLevel::AccessibilityOnly => {
                    // Drained into the boolean below — never appears in
                    // the visual map, but kept in the match so a future
                    // variant addition is a compile-time reminder.
                }
            }
        }

        // Orthogonal to the visual dirty pass: if any signal bound at
        // `BindingLevel::AccessibilityOnly` fired, flip the tree-wide
        // `a11y_dirty` flag so the next `sync_accessibility` rebuilds
        // the AccessKit tree. Decoupled from layout / paint so a text
        // edit that changes no visual geometry still reaches screen
        // readers within one frame.
        if a11y_binding_dirty {
            self.a11y_dirty = true;
        }

        // Rebuild data-driven widgets whose data model changed.
        self.process_pending_rebuilds(&mut *ops);

        let mut to_dormant = Vec::new();
        let mut to_activate = Vec::new();
        for (id, is_active, should_be_visible) in self.arena.visibility_checks_iter() {
            if is_active && !should_be_visible {
                to_dormant.push(id);
            } else if !is_active && should_be_visible {
                // Only wake a `visible_when(true)` node whose parent is active.
                // A gated node inside a dormant ancestor (e.g. a row in a
                // closed popover / overflow menu) must NOT escape that
                // ancestor's dormancy and render on its own. When the ancestor
                // is later activated, `arena.activate` wakes this node via the
                // cascade (its gate is true). The dormancy invariant — an
                // active node has an active parent — makes the immediate-parent
                // check sufficient.
                let parent_active = self
                    .arena
                    .parent(id)
                    .map(|p| self.arena.is_active(p))
                    .unwrap_or(true);
                if parent_active {
                    to_activate.push(id);
                }
            }
        }
        // The accessibility walk skips dormant nodes, so any
        // active↔dormant transition changes the AccessKit tree shape
        // and must dirty the cached snapshot. Other Relayout-causing
        // signal flips (a Switcher visibility binding that doesn't
        // straddle activation, an opacity change) do not — the
        // unconditional `a11y_dirty = true` was removed from `layout()`
        // and is now set only by events that actually change the AT tree.
        //
        // A *resize* is one of them: since a label carries its text one
        // run per visual line, re-wrapping it at a new width produces a
        // different set of runs, not the same set somewhere else. A pure
        // translation is absorbed by `sync_accessibility` instead, which
        // re-places the cached nodes without walking.
        if !to_dormant.is_empty() || !to_activate.is_empty() {
            self.a11y_dirty = true;
        }
        for id in to_dormant {
            // Through the tree-level door, so a pointer working inside a
            // `visible_when` branch that just flipped false is told its
            // interaction is over rather than left holding a widget the
            // dispatcher will no longer reach.
            self.park_subtree_with_ops(id, &mut *ops);
        }
        for id in to_activate {
            self.arena.activate(id);
        }
        // Fire activation_signal observers (e.g. a WebView's set_visible
        // bridge) after the whole visibility pass has committed — not from
        // inside the set_dormant/activate recursion above.
        self.flush_activation_signals();

        // Reclaim binding groups nothing points at any more. Deliberately
        // last: `unregister_for_widget` leaves emptied groups in place so
        // that a rebuild — which is unregister-then-re-register — keeps
        // the group's `last_seen` ledger and cannot swallow a write its
        // own `build()` made before re-binding. By here every rebuild in
        // this pass has re-registered, so anything still empty belongs to
        // a widget that is genuinely gone.
        self.binding_registry.reclaim_empty_groups();
    }

    /// Dismiss any active overlay whose content widget is no longer
    /// alive in the arena. An overlay's owner can be torn down
    /// out-of-band: a data-driven rebuild destroys the widget that
    /// showed it (clicking "mark all read" inside a notification popover
    /// rebuilds the bell that owns the overlay; closing a document tears
    /// down a still-open inline popover). The content then disappears
    /// visually, but the overlay ENTRY survives in the manager and keeps
    /// intercepting clicks (the click-outside scrim) until the user
    /// clicks elsewhere. This GC removes such orphans immediately (no
    /// fade — the content is already gone). A normally-open overlay's
    /// content stays active (gated `true`), so it is never touched.
    pub(super) fn gc_orphaned_overlays(&mut self) {
        let orphaned: Vec<crate::overlay::OverlayId> = self
            .overlay_manager
            .active_ids()
            .into_iter()
            .filter(|&id| {
                self.overlay_manager
                    .overlay(id)
                    .map(|o| !self.arena.is_active(o.content_id))
                    .unwrap_or(false)
            })
            .collect();
        if orphaned.is_empty() {
            return;
        }
        for id in orphaned {
            // The content widget is already destroyed, so this is bookkeeping
            // rather than anything the user did.
            self.overlay_manager
                .dismiss_immediate(id, crate::overlay::DismissReason::Programmatic);
        }
        // This is one of the two dismissal paths that does NOT park its
        // content — the content is already gone — so it never reaches
        // `dormant_dismissed_content`, where the dismissal callbacks are
        // normally run. Draining here rather than leaving it to a later pass
        // is what keeps an anchor's "is my overlay up?" state honest: the
        // touch-selection handles re-raise on the next hold only because this
        // tells the field its previous layer went away.
        //
        // `NoopWindowOps` because a GC runs from the layout pass, outside any
        // dispatch — the same reason `dismiss_overlay` uses one.
        let mut noop = crate::window::NoopWindowOps;
        self.run_pending_dismiss_callbacks(&mut noop);
    }

    /// Every widget holding live interaction state a park would destroy:
    /// the focused node, each live pointer's captor, and the source of an
    /// in-flight drag.
    ///
    /// Handed to the layout pass as `LayoutExtras::interaction_anchors` so a
    /// container deciding what to keep can protect what the user is in the
    /// middle of. Almost always empty or a single id, so the `Vec` is one
    /// small allocation per pass on a tree that is being interacted with.
    fn collect_interaction_anchors(&self) -> Vec<WidgetId> {
        let mut out: Vec<WidgetId> = Vec::new();
        let push = |id: WidgetId, out: &mut Vec<WidgetId>| {
            if !out.contains(&id) {
                out.push(id);
            }
        };
        if let Some(id) = self.focused {
            push(id, &mut out);
        }
        for entry in self.pointers.iter() {
            if let Some(id) = entry.captured_by {
                push(id, &mut out);
            }
        }
        if let Some(id) = self.active_drag.as_ref().and_then(|d| d.source_widget) {
            push(id, &mut out);
        }
        out
    }

    /// Re-ask every `culls_children` parent whose decision the user's own
    /// position is an input to, when that position has changed since the last
    /// walk.
    ///
    /// A culling parent decides which of its children exist, and the contract
    /// says it must keep the one the user is in the middle of — it reads the
    /// anchors through `LayoutContext::for_each_interaction_ancestor`. But it
    /// is asked *during layout*, and the idle early-return below skips the
    /// walk whenever nothing needs laying out. Focus moving from one card to
    /// another moves nothing and resizes nothing, so without this the parent
    /// keeps answering with the anchor set from whenever the camera last
    /// moved: it would go on pinning the card the user has left, and — worse
    /// for anything that publishes a narrower set than it keeps alive, as
    /// `SceneView` does — would not pin the card the user has just arrived in.
    ///
    /// Scoped so that a tree with no culling container pays nothing but a
    /// parent-chain walk per changed anchor, and forces no pass at all. Anchors
    /// are almost always empty or a single id.
    fn invalidate_culls_for_moved_interaction(&mut self) {
        let anchors = self.collect_interaction_anchors();
        if anchors == self.last_interaction_anchors {
            return;
        }
        // Both directions: an anchor that arrived needs its ancestors to start
        // pinning it, one that left needs them to stop.
        let mut moved: Vec<WidgetId> = anchors
            .iter()
            .filter(|id| !self.last_interaction_anchors.contains(id))
            .copied()
            .collect();
        moved.extend(
            self.last_interaction_anchors
                .iter()
                .filter(|id| !anchors.contains(id))
                .copied(),
        );
        self.last_interaction_anchors = anchors;
        for id in moved {
            // From the parent up: the anchor itself culling its own children
            // is not affected by being an anchor.
            let mut current = self.arena.parent(id);
            while let Some(curr) = current {
                if self
                    .arena
                    .get(curr)
                    .is_some_and(|node| node.widget.culls_children())
                {
                    self.arena.mark_needs_layout(curr);
                    // A culling parent may publish a narrower accessibility
                    // set than it keeps alive, and pinning an anchor into that
                    // set widens it without parking or waking anything — so
                    // the park/wake invalidation below cannot see it. Without
                    // this, `sync_accessibility` serves a cached tree that
                    // omits the newly-pinned node and names an ancestor as the
                    // focus. `WidgetTree::focus` happens to set the same flag
                    // for its own reasons, but whichever sync runs first
                    // consumes it, and that sync precedes this pass.
                    self.a11y_dirty = true;
                }
                current = self.arena.parent(curr);
            }
        }
    }

    /// Drain any widgets flagged `needs_rebuild` that are currently
    /// active + have built children. Called from
    /// `process_state_changes` after dirty bindings have been
    /// flushed, and again after overlay / tooltip activation so that
    /// widgets transitioning from dormant → active in the same
    /// layout pass get rebuilt *this* frame rather than the next.
    pub(super) fn process_pending_rebuilds(&mut self, ops: &mut dyn crate::window::WindowOps) {
        // Defer *selected* rebuilds while a pointer capture is held:
        // from `PointerDown` (which stores the press position in the
        // captured widget's arena) until `PointerUp`. Rebuilding the
        // captured widget, or any of its ancestors, would destroy that
        // arena and lose the press state — the recognizer would never
        // fire.
        //
        // The window really does last the whole gesture, NOT just up to
        // `DragStarted`: a gesture drag auto-captures on `DragStarted`
        // (`gesture_dispatch_impl`) and holds until `DragEnded`, and the
        // only thing that lifts this filter is `active_drag`, which is
        // the drag-and-DROP session set by `start_drag` — never a
        // scrollbar thumb. So a widget holding a live gesture must not
        // be a descendant of anything that rebuilds on data or scroll
        // changes, or that rebuild is silently dropped until release.
        //
        // Rebuilds targeting widgets *outside* the captured widget's
        // ancestor chain are safe: destroying sibling subtrees leaves
        // the captured widget intact, so ongoing drags keep routing
        // correctly. That is exactly why all five virtualized views
        // (`ListView`, `TreeView`, `TableView`, `TreeTableView`,
        // `GridView`) hoist their rows into a body pane that is a
        // *sibling* of their scrollbar rather than realizing rows on
        // the view root — see `common::thumb_drag_test` in
        // `teksilo-widgets`, which asserts it for each of them.
        //
        // Once `active_drag` is set, the framework routes PointerMove /
        // PointerUp via `handle_drag_move` / `handle_drag_drop` keyed
        // on the `DragSession`, not on the captured widget's arena —
        // so a mid-drag rebuild is safe regardless of topology. Post-
        // rebuild, `revalidate_interaction_state` clears a now-stale
        // `pointer_captured_by`; subsequent events hit-test normally.
        let to_rebuild_all = self.arena.collect_needs_rebuild();
        if to_rebuild_all.is_empty() {
            self.revalidate_interaction_state(&mut *ops);
            return;
        }
        let captured_ancestors: Option<Vec<WidgetId>> = if self.active_drag.is_none() {
            // Every captured widget, not just the primary pointer's: two
            // contacts can hold two captures, and rebuilding either one's
            // ancestors mid-gesture is what this guard exists to prevent.
            let captors: Vec<WidgetId> = self
                .pointers
                .iter()
                .filter_map(|entry| entry.captured_by)
                .collect();
            (!captors.is_empty()).then(|| {
                let mut ids = Vec::new();
                for cap in captors {
                    let mut cur = Some(cap);
                    while let Some(id) = cur {
                        if !ids.contains(&id) {
                            ids.push(id);
                        }
                        cur = self.arena.parent(id);
                    }
                }
                ids
            })
        } else {
            None
        };
        let to_rebuild: Vec<WidgetId> = match &captured_ancestors {
            Some(chain) => to_rebuild_all
                .into_iter()
                .filter(|id| !chain.contains(id))
                .collect(),
            None => to_rebuild_all,
        };
        if to_rebuild.is_empty() {
            self.revalidate_interaction_state(&mut *ops);
            return;
        }
        // Does focus live inside a subtree we are about to rebuild? Its children
        // are about to be destroyed and re-allocated with fresh ids, taking the
        // focused node with them — and once that has happened there is no way
        // back from the dead id to the subtree it belonged to. Work it out now.
        let focus_owner: Option<WidgetId> = self.focused.and_then(|focused| {
            let depth = |id: WidgetId| -> usize {
                let mut d = 0;
                let mut cur = id;
                while let Some(parent) = self.arena.parent(cur) {
                    d += 1;
                    cur = parent;
                }
                d
            };
            // Every root containing `focused` sits on its ancestor chain, so the
            // candidates are totally ordered by depth. Take the OUTERMOST: it is
            // the only one sure to survive, since a rebuild destroys its children
            // — an inner rebuild root nested inside an outer one is torn down by
            // the outer's rebuild, and its id would be dead by restore time.
            to_rebuild
                .iter()
                .copied()
                .filter(|&root| self.is_descendant_of(focused, root))
                .min_by_key(|&root| depth(root))
        });

        for widget_id in to_rebuild {
            self.rebuild_single_widget(widget_id);
        }
        // A rebuild destroys old child subtrees and allocates fresh
        // WidgetIds, so the AccessKit tree shape changed — dirty the cached
        // snapshot so the next `sync_accessibility` re-walks. This is the one
        // place every `BindingLevel::Rebuild` consumer converges (data-view
        // model updates via the binding registry AND `with_widget_mut(Rebuild)`
        // via `apply_tree_mutations`, both draining the same `needs_rebuild`
        // arena flag) — without this, an ordinary `ListModel::push()` leaves
        // screen readers on a stale tree indefinitely.
        self.a11y_dirty = true;
        // Rebuild destroys old child subtrees and allocates fresh WidgetIds;
        // drop any focus/hover state whose target is no longer valid so we
        // don't dispatch to dead widgets on the next event.
        self.revalidate_interaction_state(&mut *ops);
        // ...but "no longer valid" must not mean "gone". If focus lived in the
        // subtree we just rebuilt, the drop above kicked the user clean out of
        // the widget they were in: a popover that re-scans its content when it
        // opens throws away the row the popover itself had just focused, and the
        // menu comes up with nothing focused — no arrow keys, no Enter. Put focus
        // back inside that subtree, at the end of the layout pass (the fresh
        // children have no bounds yet, and the focus-driven scroll-into-view
        // needs them). A rebuild that never held focus, or one whose focused node
        // survived it (the rebuild root itself is not destroyed), records nothing.
        if self.focused.is_none()
            && let Some(root) = focus_owner
        {
            self.pending_focus_restore = Some(root);
        }
        // A rebuild's `build()` may arm new animations (looping or
        // one-shot) by calling `signal.animate_to(...)` /
        // `animate_looping(...)` — these set `pending` on the signal
        // but don't enter the scheduler until `process_pending_animations`
        // runs again. The early-frame `process_pending_animations`
        // (`layout_impl::layout_with_ops`) already ran *before* this
        // rebuild, so without this second drain the animation would
        // wait for the next frame; if the rebuild also cancelled
        // existing scheduler entries (`cancel_by_widget` is called by
        // `rebuild_single_widget`), the scheduler ends up empty, no
        // frame deadline is set, and the freshly-armed animation
        // *never* gets picked up — the user sees animations freeze
        // after any state-driven rebuild that re-arms them
        // (e.g. SceneView's drag-end rebuild re-arming PulsingDot
        // loopers via `register_bindings`).
        self.process_pending_animations();
    }

    /// Run the layout pass with the given size proposal, using
    /// [`NoopWindowOps`](crate::window::NoopWindowOps). Handlers
    /// triggered from drag_tick / tooltip activation / etc cannot
    /// call `ctx.open_window(...)` from this path.
    ///
    /// `teksilo-app` calls [`layout_with_ops`](Self::layout_with_ops)
    /// with a real sink so those handlers can open windows.
    pub fn layout(&mut self, proposal: SizeProposal) {
        let mut noop = crate::window::NoopWindowOps;
        self.layout_with_ops(proposal, &mut noop);
    }

    /// Measure the intrinsic size of the primary (non-overlay) content root(s)
    /// at `proposal` — e.g. `{ width: Some(w), height: None }` for the natural
    /// height at a fixed width. Mirrors the overlay intrinsic pass below: it
    /// calls the root's `layout_response` *directly* — NOT the
    /// activation-ignoring `WidgetArena::measure_intrinsic` — so a
    /// `visible_when(false)` / parked-`Switcher` descendant is excluded exactly
    /// as the real layout excludes it. A size-to-content window is therefore
    /// sized to what is actually shown. Computes sizes only (never writes
    /// bounds), so it is safe to call right after a layout pass.
    ///
    /// Drives size-to-content windows (see
    /// [`WindowConfig::size_to_content`](crate::window::WindowConfig::size_to_content)):
    /// the native-window path has no in-tree overlay to size to content, so
    /// `teksilo-app` measures the root here and resizes the OS window to fit.
    /// Returns `None` if there is no active primary root; with more than one
    /// active primary root the per-axis maximum is returned (size-to-content is
    /// intended for single-primary-root windows).
    pub fn measure_root_intrinsic(&self, proposal: SizeProposal) -> Option<teksilo_canvas::Size> {
        let overlay_content_ids = self.overlay_manager.active_content_ids();
        let base_theme = self.effective_theme.clone();
        let mut result: Option<teksilo_canvas::Size> = None;
        for root_id in self.arena.roots() {
            if overlay_content_ids.contains(&root_id) || !self.arena.is_active(root_id) {
                continue;
            }
            let resolved_theme = self.arena.resolve_theme(root_id, &base_theme);
            let extras = crate::widget::LayoutExtras {
                focused: self.focused,
                // A measurement, not a pass: nothing is parked off the back of
                // it, so there is nothing for an anchor to protect.
                interaction_anchors: &[],
                shortcut_registry: Some(&self.shortcut_registry),
                overlay_manager: Some(&self.overlay_manager),
            };
            let ctx = LayoutContext {
                theme: &resolved_theme,
                layout_direction: self.layout_direction,
                scale_factor: self.device_scale_factor,
                text_scale: self.effective_text_scale,
                text_backend: self.text_backend.as_ref(),
                arena: Some(&self.arena),
                extras: Some(extras),
                stack_main_axis: None,
            };
            let Some(node) = self.arena.get(root_id) else {
                continue;
            };
            // Direct `layout_response` (activation-respecting), like the overlay
            // pass — dormant descendants fall out via `child_size` returning
            // `None`, so we measure only what is actually shown.
            let size = node.widget.layout_response(proposal, &ctx).size;
            result = Some(match result {
                Some(acc) => teksilo_canvas::Size::new(
                    acc.width.max(size.width),
                    acc.height.max(size.height),
                ),
                None => size,
            });
        }
        result
    }

    /// Run the layout pass with the given size proposal, threading
    /// the app's [`WindowOps`](crate::window::WindowOps) sink
    /// through to drag_tick / tooltip / delayed-overlay handlers.
    pub fn layout_with_ops(
        &mut self,
        proposal: SizeProposal,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        self.process_pending_animations();

        let now = std::time::Instant::now();
        // Deadline-driven wake-up: if a widget requested a future
        // frame via `wake_at_handle()` and that deadline is now past,
        // arm the frame tick so its effect runs on this layout pass.
        // Used by the rich text editor's caret blink to avoid
        // keeping winit in Poll mode.
        if let Some(deadline) = self.pending_wake_at.get()
            && deadline <= now
        {
            self.pending_wake_at.set(None);
            self.frame_tick_requested.set(true);
        }
        self.advance_frame_tick(now);
        // Ticked on the same clock the animations were *promoted* against
        // (`process_pending_animations` immediately above reads it too). While
        // the tree runs on real time that is `now`; while an automation
        // operation has time taken over it is `sim_clock`, and ticking at
        // `Instant::now()` there would hand every animation an elapsed time of
        // the tree's whole wall-clock age and complete it on its first layout
        // pass. The operation gives the clock back when it ends, rebasing the
        // scheduler as it goes, so this reads the wall clock again from the
        // next frame on — see `WidgetTree::resume_real_time`.
        let animation_now = self.animation_clock();
        self.animation_scheduler
            .tick(animation_now, &self.arena, self.paint_epoch);

        // Fire on_drag_tick on the current drop target, if any. Runs once
        // per layout pass so widgets can implement per-frame behaviours
        // (viewport-edge auto-scroll, spring-loaded folders) without
        // depending on pointer events — crucial when the user holds the
        // cursor still at the edge or over a collapsed branch.
        self.process_drag_tick(&mut *ops);

        self.process_state_changes(&mut *ops);
        // A drag owns the pointer. `handle_pointer_move` is short-circuited for
        // the duration, so a dwell armed just before the drag started would sit
        // frozen at its hover origin and then mature here — popping a tooltip
        // over the drag. Keep the timers cleared instead of letting them ripen.
        if self.active_drag.is_some() {
            self.tooltip_cancel_pending_dwell();
        }
        self.process_tooltips_real();
        self.process_delayed_overlays_real(&mut *ops);
        self.process_pointer_leave_overlays_real(&mut *ops);
        self.process_auto_dismiss_overlays_real(&mut *ops);
        self.process_overlay_fade_dismissals_real(&mut *ops);
        // The show paths above may arm a fade animation via
        // `attach_overlay_fade` (plain tooltips, delayed overlays).
        // That sets `pending` on the opacity signal but does NOT
        // register the animation with the scheduler — registration
        // happens via `process_pending_animations`, which already ran
        // earlier in this layout pass. Without a second drain here,
        // the fade only enters the scheduler on the *next* layout
        // pass, and for surfaces with no further wake source (plain
        // tooltips, no dwell timer) `next_deadline` returns `None`
        // and the event loop sleeps with the fade stuck at opacity 0
        // — the tooltip is "shown" but invisible until an unrelated
        // input event forces another layout pass.
        self.process_pending_animations();
        // Overlay / tooltip activation may have flipped widgets from
        // dormant → active; if any of those had `needs_rebuild`
        // pending (e.g. a shortcut rebind happened while the tooltip
        // was hidden), drain them now so the freshly-visible surface
        // shows fresh content in the *same* layout pass rather than
        // waiting for another paint-triggering event.
        self.process_pending_rebuilds(&mut *ops);

        // Now that any data-driven rebuilds have torn down their old
        // subtrees, drop any overlay whose content was destroyed out-of-
        // band (e.g. clicking "mark all read" inside a notification
        // popover rebuilds the bell that owns it). Without this the
        // overlay lingers as an invisible click-blocker. Runs before the
        // early-return so it takes effect even on otherwise-idle passes.
        self.gc_orphaned_overlays();

        self.arena.refresh_roots();

        // Before the idle early-return, because this is precisely the case it
        // would swallow: the user moved and nothing else did.
        self.invalidate_culls_for_moved_interaction();

        let proposal_changed = self.last_proposal != proposal;
        self.last_proposal = proposal;

        if !proposal_changed && !self.arena.any_needs_layout() {
            return;
        }

        // Per-pass layout memoization: a widget's `layout_response` is a pure
        // function of (state, proposal) within a pass, so memoizing across the
        // main-then-cross queries that height-for-width negotiation issues keeps
        // the pass O(n). Cleared here — once, dominating both the main-tree and
        // overlay root recursions below — because geometry may change between
        // passes. See `WidgetArena::cached_layout_response`.
        self.arena.clear_layout_cache();

        // `effective_theme` carries the user/OS text-scale multiplier baked into
        // its typography, so every text widget measures at the scaled size.
        let base_theme = self.effective_theme.clone();

        let overlay_content_ids = self.overlay_manager.active_content_ids();
        let roots: Vec<WidgetId> = self.arena.roots();
        let focused = self.focused;
        // Everything a park would take away from the user, gathered once so a
        // culling container can ask
        // `LayoutContext::for_each_interaction_ancestor` without the tree.
        // Empty on an idle tree.
        let interaction_anchors = self.collect_interaction_anchors();
        // What the `culls_children` parents decided about their children
        // during this walk — parked and woken alike. Settled after it, because
        // parking goes through the tree-level door and both halves change the
        // AccessKit tree.
        let mut culled = CullTransitions::default();
        for root_id in roots {
            if overlay_content_ids.contains(&root_id) {
                continue;
            }
            let extras = crate::widget::LayoutExtras {
                focused,
                interaction_anchors: &interaction_anchors,
                shortcut_registry: Some(&self.shortcut_registry),
                overlay_manager: Some(&self.overlay_manager),
            };
            layout_widget_recursive(
                &mut self.arena,
                root_id,
                Rect::from_origin_size(Point::ZERO, proposal.resolve(0.0, 0.0)),
                proposal,
                &base_theme,
                self.layout_direction,
                self.device_scale_factor,
                self.effective_text_scale,
                self.text_backend.as_ref(),
                Some(extras),
                &mut culled,
            );
        }

        let anchor_bounds = |id: WidgetId| -> Option<Rect> {
            self.arena.is_active(id).then(|| self.arena.bounds(id))
        };
        // The window, less the platform safe area, less whatever is covering
        // it. Both are `ZERO`/`None` unless something supplied them, so a
        // desktop frame produces exactly the bare `(width, height)` this used
        // to pass.
        let viewport = self.overlay_viewport_for(teksilo_canvas::Size::new(
            proposal.width.unwrap_or(800.0),
            proposal.height.unwrap_or(600.0),
        ));
        self.overlay_manager
            .position_overlays(anchor_bounds, viewport, self.layout_direction);
        for content_id in &overlay_content_ids {
            if !self.arena.is_active(*content_id) {
                continue;
            }
            let overlay_id = self.overlay_manager.find_by_content(*content_id);
            let intrinsic = {
                let resolved_theme = self.arena.resolve_theme(*content_id, &base_theme);
                let extras = crate::widget::LayoutExtras {
                    focused: self.focused,
                    interaction_anchors: &interaction_anchors,
                    shortcut_registry: Some(&self.shortcut_registry),
                    overlay_manager: Some(&self.overlay_manager),
                };
                let ctx = LayoutContext {
                    theme: &resolved_theme,
                    layout_direction: self.layout_direction,
                    scale_factor: self.device_scale_factor,
                    text_scale: self.effective_text_scale,
                    text_backend: self.text_backend.as_ref(),
                    arena: Some(&self.arena),
                    extras: Some(extras),
                    stack_main_axis: None,
                };
                let node = self
                    .arena
                    .get(*content_id)
                    .expect("content_id from active arena children");
                node.widget
                    .layout_response(
                        SizeProposal {
                            width: None,
                            height: None,
                        },
                        &ctx,
                    )
                    .size
            };
            if let Some(overlay_id) = overlay_id {
                self.overlay_manager
                    .set_content_bounds(overlay_id, intrinsic);
                let anchor_bounds = |id: WidgetId| -> Option<Rect> {
                    self.arena.is_active(id).then(|| self.arena.bounds(id))
                };
                self.overlay_manager.position_overlays(
                    anchor_bounds,
                    viewport,
                    self.layout_direction,
                );
            }
            let overlay_bounds = overlay_id
                .and_then(|overlay_id| {
                    self.overlay_manager
                        .stack
                        .iter()
                        .find(|overlay| overlay.id == overlay_id)
                        .map(|overlay| overlay.bounds)
                })
                .unwrap_or(Rect::ZERO);
            // Use the positioned overlay_bounds for layout, not the intrinsic
            // size. For `Below` / `BelowPreferred` (and any other placement
            // that inflates the overlay rect beyond the content's intrinsic
            // size to match an anchor, e.g. a combo-box dropdown that must be
            // at least as wide as its trigger), this lets the content widget
            // actually fill the overlay rather than sitting as a narrow
            // strip inside it. It carries the placements that *shrink* the
            // rect just as well — `Above`/`BelowPreferred` to the room they
            // found, `Centered`/`BottomCenter`/`ViewportCorner` to the usable
            // area, `FullViewport` to the whole window — so the content is
            // laid out at the rectangle it was actually given, whichever
            // placement decided it.
            let content_proposal = SizeProposal::exact(overlay_bounds.width, overlay_bounds.height);
            let extras = crate::widget::LayoutExtras {
                focused: self.focused,
                interaction_anchors: &interaction_anchors,
                shortcut_registry: Some(&self.shortcut_registry),
                overlay_manager: Some(&self.overlay_manager),
            };
            layout_widget_recursive(
                &mut self.arena,
                *content_id,
                overlay_bounds,
                content_proposal,
                &base_theme,
                self.layout_direction,
                self.device_scale_factor,
                self.effective_text_scale,
                self.text_backend.as_ref(),
                Some(extras),
                &mut culled,
            );
        }

        // ── Settle what a culling parent decided ──────────────────────
        // A widget that culls its children decides during layout which of them
        // exist, and it can only decide once it knows its own bounds and — for
        // a scene — the camera it is looking through. Waking has already
        // happened inline, so a child brought back was laid out this pass;
        // parking is here because it has to go through the tree-level door,
        // which tells any pointer working inside the subtree that its
        // interaction is over rather than leaving it holding a widget the
        // dispatcher will no longer reach.
        //
        // Both halves land here, and neither is the special case. The
        // accessibility walk skips dormant nodes, so an active↔dormant
        // transition in EITHER direction changes the AT tree's shape; and
        // `activation_signal` is the hook a native subview (a `WebView`'s
        // `set_visible` bridge) hangs its own visibility on, so a queued
        // `true` that nothing drains is a subview that never comes back. This
        // is the same rule the `visible_when` sweep at the top of
        // `process_state_changes` applies to `to_dormant` / `to_activate`;
        // writing it for parking alone made waking a silent no-op that the
        // usual probe cannot see, because a card waking *into* the viewport
        // resizes from `Size::ZERO` and a resize dirties the tree on its own.
        // A card that wakes and stays zero-sized — which is every card in the
        // band `A11yOffScreenMode::ViewportPlusN` promises to enumerate — does
        // not.
        if !culled.is_empty() {
            self.a11y_dirty = true;
            // `revalidate_interaction_state` follows the parks immediately:
            // focus must never survive a pass pointing at a node this just
            // parked, because dispatch rejects inactive targets and a
            // keystroke into the void is worse than a focus loss the user can
            // see. A culling parent is expected to pin what the user is using
            // (see `LayoutContext::for_each_interaction_ancestor`), so this is
            // the backstop, not the plan.
            let parked = !culled.park.is_empty();
            for id in std::mem::take(&mut culled.park) {
                self.park_subtree_with_ops(id, &mut *ops);
            }
            self.flush_activation_signals();
            if parked {
                self.revalidate_interaction_state(&mut *ops);
            }
        }

        // Clear `needs_layout` for every active widget — layout just
        // ran. `needs_rebuild` is NOT cleared here: `rebuild_single_widget`
        // clears it for widgets it processes, and widgets whose rebuild
        // was deferred (captured-pointer window) must keep the flag set
        // so the next layout pass picks them up. Wiping it here caused
        // a regression where a scroll-driven ListView rebuild, deferred
        // during a scrollbar thumb drag, was silently dropped — the
        // user saw the thumb move but the list view stayed frozen.
        // Clear `needs_layout` on every active node. Mutation during
        // iter — pull the snapshot via the reusable scratch.
        self.arena.fill_active_ids(&mut self.active_ids_scratch);
        let ids = std::mem::take(&mut self.active_ids_scratch);
        for &id in &ids {
            if let Some(node) = self.arena.get_mut(id) {
                node.dirty.needs_layout = false;
            }
        }
        self.active_ids_scratch = ids;

        // Post-layout hover refresh. When a rebuild destroyed the
        // hovered widget, `revalidate_interaction_state` cleared
        // `hovered` to `None`. Now that widgets have fresh bounds
        // from this layout pass, re-hit-test at the cached pointer
        // position so the next wheel/pointer event routes to the
        // widget the cursor is actually over. Without this, a
        // virtualized list that materializes new rows under a
        // stationary cursor would see the next `Scroll` fall through
        // to `focused` and bubble to an ancestor scrollable.
        // Hover recovery is the **hover owner**'s business: re-deriving hover
        // from the primary would invent one on a touch-only device, where the
        // primary is a finger and nothing hovers at all.
        if self.hovered_id().is_none()
            && let Some(pos) = self.hover_owner_position()
        {
            let new_target = self.hit_test(pos);
            if new_target.is_some() {
                if let Some(new) = new_target {
                    // Credited to the hover owner, whose cached position is
                    // what re-derived the target — no sample raised this.
                    let enter = WidgetEvent::PointerEnter {
                        pointer: self.hover_transition_pointer(),
                    };
                    self.dispatch_to_widget(new, &enter, &mut *ops);
                    // Seed the tooltip dwell too, exactly as `handle_pointer_move`
                    // pairs these two. The rebuild replaced the anchor's tooltip
                    // entry with a fresh one whose `hover_start` is `None`, and
                    // the pointer is not going to move again — so without this the
                    // widget's tooltip is unreachable for the rest of the hover.
                    self.tooltip_pointer_enter(new);
                }
                self.set_hovered(new_target);
            }
        }

        // Post-layout focus refresh — the symmetric case to the hover refresh
        // above. A rebuild destroyed the focused widget, so
        // `revalidate_interaction_state` cleared `focused` to `None`; the
        // subtree that owned it was recorded as `pending_focus_restore`. Now
        // that its fresh children have bounds from this layout pass, land focus
        // back inside it, so a rebuild keeps focus in the subtree that had it
        // rather than dumping it out of the widget entirely.
        //
        // Deliberately conservative: only when nothing else has taken focus in
        // the meantime, only into a subtree that is still active (a rebuild that
        // also went dormant, e.g. a popover closing, must NOT drag focus back
        // into hidden content — its own dismiss path restores focus to the
        // trigger), and only if it still has somewhere to put it. Otherwise focus
        // stays `None`, exactly as before.
        if let Some(root) = self.pending_focus_restore.take()
            && self.focused.is_none()
            && self.arena.is_active(root)
            && let Some(target) = self.first_focusable_descendant(root)
        {
            self.focus_ops(target, &mut *ops);
        }

        // A widget that changed size may have re-wrapped its text, and a
        // wrapped label carries one accessibility text run per visual line
        // — a different set of runs, not the same set somewhere else. Pure
        // translations stay recorded on the arena for `sync_accessibility`
        // to absorb without walking.
        if self.arena.take_a11y_resized() {
            self.a11y_dirty = true;
        }

        // Backstop. Every dismissal path is supposed to drain its callbacks
        // itself — `dormant_dismissed_content` for the ones that park content,
        // `gc_orphaned_overlays` for the one whose content is already gone —
        // because draining *there* is what keeps the documented ordering
        // (during dismissal, before focus returns to the trigger). This exists
        // for the path nobody thought of: a parked callback that reaches the
        // end of a frame has been stranded, and running it a frame late beats
        // never. Costs a bool test when the queue is empty, which is always.
        self.run_pending_dismiss_callbacks(&mut *ops);
    }
}

/// What the `culls_children` parents in one layout walk decided about their
/// children, collected here because settling either half needs `WidgetTree`,
/// which the free function below does not have.
///
/// Both halves are recorded, not just the parks. A wake is applied inline —
/// the child has to be laid out in the same pass or a camera that jumps shows
/// a hole — but it still owes the tree the two things a park owes it: an
/// invalidated AccessKit cache and a drained `activation_signal` queue.
#[derive(Default)]
pub(super) struct CullTransitions {
    /// Children to park, applied once the walk is over so parking can go
    /// through `WidgetTree::park_subtree_with_ops`.
    park: Vec<WidgetId>,
    /// Children already woken during the walk, kept so the settle step can
    /// tell "nothing happened" from "something came back".
    woke: Vec<WidgetId>,
}

impl CullTransitions {
    /// Whether this walk changed any child's activation, either way.
    fn is_empty(&self) -> bool {
        self.park.is_empty() && self.woke.is_empty()
    }
}

/// Recursive layout pass operating on the arena directly (avoids borrow conflicts).
#[allow(clippy::too_many_arguments)]
fn layout_widget_recursive(
    arena: &mut WidgetArena,
    id: WidgetId,
    parent_bounds: Rect,
    proposal: SizeProposal,
    base_theme: &crate::styles::Theme,
    layout_direction: crate::environment::LayoutDirection,
    scale_factor: f32,
    text_scale: f32,
    text_backend: Option<&std::rc::Rc<std::cell::RefCell<dyn teksilo_canvas::TextBackend>>>,
    extras: Option<crate::widget::LayoutExtras<'_>>,
    // Every activation change a culling parent asked for during this walk.
    // Settled by the caller once the walk is over.
    culled: &mut CullTransitions,
) {
    if !arena.is_active(id) {
        return;
    }

    let resolved_theme = arena.resolve_theme(id, base_theme);

    let desired_size = {
        let ctx = LayoutContext {
            theme: &resolved_theme,
            layout_direction,
            scale_factor,
            text_scale,
            text_backend,
            arena: Some(arena),
            extras,
            stack_main_axis: None,
        };
        arena
            .cached_layout_response(id, proposal, &ctx)
            .map(|r| r.size)
            .unwrap_or(teksilo_canvas::Size::ZERO)
    };

    let bounds = Rect::new(
        parent_bounds.x,
        parent_bounds.y,
        proposal.width.unwrap_or(desired_size.width),
        proposal.height.unwrap_or(desired_size.height),
    );
    let previous = arena.get_mut(id).and_then(|node| {
        let previous = node.bounds;
        (previous != bounds).then(|| {
            node.cached_paint = None;
            node.dirty.needs_paint = true;
            node.bounds = bounds;
            previous
        })
    });
    if let Some(previous) = previous {
        arena.note_bounds_change(id, previous, bounds);
    }

    let child_ids: Vec<WidgetId> = arena.children(id).to_vec();
    // A widget that culls its children is handed the dormant ones too — it is
    // the only way it can ask for one back, having parked it. Every other
    // widget sees its active children and nothing else, exactly as before.
    let culls_children = arena
        .get(id)
        .is_some_and(|node| node.widget.culls_children());
    let mut placements: Vec<WidgetPlacement> = child_ids
        .iter()
        .copied()
        .filter_map(|child_id| {
            let active = arena.is_active(child_id);
            (active || culls_children).then_some(WidgetPlacement {
                id: child_id,
                origin: bounds.origin(),
                size: bounds.size(),
                dormant: !active,
            })
        })
        .collect();

    // `place_children` is a widget's ONLY hook that receives its final,
    // parent-assigned `bounds`, so it runs for EVERY active widget on every
    // pass — including leaves, which get an empty `placements` slice. A widget
    // whose paint depends on where the parent put it (a scene folding its
    // origin into a view transform, a text engine sizing its viewport) can then
    // read its bounds during *layout*, which is the only point early enough:
    // the render walker pushes node-level transform scopes before `paint` runs.
    {
        let ctx = LayoutContext {
            theme: &resolved_theme,
            layout_direction,
            scale_factor,
            text_scale,
            text_backend,
            arena: Some(arena),
            extras,
            stack_main_axis: None,
        };
        let node = arena.get(id).expect("widget id is active in arena");
        node.widget
            .place_children(bounds, proposal, &mut placements, &ctx);
    }

    for placement in &placements {
        if culls_children {
            // Apply the parent's decision before anything reads the child's
            // state. Waking is immediate — the child is laid out below, this
            // pass, so a camera that jumps shows no hole. Parking is recorded
            // and applied once the walk is over, because it has to go through
            // the tree-level door (`WidgetTree::park_subtree_with_ops`) to
            // tell any pointer working inside that its interaction is over.
            // Either way the child's bounds are written first, so a parked
            // card keeps the coordinate that `scroll_into_view` and
            // focus-follow read.
            let active = arena.is_active(placement.id);
            if !placement.dormant && !active {
                arena.activate(placement.id);
                // `activate` only *queues* the `(id, true)` transition; the
                // caller's settle step drains it. Recorded so that step can
                // run at all — a pass that woke a child and parked none used
                // to leave the queue and the AT cache untouched.
                culled.woke.push(placement.id);
            } else if placement.dormant && active {
                culled.park.push(placement.id);
            }
        }

        let child_bounds = Rect::from_origin_size(placement.origin, placement.size);
        let previous = arena.get_mut(placement.id).and_then(|child_node| {
            let previous = child_node.bounds;
            (previous != child_bounds).then(|| {
                child_node.cached_paint = None;
                child_node.dirty.needs_paint = true;
                child_node.bounds = child_bounds;
                previous
            })
        });
        if let Some(previous) = previous {
            arena.note_bounds_change(placement.id, previous, child_bounds);
        }

        // Gated on `culls_children`, because that is the contract: for every
        // other widget `dormant` arrives `false` and is not read back, and a
        // widget that set it anyway must not be able to take a child out of
        // the pass by writing a field it was told does nothing.
        if culls_children && placement.dormant {
            // Nothing below a parked child is laid out, painted, walked for
            // accessibility or reachable by Tab. That is the whole point.
            continue;
        }

        let child_proposal = SizeProposal::exact(placement.size.width, placement.size.height);
        let grandchild_ids: Vec<WidgetId> = arena.children(placement.id).to_vec();
        if !grandchild_ids.is_empty() {
            layout_widget_recursive(
                arena,
                placement.id,
                child_bounds,
                child_proposal,
                base_theme,
                layout_direction,
                scale_factor,
                text_scale,
                text_backend,
                extras,
                culled,
            );
        } else {
            // A childless child is never visited by the recursion above, so
            // hand it its final bounds here — with an empty `placements` slice.
            //
            // Deliberately NOT a `layout_widget_recursive` call: that would
            // re-measure the leaf against a fresh `exact` proposal (a memo miss,
            // since the parent measured it under a different proposal), adding a
            // redundant `layout_response` per leaf on every pass.
            let ctx = LayoutContext {
                theme: &resolved_theme,
                layout_direction,
                scale_factor,
                text_scale,
                text_backend,
                arena: Some(arena),
                extras,
                stack_main_axis: None,
            };
            let node = arena.get(placement.id).expect("child id is active");
            node.widget
                .place_children(child_bounds, child_proposal, &mut [], &ctx);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_widgets::{FillWidget, InsetWidget, StackWidget};
    use teksilo_canvas::Size;
    use teksilo_tokens::Color;

    /// A leaf of a fixed intrinsic size, so a `Centered` overlay has something
    /// to centre.
    #[derive(Debug)]
    struct Sized(f32, f32);

    impl Widget for Sized {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            Size::new(self.0, self.1).into()
        }
    }

    fn tree_with_centred_modal(content_height: f32) -> (WidgetTree, crate::overlay::OverlayId) {
        let mut tree = WidgetTree::new();
        let anchor = tree.add(FillWidget::new());
        let content = tree.add(Sized(200.0, content_height));
        let id = tree.show_overlay(crate::overlay::OverlayRequest {
            content_id: content,
            anchor,
            placement: crate::overlay::OverlayPlacement::Centered,
            dismiss: crate::overlay::DismissBehavior::Manual,
            layer: crate::overlay::OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        (tree, id)
    }

    /// The supply this package exists to add: with nothing covering the window
    /// and no safe area, the viewport is the whole window — byte for byte the
    /// bare `(width, height)` tuple that used to be passed.
    #[test]
    fn a_bare_window_is_usable_to_its_last_pixel() {
        let (mut tree, id) = tree_with_centred_modal(100.0);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        assert_eq!(tree.usable_viewport(), Rect::new(0.0, 0.0, 400.0, 300.0));
        let bounds = tree.overlay_content_bounds(id).expect("placed");
        assert_eq!(bounds.y, 100.0, "centred in 300: (300 - 100) / 2");
    }

    /// A soft keyboard covering the bottom band shrinks the viewport, and the
    /// modal recomputes against what is left instead of centring behind it.
    #[test]
    fn an_occluding_band_shrinks_the_viewport_and_moves_the_modal() {
        let (mut tree, id) = tree_with_centred_modal(100.0);
        // The bottom 140 of a 300-tall window: a keyboard.
        tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
        tree.layout(SizeProposal::exact(400.0, 300.0));

        assert_eq!(
            tree.usable_viewport(),
            Rect::new(0.0, 0.0, 400.0, 160.0),
            "the largest free slab is the band above the keyboard"
        );
        let bounds = tree.overlay_content_bounds(id).expect("placed");
        assert_eq!(bounds.y, 30.0, "centred in 160: (160 - 100) / 2");
        assert!(
            bounds.y + bounds.height <= 160.0,
            "and the whole modal clears the keyboard"
        );
    }

    /// When the content is taller than what is left, centring would push it off
    /// the top. It pins to the top of the usable area instead, so the first
    /// line stays reachable and the rest is scrolled to.
    #[test]
    fn a_modal_taller_than_the_usable_area_pins_to_its_top() {
        let (mut tree, id) = tree_with_centred_modal(240.0);
        tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
        tree.layout(SizeProposal::exact(400.0, 300.0));
        let bounds = tree.overlay_content_bounds(id).expect("placed");
        assert_eq!(bounds.y, 0.0, "pinned to the top of the usable band");
    }

    /// A safe area does the same for the reason a notch exists.
    #[test]
    fn a_safe_area_insets_the_viewport() {
        let (mut tree, id) = tree_with_centred_modal(100.0);
        tree.set_safe_area(teksilo_canvas::EdgeInsets {
            top: 40.0,
            bottom: 20.0,
            leading: 10.0,
            trailing: 10.0,
        });
        tree.layout(SizeProposal::exact(400.0, 300.0));
        assert_eq!(tree.usable_viewport(), Rect::new(10.0, 40.0, 380.0, 240.0));
        let bounds = tree.overlay_content_bounds(id).expect("placed");
        assert_eq!(bounds.y, 40.0 + (240.0 - 100.0) / 2.0);
    }

    /// The scrim is deliberately not inset: one that respected the safe area
    /// would leave the notch undimmed and the content behind it legible.
    #[test]
    fn the_supply_does_not_move_the_root_layout() {
        // Occlusion reaches overlay placement and nothing else. A keyboard
        // rising must not reflow the document behind it — that is a scroll, not
        // a resize, and this is where the difference is decided.
        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        tree.set_occluded_inset(Some(Rect::new(0.0, 160.0, 400.0, 140.0)));
        tree.set_safe_area(teksilo_canvas::EdgeInsets {
            top: 40.0,
            bottom: 0.0,
            leading: 0.0,
            trailing: 0.0,
        });
        tree.layout(SizeProposal::exact(400.0, 300.0));
        assert_eq!(
            tree.bounds(root),
            Rect::new(0.0, 0.0, 400.0, 300.0),
            "the root still owns the whole window"
        );
    }

    /// A pending soft-keyboard request is recorded on the tree and taken
    /// exactly once, by the app layer, after its IME reconcile.
    #[test]
    fn a_soft_keyboard_request_is_taken_once() {
        let mut tree = WidgetTree::new();
        assert_eq!(tree.take_soft_keyboard_request(), None);
        tree.request_soft_keyboard(true);
        assert_eq!(tree.take_soft_keyboard_request(), Some(true));
        assert_eq!(
            tree.take_soft_keyboard_request(),
            None,
            "a request is a one-shot; a second take must not re-ask"
        );
    }

    /// A leaf that records the bounds `place_children` hands it, and how often.
    #[derive(Debug, Clone, Default)]
    struct BoundsRecorder {
        seen: std::rc::Rc<std::cell::RefCell<Vec<Rect>>>,
    }

    impl Widget for BoundsRecorder {
        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            Size::new(
                proposal.width.unwrap_or(10.0),
                proposal.height.unwrap_or(10.0),
            )
            .into()
        }

        fn place_children(
            &self,
            bounds: Rect,
            _proposal: SizeProposal,
            children: &mut [WidgetPlacement],
            _ctx: &LayoutContext,
        ) {
            assert!(
                children.is_empty(),
                "a leaf must be handed an empty placements slice"
            );
            self.seen.borrow_mut().push(bounds);
        }
    }

    /// The invariant `SceneView` (and both text engines) depend on: a widget with
    /// NO children still gets `place_children`, carrying its final bounds.
    ///
    /// Before this was guaranteed, the walker skipped `place_children` whenever
    /// there was nothing to place, so a leaf could only discover its bounds in
    /// `paint`. That is too late for anything the renderer consumes *before*
    /// paint — a `SceneView` folds `bounds.origin` into the transform scope the
    /// walker pushes around its subtree, so a scene holding only lightweight
    /// items (hence no arena children) painted its content offset by
    /// `-bounds.origin`, an error that scaled with zoom.
    #[test]
    fn a_childless_widget_still_receives_its_bounds() {
        let mut tree = WidgetTree::new();
        let leaf = BoundsRecorder::default();
        let seen = leaf.seen.clone();

        // Nested inside an inset container, so a correct origin is non-zero and a
        // stale/zero origin cannot pass by accident.
        let leaf_id = tree.add(leaf);
        let _root = tree.add(InsetWidget::new(12.0).set_child(leaf_id));
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let bounds = seen.borrow();
        assert_eq!(
            bounds.len(),
            1,
            "the leaf must be placed exactly once per layout pass, got {bounds:?}"
        );
        assert_eq!(
            (bounds[0].x, bounds[0].y),
            (12.0, 12.0),
            "the leaf must receive its real, parent-assigned origin"
        );
        assert_eq!(
            (bounds[0].width, bounds[0].height),
            (176.0, 76.0),
            "the leaf must receive its real, parent-assigned size"
        );
    }

    /// The same guarantee at the root: a tree whose root IS a leaf.
    #[test]
    fn a_childless_root_still_receives_its_bounds() {
        let mut tree = WidgetTree::new();
        let leaf = BoundsRecorder::default();
        let seen = leaf.seen.clone();
        let _id = tree.add(leaf);
        tree.layout(SizeProposal::exact(320.0, 240.0));

        let bounds = seen.borrow();
        assert_eq!(bounds.len(), 1, "root leaf must be placed once");
        assert_eq!((bounds[0].width, bounds[0].height), (320.0, 240.0));
    }

    #[derive(Debug)]
    struct ShrinkWrapContainer {
        child: WidgetId,
        inset: f32,
    }

    impl Widget for ShrinkWrapContainer {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            let child_size = ctx
                .child_size(self.child, SizeProposal::unspecified())
                .unwrap_or(Size::ZERO);
            Size::new(
                child_size.width + self.inset * 2.0,
                child_size.height + self.inset * 2.0,
            )
            .into()
        }

        fn place_children(
            &self,
            bounds: Rect,
            _proposal: SizeProposal,
            children: &mut [WidgetPlacement],
            _ctx: &LayoutContext,
        ) {
            for child in children.iter_mut() {
                child.origin = Point::new(bounds.x + self.inset, bounds.y + self.inset);
                child.size = Size::new(
                    (bounds.width - self.inset * 2.0).max(0.0),
                    (bounds.height - self.inset * 2.0).max(0.0),
                );
            }
        }

        fn children(&self) -> Vec<WidgetId> {
            vec![self.child]
        }
    }

    // ── Per-pass layout memoization cache (Part C) ──────────────────────────

    /// A childless leaf that counts how many times `layout_response` runs and
    /// can opt out of caching. The driver does not recurse into a childless
    /// leaf's placement, so the only calls come from a parent's `child_size`
    /// queries — making the count a precise probe of the cache.
    #[derive(Debug)]
    struct CountingLeaf {
        calls: std::rc::Rc<std::cell::Cell<u32>>,
        cacheable: bool,
    }

    impl Widget for CountingLeaf {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            self.calls.set(self.calls.get() + 1);
            Size::new(50.0, 20.0).into()
        }
        fn cacheable_layout(&self) -> bool {
            self.cacheable
        }
    }

    /// Queries its single child with the *same* proposal in both
    /// `layout_response` and `place_children` — the pattern real stacks use
    /// for height-for-width. With caching the child computes once; without it,
    /// twice.
    #[derive(Debug)]
    struct DoubleQueryContainer {
        child: WidgetId,
    }

    impl Widget for DoubleQueryContainer {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            ctx.child_size(self.child, SizeProposal::exact(50.0, 20.0))
                .unwrap_or(Size::ZERO)
                .into()
        }
        fn place_children(
            &self,
            bounds: Rect,
            _proposal: SizeProposal,
            children: &mut [WidgetPlacement],
            ctx: &LayoutContext,
        ) {
            // Second query with the identical proposal.
            let _ = ctx.child_size(self.child, SizeProposal::exact(50.0, 20.0));
            for child in children.iter_mut() {
                child.origin = bounds.origin();
                child.size = bounds.size();
            }
        }
        fn children(&self) -> Vec<WidgetId> {
            vec![self.child]
        }
    }

    #[test]
    fn cache_dedupes_identical_child_queries_within_a_pass() {
        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
        let mut tree = WidgetTree::new();
        let leaf = tree.add(CountingLeaf {
            calls: calls.clone(),
            cacheable: true,
        });
        let _root = tree.add(DoubleQueryContainer { child: leaf });
        tree.layout(SizeProposal::exact(100.0, 50.0));
        // Two identical `exact(50,20)` queries (layout_response + place_children)
        // collapse to one real call; the driver does not recurse into the
        // childless leaf.
        assert_eq!(calls.get(), 1, "cacheable leaf should be computed once");
    }

    #[test]
    fn cache_opt_out_recomputes_every_query() {
        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
        let mut tree = WidgetTree::new();
        let leaf = tree.add(CountingLeaf {
            calls: calls.clone(),
            cacheable: false,
        });
        let _root = tree.add(DoubleQueryContainer { child: leaf });
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert_eq!(
            calls.get(),
            2,
            "opt-out leaf must run on every query (side effects preserved)"
        );
    }

    #[test]
    fn cache_is_cleared_between_passes() {
        let calls = std::rc::Rc::new(std::cell::Cell::new(0));
        let mut tree = WidgetTree::new();
        let leaf = tree.add(CountingLeaf {
            calls: calls.clone(),
            cacheable: true,
        });
        let _root = tree.add(DoubleQueryContainer { child: leaf });
        tree.layout(SizeProposal::exact(100.0, 50.0));
        // A second pass with a different proposal must re-run layout — proving
        // the cache is per-pass, not stale across passes (the `exact(50,20)`
        // child key is identical between passes).
        tree.layout(SizeProposal::exact(120.0, 60.0));
        assert_eq!(
            calls.get(),
            2,
            "each pass recomputes; cache cleared per pass"
        );
    }

    // ── measure_intrinsic (Primitive 2) ─────────────────────────────────────

    /// Probe: from its own `layout_response`, measures `target` two ways and
    /// stashes the results — the normal (activation-gated) query and the
    /// intrinsic (activation-ignoring) query.
    #[derive(Debug)]
    struct MeasureProbe {
        target: WidgetId,
        active_w: std::rc::Rc<std::cell::Cell<f32>>, // -1.0 == None
        intrinsic_w: std::rc::Rc<std::cell::Cell<f32>>,
    }
    impl Widget for MeasureProbe {
        fn layout_response(
            &self,
            p: SizeProposal,
            ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            // Measure intrinsic FIRST, then the normal gated query: if the
            // measure had polluted the cache, the gated query could wrongly
            // return a size for the dormant target. `exact` because FillWidget
            // fills its proposal (it has no intrinsic size of its own).
            let probe = SizeProposal::exact(120.0, 30.0);
            let intrinsic = ctx
                .measure_intrinsic(self.target, probe)
                .map(|s| s.width)
                .unwrap_or(-1.0);
            let active = ctx
                .child_size(self.target, probe)
                .map(|s| s.width)
                .unwrap_or(-1.0);
            self.intrinsic_w.set(intrinsic);
            self.active_w.set(active);
            p.resolve(0.0, 0.0).into()
        }
        fn cacheable_layout(&self) -> bool {
            false
        }
    }

    #[test]
    fn measure_intrinsic_sees_a_dormant_widget_normal_query_does_not() {
        let active = std::rc::Rc::new(std::cell::Cell::new(0.0));
        let intrinsic = std::rc::Rc::new(std::cell::Cell::new(0.0));
        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new());
        tree.set_dormant(leaf);
        let _probe = tree.add(MeasureProbe {
            target: leaf,
            active_w: active.clone(),
            intrinsic_w: intrinsic.clone(),
        });
        tree.layout(SizeProposal::exact(200.0, 50.0));

        // measure_intrinsic measures the dormant widget (FillWidget fills the
        // 120px probe)…
        assert!(
            (intrinsic.get() - 120.0).abs() < 0.01,
            "measure_intrinsic should size the dormant widget, got {}",
            intrinsic.get()
        );
        // …and the normal gated query (run AFTER) still returns None — proving
        // the measure bypassed, and did not seed, the per-pass cache.
        assert_eq!(
            active.get(),
            -1.0,
            "child_size must stay None for a dormant widget (no cache pollution)"
        );
    }

    /// A box whose height is driven by a signal and whose width echoes the
    /// proposed width (height-for-width) — models a widget (e.g. a `MessageBox`
    /// "Show details" expander) whose intrinsic height changes with content.
    /// Echoing the width lets a fixed-width intrinsic measurement be exercised.
    #[derive(Debug)]
    struct SignalBox {
        h: crate::signal::Signal<f32>,
    }
    impl Widget for SignalBox {
        fn layout_response(
            &self,
            p: SizeProposal,
            _ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            teksilo_canvas::Size::new(p.width.unwrap_or(0.0), self.h.get()).into()
        }
        fn cacheable_layout(&self) -> bool {
            false
        }
    }

    /// Sums the ACTIVE children's heights via `child_size` (which returns
    /// `None` for a dormant child, so a hidden child contributes nothing) —
    /// lets a test assert size-to-content excludes dormant subtrees.
    #[derive(Debug)]
    struct VSumBox {
        children: Vec<WidgetId>,
    }
    impl Widget for VSumBox {
        fn layout_response(
            &self,
            p: SizeProposal,
            ctx: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            let h: f32 = self
                .children
                .iter()
                .filter_map(|&c| ctx.child_size(c, p))
                .map(|s| s.height)
                .sum();
            teksilo_canvas::Size::new(p.width.unwrap_or(0.0), h).into()
        }
        fn children(&self) -> Vec<WidgetId> {
            self.children.clone()
        }
    }

    #[test]
    fn measure_root_intrinsic_honors_fixed_width_and_tracks_content() {
        let h = crate::signal::Signal::new(140.0);
        let mut tree = WidgetTree::new();
        let _root = tree.add(SignalBox { h: h.clone() });
        // Lay the root out constrained to a fixed native-modal size.
        tree.layout(SizeProposal::exact(460.0, 140.0));

        // Intrinsic measurement at a fixed width / unbounded height reports the
        // proposed width and the content's natural height — the size a
        // size-to-content window grows to, independent of the constrained pass.
        let m = tree
            .measure_root_intrinsic(SizeProposal {
                width: Some(460.0),
                height: None,
            })
            .expect("one active primary root");
        assert!(
            (m.width - 460.0).abs() < 0.01,
            "fixed width honored, got {}",
            m.width
        );
        assert!(
            (m.height - 140.0).abs() < 0.01,
            "natural height, got {}",
            m.height
        );

        // A different fixed width flows through (the proposal really is used).
        let narrow = tree
            .measure_root_intrinsic(SizeProposal {
                width: Some(300.0),
                height: None,
            })
            .expect("root active");
        assert!(
            (narrow.width - 300.0).abs() < 0.01,
            "proposal width, got {}",
            narrow.width
        );

        // Content growth (a "Show details" expander) is reflected.
        h.set(300.0);
        let grown = tree
            .measure_root_intrinsic(SizeProposal {
                width: Some(460.0),
                height: None,
            })
            .expect("root active");
        assert!(
            (grown.height - 300.0).abs() < 0.01,
            "grows with content, got {}",
            grown.height
        );
    }

    #[test]
    fn measure_root_intrinsic_excludes_dormant_content() {
        let mut tree = WidgetTree::new();
        let shown = tree.add(SignalBox {
            h: crate::signal::Signal::new(200.0),
        });
        let hidden = tree.add(SignalBox {
            h: crate::signal::Signal::new(1000.0),
        });
        tree.set_dormant(hidden);
        let _root = tree.add(VSumBox {
            children: vec![shown, hidden],
        });
        tree.layout(SizeProposal::exact(460.0, 200.0));

        // The dormant child must NOT contribute — a size-to-content window is
        // sized to what is actually shown. Regression guard for measuring via
        // `layout_response` (activation-respecting) rather than the
        // activation-ignoring `measure_intrinsic` (which would return 1200).
        let m = tree
            .measure_root_intrinsic(SizeProposal {
                width: Some(460.0),
                height: None,
            })
            .expect("one active primary root");
        assert!(
            (m.height - 200.0).abs() < 0.01,
            "dormant child must be excluded, got {}",
            m.height
        );
    }

    #[test]
    fn single_widget_fills_proposal() {
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().background(Color::RED));
        tree.layout(SizeProposal::exact(200.0, 40.0));
        let bounds = tree.bounds(widget);
        assert_eq!(bounds.width, 200.0);
        assert_eq!(bounds.height, 40.0);
    }

    #[test]
    fn stack_children_overlap() {
        let mut tree = WidgetTree::new();
        let a = tree.add(FillWidget::new());
        let b = tree.add(FillWidget::new());
        let stack = tree.add(StackWidget::new().child(a).child(b));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        let children = tree.children(stack);
        assert_eq!(children.len(), 2);
        let a_bounds = tree.bounds(children[0]);
        let b_bounds = tree.bounds(children[1]);
        assert_eq!(a_bounds.origin(), b_bounds.origin());
        assert_eq!(a_bounds.size(), b_bounds.size());
    }

    #[test]
    fn inset_widget_insets_child() {
        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new());
        let parent = tree.add(InsetWidget::new(10.0).set_child(child));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        let children = tree.children(parent);
        let child_bounds = tree.bounds(children[0]);
        assert_eq!(child_bounds.x, 10.0);
        assert_eq!(child_bounds.y, 10.0);
        assert_eq!(child_bounds.width, 80.0);
        assert_eq!(child_bounds.height, 30.0);
    }

    #[test]
    fn recursive_layout_preserves_exact_parent_placement_for_containers() {
        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new());
        let shrink = tree.add(ShrinkWrapContainer {
            child: leaf,
            inset: 8.0,
        });
        let root = tree.add(StackWidget::new().child(shrink));

        tree.layout(SizeProposal::exact(120.0, 80.0));

        assert_eq!(tree.bounds(root), Rect::new(0.0, 0.0, 120.0, 80.0));
        assert_eq!(
            tree.bounds(shrink),
            Rect::new(0.0, 0.0, 120.0, 80.0),
            "child container should keep the exact size assigned by its parent"
        );
        assert_eq!(tree.bounds(leaf), Rect::new(8.0, 8.0, 104.0, 64.0));
    }

    #[test]
    fn needs_paint_after_layout() {
        let mut tree = WidgetTree::new();
        tree.add(FillWidget::new());
        assert!(tree.needs_layout());
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert!(!tree.needs_layout());
    }

    #[test]
    fn signal_binding_marks_widget_dirty_on_layout() {
        use crate::signal::Signal;

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().background(Color::RED));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.render();

        assert!(!tree.needs_paint());

        let visible = Signal::new(true);
        visible.bind_to(
            widget,
            tree.binding_registry(),
            crate::binding::BindingLevel::RepaintOnly,
        );

        visible.set(false);
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert!(tree.needs_paint());
    }

    /// `culls_children` as a framework primitive, without a scene.
    ///
    /// The mechanism is one field and two rules: a widget that opts in is
    /// handed every child, parked ones included, and whatever it leaves in
    /// `WidgetPlacement::dormant` is applied — cleared wakes in the same pass,
    /// set parks after it.
    mod culling_containers {
        use super::*;
        use crate::signal::Signal;
        use crate::widget::{LayoutResponse, WidgetPlacement};
        use crate::widget_builder::WidgetBuilder;
        use std::cell::Cell;
        use std::rc::Rc;

        /// Parks every child whose index is set in the `park` bitmask, and
        /// reports how many children its `place_children` was handed.
        ///
        /// `park` is a `Signal` bound at `BindingLevel::Relayout` — the same
        /// level a `SceneView` binds its camera at — because that is what makes
        /// changing it run a pass at all: `layout_with_ops` returns early when
        /// the proposal is unchanged and nothing needs layout.
        #[derive(Debug)]
        struct Culler {
            kids: Vec<WidgetId>,
            park: Signal<u64>,
            seen: Rc<Cell<usize>>,
            opts_in: bool,
            /// Stop writing `dormant` at all, so what the framework pre-set
            /// there is what gets applied.
            ignore_dormant: Rc<Cell<bool>>,
            /// One per child, so "was this subtree recursed into" is
            /// observable and not merely inferred from the child's activation.
            grandkids: Rc<std::cell::RefCell<Vec<WidgetId>>>,
            /// How many times the culler has been asked to decide. The
            /// question "was the decision re-taken?" has no other witness — a
            /// re-run that reaches the same answer changes nothing else.
            passes: Rc<Cell<usize>>,
        }

        impl Culler {
            fn new(park: Signal<u64>, seen: Rc<Cell<usize>>, opts_in: bool) -> Self {
                Self {
                    kids: Vec::new(),
                    park,
                    seen,
                    opts_in,
                    ignore_dormant: Rc::new(Cell::new(false)),
                    grandkids: Rc::new(std::cell::RefCell::new(Vec::new())),
                    passes: Rc::new(Cell::new(0)),
                }
            }
        }

        impl Widget for Culler {
            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
                self.park.bind_to(
                    ctx.self_id(),
                    ctx.binding_registry(),
                    crate::binding::BindingLevel::Relayout,
                );
                // Each child has a child of its own, so "was this subtree
                // recursed into" is observable from the grandchild's bounds
                // and not only from the child's activation.
                self.kids = (0..3)
                    .map(|i| {
                        let grandkid = ctx.add(FillWidget::new().label(format!("grandkid{i}")));
                        self.grandkids.borrow_mut().push(grandkid);
                        ctx.add(StackWidget::new().child(grandkid).focusable(true))
                    })
                    .collect();
                self.kids.clone()
            }
            fn layout_response(
                &self,
                _p: SizeProposal,
                _c: &crate::widget::LayoutContext,
            ) -> LayoutResponse {
                teksilo_canvas::Size::new(100.0, 100.0).into()
            }
            fn children(&self) -> Vec<WidgetId> {
                self.kids.clone()
            }
            fn culls_children(&self) -> bool {
                self.opts_in
            }
            fn place_children(
                &self,
                bounds: Rect,
                _proposal: SizeProposal,
                children: &mut [WidgetPlacement],
                _ctx: &crate::widget::LayoutContext,
            ) {
                self.seen.set(children.len());
                self.passes.set(self.passes.get() + 1);
                let mask = self.park.get();
                for placement in children.iter_mut() {
                    let Some(i) = self.kids.iter().position(|&k| k == placement.id) else {
                        continue;
                    };
                    placement.origin = teksilo_canvas::Point::new(0.0, i as f32 * 20.0);
                    // Width follows the proposal so a *grandchild*'s size says
                    // whether the recursion reached it — a child's own size is
                    // written here, before any cull decision, and so proves
                    // nothing.
                    placement.size = teksilo_canvas::Size::new(bounds.width, 20.0);
                    if !self.ignore_dormant.get() {
                        placement.dormant = mask & (1 << i) != 0;
                    }
                }
            }
        }

        struct Rig {
            tree: WidgetTree,
            id: WidgetId,
            park: Signal<u64>,
            seen: Rc<Cell<usize>>,
            ignore_dormant: Rc<Cell<bool>>,
            grandkids: Rc<std::cell::RefCell<Vec<WidgetId>>>,
            passes: Rc<Cell<usize>>,
        }

        fn tree_with(opts_in: bool) -> Rig {
            let park = Signal::new(0u64);
            let seen = Rc::new(Cell::new(0usize));
            let culler = Culler::new(park.clone(), seen.clone(), opts_in);
            let ignore_dormant = culler.ignore_dormant.clone();
            let grandkids = culler.grandkids.clone();
            let passes = culler.passes.clone();
            let mut tree = WidgetTree::new();
            let id = tree.add(culler);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            Rig {
                tree,
                id,
                park,
                seen,
                ignore_dormant,
                grandkids,
                passes,
            }
        }

        #[test]
        fn focus_moving_re_asks_the_culling_parent_that_owns_it() {
            // A culling parent is told to keep what the user is in the middle
            // of, and it is only asked during layout — but focus moving from
            // one child to another moves nothing and resizes nothing, so the
            // idle early-return would skip the pass and leave the parent
            // answering with a stale anchor set. It would go on pinning the
            // child the user has left, and never pin the one they arrived in.
            //
            // Harmless while pinning only keeps a child *alive* — a newly
            // focused child is active by definition. Not harmless for a parent
            // that publishes a narrower set than it keeps alive, as
            // `SceneView` does: the published tree names its focused node, and
            // a focus the walk did not emit is a broken update.
            let Rig {
                mut tree,
                id,
                passes,
                ..
            } = tree_with(true);
            let kids = tree.children(id).to_vec();

            let before = passes.get();
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert_eq!(
                passes.get(),
                before,
                "precondition: a settled tree skips the pass entirely"
            );

            tree.focus(kids[0]);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert_eq!(
                passes.get(),
                before + 1,
                "focus arriving is a change to the culler's inputs"
            );

            tree.focus(kids[2]);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert_eq!(
                passes.get(),
                before + 2,
                "…and so is focus moving between two of its children"
            );

            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert_eq!(
                passes.get(),
                before + 2,
                "…while a pass with the same anchors is still skipped"
            );
        }

        #[test]
        fn focus_moving_forces_no_pass_where_nothing_culls() {
            // The scoping half. The invalidation walks up from the moved
            // anchor and marks only `culls_children` ancestors, so a tree
            // without one pays a parent-chain walk and forces no layout — the
            // cost lands on the trees that asked for the mechanism.
            let Rig {
                mut tree,
                id,
                passes,
                ..
            } = tree_with(false);
            let kids = tree.children(id).to_vec();
            let before = passes.get();

            tree.focus(kids[0]);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            tree.focus(kids[2]);
            tree.layout(SizeProposal::exact(100.0, 100.0));

            assert_eq!(
                passes.get(),
                before,
                "no culling ancestor, no reason to re-run layout"
            );
        }

        #[test]
        fn a_parked_child_leaves_the_tab_ring_and_the_at_tree_in_the_same_pass() {
            let Rig {
                mut tree, id, park, ..
            } = tree_with(true);
            let kids = tree.children(id).to_vec();
            assert_eq!(tree.tab_stops_within(id).len(), 3);
            let before = tree.accessibility_tree_snapshot().nodes.len();

            park.set(0b010);
            tree.layout(SizeProposal::exact(100.0, 100.0));

            assert!(!tree.is_active(kids[1]), "parked in the pass that asked");
            assert!(tree.is_active(kids[0]) && tree.is_active(kids[2]));
            let stops = tree.tab_stops_within(id);
            assert_eq!(stops.len(), 2, "stops = {stops:?}");
            assert!(!stops.contains(&kids[1]));
            assert_eq!(
                tree.accessibility_tree_snapshot().nodes.len(),
                before - 2,
                "the parked child AND its own child leave the AccessKit tree — \
                 parking is a subtree operation"
            );
        }

        #[test]
        fn a_parked_child_takes_its_subtree_out_of_the_layout_recursion() {
            // The activation flag alone does not prove this: a child could be
            // dormant and still have been recursed into. Watch the grandchild's
            // bounds, which only the recursion writes.
            let Rig {
                mut tree,
                park,
                grandkids,
                ..
            } = tree_with(true);
            let grandkid = grandkids.borrow()[1];
            assert_eq!(tree.bounds(grandkid).size(), Size::new(100.0, 20.0));

            park.set(0b010);
            tree.layout(SizeProposal::exact(100.0, 300.0));
            let parked_bounds = tree.bounds(grandkid);

            // Change the geometry the recursion would have written, and check
            // it does not reach the parked subtree.
            park.set(0b010);
            tree.layout(SizeProposal::exact(100.0, 300.0));
            assert_eq!(
                tree.bounds(grandkid),
                parked_bounds,
                "nothing below a parked child is laid out"
            );

            park.set(0);
            tree.layout(SizeProposal::exact(100.0, 300.0));
            assert_eq!(
                tree.bounds(grandkid).size(),
                Size::new(100.0, 20.0),
                "…and the recursion resumes when it wakes"
            );
        }

        #[test]
        fn a_parent_that_leaves_dormant_alone_changes_nothing() {
            // `dormant` arrives pre-set to the child's current state, so a
            // culling parent that does not write it keeps whatever it decided
            // last time. Without that, every pass in which the parent declines
            // to answer would silently wake everything it had parked.
            let Rig {
                mut tree,
                park,
                ignore_dormant,
                id,
                ..
            } = tree_with(true);
            let kids = tree.children(id).to_vec();

            park.set(0b101);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert!(!tree.is_active(kids[0]) && !tree.is_active(kids[2]));

            ignore_dormant.set(true);
            park.set(0);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert!(
                !tree.is_active(kids[0]) && !tree.is_active(kids[2]),
                "a parent that ignores the field must not resurrect anything"
            );
            assert!(tree.is_active(kids[1]), "…nor park anything");
        }

        #[test]
        fn a_woken_child_is_laid_out_in_the_same_pass() {
            // The half a signal-based gate cannot do: a gate written during
            // layout is not read until the next pass, so the woken child would
            // paint at a stale rectangle for a frame.
            let Rig {
                mut tree, id, park, ..
            } = tree_with(true);
            let kids = tree.children(id).to_vec();

            park.set(0b100);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert!(!tree.is_active(kids[2]));

            park.set(0);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert!(tree.is_active(kids[2]), "woken");
            assert_eq!(
                tree.bounds(kids[2]),
                Rect::new(0.0, 40.0, 100.0, 20.0),
                "…and laid out this pass, not the next"
            );
        }

        #[test]
        fn a_culling_parent_is_handed_its_parked_children() {
            // Otherwise it could never ask one back, having parked it.
            let Rig {
                mut tree,
                park,
                seen,
                ..
            } = tree_with(true);
            assert_eq!(seen.get(), 3);
            park.set(0b111);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            park.set(0b111);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert_eq!(
                seen.get(),
                3,
                "all three are parked, and all three are still offered"
            );
        }

        #[test]
        fn a_widget_that_did_not_opt_in_cannot_park_anything() {
            // `dormant` is documented as read only for a `culls_children`
            // parent. A widget that writes it anyway must change nothing —
            // otherwise the field is a trapdoor on every container in the
            // framework.
            let Rig {
                mut tree,
                id,
                park,
                seen,
                grandkids,
                ..
            } = tree_with(false);
            let kids = tree.children(id).to_vec();
            park.set(0b111);
            tree.layout(SizeProposal::exact(100.0, 100.0));
            assert_eq!(seen.get(), 3, "active children only, which is all of them");
            for kid in &kids {
                assert!(tree.is_active(*kid), "{kid:?} must stay active");
            }
            assert_eq!(tree.tab_stops_within(id).len(), 3);
            // Widen the view so a subtree that was recursed into changes size.
            tree.layout(SizeProposal::exact(200.0, 100.0));
            for grandkid in grandkids.borrow().iter() {
                assert_eq!(
                    tree.bounds(*grandkid).size(),
                    Size::new(200.0, 20.0),
                    "…and its subtree must still be laid out: reading `dormant` \
                     from a widget that did not opt in would take the subtree \
                     out of the recursion",
                );
            }
        }

        #[test]
        fn parking_the_focused_child_does_not_leave_focus_on_a_dormant_node() {
            // The backstop behind the pin. A culling parent is expected to keep
            // what the user is using, but if it parks it anyway, focus must not
            // survive the pass pointing at a node dispatch will refuse — a
            // keystroke into the void is worse than a focus loss the user can
            // see.
            let Rig {
                mut tree, id, park, ..
            } = tree_with(true);
            let kids = tree.children(id).to_vec();
            tree.focus(kids[0]);
            assert_eq!(tree.focused(), Some(kids[0]));

            park.set(0b001);
            tree.layout(SizeProposal::exact(100.0, 100.0));

            assert!(!tree.is_active(kids[0]));
            assert_eq!(
                tree.focused(),
                None,
                "focus must not point into a subtree this pass parked"
            );
            let _ = id;
        }
    }
}