1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
use slotmap::SlotMap;
use crate::environment::ThemeOverride;
use crate::event_handlers::EventHandlers;
use crate::event_source::{SubscriptionHandle, SubscriptionId};
use crate::gesture::MultiContact;
use crate::pointer::hit_slop::{HitCandidate, HitContext};
use crate::pointer::touch_action::{PanClaim, TouchAction};
use crate::signal::{ObserverHandle, Prop, Signal};
use crate::widget::{CursorIcon, Widget};
use crate::widget_id::WidgetId;
use teksilo_canvas::RenderFrame;
/// Minimal placeholder widget used during composite rebuild and ID reservation.
#[derive(Debug)]
pub(crate) struct PlaceholderWidget;
impl Widget for PlaceholderWidget {
fn layout_response(
&self,
_proposal: teksilo_canvas::SizeProposal,
_ctx: &crate::widget::LayoutContext,
) -> crate::widget::LayoutResponse {
teksilo_canvas::Size::ZERO.into()
}
}
/// Activation state for a widget in the arena.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivationState {
Active,
Dormant,
Destroyed,
}
/// Where a `HandlerSet` should land on the node: handlers the widget
/// attaches to itself (cleared on rebuild) vs handlers attached from
/// outside (persist across rebuilds).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HandlerScope {
/// Handlers registered during the widget's own `build()` via
/// `BuildContext::apply_self_handlers`.
Own,
/// Handlers attached externally — at insertion time via
/// `WidgetBuilder::on_tap` et al., or by a composing parent's
/// `BuildContext::apply_handlers(child_id, ...)`.
External,
}
/// Dirty flags for a widget.
#[derive(Debug, Clone, Copy, Default)]
pub struct DirtyFlags {
pub needs_layout: bool,
pub needs_paint: bool,
/// When true, the widget's `build()` should be re-run to regenerate children.
/// Set by `BindingLevel::Rebuild` bindings (data-driven widgets).
pub needs_rebuild: bool,
}
/// One node's resolved hit-test geometry: which point tests its own bounds,
/// which point its children receive, its bounds, and how much its own transform
/// scales a local distance.
///
/// Shared by the exact pass, the outset pre-pass and the slop candidate walk so
/// the three cannot disagree about where a transformed node actually is.
struct HitSpace {
bounds_point: teksilo_canvas::Point,
child_point: teksilo_canvas::Point,
bounds: teksilo_canvas::Rect,
/// The minimum singular value of this node's own transform (`1.0` when it
/// has none) — the factor that turns a distance in its local space into one
/// in its parent's.
scale: f32,
}
/// `0.0` for a non-finite or negative inset, so a widget that computes an
/// outset from a `NaN` measurement cannot inflate a rectangle into nonsense.
fn finite(v: f32) -> f32 {
if v.is_finite() && v > 0.0 { v } else { 0.0 }
}
/// A node in the widget arena storing a widget and its metadata.
pub struct WidgetNode {
pub widget: Box<dyn Widget>,
pub parent: Option<WidgetId>,
pub children: Vec<WidgetId>,
pub activation: ActivationState,
/// Whether this node is dormant **on its own account** — parked by a
/// direct [`WidgetArena::set_dormant`] rather than swept along by an
/// ancestor going dormant.
///
/// This is the ungated twin of `visible_state`, and [`WidgetArena::activate`]
/// honours the two identically: a self-parked child is left asleep when an
/// ancestor wakes, because the ancestor's dormancy was never why it was
/// asleep. Cleared the moment a caller activates this node *by id*, which is
/// exactly how pre-registered overlay content is shown.
///
/// Without it, every widget that pre-builds hidden content as a child with
/// `ctx.add(..)` + `ctx.set_dormant(..)` — `SplitButton`'s dropdown,
/// `MenuBar`'s menus, `Popover`, `Snackbar`, the date editors' calendars —
/// spilled that content onto the screen as soon as any ancestor completed a
/// dormancy cycle, laid out inline with no overlay behind it.
pub(crate) self_dormant: bool,
pub dirty: DirtyFlags,
pub bounds: teksilo_canvas::Rect,
pub(crate) theme_override: Option<ThemeOverride>,
pub(crate) visible_state: Option<Prop<bool>>,
pub(crate) enabled_state: Option<Prop<bool>>,
/// Reactive Tab-key participation. When bound and evaluates to
/// `false`, the widget is excluded from Tab / Shift+Tab traversal
/// (`cycle_focus`) — but remains reachable via `request_focus`
/// and arrow-key navigation that calls `request_focus`. This
/// implements the ARIA roving-tabindex pattern (HTML
/// `tabindex="-1"` semantics). `None` means "always a Tab stop
/// when focusable" — the default. The selected `TabHeader` is the
/// canonical user.
pub(crate) tab_stop: Option<Prop<bool>>,
/// What a data view's `Space` should do when the row containing this node
/// holds the keyboard cursor.
///
/// A `ListView` / `TreeView` row is deliberately not focusable — the
/// container is — and the view takes the row subtree out of the Tab order,
/// because a listbox is one Tab stop and a per-row stop would make the Tab
/// order track the virtualization window. That leaves a checkbox inside a
/// row with no keyboard route, so the row publishes one here and the view
/// calls it. Carrying the *action* rather than the target's id keeps the
/// views from having to know what kind of control it is.
///
/// `StandardListItem` / `StandardTreeItem` set it on the checkbox they
/// embed, so the common path needs no wiring; a hand-written delegate
/// calls `BuildContext::set_keyboard_toggle`.
#[allow(clippy::type_complexity)]
pub(crate) keyboard_toggle: Option<std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>>,
/// User-bound signal that the framework sets to `true` whenever
/// the focused widget is a strict descendant of this node, and
/// `false` otherwise. Used by `Panel` / `Card` / composite
/// widgets that want a unified focus halo without per-child
/// `on_focus` plumbing. See `WidgetBuilder::focus_within`.
pub(crate) focus_within_signal: Option<Signal<bool>>,
/// Framework-managed signal, lazily attached to a focusable node, set to
/// `true` whenever the focus is this node **or** a descendant (i.e. the node
/// is an *inclusive* ancestor of the focused widget). Unlike
/// `focus_within_signal` (strict descendants), this includes the node being
/// focused itself — so a data view that holds focus directly reads `true`.
/// Powers focus-aware selection (`BuildContext::view_focus_active`).
pub(crate) view_focus_signal: Option<Signal<bool>>,
/// User-bound signal that the framework sets to `true` whenever
/// the hovered widget is a strict descendant of this node.
/// Symmetric to `focus_within_signal`. See
/// `WidgetBuilder::hover_within`.
pub(crate) hover_within_signal: Option<Signal<bool>>,
/// User-bound signal that the framework sets to `true` while this
/// node is `ActivationState::Active` and `false` while it is
/// `Dormant`. Opted into via `BuildContext::activation_signal`.
/// Unlike every other widget — which is hidden automatically when
/// the paint pass skips a dormant subtree — a widget that owns a
/// resource living *outside* the wgpu pass (a native OS subview: a
/// `WebView` engine surface) has no other way to learn it was parked
/// dormant by a `Switcher` / `visible_when` gate, so it cannot hide
/// that resource. This signal is that notification. Set only on an
/// actual Active↔Dormant transition. See `set_dormant` / `activate`.
pub(crate) activation_signal: Option<Signal<bool>>,
/// Framework-written press visual: `true` while this node holds a pointer
/// press that has not slid off, been claimed by a peer, or been cancelled.
/// Opted into via `BuildContext::pressed_signal`, and written by the
/// router — see [`crate::press`] for why the widget cannot maintain this
/// from its own handlers.
pub(crate) pressed_signal: Option<Signal<bool>>,
/// Framework-written mirror of [`WidgetArena::is_enabled`] for this node —
/// the AND of its own `enabled_state` and every ancestor's. Opted into via
/// `BuildContext::effective_enabled_signal`.
///
/// This has to be a *node-resident* signal that the framework refreshes,
/// rather than a signal derived by walking ancestors at call time, because
/// a widget's `parent` is still `None` while its own `build()` runs — the
/// parent link is wired only after `build()` returns (see
/// `WidgetTree::insert_widget`). A signal derived during `build()` would
/// therefore capture an empty ancestor chain and report only the widget's
/// own `enabled` prop, forever. Refreshed in
/// `WidgetTree::flush_effective_enabled_signals`.
pub(crate) effective_enabled_signal: Option<Signal<bool>>,
pub(crate) alignment_override: Option<teksilo_tokens::Alignment>,
/// When true, the paint pass clips child rendering to this widget's bounds.
/// Set by scroll areas and overflow-hidden containers.
pub clips_children: bool,
/// Optional OS input-method (IME) descriptor. `Some(..)` declares this
/// node a text-input surface — the platform enables the OS IME (with the
/// descriptor's purpose) while the node is focused. `None` (the default)
/// means no OS IME: enabling IME changes how text arrives, so the safe
/// common-case default is off. The platform reads the focused node's
/// descriptor at focus-change time. See [`crate::ime`].
pub ime: Option<crate::ime::ImeContext>,
/// When true, hit-testing skips this node — pointer events fall
/// through to whatever sits behind it. Descendants are still
/// hit-tested normally (the recursion walks into children before
/// the pass-through check), so an interactive subtree under a
/// pass-through wrapper stays usable. Used by the debug inspector's
/// `HighlightLayer` and `HoverProbe` to paint over the user's
/// content without absorbing clicks. Default `false`.
pub event_pass_through: bool,
/// When `true`, a pointer press anywhere in this widget's subtree must
/// NOT arm a drag/swipe recognizer on any ancestor **above** this node —
/// the subtree is a *gesture dead zone* for ancestor gestures. Used so
/// interactive controls (buttons, a `⋮` menu) placed inside a draggable /
/// swipeable container (a dock-panel header, a card, a list row) can be
/// clicked without a few px of pointer jitter starting the ancestor's drag.
/// The boundary is honored by `PointerSequence` member enrolment. Mirrors Electron's
/// `-webkit-app-region: no-drag`. Default `false`. See the `DeadZone`
/// wrapper widget.
pub gesture_dead_zone: bool,
/// What a **hold** on this node's subtree means when the widget itself does
/// not say — the selector for the tree-owned long-press route. Default
/// `LongPressRole::Auto`. Set via `.long_press_role(..)`. A node's own
/// `on_long_press` always takes precedence over this, and a mouse never
/// consults it. See [`crate::widget_tree::touch_route`].
pub long_press_role: crate::widget_tree::touch_route::LongPressRole,
/// What a direct pointer (touch, pen) is permitted to do to this node's
/// subtree. Intersected with every ancestor's on the way down by
/// `WidgetTree::effective_touch_action` — an ancestor can only narrow
/// what a descendant permits, never widen it. Default
/// [`TouchAction::AUTO`] (everything permitted). Set via
/// `.touch_action(..)`. A mouse never consults this field. Read at press
/// time, to gate pan claimants and the two-contact pinch — see
/// [`crate::pointer::touch_action`].
pub touch_action: TouchAction,
/// This node's declaration that it is a **pan surface** — it wants to
/// consume a direct pointer's drag as content panning. `None` (the
/// default) means the node makes no such claim. `WidgetTree::
/// pan_candidates` collects every claim from a target up to the root.
/// Set via `.pan_claim(..)` or the `.scroll_container(..)` sugar. Read at
/// press time to build the chain a synthesised pan walks — see
/// [`crate::pointer::touch_action`].
pub pan_claim: Option<PanClaim>,
/// Whether this node absorbs a scroll it cannot use, or lets it chain to
/// the next scrollable outward — the CSS `overscroll-behavior` model.
///
/// Read by `WidgetTree::deliver_pan` when it walks the claimant chain: an
/// [`OverscrollBehavior::Contain`](crate::OverscrollBehavior::Contain)
/// claimant **stops** the chain even when it absorbed nothing, so a
/// self-contained panel never lets a boundary pan escape into the page
/// behind it. Default
/// [`Chain`](crate::OverscrollBehavior::Chain). Set via
/// `.overscroll_behavior(..)`.
///
/// Declared on the node rather than left inside each scrollable's own
/// `on_scroll` closure because the *chain* has to read it, and the chain
/// runs in the router, above every handler.
pub overscroll_behavior: crate::OverscrollBehavior,
/// When a drag on this node may begin relative to the press that starts
/// it. [`DragActivation::Auto`](teksilo_tokens::DragActivation::Auto) — the
/// default — resolves to `Immediate`
/// for a precise pointer (today's behaviour, unchanged) and to
/// `AfterLongPress` for a coarse pointer whose axis is already claimed by
/// a pan surface. Set via `.drag_activation(..)`, read by the arbitration
/// when the node is enrolled as a sequence member.
pub drag_activation: teksilo_tokens::DragActivation,
/// How many simultaneous contacts this node's gesture recognizers serve.
/// Default [`MultiContact::First`] — one press at a time, which is what
/// every widget written before the touch programme assumes. Under it a
/// *second* contact arriving while the first is live is terminated at this
/// node: not delivered to it, and not bubbled to an ancestor either, so two
/// fingers on a button inside a scroll area cannot start a pan with the
/// second finger. Set via `.multi_contact(..)`.
pub multi_contact: MultiContact,
/// When `true` and this widget holds keyboard focus, a `KeyDown` is
/// delivered straight to it **without** first running shortcut →
/// intent → action resolution. The node is a *keyboard capture*
/// surface: it wants every keystroke (including chords the host app
/// binds as `Shortcut`s — `Ctrl+C`, `Ctrl+W`, `Alt+<letter>`, …).
/// Used by a terminal emulator (which must forward `Ctrl+C` to the
/// child process, not trigger the app's copy shortcut), a game
/// viewport, or a vim-mode editor. Honored by `dispatch_event_impl`,
/// which skips the shortcut block for a focused capture node.
///
/// **`Ctrl+Tab` / `Ctrl+Shift+Tab` are reserved**: `dispatch_event_impl`
/// cycles focus on that chord before dispatching to a focused capture
/// node, so no capture surface can trap the keyboard (WCAG 2.1.2).
/// Escape is not reserved — overlay back-navigation runs ahead of the
/// check only while an overlay is open, so a capture surface below no
/// overlay does see Escape. Default `false`.
pub keyboard_capture: bool,
/// When `true`, this widget AND its entire subtree are invisible to
/// hit-testing: the recursion returns immediately without descending
/// into children, so the point falls through to whatever sits
/// behind. Unlike [`event_pass_through`](Self::event_pass_through)
/// (which is per-node — descendants stay hittable), this excludes
/// the whole subtree. Use for purely decorative overlays whose
/// children are themselves widgets — a count badge over a button, a
/// watermark, a status dot — so they never steal clicks meant for
/// the control underneath. Default `false`.
pub hit_transparent: bool,
/// Per-node override of the *miss-only* slop this node may earn, set via
/// `.hit_slop(..)`. Second link of the precedence chain — it beats the
/// widget's own `Widget::hit_slop` and the density default, and loses only
/// to [`no_hit_slop`](Self::no_hit_slop). `None` (the default) defers to
/// the widget, then to the density.
pub hit_slop: Option<crate::pointer::hit_slop::HitSlop>,
/// When `true`, this node is excluded from **both** hit-widening
/// mechanisms: it earns no slop outset in the miss-only pass, and its
/// `Widget::hit_outset` is ignored inside the exact pass. The head of the
/// precedence chain, set via `.no_hit_slop()`.
///
/// Per-node, not per-subtree: a descendant may still widen. Excluding a
/// whole subtree from hit-testing is
/// [`hit_transparent`](Self::hit_transparent)'s job, and excluding a region
/// that hosts foreign content (a `WebView` surface) is exactly this flag on
/// that one node. Default `false`.
pub no_hit_slop: bool,
/// Optional opacity multiplier (0..1) applied to this widget's
/// entire subtree during paint. The render walker emits
/// `SetOpacity(value)` before walking the widget's own paint and
/// children, then `RestoreOpacity` afterwards — so the multiplier
/// composes with ancestor opacity scopes via the canvas's
/// already-stacked opacity model. Bound at `Repaint` level: opacity
/// changes never trigger relayout. `None` means "no opacity scope"
/// (the default for almost every widget). The `Fade` widget sets
/// this on its own node to drive an animated visibility tween.
pub(crate) opacity_prop: Option<Prop<f32>>,
/// Optional 2D affine transform applied to this widget's entire
/// subtree during paint. The render walker emits
/// `PushTransform(value)` before walking the widget's own paint
/// and children, then `PopTransform` afterwards — the renderer
/// composes it onto its transform stack so nested wrappers and
/// widget-internal canvas transforms compose correctly. Bound at
/// `Repaint` level by default (visual-only); a wrapper that wants
/// the transform to drive layout (e.g. `Scale::reflow(true)`)
/// must additionally bind its driver signal at `Relayout`.
/// `None` means "no transform scope" (the default for almost every
/// widget). The `Scale` and `Rotate` widgets set this on their own
/// node.
pub(crate) transform_prop: Option<Prop<teksilo_canvas::Transform2D>>,
/// Whether [`transform_prop`](Self::transform_prop) transforms this node's
/// **content** within a fixed parent-space viewport (`true`), versus
/// transforming the **node itself** (`false`, the default).
///
/// `Scale` / `Rotate` are *self* transforms: the node's own bounds move
/// with the transform, so hit-testing inverse-applies the transform before
/// the bounds test (a click lands where the scaled/rotated visual is).
///
/// `SceneView` is a *content* transform: its bounds are a fixed screen
/// viewport and the pan/zoom only moves its content, so hit-testing must
/// test the bounds in parent space (keeping the whole visible viewport
/// interactive at any pan) and apply the transform only when descending
/// into children. Set via `BuildContext::set_content_transform`.
pub(crate) content_transform: bool,
/// Optional Gaussian-equivalent blur radius applied to this widget's
/// entire subtree during paint. The render walker emits
/// `BeginBlurredSubtree { bounds, radius }` before walking the
/// widget's own paint and children, then `EndBlurredSubtree`
/// afterwards — the renderer redirects drawing into an intermediate
/// texture, runs a dual-Kawase blur chain at the requested radius,
/// and composites the blurred result back into the parent pass.
/// Bound at `Repaint` level: blur radius changes never trigger
/// relayout. `None` (or `Some(radius < 0.5)`) means "no blur scope"
/// — the walker skips the Begin/End pair entirely so disabled blur
/// has zero per-frame cost. The `Blur` widget sets this on its own
/// node.
pub(crate) blur_prop: Option<Prop<f32>>,
/// Cached paint output for this widget (excludes children).
/// Reused when `needs_paint` is false to avoid re-running `paint()`.
pub(crate) cached_paint: Option<RenderFrame>,
/// Cached foreground output for widgets that override
/// [`Widget::post_paint`] — the
/// draws emitted *after* this widget's children. Separate frame from
/// `cached_paint` because it lands at a different position in
/// `draw_order` (after the child subtree). Reused on the same
/// `needs_paint` gate.
pub(crate) cached_post_paint: Option<RenderFrame>,
/// The ambient raster scale `cached_paint` / `cached_post_paint`
/// were baked at (the paint walker's accumulated transform scale,
/// quantized). Glyph quads in those frames reference bitmaps of
/// that density; when the walker's current scale differs (a scene
/// zoom crossed a quantization bucket), the cached frames are
/// treated as `needs_paint` even though the widget itself is clean.
pub(crate) paint_raster_scale: f32,
/// The `WidgetTree::paint_epoch` at which this widget's bounds were
/// last observed inside the window viewport by the paint pass.
/// The animation scheduler uses this to pause looping animations
/// for offscreen widgets: an animation whose
/// `last_painted_epoch + 1 < tree.paint_epoch` is considered
/// off-screen and skipped. `0` means "not yet painted"; visibility is
/// waived wholesale while `tree.paint_epoch` is itself `0`, which keeps
/// headless tests (no `render()` call) from regressing.
pub last_painted_epoch: u64,
// --- V2 fields ---
/// Event handlers the widget attached to itself during its own
/// `build()` via `BuildContext::apply_self_handlers`. Cleared on
/// rebuild so accumulating `apply_self_handlers` calls across
/// rebuilds don't stack N-fold handler chains.
pub(crate) handlers: EventHandlers,
/// Event handlers attached *externally* — either via the
/// `WidgetBuilder` chain at the widget's creation site
/// (`SomeWidget::new().on_tap(...)`) or by a parent's
/// `BuildContext::apply_handlers(child_id, ...)`. These survive
/// rebuilds: the widget didn't register them and shouldn't decide
/// when they go away.
pub(crate) external_handlers: EventHandlers,
/// Focusable override set via HandlerSet. The only source of a node's
/// focusability — `WidgetTree::is_node_focusable` reads this field and
/// nothing else, so `None` means not focusable.
pub(crate) node_focusable: Option<bool>,
/// Tab index override set via HandlerSet.
pub(crate) node_tab_index: Option<i32>,
/// Traversal-scope marker. When `Some(policy)`, `cycle_focus` treats this
/// node's subtree as an independent Tab group: `tab_index` numbering is
/// scoped to its descendants (so sibling scopes never interleave) and
/// `policy` governs what Tab does at the scope's ends. `None` (default)
/// means the node is transparent to traversal scoping. Set by the
/// `FocusScope` wrapper via `BuildContext::set_traversal_scope`. A node
/// carrying this marker is forced non-focusable (it is a boundary, never a
/// Tab stop). See [`crate::focus::TraversalScopePolicy`].
pub(crate) node_traversal_scope: Option<crate::focus::TraversalScopePolicy>,
/// Cursor override set via HandlerSet.
pub(crate) node_cursor: Option<CursorIcon>,
/// RAII observer handles for effects registered during build().
/// Dropped on rebuild or widget destruction.
pub(crate) effect_handles: Vec<ObserverHandle>,
/// Backend-event subscriptions registered during build() via
/// `BuildContext::subscribe_event`. Each entry pairs a subscription id
/// (used to remove the UI-side callback from `TreeAppContext`) with the
/// opaque source-side handle whose `Drop` removes the subscriber from
/// the source's internal registry.
pub(crate) subscription_handles: Vec<(SubscriptionId, SubscriptionHandle)>,
/// Parentless nodes this widget created during `build()` and still owns —
/// pre-built overlay content (a menu, a calendar, a tooltip's nested
/// cascade children) that is deliberately *not* a child.
///
/// Such content cannot be a child: activation and the paint walk both
/// descend through `children`, so a dormant popup parked there wakes with
/// its host and paints inline at zero size. Keeping it parentless fixes
/// that and creates the opposite problem — no teardown walk reaches it, so
/// every rebuild of the host strands another copy in the arena for the
/// lifetime of the process. This list is the missing ownership edge:
/// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) reaps it
/// with the owner, and a rebuild reaps the previous generation. Recorded
/// via `BuildContext::add_detached`.
pub(crate) detached: Vec<WidgetId>,
/// Context menu factory — invoked on right-click to produce overlay content.
pub(crate) context_menu_factory: Option<crate::widget_builder::ContextMenuFactory>,
/// Intent-bound actions attached by this widget during `build()`.
/// Consulted during intent dispatch (source-widget → root walk).
/// Cleared on rebuild in the same pass that clears handlers.
pub(crate) actions: Vec<crate::action::Action>,
/// Builder-level accessibility overrides (`access_label`,
/// `access_role`, etc.). Mirrored from the wrapper's `HandlerSet`
/// at insertion via `apply_handler_set`. Applied by the
/// accessibility tree walker after the inner widget's
/// `accessibility(&self, builder)` runs. Action callbacks
/// (`actions`, `custom_actions` inside this struct) are dispatched
/// by `pointer_router.rs` when handling
/// `WidgetEvent::AccessAction`.
pub(crate) access_overrides: Option<Box<crate::widget_builder::AccessibilityOverrides>>,
/// Subtree visibility / merge mode (`access_exclude_subtree` /
/// `access_merge_subtree`). Mirrored from the wrapper's
/// `HandlerSet`.
pub(crate) access_subtree: crate::widget_builder::AccessSubtreeMode,
}
impl std::fmt::Debug for WidgetNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WidgetNode")
.field("widget", &self.widget)
.field("parent", &self.parent)
.field("children", &self.children)
.field("activation", &self.activation)
.field("dirty", &self.dirty)
.field("bounds", &self.bounds)
.field("has_gesture_arena", &self.handlers.gesture_arena.is_some())
.field("has_theme_override", &self.theme_override.is_some())
.field("has_visible_state", &self.visible_state.is_some())
.field("has_enabled_state", &self.enabled_state.is_some())
.finish()
}
}
impl WidgetNode {
/// Construct a fresh node wrapping `widget`, parented at `parent`
/// (`None` for a root). All other fields take their insertion defaults;
/// the caller wires up `children` / parent back-links afterward.
pub(crate) fn new(widget: Box<dyn Widget>, parent: Option<WidgetId>) -> Self {
WidgetNode {
widget,
parent,
children: Vec::new(),
activation: ActivationState::Active,
self_dormant: false,
dirty: DirtyFlags {
needs_layout: true,
needs_paint: true,
needs_rebuild: false,
},
bounds: teksilo_canvas::Rect::ZERO,
theme_override: None,
visible_state: None,
enabled_state: None,
tab_stop: None,
keyboard_toggle: None,
focus_within_signal: None,
view_focus_signal: None,
hover_within_signal: None,
activation_signal: None,
pressed_signal: None,
effective_enabled_signal: None,
alignment_override: None,
clips_children: false,
ime: None,
event_pass_through: false,
gesture_dead_zone: false,
long_press_role: crate::widget_tree::touch_route::LongPressRole::Auto,
touch_action: TouchAction::AUTO,
pan_claim: None,
overscroll_behavior: crate::OverscrollBehavior::Chain,
drag_activation: teksilo_tokens::DragActivation::Auto,
multi_contact: MultiContact::First,
keyboard_capture: false,
hit_transparent: false,
hit_slop: None,
no_hit_slop: false,
opacity_prop: None,
transform_prop: None,
content_transform: false,
blur_prop: None,
cached_paint: None,
cached_post_paint: None,
paint_raster_scale: 1.0,
last_painted_epoch: 0,
handlers: EventHandlers::new(),
external_handlers: EventHandlers::new(),
node_focusable: None,
node_tab_index: None,
node_traversal_scope: None,
node_cursor: None,
effect_handles: Vec::new(),
subscription_handles: Vec::new(),
detached: Vec::new(),
context_menu_factory: None,
actions: Vec::new(),
access_overrides: None,
access_subtree: crate::widget_builder::AccessSubtreeMode::default(),
}
}
/// Does EITHER handler slot (own or external) have a handler of the
/// requested kind? Use this when deciding whether to build a gesture
/// arena, mark the node as a drop target, etc.
pub(crate) fn any_handler<F>(&self, f: F) -> bool
where
F: Fn(&EventHandlers) -> bool,
{
f(&self.handlers) || f(&self.external_handlers)
}
}
/// Flat arena storage for all widgets, using SlotMap for O(1) access.
pub struct WidgetArena {
nodes: SlotMap<WidgetId, WidgetNode>,
/// Number of nodes with theme overrides. When zero, resolve_theme is O(1).
pub(crate) theme_override_count: usize,
/// Cached root widget IDs (widgets with no parent).
cached_roots: Vec<WidgetId>,
/// Whether the cached_roots list needs rebuilding.
roots_dirty: bool,
/// Per-pass memoization of `Widget::layout_response`, keyed by
/// `(WidgetId, ProposalKey)`. Cleared once at the start of every layout
/// pass (see `clear_layout_cache`). Height-for-width negotiation queries
/// each child along the main axis and again along the cross axis, so
/// without this the cost compounds super-linearly with nesting depth;
/// with it, each `(id, proposal)` is computed at most once per pass.
/// `RefCell` because layout runs through shared `&WidgetArena` borrows.
layout_cache: std::cell::RefCell<
std::collections::HashMap<(WidgetId, ProposalKey), crate::widget::LayoutResponse>,
>,
/// Widgets whose box moved without changing size since the last
/// accessibility walk, and by how much.
///
/// A move is the one geometry change the accessibility tree can absorb
/// without being rebuilt: nothing about a widget's *content* depends
/// on where it sits, so its node and every text run under it can be
/// re-placed in the cached tree by the same delta. A scroll frame
/// moves every descendant of the scroll area, so this is the common
/// case and re-walking for it was what made the AT tree go stale
/// instead — the walk was too expensive to run per frame, so it was
/// not run at all and every node's bounds drifted.
a11y_moved: std::collections::HashMap<WidgetId, teksilo_canvas::Point>,
/// Set when any widget's box changed *size* since the last
/// accessibility walk.
///
/// A resize is not absorbable: a wrapped label re-wraps, so its lines —
/// and therefore its text runs — are a different set, not the same set
/// somewhere else.
a11y_resized: bool,
/// True while [`measure_intrinsic`](Self::measure_intrinsic) is running.
/// In this mode `cached_layout_response` measures even dormant widgets
/// (and their dormant subtrees) and bypasses the cache, so an adaptive
/// container can size an item it intends to keep hidden without that size
/// leaking into the normal per-pass cache.
measuring: std::cell::Cell<bool>,
/// Active↔Dormant transitions of nodes carrying an `activation_signal`,
/// recorded by [`set_dormant`](Self::set_dormant) / [`activate`](Self::activate)
/// and drained by `WidgetTree::flush_activation_signals` *after* the
/// mutation completes. Signals are fired at the tree level, never from
/// inside the arena recursion — mirroring how `focus_within` /
/// `hover_within` are updated from `WidgetTree` methods rather than mid
/// mutation, so an observer (e.g. a `WebView`'s `set_visible`, which on a
/// real backend is an OS call) never runs while the arena is being walked.
/// Only nodes with a signal contribute, so the buffer is empty for the
/// overwhelming majority of trees.
pending_activation_changes: Vec<(WidgetId, bool)>,
/// Every node that installed an `effective_enabled_signal`, so the
/// per-pass refresh visits only opted-in nodes instead of the whole arena.
/// Unlike `pending_activation_changes` this is NOT a change queue: an
/// ancestor's `enabled` prop is a `Signal` that can flip at any time
/// without the arena being told, so there is no single mutation site to
/// record a transition at. The refresh recomputes and diffs instead —
/// see `WidgetTree::flush_effective_enabled_signals`. Dead ids are pruned
/// there, so a destroyed widget cannot leak.
effective_enabled_watchers: Vec<WidgetId>,
}
/// Hashable key for a [`teksilo_canvas::SizeProposal`] used by the per-pass
/// layout cache. Each axis is encoded to a `u64`: `None` → a sentinel
/// distinct from any finite `f32`, `Some(v)` → the canonicalized `f32` bits
/// (`-0.0` folded to `0.0`, all NaNs folded to one pattern) so two equal
/// proposals always hash and compare equal.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct ProposalKey([u64; 2]);
impl ProposalKey {
fn from_proposal(p: teksilo_canvas::SizeProposal) -> Self {
fn axis_bits(v: Option<f32>) -> u64 {
match v {
// `f32::to_bits()` widens into 0..=u32::MAX, so u64::MAX is a
// safe sentinel that no `Some(_)` can collide with.
None => u64::MAX,
Some(f) => {
let canon = if f == 0.0 {
0.0
} else if f.is_nan() {
f32::NAN
} else {
f
};
canon.to_bits() as u64
}
}
}
Self([axis_bits(p.width), axis_bits(p.height)])
}
}
impl WidgetArena {
pub fn new() -> Self {
Self {
nodes: SlotMap::with_key(),
theme_override_count: 0,
cached_roots: Vec::new(),
roots_dirty: true,
layout_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
measuring: std::cell::Cell::new(false),
a11y_moved: std::collections::HashMap::new(),
a11y_resized: false,
pending_activation_changes: Vec::new(),
effective_enabled_watchers: Vec::new(),
}
}
/// Record what a bounds change means for the accessibility tree.
///
/// Called by the layout pass at each of its two bounds writers, after
/// the node has been updated. Same size = a move the cached tree can
/// absorb; any size change = a rebuild.
pub(crate) fn note_bounds_change(
&mut self,
id: WidgetId,
previous: teksilo_canvas::Rect,
current: teksilo_canvas::Rect,
) {
if previous.width != current.width || previous.height != current.height {
self.a11y_resized = true;
self.a11y_moved.remove(&id);
return;
}
let delta = teksilo_canvas::Point::new(current.x - previous.x, current.y - previous.y);
// A widget can move several times between two walks; the cached
// tree only ever sees the total.
let entry = self
.a11y_moved
.entry(id)
.or_insert(teksilo_canvas::Point::new(0.0, 0.0));
entry.x += delta.x;
entry.y += delta.y;
}
/// Whether any widget changed size since the last accessibility walk,
/// clearing the flag.
pub(crate) fn take_a11y_resized(&mut self) -> bool {
std::mem::take(&mut self.a11y_resized)
}
/// The widgets that moved since the last accessibility walk, clearing
/// the record.
pub(crate) fn take_a11y_moved(
&mut self,
) -> std::collections::HashMap<WidgetId, teksilo_canvas::Point> {
std::mem::take(&mut self.a11y_moved)
}
/// Clear the per-pass layout memoization cache. Called once at the start of
/// each layout pass — geometry (and therefore `layout_response` results)
/// may change between passes, so the cache is valid only within one pass.
pub(crate) fn clear_layout_cache(&self) {
self.layout_cache.borrow_mut().clear();
}
/// Compute a widget's layout response, memoized per `(id, proposal)` for
/// the current layout pass. Returns `None` if the id is missing or
/// dormant. Widgets that opt out via `Widget::cacheable_layout() == false`
/// (e.g. the inspector's bounds tracker, which deliberately mutates signals
/// in `layout_response`) bypass the cache so their side effect fires on
/// every call.
///
/// The key is `(id, proposal)` only: `layout_response` also reads the
/// `LayoutContext` (resolved theme, layout direction, text backend), but
/// those are a stable function of `id` within a single pass, so the pair
/// uniquely determines the input.
pub(crate) fn cached_layout_response(
&self,
id: WidgetId,
proposal: teksilo_canvas::SizeProposal,
ctx: &crate::widget::LayoutContext,
) -> Option<crate::widget::LayoutResponse> {
let node = self.nodes.get(id)?;
let measuring = self.measuring.get();
if node.activation != ActivationState::Active && !measuring {
return None;
}
// While measuring intrinsic sizes (incl. of dormant subtrees), bypass
// the cache entirely so a dormant widget's size never pollutes the
// normal per-pass cache.
if measuring || !node.widget.cacheable_layout() {
return Some(node.widget.layout_response(proposal, ctx));
}
let key = (id, ProposalKey::from_proposal(proposal));
// Scope the shared borrow so it is released before `layout_response`
// runs — that call recurses into children, which borrow the same
// `layout_cache` (read, then write) and would otherwise alias.
{
if let Some(cached) = self.layout_cache.borrow().get(&key) {
return Some(*cached);
}
}
let resp = node.widget.layout_response(proposal, ctx);
self.layout_cache.borrow_mut().insert(key, resp);
Some(resp)
}
/// Measure a widget's intrinsic `layout_response` size for `proposal`,
/// **regardless of activation** — including dormant/collapsed widgets and
/// their dormant subtrees. Returns `None` only if the id is absent.
///
/// Adaptive containers (e.g. an overflow [`Toolbar`](crate) that collapses
/// items into a menu) use this to size an item they intend to keep hidden,
/// so they can decide when to show it again as space grows — something
/// `child_layout_response` cannot do, since it returns `None` for inactive
/// widgets.
///
/// Runs uncached (a dormant widget's size never enters the per-pass cache)
/// and is re-entrant-safe (saves/restores the measuring flag). Calls
/// `layout_response`, which must be idempotent (see
/// [`Widget::cacheable_layout`]).
pub(crate) fn measure_intrinsic(
&self,
id: WidgetId,
proposal: teksilo_canvas::SizeProposal,
ctx: &crate::widget::LayoutContext,
) -> Option<teksilo_canvas::Size> {
if !self.nodes.contains_key(id) {
return None;
}
let prev = self.measuring.replace(true);
// `cached_layout_response` (and every nested child query during this
// call) sees `measuring == true`, so it bypasses the active check and
// the cache for the whole subtree.
let resp = self.cached_layout_response(id, proposal, ctx);
self.measuring.set(prev);
resp.map(|r| r.size)
}
/// Insert a widget into the arena as a root-level widget.
pub fn insert(&mut self, widget: Box<dyn Widget>) -> WidgetId {
self.roots_dirty = true;
let children = widget.children();
let id = self.nodes.insert(WidgetNode::new(widget, None));
// Set up parent-child for declared children
for &child_id in &children {
if let Some(child_node) = self.nodes.get_mut(child_id) {
child_node.parent = Some(id);
}
}
if let Some(node) = self.nodes.get_mut(id) {
node.children = children;
}
id
}
/// Insert a widget as a child of the given parent.
pub fn insert_child(&mut self, parent: WidgetId, widget: Box<dyn Widget>) -> WidgetId {
assert!(
self.nodes.contains_key(parent),
"insert_child() called with invalid parent WidgetId {parent:?}"
);
self.roots_dirty = true;
let children = widget.children();
let id = self.nodes.insert(WidgetNode::new(widget, Some(parent)));
// Set up parent-child for declared children
for &child_id in &children {
if let Some(child_node) = self.nodes.get_mut(child_id) {
child_node.parent = Some(id);
}
}
if let Some(node) = self.nodes.get_mut(id) {
node.children = children;
}
if let Some(parent_node) = self.nodes.get_mut(parent) {
parent_node.children.push(id);
}
id
}
pub fn get(&self, id: WidgetId) -> Option<&WidgetNode> {
self.nodes.get(id)
}
pub fn get_mut(&mut self, id: WidgetId) -> Option<&mut WidgetNode> {
self.nodes.get_mut(id)
}
pub fn children(&self, id: WidgetId) -> &[WidgetId] {
self.nodes
.get(id)
.map(|n| n.children.as_slice())
.unwrap_or(&[])
}
pub fn parent(&self, id: WidgetId) -> Option<WidgetId> {
self.nodes.get(id).and_then(|n| n.parent)
}
pub fn bounds(&self, id: WidgetId) -> teksilo_canvas::Rect {
self.nodes
.get(id)
.map(|n| n.bounds)
.unwrap_or(teksilo_canvas::Rect::ZERO)
}
/// The accumulated 2D affine transform that maps `id`'s pre-transform
/// local-space points to screen space — equivalent to the renderer's
/// `transform_stack` top by the time it begins painting `id`. Used by
/// hit-testing and any consumer that needs to project a node's
/// pre-transform bounds into screen space (e.g. teksilo-scene's a11y
/// bounds projection of view-transformed scene items).
///
/// **Composition order.** Mirrors `crates/teksilo-render/src/renderer.rs`'s
/// `PushTransform` handling: each push composes as
/// `new_top = device_t.then(prev_top)`, so the deepest (innermost)
/// transform is applied **first** to a local point and outer ancestors
/// compose afterward. Walking root→leaf, each ancestor's
/// `transform_prop` is folded in via `t.then(effective)` (NOT
/// `effective.then(t)`).
///
/// Returns `Transform2D::IDENTITY` if no ancestor sets a non-identity
/// transform, which is the common case (90%+ of widgets).
pub fn effective_transform(&self, id: WidgetId) -> teksilo_canvas::Transform2D {
// Collect leaf→root, then iterate root→leaf. Composition is
// `t_new.then(effective_so_far)` so the outer ancestor is applied
// *after* the deeper push — matching the renderer's stack semantic
// (`device_t.then(prev_top)` at PushTransform).
let mut chain: Vec<WidgetId> = Vec::new();
let mut current = Some(id);
while let Some(c) = current {
chain.push(c);
current = self.parent(c);
}
let mut effective = teksilo_canvas::Transform2D::IDENTITY;
for node_id in chain.iter().rev() {
if let Some(node) = self.nodes.get(*node_id)
&& let Some(p) = node.transform_prop.as_ref()
{
let t = p.get();
if !t.is_identity() {
effective = t.then(&effective);
}
}
}
effective
}
/// Convert a **window-space** pointer position into the **widget-local**
/// coordinate space of `id`'s event handlers — i.e. relative to `id`'s
/// top-left, after undoing any transform scopes between the window and
/// `id`. This is the single conversion the dispatcher applies before
/// handing a position to `on_tap` / `on_drag` / `on_pointer_event`, so
/// every handler sees positions in its own local space.
///
/// The transform handling mirrors `Self::hit_test_recursive` so the
/// position a handler receives is in the same space the hit-test used
/// to pick it:
/// * A **content** transform node (`content_transform`, e.g.
/// `SceneView`) owns its transform and maps its content itself. The
/// framework feeds such a node positions in its **parent-effective**
/// space (the same space `hit_test_recursive` passes through
/// `inv(transform)`), with **no** bounds-origin subtraction — the
/// node's `view_transform` already accounts for its placement.
/// * Any other node (the 90%+ identity case, plus `Scale` / `Rotate`
/// self-transforms) receives widget-local coordinates: undo the full
/// transform chain including its own, then subtract its bounds
/// origin so the result is relative to its top-left.
///
/// In the common no-transform case this collapses to
/// `window_point - bounds.origin`.
pub fn local_pointer_position(
&self,
id: WidgetId,
window_point: teksilo_canvas::Point,
) -> teksilo_canvas::Point {
let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
if content_transform {
// Parent-effective space, no origin subtraction (the node's
// own transform consumes these coordinates).
let to_parent = self
.parent(id)
.map(|p| self.effective_transform(p))
.unwrap_or(teksilo_canvas::Transform2D::IDENTITY);
return match to_parent.inverse() {
Some(inv) => inv.apply_point(window_point),
None => window_point,
};
}
let in_local = match self.effective_transform(id).inverse() {
Some(inv) => inv.apply_point(window_point),
// Degenerate transform: fall back to the raw point rather than
// dropping the event.
None => window_point,
};
let bounds = self.bounds(id);
teksilo_canvas::Point::new(in_local.x - bounds.x, in_local.y - bounds.y)
}
/// Get all root-level widget IDs (widgets with no parent).
pub fn roots(&self) -> Vec<WidgetId> {
if self.roots_dirty {
// Fall back to scanning when cache is stale.
// refresh_roots() should be called from layout() for the fast path.
return self
.nodes
.iter()
.filter(|(_, node)| node.parent.is_none())
.map(|(id, _)| id)
.collect();
}
self.cached_roots.clone()
}
/// Refresh the cached roots list. Call once per frame from layout().
pub fn refresh_roots(&mut self) {
if self.roots_dirty {
self.cached_roots = self
.nodes
.iter()
.filter(|(_, node)| node.parent.is_none())
.map(|(id, _)| id)
.collect();
self.roots_dirty = false;
}
}
/// Walk the active widget tree at `point` and return the deepest
/// widget under it (the front-most hit, last child wins). Honors
/// `event_pass_through` (such nodes pass through to whatever sits
/// behind them but their descendants are still hit-testable). Does
/// not consider overlays — for the full pointer-routing hit-test
/// see `WidgetTree::hit_test`.
///
/// `exclude`: if `Some(id)`, that widget (and any descendants
/// within its subtree) are skipped during the walk. Used by the
/// debug inspector's picker tool to ignore the picker overlay
/// itself, and by drag-and-drop to ignore the drag preview.
pub fn hit_test_at(
&self,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
) -> Option<WidgetId> {
self.hit_test_at_with(point, exclude, &HitContext::mouse())
}
/// [`hit_test_at`](Self::hit_test_at) on behalf of a named pointer.
///
/// The **exact** pass only: `Widget::hit_outset` is consulted (so a grip
/// wins over what it overlaps for the kind that asked), but no slop
/// re-attribution happens. Callers that want re-attribution too use
/// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop).
pub fn hit_test_at_with(
&self,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
) -> Option<WidgetId> {
let roots = self.roots();
// Roots take the outset pre-pass too, so a grip that happens to be a
// top-level node behaves like one nested anywhere else. The window is
// its "parent", and the window does not clip — and, having no widget,
// it vetoes nothing.
let no_veto = |_: WidgetId| false;
if let Some(grip) = self.outset_hit(&roots, point, exclude, hit, &no_veto) {
return Some(grip);
}
for &root in roots.iter().rev() {
if let Some(found) = self.hit_test_recursive(root, point, exclude, hit) {
return Some(found);
}
}
None
}
/// The full two-stage hit test: the exact pass, then — **only when it found
/// nothing eligible** — the nearest-candidate slop pass.
///
/// Returns whatever the exact pass returned unless a slop candidate is
/// strictly closer than the bubble owner's uninflated shape. See
/// [`hit_candidates`](Self::hit_candidates) for the eligibility rules and
/// `docs/density-and-targets.md` for the prose.
///
/// For a mouse this is [`hit_test_at`](Self::hit_test_at): the mouse slop
/// radius is `0.0` at every density, so the second stage short-circuits
/// before it walks anything.
pub fn hit_test_at_with_slop(
&self,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
) -> Option<WidgetId> {
let exact = self.hit_test_at_with(point, exclude, hit);
self.apply_slop(self.roots(), point, exclude, hit, exact)
}
/// [`hit_test_in_subtree`](Self::hit_test_in_subtree) with the slop pass,
/// scoped so candidates never leave `start`'s subtree.
///
/// This is what restricts the pass to the topmost overlay layer the exact
/// pass entered: the tree calls it with the overlay's content root, so a
/// press inside a menu can never be re-attributed to a control on the page
/// behind it.
pub fn hit_test_in_subtree_with_slop(
&self,
start: WidgetId,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
) -> Option<WidgetId> {
let exact = self.hit_test_recursive(start, point, exclude, hit);
self.apply_slop(vec![start], point, exclude, hit, exact)
}
/// Hit-test starting from a specific subtree root rather than the
/// arena's top-level roots. Same semantics as
/// [`hit_test_at`](Self::hit_test_at) but scoped — useful when
/// callers want to ignore everything outside a known subtree
/// (e.g. the inspector's picker hit-tests inside the user-root
/// subtree so it never resolves to its own chrome).
pub fn hit_test_in_subtree(
&self,
start: WidgetId,
point: teksilo_canvas::Point,
) -> Option<WidgetId> {
self.hit_test_recursive(start, point, None, &HitContext::mouse())
}
/// Like [`hit_test_in_subtree`](Self::hit_test_in_subtree) but also
/// excludes a widget (and its descendants) from the walk. Lets the
/// overlay / drag-and-drop hit-test reuse the single canonical recursion
/// in `hit_test_recursive` instead of duplicating it.
pub fn hit_test_in_subtree_excluding(
&self,
start: WidgetId,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
) -> Option<WidgetId> {
self.hit_test_recursive(start, point, exclude, &HitContext::mouse())
}
/// [`hit_test_in_subtree_excluding`](Self::hit_test_in_subtree_excluding)
/// on behalf of a named pointer. Exact pass only.
pub fn hit_test_in_subtree_with(
&self,
start: WidgetId,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
) -> Option<WidgetId> {
self.hit_test_recursive(start, point, exclude, hit)
}
fn hit_test_recursive(
&self,
id: WidgetId,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
) -> Option<WidgetId> {
if !self.is_active(id) || Some(id) == exclude {
return None;
}
// Decorative subtree: skip this node and ALL its descendants so
// the point falls through to whatever is painted behind. Checked
// before descending into children (the difference from
// `event_pass_through`, which is applied only after the children
// miss).
if self.get(id).map(|n| n.hit_transparent).unwrap_or(false) {
return None;
}
let space = self.hit_space(id, point)?;
let HitSpace {
bounds_point,
child_point,
bounds,
..
} = space;
if !bounds.contains(bounds_point) {
return None;
}
// Shape rejection: a widget with a non-rectangular silhouette (an
// ellipse / cloud scene node, a circular handle) can reject a point
// that is inside its bounding box but outside its actual shape via
// `Widget::hit_shape`. Returning None here lets the caller's
// reverse-sibling loop fall through to whatever is painted
// underneath — the same path `event_pass_through` takes, but
// shape-aware (only the rejected sub-region falls through, not the
// whole widget). Default `hit_shape` returns true, so rectangular
// widgets take this branch for free with no behavior change.
if let Some(node) = self.get(id)
&& !node.widget.hit_shape(bounds_point, bounds)
{
return None;
}
let pass_through = self.get(id).map(|n| n.event_pass_through).unwrap_or(false);
let children: Vec<WidgetId> = self.children(id).to_vec();
// A child that declares a `Widget::hit_outset` is offered the point
// BEFORE the ordinary reverse-sibling walk, so a thin grip wins over
// whatever it overlaps rather than losing to whichever neighbour is
// painted on top of it. Only the ring OUTSIDE a child's own bounds is
// resolved here — a point genuinely inside a child falls through to the
// normal walk below, which resolves descendants and honours
// `hit_shape`, so declaring an outset never changes where an in-bounds
// press lands.
// A parent that owns a second picking system over the same area gets
// to veto a child for this point — see `Widget::accepts_child_hit`.
// Resolved once here and threaded into `outset_hit`, so a grip cannot
// sneak past a veto the ordinary walk would have honoured.
let parent = self.get(id);
let vetoes = |child: WidgetId| {
parent.is_some_and(|node| !node.widget.accepts_child_hit(child, child_point))
};
if let Some(grip) = self.outset_hit(&children, child_point, exclude, hit, &vetoes) {
return Some(grip);
}
for &child in children.iter().rev() {
if vetoes(child) {
continue;
}
if let Some(found) = self.hit_test_recursive(child, child_point, exclude, hit) {
return Some(found);
}
}
if pass_through {
return None;
}
Some(id)
}
/// The outset pre-pass over one parent's children.
///
/// A child that declares an outset is offered the point against its
/// **inflated** bounds, ahead of the ordinary reverse-sibling walk, so a
/// thin grip wins over whatever is painted on top of it — both in its ring
/// and in its own body, which is the whole point of a splitter gutter lying
/// under two panes.
///
/// Ordering is by distance to the child's own uninflated rectangle, so two
/// adjacent grips whose rings overlap split the difference at the midpoint
/// rather than letting sibling order decide; ties go to the later sibling,
/// which is the one painted on top.
///
/// A candidate is resolved through the ordinary recursion first, so a
/// descendant inside the grip still wins and `hit_shape` is still honoured;
/// only a point genuinely in the ring — outside the child's real bounds —
/// resolves to the child itself. A candidate that resolves to nothing hands
/// over to the next-nearest, and finally to the normal walk.
///
/// `vetoes` is the parent's own per-point rejection
/// ([`Widget::accepts_child_hit`]),
/// applied here as well as in the ordinary walk — a grip must not win a
/// point the parent has already refused for it.
fn outset_hit(
&self,
children: &[WidgetId],
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
vetoes: &dyn Fn(WidgetId) -> bool,
) -> Option<WidgetId> {
// Almost every parent has no outset-declaring child at all, so the
// common case allocates nothing and returns on the first loop.
let mut candidates: Vec<(WidgetId, f32, bool)> = Vec::new();
// Walked topmost-first so that, after a STABLE ascending sort, two
// grips at exactly the same distance are resolved in paint order.
for &child in children.iter().rev() {
if !self.is_active(child) || Some(child) == exclude {
continue;
}
let Some(node) = self.get(child) else {
continue;
};
// A decorative or pass-through node never absorbs a press, so
// widening it would only punch a hole in whatever is behind it.
// `no_hit_slop` is the head of the precedence chain and turns off
// BOTH widening mechanisms.
if node.hit_transparent || node.event_pass_through || node.no_hit_slop {
continue;
}
let outset = node.widget.hit_outset(hit.kind(), hit.tokens());
let (top, bottom) = (finite(outset.top), finite(outset.bottom));
let (leading, trailing) = (finite(outset.leading), finite(outset.trailing));
if top <= 0.0 && bottom <= 0.0 && leading <= 0.0 && trailing <= 0.0 {
continue;
}
// The parent's per-point veto applies here too: a grip that the
// ordinary walk would refuse must not win by being offered first.
//
// Asked **after** the zero-outset test, not before. Almost no child
// declares an outset, and this predicate is a real per-point query
// (the `SceneView`'s is a snapshot scan), so asking it first made
// every hit test on a vetoing parent pay it twice per child — once
// here for children that were about to be skipped anyway, and once
// in the ordinary walk. The order does not change the answer: a
// child that survives to `candidates` is exactly one this used to
// reach.
if vetoes(child) {
continue;
}
let Some(space) = self.hit_space(child, point) else {
continue;
};
// Reading order → screen edges.
let (left, right) = match hit.layout_direction() {
crate::environment::LayoutDirection::LeftToRight => (leading, trailing),
crate::environment::LayoutDirection::RightToLeft => (trailing, leading),
};
let inflated = teksilo_canvas::Rect::new(
space.bounds.x - left,
space.bounds.y - top,
space.bounds.width + left + right,
space.bounds.height + top + bottom,
);
if !inflated.contains(space.bounds_point) {
continue;
}
let inside = space.bounds.contains(space.bounds_point);
let distance =
crate::pointer::hit_slop::rect_distance(space.bounds, space.bounds_point);
candidates.push((child, distance, inside));
}
if candidates.is_empty() {
return None;
}
candidates.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
for (child, _, inside) in candidates {
if let Some(found) = self.hit_test_recursive(child, point, exclude, hit) {
return Some(found);
}
// The ring: the point is outside the child's real bounds, so the
// ordinary recursion could never have found it, and the outset is
// the whole reason it is being offered.
if !inside {
return Some(child);
}
// Inside the bounds but the recursion declined (a `hit_shape`
// rejection, an empty pass-through): the outset has nothing to add,
// so hand back to the normal walk.
}
None
}
/// Resolve one node's transform for hit-testing: the point to test its own
/// bounds against, the point to hand its children, and its bounds.
///
/// The input point arrives in this node's parent-effective space. A
/// `set_transform` scope is composed by the render walker around this
/// node's subtree, so hit-testing mirrors it by inverse-applying the
/// transform once. *Which* rectangle the transform applies to depends
/// on whether it's a **content** transform or a **self** transform
/// (see `WidgetNode::content_transform`):
///
/// * A **content** transform (`content_transform`, e.g. `SceneView`) is
/// a fixed viewport: its bounds are a rectangle in PARENT space and
/// the transform pans / zooms only its CONTENT. Test the bounds
/// against the parent-space point; inverse-transform only for
/// descending into children, so the whole visible viewport stays
/// interactive regardless of pan / zoom. (Without this, panning the
/// content shifts the hittable region off the viewport — clicks /
/// wheel over the visible scene fall through to whatever is behind.)
/// * A **self** transform (`Scale` / `Rotate`, whose own bounds move
/// with the transform) inverse-transforms first, then tests its
/// bounds in the resulting local space (a click lands where the
/// scaled / rotated visual actually is).
///
/// Identity / missing transforms collapse both paths to the scalar
/// case, so the hot path stays cheap. `content_transform` is
/// `SceneView`-only today, so this only changes SceneView hit-testing;
/// `Scale` / `Rotate` (also `clips_children`) keep the self-transform
/// path.
///
/// `None` when the transform is singular (a collapsed axis) — that hides
/// the entire subtree visually, and hit-testing mirrors it.
fn hit_space(&self, id: WidgetId, point: teksilo_canvas::Point) -> Option<HitSpace> {
let transform = self
.get(id)
.and_then(|n| n.transform_prop.as_ref())
.map(|p| p.get())
.filter(|t| !t.is_identity());
let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
let child_point = match transform {
Some(t) => t.inverse()?.apply_point(point),
None => point,
};
let bounds_point = if content_transform {
point
} else {
child_point
};
Some(HitSpace {
bounds_point,
child_point,
bounds: self.bounds(id),
scale: transform
.as_ref()
.map(crate::pointer::hit_slop::min_singular_value)
.unwrap_or(1.0),
})
}
/// Every node the *miss-only* slop pass would consider for `point`, nearest
/// first, scoped to `start`'s subtree.
///
/// Public so a test — and the target-conformance audit — can inspect the
/// pass's reasoning rather than only its verdict. Returning candidates does
/// **not** mean one of them wins: see
/// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop) for the
/// bubble-path rule that decides.
///
/// # Eligibility
///
/// A node is a candidate only if all of the following hold. Each is pinned
/// by its own test in `widget_tree::hit_targeting_tests`.
///
/// * It earns a non-zero outset from its resolved [`HitSlop`] — which, by
/// the size formula, excludes anything already at least `up_to` on its
/// smaller axis. A scrim, a page, a list row are excluded by arithmetic.
/// * It would actually *do* something with the press:
/// [`takes_a_press`](Self::takes_a_press). Re-attributing to a node that
/// ignores presses would silently swallow one.
/// * It is **enabled** — its own `enabled_state` and every ancestor's.
/// * It is not **read-only**, as reported by the context's probe.
/// * It does not carry `no_hit_slop`, and it is not `event_pass_through`
/// (which absorbs nothing; its **children** stay eligible).
/// * It is not inside a `hit_transparent` subtree — those are pruned whole.
/// * No `clips_children` ancestor's **uninflated** rectangle excludes the
/// point: slop never reaches out of a scroller.
/// * Its [`Widget::hit_distance`] answers `Some(d)` with `0 < d ≤ outset`.
/// `d = 0` means the point is inside the shape, which is the exact pass's
/// business — the slop pass only ever re-attributes a genuine miss.
///
/// Distances are measured in each node's own space and converted to screen
/// dp through the accumulated
/// [`min_singular_value`](crate::pointer::hit_slop::min_singular_value) of
/// the transforms above it. For a chain of transforms the product of the
/// per-node minima is a lower bound on the true composed minimum, so the
/// reach under a stack of transforms errs towards being generous rather
/// than short.
///
/// [`HitSlop`]: crate::pointer::hit_slop::HitSlop
/// [`Widget::hit_distance`]: crate::widget::Widget::hit_distance
pub fn hit_candidates(
&self,
start: WidgetId,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
) -> Vec<HitCandidate> {
let mut out = Vec::new();
if hit.slop_enabled() {
self.collect_candidates(start, point, 1.0, true, exclude, hit, &mut out);
out.sort_by(|a, b| {
a.distance
.partial_cmp(&b.distance)
.unwrap_or(std::cmp::Ordering::Equal)
});
}
out
}
#[allow(clippy::too_many_arguments)]
fn collect_candidates(
&self,
id: WidgetId,
point: teksilo_canvas::Point,
scale: f32,
enabled: bool,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
out: &mut Vec<HitCandidate>,
) {
if !self.is_active(id) || Some(id) == exclude {
return;
}
let Some(node) = self.get(id) else { return };
// Decorative subtree: pruned whole, exactly as in the exact pass.
if node.hit_transparent {
return;
}
let Some(space) = self.hit_space(id, point) else {
return;
};
// Slop never escapes a clipping ancestor's UNINFLATED rectangle: a
// control scrolled out of a `ScrollArea` must not catch a press landing
// on the scroller's border.
if node.clips_children && !space.bounds.contains(space.bounds_point) {
return;
}
let enabled = enabled
&& node
.enabled_state
.as_ref()
.map(|state| state.get())
.unwrap_or(true);
let scale_children = scale * space.scale;
// A content transform leaves the node's own bounds in parent space; a
// self transform moves them with it.
let scale_self = if node.content_transform {
scale
} else {
scale_children
};
if enabled
&& !node.no_hit_slop
&& !node.event_pass_through
&& !hit.is_read_only(id)
&& self.takes_a_press(id)
{
let slop = node
.hit_slop
.or_else(|| node.widget.hit_slop(hit.kind(), hit.tokens()))
.unwrap_or_else(|| hit.default_slop());
let outset = slop.outset_for(space.bounds.size());
if outset > 0.0
&& let Some(local) = node.widget.hit_distance(space.bounds_point, space.bounds)
{
let distance = local * scale_self;
if distance > 0.0 && distance <= outset && distance.is_finite() {
out.push(HitCandidate {
id,
distance,
outset,
});
}
}
}
for &child in self.children(id) {
self.collect_candidates(
child,
space.child_point,
scale_children,
enabled,
exclude,
hit,
out,
);
}
}
/// Whether a press landing on this node would do anything at all — the
/// definition of an "eligible handler" for the slop pass's bubble-path
/// rule.
///
/// A node qualifies if it carries any pointer-facing handler (tap, multi
/// tap, long press, drag, swipe, pinch, the raw pointer stream, scroll) or
/// is focusable, and is enabled. Accessibility actions and key handlers do
/// not count: neither is reachable from a pointer.
pub fn takes_a_press(&self, id: WidgetId) -> bool {
let Some(node) = self.get(id) else {
return false;
};
if !self.is_enabled(id) {
return false;
}
let pointer_facing = |h: &crate::event_handlers::EventHandlers| {
h.on_tap.is_some()
|| h.on_double_tap.is_some()
|| h.on_triple_tap.is_some()
|| h.on_long_press.is_some()
|| h.on_drag.is_some()
|| h.on_swipe.is_some()
|| h.on_pinch.is_some()
|| h.on_pointer_event.is_some()
|| h.on_scroll.is_some()
};
pointer_facing(&node.handlers)
|| pointer_facing(&node.external_handlers)
|| node.node_focusable.unwrap_or(false)
}
/// Run the miss-only pass over `roots` and decide between it and `exact`.
///
/// The rule, in one place: the exact hit's **entire bubble path** is
/// examined, and a slop candidate wins only when that path carries no
/// eligible handler at all, or when the candidate is strictly closer than
/// the bubble owner's *uninflated* shape. That is what keeps a press on a
/// row label 5 dp from an inline checkbox on the row — the row owns the
/// press at distance zero, and nothing beats zero.
fn apply_slop(
&self,
roots: Vec<WidgetId>,
point: teksilo_canvas::Point,
exclude: Option<WidgetId>,
hit: &HitContext<'_>,
exact: Option<WidgetId>,
) -> Option<WidgetId> {
if !hit.slop_enabled() {
return exact;
}
let owner_distance = match exact.and_then(|target| self.bubble_owner(target, &roots)) {
Some(owner) => self.distance_to(owner, point, &roots).unwrap_or(0.0),
// Either nothing was hit, or what was hit ignores presses all the
// way up: there is nothing to beat.
None => f32::INFINITY,
};
if owner_distance <= 0.0 {
return exact;
}
// A grip that won its point through its own `Widget::hit_outset` made a
// deliberate claim *inside* the exact pass, and the miss-only pass must
// not take it back.
//
// Without this the two mechanisms fight, and the outset loses every
// time: a grip only ever claims a point at a positive distance from its
// own shape, so any slop-eligible node under its ring is strictly
// closer and wins. The rule, rather than the arithmetic: a ring is taken
// back wherever a neighbour is still small enough to earn a top-up of
// its own, so raising the density can LOWER a grip's reach — `up_to`
// grows from 24 to 44 dp and rows that earned nothing become candidates.
// It is not confined to the coarse densities either: at Compact a
// neighbour under 24 dp is already a candidate.
//
// The two measurements this rests on are pinned in
// teksilo-target-conformance by
// `an_outsets_claim_survives_the_slop_pass_in_the_shipped_controls`
// (a SearchField's clear button at Compact, a TableView's scroll bar at
// Touch), and the mechanism itself by
// `a_grip_that_won_through_its_outset_keeps_its_point_against_the_slop_pass`
// in this crate. Reverting this branch reddens all three. The precedence
// chain in `docs/density-and-targets.md` names one chain for both
// mechanisms, and this is what keeps it one.
if exact.is_some_and(|target| self.won_through_outset(target, point, &roots, hit)) {
return exact;
}
let mut best: Option<HitCandidate> = None;
for &root in roots.iter().rev() {
for candidate in self.hit_candidates(root, point, exclude, hit) {
if candidate.distance < owner_distance
&& best.is_none_or(|b| candidate.distance < b.distance)
{
best = Some(candidate);
}
}
}
best.map(|c| c.id).or(exact)
}
/// The deepest node on `target`'s own path (itself, then ancestors, up to
/// and including whichever of `roots` contains it) that would act on a
/// press.
fn bubble_owner(&self, target: WidgetId, roots: &[WidgetId]) -> Option<WidgetId> {
let mut current = Some(target);
while let Some(id) = current {
if self.takes_a_press(id) {
return Some(id);
}
if roots.contains(&id) {
return None;
}
current = self.get(id).and_then(|n| n.parent);
}
None
}
/// Whether `target`, or a node on its path to a root, claimed `point`
/// through its own [`Widget::hit_outset`] — the point sits outside that
/// node's real bounds and inside its inflated ones.
///
/// The predicate behind the outset's precedence over the miss-only pass in
/// [`apply_slop`](Self::apply_slop). The whole path is examined because the
/// pre-pass resolves a candidate *through* the ordinary recursion, so the
/// node the exact pass returns may be a descendant of the grip that won.
///
/// [`Widget::hit_outset`]: crate::widget::Widget::hit_outset
fn won_through_outset(
&self,
target: WidgetId,
point: teksilo_canvas::Point,
roots: &[WidgetId],
hit: &HitContext<'_>,
) -> bool {
let mut chain = vec![target];
let mut current = target;
while !roots.contains(¤t) {
match self.get(current).and_then(|n| n.parent) {
Some(parent) => {
chain.push(parent);
current = parent;
}
None => break,
}
}
chain.reverse();
let mut p = point;
for &node_id in &chain {
let Some(space) = self.hit_space(node_id, p) else {
return false;
};
let Some(node) = self.get(node_id) else {
return false;
};
if !node.no_hit_slop {
let outset = node.widget.hit_outset(hit.kind(), hit.tokens());
let (top, bottom) = (finite(outset.top), finite(outset.bottom));
let (leading, trailing) = (finite(outset.leading), finite(outset.trailing));
if top > 0.0 || bottom > 0.0 || leading > 0.0 || trailing > 0.0 {
let (left, right) = match hit.layout_direction() {
crate::environment::LayoutDirection::LeftToRight => (leading, trailing),
crate::environment::LayoutDirection::RightToLeft => (trailing, leading),
};
let inflated = teksilo_canvas::Rect::new(
space.bounds.x - left,
space.bounds.y - top,
space.bounds.width + left + right,
space.bounds.height + top + bottom,
);
if !space.bounds.contains(space.bounds_point)
&& inflated.contains(space.bounds_point)
{
return true;
}
}
}
p = space.child_point;
}
false
}
/// Distance from a root-space `point` to `id`'s own shape, in screen dp.
///
/// Walks down from whichever of `roots` owns `id` so the transforms are
/// applied in the same order the hit test applies them, and converts the
/// local distance through the accumulated minimum singular value.
fn distance_to(
&self,
id: WidgetId,
point: teksilo_canvas::Point,
roots: &[WidgetId],
) -> Option<f32> {
let mut chain = vec![id];
let mut current = id;
while !roots.contains(¤t) {
match self.get(current).and_then(|n| n.parent) {
Some(parent) => {
chain.push(parent);
current = parent;
}
None => break,
}
}
chain.reverse();
let mut p = point;
let mut scale = 1.0_f32;
for (index, &node_id) in chain.iter().enumerate() {
let space = self.hit_space(node_id, p)?;
if index + 1 == chain.len() {
let scale_self = if self.get(node_id).map(|n| n.content_transform)? {
scale
} else {
scale * space.scale
};
let local = self
.get(node_id)?
.widget
.hit_distance(space.bounds_point, space.bounds)?;
return Some(local * scale_self);
}
scale *= space.scale;
p = space.child_point;
}
None
}
/// Iterate over all active widget IDs.
///
/// Allocating wrapper around [`Self::active_ids_iter`]. Hot-path
/// callers that hold `&self` for the whole iteration should call
/// the iterator directly to avoid the per-call `Vec` allocation;
/// callers that need an owned snapshot (because they mutate
/// arena state inside the loop) should use
/// [`Self::fill_active_ids`] with a reusable buffer.
pub fn active_ids(&self) -> Vec<WidgetId> {
self.active_ids_iter().collect()
}
/// Stream all active widget IDs without allocating. The iterator
/// borrows the arena, so the caller cannot mutate it while
/// iterating — for that case use [`Self::fill_active_ids`].
pub fn active_ids_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
self.nodes
.iter()
.filter(|(_, node)| node.activation == ActivationState::Active)
.map(|(id, _)| id)
}
/// Fill `out` with every active widget ID. Clears `out` first so
/// callers can reuse a long-lived buffer across calls. Use this
/// when the iteration site needs an owned snapshot independent
/// of the arena borrow (typically because it mutates per-widget
/// state with `arena.get_mut(id)` inside the loop).
pub fn fill_active_ids(&self, out: &mut Vec<WidgetId>) {
out.clear();
out.extend(self.active_ids_iter());
}
/// Set a widget subtree to dormant state (state preserved, not rendered).
/// Recursively dormants all children.
///
/// The node named here is marked self-parked (`WidgetNode::self_dormant`);
/// the descendants swept along by the recursion are not, since their
/// dormancy belongs to this ancestor rather than to them. That distinction
/// is what lets [`activate`](Self::activate) put the subtree back exactly as
/// it found it instead of waking content that was already closed.
///
/// **Returns the whole parked subtree**, `id` first, because a caller that
/// cannot see which nodes went to sleep cannot cancel the pointers holding
/// them. Dormancy is invisible to hit-testing and to dispatch, so a widget
/// parked mid-interaction keeps whatever the press latched and never
/// receives another event: the ids are how the tree finds it and tells it
/// to let go. Every caller is audited in `docs/touch-and-pen.md` §3.3.
pub fn set_dormant(&mut self, id: WidgetId) -> Vec<WidgetId> {
let mut parked = Vec::new();
self.park(id, true, &mut parked);
parked
}
/// [`set_dormant`](Self::set_dormant)'s body, plus whether `id` is being
/// parked on its own account or dragged along by an ancestor, and the
/// accumulator the parked ids land in.
///
/// A node already self-parked stays that way when an ancestor sweeps over
/// it — the flag is only ever set here, never cleared, so nesting two
/// dormancy cycles cannot lose the inner one.
fn park(&mut self, id: WidgetId, on_its_own_account: bool, parked: &mut Vec<WidgetId>) {
if let Some(node) = self.nodes.get_mut(id) {
let was_active = node.activation == ActivationState::Active;
node.activation = ActivationState::Dormant;
if on_its_own_account {
node.self_dormant = true;
}
// Record the Active→Dormant transition for nodes that opted into an
// activation signal; the signal is fired later by
// `WidgetTree::flush_activation_signals`, not here — see the
// `pending_activation_changes` field docs.
if was_active && node.activation_signal.is_some() {
self.pending_activation_changes.push((id, false));
}
parked.push(id);
}
let children: Vec<WidgetId> = self.children(id).to_vec();
for child in children {
self.park(child, false, parked);
}
}
/// Activate a dormant widget subtree (triggers relayout and repaint).
/// Recursively activates all children, **except** those a descendant
/// widget has independently gated off via `visible_when(false)`.
///
/// The directly-targeted `id` is always activated (the caller asked for
/// it). When recursing, a child whose own `visible_state` currently
/// evaluates to `false` is left dormant along with its subtree: it is
/// hidden by its own gate, not by the ancestor's dormancy, so a parent
/// reactivation must not wake it. This is what keeps a `ComboBox`'s
/// closed dropdown panel, a collapsed overlay, or any `visible_when`-
/// gated child from leaking back to the screen when an ancestor (e.g. a
/// `Toolbar` item reappearing from overflow) is re-activated. The
/// per-pass visibility reconciliation
/// ([`visibility_checks_iter`](Self::visibility_checks_iter)) still owns
/// the eventual activate/dormant transitions when the gate flips.
pub fn activate(&mut self, id: WidgetId) {
if let Some(node) = self.nodes.get_mut(id) {
// Only Dormant→Active is a real "show" transition. Guard on
// `== Dormant` (not `!= Active`) so a `Destroyed` node — or any
// future non-Active state — is never resurrected or signalled.
let was_dormant = node.activation == ActivationState::Dormant;
node.activation = ActivationState::Active;
node.self_dormant = false;
node.dirty.needs_layout = true;
node.dirty.needs_paint = true;
if was_dormant && node.activation_signal.is_some() {
self.pending_activation_changes.push((id, true));
}
}
let children: Vec<WidgetId> = self.children(id).to_vec();
for child in children {
let asleep_on_its_own_account = self
.nodes
.get(child)
.map(|n| {
n.self_dormant
|| n.visible_state
.as_ref()
.map(|vs| !vs.get())
.unwrap_or(false)
})
.unwrap_or(false);
if asleep_on_its_own_account {
continue;
}
self.activate(child);
}
}
/// Destroy a widget and remove it from the arena entirely.
/// Recursively destroys all children. State is gone.
pub fn destroy(&mut self, id: WidgetId) {
self.roots_dirty = true;
let children: Vec<WidgetId> = self.children(id).to_vec();
for child in children {
self.destroy(child);
}
self.remove_node(id);
}
/// Remove a *single* node: unlink it from its parent's child list and drop
/// it from the arena. Does **not** recurse into its children.
///
/// The caller owns the recursion. This exists for
/// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) /
/// the reconciling rebuild path, which walks the subtree itself so it can
/// honour re-parenting — a child re-homed into the surviving tree must NOT
/// be torn down via this node's now-stale `children` list. Using
/// [`destroy`](Self::destroy) there would re-recurse that stale list and
/// destroy the re-homed survivor.
pub fn remove_node(&mut self, id: WidgetId) {
self.roots_dirty = true;
if let Some(parent_id) = self.parent(id)
&& let Some(parent) = self.nodes.get_mut(parent_id)
{
parent.children.retain(|&c| c != id);
}
self.nodes.remove(id);
}
/// Drain the buffered Active↔Dormant transitions recorded since the last
/// call. Each `(id, active)` is fed to `WidgetTree::flush_activation_signals`
/// which fires the node's `activation_signal` — at the tree level, outside
/// any arena mutation.
pub(crate) fn take_activation_changes(&mut self) -> Vec<(WidgetId, bool)> {
std::mem::take(&mut self.pending_activation_changes)
}
/// Record that `id` installed an `effective_enabled_signal`. Idempotent —
/// the signal is install-or-reuse, so a rebuild re-registering the same
/// node must not grow the list.
pub(crate) fn watch_effective_enabled(&mut self, id: WidgetId) {
if !self.effective_enabled_watchers.contains(&id) {
self.effective_enabled_watchers.push(id);
}
}
/// The nodes carrying an `effective_enabled_signal`, for the per-pass
/// refresh. Cloned so the caller can recompute `is_enabled` (an immutable
/// ancestor walk) without holding a borrow on the arena.
pub(crate) fn effective_enabled_watchers(&self) -> Vec<WidgetId> {
self.effective_enabled_watchers.clone()
}
/// Drop watchers whose node is gone (destroyed / rebuilt away).
pub(crate) fn prune_effective_enabled_watchers(&mut self) {
self.effective_enabled_watchers
.retain(|id| self.nodes.contains_key(*id));
}
pub fn is_active(&self, id: WidgetId) -> bool {
self.nodes
.get(id)
.map(|n| n.activation == ActivationState::Active)
.unwrap_or(false)
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn mark_all_clean(&mut self) {
for (_, node) in self.nodes.iter_mut() {
node.dirty = DirtyFlags::default();
}
}
pub fn any_needs_layout(&self) -> bool {
self.nodes
.values()
.any(|n| n.activation == ActivationState::Active && n.dirty.needs_layout)
}
pub fn any_needs_paint(&self) -> bool {
self.nodes
.values()
.any(|n| n.activation == ActivationState::Active && n.dirty.needs_paint)
}
pub fn mark_needs_paint(&mut self, id: WidgetId) {
if let Some(node) = self.nodes.get_mut(id) {
node.dirty.needs_paint = true;
}
}
/// Recursively mark a widget and all its descendants needs_paint.
/// Used by callers that want a fresh paint of an entire subtree
/// — e.g. a rich tooltip whose dwell indicator child would
/// otherwise reuse its cached_paint while the parent re-runs
/// some per-frame logic.
pub fn mark_subtree_needs_paint(&mut self, id: WidgetId) {
if let Some(node) = self.nodes.get_mut(id) {
node.dirty.needs_paint = true;
}
let children: Vec<WidgetId> = self.children(id).to_vec();
for child in children {
self.mark_subtree_needs_paint(child);
}
}
pub fn mark_needs_layout(&mut self, id: WidgetId) {
if let Some(node) = self.nodes.get_mut(id) {
node.dirty.needs_layout = true;
node.dirty.needs_paint = true;
}
}
/// Mark a widget as needing its `build()` re-run.
/// Also marks for layout and paint since rebuilt children need both.
pub fn mark_needs_rebuild(&mut self, id: WidgetId) {
if let Some(node) = self.nodes.get_mut(id) {
node.dirty.needs_rebuild = true;
node.dirty.needs_layout = true;
node.dirty.needs_paint = true;
}
}
/// Collect widgets that need their `build()` re-run (data-driven rebuild).
/// Only returns active widgets with `needs_rebuild == true`.
///
/// Allocating wrapper around [`Self::needs_rebuild_iter`]. Prefer
/// the iterator on hot paths.
pub fn collect_needs_rebuild(&self) -> Vec<WidgetId> {
self.needs_rebuild_iter().collect()
}
/// Stream widgets that need `build()` re-run without allocating.
///
/// `needs_rebuild` is set only by `BindingLevel::Rebuild` bindings —
/// i.e. on composing widgets that explicitly want `build()` re-run
/// when their data model changes. It is intentionally NOT gated on
/// the widget currently having children: a data-driven widget that
/// builds its children directly and starts EMPTY (e.g. the toast
/// host with no toasts yet, an empty list that renders rows without
/// a persistent container) must still rebuild to materialise its
/// FIRST child. `rebuild_single_widget` handles a childless widget
/// correctly (nothing to tear down, then it adopts `build()`'s
/// output).
pub fn needs_rebuild_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
self.nodes
.iter()
.filter(|(_, n)| n.activation == ActivationState::Active && n.dirty.needs_rebuild)
.map(|(id, _)| id)
}
/// Check all widgets with visible_state bindings and return
/// (id, is_currently_active, should_be_visible) tuples.
///
/// Allocating wrapper around [`Self::visibility_checks_iter`].
pub fn visibility_checks(&self) -> Vec<(WidgetId, bool, bool)> {
self.visibility_checks_iter().collect()
}
/// Stream widgets with `visible_state` bindings without
/// allocating. Each entry is `(id, is_currently_active,
/// should_be_visible)`.
pub fn visibility_checks_iter(&self) -> impl Iterator<Item = (WidgetId, bool, bool)> + '_ {
self.nodes.iter().filter_map(|(id, node)| {
node.visible_state.as_ref().map(|state| {
let is_active = node.activation == ActivationState::Active;
let should_be_visible = state.get();
(id, is_active, should_be_visible)
})
})
}
/// Check if a widget is effectively enabled, walking up the parent chain.
///
/// Returns `false` if the widget itself or any ancestor has `enabled_state`
/// bound to `false`. This lets containers like `GroupBox` disable a whole
/// subtree by binding a single signal on their content wrapper.
pub fn is_enabled(&self, id: WidgetId) -> bool {
let mut current = Some(id);
while let Some(node_id) = current {
if let Some(node) = self.nodes.get(node_id) {
if let Some(ref state) = node.enabled_state
&& !state.get()
{
return false;
}
current = node.parent;
} else {
return true;
}
}
true
}
/// Set a per-child alignment override on a widget.
pub fn set_alignment_override(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
if let Some(node) = self.get_mut(id) {
node.alignment_override = Some(alignment);
}
}
/// Mark a widget as clipping its children (scroll area, overflow hidden).
pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
if let Some(node) = self.get_mut(id) {
node.clips_children = clips;
}
}
/// The OS-IME descriptor for the widget at `id`, or `None` if the node
/// is not a text-input surface (the default) or the id is unknown. The
/// platform IME layer queries this for the focused widget to decide
/// whether to enable the OS input method and with which purpose.
pub fn ime_context(&self, id: WidgetId) -> Option<crate::ime::ImeContext> {
self.get(id).and_then(|n| n.ime)
}
/// Set (or clear, with `None`) the OS-IME descriptor for the widget at
/// `id`.
pub fn set_ime_context(&mut self, id: WidgetId, ime: Option<crate::ime::ImeContext>) {
if let Some(node) = self.get_mut(id) {
node.ime = ime;
}
}
/// Apply a `HandlerSet` to an existing node, merging handlers and
/// transferring node-level metadata (focusable, cursor, clips,
/// context menu). The `scope` argument controls whether the
/// handlers go into the rebuild-cleared `handlers` slot or the
/// persistent `external_handlers` slot.
pub(crate) fn apply_handler_set(
&mut self,
id: WidgetId,
handler_set: crate::widget_builder::HandlerSet,
scope: HandlerScope,
) {
if let Some(node) = self.get_mut(id) {
let target = match scope {
HandlerScope::Own => &mut node.handlers,
HandlerScope::External => &mut node.external_handlers,
};
let existing = std::mem::take(target);
*target = existing.merge(handler_set.handlers);
if let Some(focusable) = handler_set.focusable {
node.node_focusable = Some(focusable);
}
if let Some(tab_index) = handler_set.tab_index {
node.node_tab_index = Some(tab_index);
}
if let Some(cursor) = handler_set.cursor {
node.node_cursor = Some(cursor);
}
if let Some(clips) = handler_set.clips_children {
node.clips_children = clips;
}
if let Some(ime) = handler_set.ime {
node.ime = Some(ime);
}
if let Some(pass_through) = handler_set.event_pass_through {
node.event_pass_through = pass_through;
}
if let Some(dead_zone) = handler_set.gesture_dead_zone {
node.gesture_dead_zone = dead_zone;
}
if let Some(role) = handler_set.long_press_role {
node.long_press_role = role;
}
if let Some(action) = handler_set.touch_action {
node.touch_action = action;
}
if let Some(claim) = handler_set.pan_claim {
node.pan_claim = Some(claim);
}
if let Some(behavior) = handler_set.overscroll_behavior {
node.overscroll_behavior = behavior;
}
if let Some(activation) = handler_set.drag_activation {
node.drag_activation = activation;
}
if let Some(policy) = handler_set.multi_contact {
node.multi_contact = policy;
}
if let Some(keyboard_capture) = handler_set.keyboard_capture {
node.keyboard_capture = keyboard_capture;
}
if let Some(hit_transparent) = handler_set.hit_transparent {
node.hit_transparent = hit_transparent;
}
if let Some(slop) = handler_set.hit_slop {
node.hit_slop = Some(slop);
}
if let Some(no_slop) = handler_set.no_hit_slop {
node.no_hit_slop = no_slop;
}
if handler_set.context_menu_factory.is_some() {
node.context_menu_factory = handler_set.context_menu_factory;
}
if let Some(sig) = handler_set.focus_within {
node.focus_within_signal = Some(sig);
}
if let Some(sig) = handler_set.hover_within {
node.hover_within_signal = Some(sig);
}
// Mirror builder-level accessibility overrides + subtree mode
// onto the persistent WidgetNode so the accessibility tree
// walker (and the event dispatcher, for action callbacks) can
// read them after handler extraction.
if handler_set.access.is_some() {
// Merged, not assigned: a node can already carry a
// block from its builder chain, and replacing it
// drops everything in it (see
// `AccessibilityOverrides::merge_from`).
match (&mut node.access_overrides, handler_set.access) {
(Some(existing), Some(incoming)) => existing.merge_from(*incoming),
(slot, incoming) => *slot = incoming,
}
}
if let Some(mode) = handler_set.access_subtree {
node.access_subtree = mode;
}
}
}
/// Get a widget's alignment override, if any.
pub fn alignment_override(&self, id: WidgetId) -> Option<teksilo_tokens::Alignment> {
self.get(id)?.alignment_override
}
/// Temporarily take the widget box out of a node (for rebuild).
/// The node remains in the arena with a placeholder.
pub fn take_widget(&mut self, id: WidgetId) -> Option<Box<dyn Widget>> {
let node = self.nodes.get_mut(id)?;
// Replace with a minimal placeholder
let taken = std::mem::replace(&mut node.widget, Box::new(PlaceholderWidget));
Some(taken)
}
/// Restore a widget box that was previously taken out.
pub fn restore_widget(&mut self, id: WidgetId, widget: Box<dyn Widget>) {
if let Some(node) = self.nodes.get_mut(id) {
node.widget = widget;
}
}
/// Walk up the parent chain from `id` and mark each ancestor as needing layout.
/// Called when a relayout-level binding changes, since a child's size change
/// may affect its parent's size, and so on up to the root.
pub fn mark_ancestors_need_layout(&mut self, id: WidgetId) {
let mut current = self.parent(id);
while let Some(pid) = current {
if let Some(node) = self.get_mut(pid) {
node.dirty.needs_layout = true;
node.dirty.needs_paint = true;
}
current = self.parent(pid);
}
}
/// Mark all widgets as needing layout and paint (e.g. after a theme change).
/// Also clears per-widget paint caches since the visual output is stale.
pub fn mark_all_dirty(&mut self) {
for (_, node) in self.nodes.iter_mut() {
node.dirty.needs_layout = true;
node.dirty.needs_paint = true;
node.cached_paint = None;
node.cached_post_paint = None;
}
}
/// Mark every active node for repaint **without** touching layout, rebuild,
/// or the per-widget paint caches. Used for a global visual change that
/// leaves geometry untouched — the window's active-state flip (caret
/// hiding, selection desaturation, `DimWhenInactive`). Lighter than
/// [`Self::mark_all_dirty`]: the paint walker re-runs `paint()` for any
/// node whose `needs_paint` is set and overwrites its cache, so there is no
/// need to clear `cached_paint`; and skipping `needs_layout` avoids a
/// pointless relayout pass. Dormant nodes are skipped — they don't paint,
/// and they're re-marked on reactivation.
pub fn mark_all_needs_paint_only(&mut self) {
for (_, node) in self.nodes.iter_mut() {
if node.activation == ActivationState::Active {
node.dirty.needs_paint = true;
}
}
}
/// Resolve the effective theme for a widget by walking ancestors and
/// applying any theme overrides encountered along the way.
/// The base theme is the tree-level default.
pub fn resolve_theme<'a>(
&self,
id: WidgetId,
base: &'a crate::styles::Theme,
) -> std::borrow::Cow<'a, crate::styles::Theme> {
// Fast path: if no widget has a theme override, borrow the base
// theme — no clone. This is the per-widget hot path during layout
// and paint, so avoiding `Theme::clone()` (which clones the
// typography token strings and bumps ~42 style-slot `Rc`s) here
// saves that work on every node, every pass, in the common case.
if self.theme_override_count == 0 {
return std::borrow::Cow::Borrowed(base);
}
// Collect ancestor chain from root to widget
let mut chain = vec![id];
let mut current = self.parent(id);
while let Some(pid) = current {
chain.push(pid);
current = self.parent(pid);
}
chain.reverse(); // root first
let mut theme = base.clone();
for nid in chain {
if let Some(node) = self.nodes.get(nid)
&& let Some(ovr) = &node.theme_override
{
(ovr.func)(&mut theme);
}
}
std::borrow::Cow::Owned(theme)
}
}
impl Default for WidgetArena {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_widgets::FillWidget;
use teksilo_canvas::SizeProposal;
fn key(w: Option<f32>, h: Option<f32>) -> ProposalKey {
ProposalKey::from_proposal(SizeProposal {
width: w,
height: h,
})
}
#[test]
fn activate_skips_a_child_gated_off_by_visible_state() {
// Reactivating a subtree must not wake a child that its own widget
// has gated off via `visible_when(false)` — e.g. a ComboBox's closed
// dropdown panel, or a collapsed overlay. Regression for ghost
// dropdown rows after a `visible_when` collapse→reappear cycle.
let mut arena = WidgetArena::new();
let parent = arena.insert(Box::new(FillWidget::new()));
let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
let gated_child = arena.insert_child(parent, Box::new(FillWidget::new()));
// The gated child is hidden by its own visibility gate.
if let Some(node) = arena.get_mut(gated_child) {
node.visible_state = Some(Prop::Static(false));
}
arena.set_dormant(parent);
assert!(!arena.is_active(gated_child));
arena.activate(parent);
assert!(arena.is_active(parent), "the targeted node activates");
assert!(
arena.is_active(visible_child),
"an ungated child activates with its parent"
);
assert!(
!arena.is_active(gated_child),
"a visible_when(false) child stays dormant when its parent reactivates"
);
}
#[test]
fn activate_skips_a_child_parked_directly_by_set_dormant() {
// The ungated twin of the test above, and the one that was missing.
//
// Widgets that pre-build hidden content register it as a child with
// `ctx.add(..)` + `ctx.set_dormant(..)` and show it through an overlay:
// `SplitButton` and `MenuBar` menus, `Popover`, `Snackbar`, the date
// editors' calendars. Such a child carries no `visible_state`, so the
// gate check alone let an ancestor's dormancy cycle wake it — and it
// then rendered inline, with no overlay behind it, because the overlay
// presentation never ran. Seen as export menu-item labels floating
// under the title bar after leaving a mode that parked the shell.
let mut arena = WidgetArena::new();
let parent = arena.insert(Box::new(FillWidget::new()));
let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
let menu_row = arena.insert_child(menu, Box::new(FillWidget::new()));
// The widget parks its own closed menu — no gate involved.
arena.set_dormant(menu);
assert!(!arena.is_active(menu));
// An ancestor now goes dormant and comes back.
arena.set_dormant(parent);
arena.activate(parent);
assert!(arena.is_active(parent), "the targeted node activates");
assert!(
arena.is_active(visible_child),
"an ordinary child activates with its parent"
);
assert!(
!arena.is_active(menu),
"the ancestor's dormancy cycle woke a menu that was closed before it \
started — its content is now on screen with no overlay behind it"
);
assert!(
!arena.is_active(menu_row),
"the closed menu's own subtree woke with it"
);
// …and opening it still works: activating by id is how the overlay
// shows this content, so it must clear the self-parked mark.
arena.activate(menu);
assert!(arena.is_active(menu), "the menu can still be opened");
assert!(arena.is_active(menu_row), "…along with its rows");
}
#[test]
fn a_reopened_menu_parks_again_and_survives_the_next_cycle() {
// The flag must be re-armed by every `set_dormant`, not just the first:
// open the menu, close it, then put an ancestor through another
// dormancy cycle. Without re-arming, the second cycle leaks.
let mut arena = WidgetArena::new();
let parent = arena.insert(Box::new(FillWidget::new()));
let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
arena.set_dormant(menu);
arena.activate(menu); // opened
arena.set_dormant(menu); // dismissed
arena.set_dormant(parent);
arena.activate(parent);
assert!(
!arena.is_active(menu),
"a menu that was opened once no longer stays closed across a \
dormancy cycle"
);
}
#[test]
fn an_ancestor_cycle_does_not_strand_an_open_menu() {
// The mirror risk of the fix: `park` marks only the node it is given,
// so a menu that is *open* when an ancestor parks must come back with
// that ancestor rather than being stranded closed.
let mut arena = WidgetArena::new();
let parent = arena.insert(Box::new(FillWidget::new()));
let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
arena.set_dormant(menu);
arena.activate(menu); // open when the ancestor parks
arena.set_dormant(parent);
arena.activate(parent);
assert!(
arena.is_active(menu),
"an open menu was stranded closed by its ancestor's dormancy cycle"
);
}
#[test]
fn proposal_key_distinguishes_none_from_zero() {
// `None` (ask for ideal) must not collide with `Some(0.0)` (give zero).
assert_ne!(key(None, None), key(Some(0.0), None));
assert_ne!(key(Some(0.0), None), key(None, Some(0.0)));
}
#[test]
fn proposal_key_canonicalizes_signed_zero_and_nan() {
assert_eq!(key(Some(-0.0), None), key(Some(0.0), None));
assert_eq!(key(Some(f32::NAN), None), key(Some(f32::NAN), None));
}
#[test]
fn proposal_key_separates_distinct_values_and_axes() {
assert_ne!(key(Some(1.0), None), key(Some(2.0), None));
// Same scalar on different axes must not collide.
assert_ne!(key(Some(10.0), None), key(None, Some(10.0)));
}
#[test]
fn insert_and_retrieve() {
let mut arena = WidgetArena::new();
let id = arena.insert(Box::new(FillWidget::new()));
assert!(arena.get(id).is_some());
assert_eq!(arena.len(), 1);
}
#[test]
fn new_widget_is_dirty() {
let mut arena = WidgetArena::new();
let id = arena.insert(Box::new(FillWidget::new()));
let node = arena.get(id).unwrap();
assert!(node.dirty.needs_layout);
assert!(node.dirty.needs_paint);
}
#[test]
fn roots_returns_parentless_widgets() {
let mut arena = WidgetArena::new();
let root = arena.insert(Box::new(FillWidget::new()));
let _child = arena.insert_child(root, Box::new(FillWidget::new()));
let roots = arena.roots();
assert_eq!(roots.len(), 1);
assert_eq!(roots[0], root);
}
#[test]
fn content_transform_node_claims_viewport_in_parent_space() {
// A content-transform node (the SceneView pattern) is a fixed
// viewport: its bounds are tested in PARENT space and the transform
// only positions its content, so the whole visible viewport stays
// hittable regardless of the content pan/zoom. Before the fix, the
// bounds were tested in content space, so a content pan shifted the
// hittable region off the viewport.
use teksilo_canvas::{Point, Rect, Transform2D};
let mut arena = WidgetArena::new();
let id = arena.insert(Box::new(FillWidget::new()));
{
let node = arena.get_mut(id).unwrap();
node.bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
node.clips_children = true;
node.content_transform = true;
// Content panned by (50, 30).
node.transform_prop = Some(Prop::Static(Transform2D::translate(50.0, 30.0)));
}
// Points across the whole parent-space viewport hit, regardless of the
// pan (these all missed before the fix).
assert_eq!(arena.hit_test_at(Point::new(10.0, 10.0), None), Some(id));
assert_eq!(arena.hit_test_at(Point::new(100.0, 50.0), None), Some(id));
assert_eq!(arena.hit_test_at(Point::new(199.0, 99.0), None), Some(id));
// Outside the viewport: miss.
assert_eq!(arena.hit_test_at(Point::new(250.0, 50.0), None), None);
}
#[test]
fn self_transform_node_tests_bounds_in_local_space() {
// Regression guard: a *self* transform wrapper (Scale / Rotate, NOT a
// content transform) keeps the original semantics — its own bounds
// move with the transform, so the point is inverse-transformed before
// the bounds test. `clips_children` is irrelevant here (Scale clips
// too); only `content_transform` selects the viewport path.
use teksilo_canvas::{Point, Rect, Transform2D};
let mut arena = WidgetArena::new();
let id = arena.insert(Box::new(FillWidget::new()));
{
let node = arena.get_mut(id).unwrap();
node.bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
node.clips_children = true; // Scale clips, but is NOT content_transform.
node.content_transform = false;
// Visually scaled to 50x50 around the origin.
node.transform_prop = Some(Prop::Static(Transform2D::scale(0.5, 0.5)));
}
// Inside the scaled-down 50x50 visual → hit.
assert_eq!(arena.hit_test_at(Point::new(25.0, 25.0), None), Some(id));
// Past the scaled-down visual (but inside the un-scaled 100x100 bounds
// in parent space) → miss, because the bounds test is in local space.
assert_eq!(arena.hit_test_at(Point::new(75.0, 75.0), None), None);
}
#[test]
fn nested_content_transform_nodes_each_claim_their_viewport() {
// A content-transform node embedded inside another (the nested-
// SceneView case): each level tests its own viewport bounds in its
// parent's space, and only the transform is applied when descending.
// The inner viewport stays hittable regardless of either node's pan.
use teksilo_canvas::{Point, Rect, Transform2D};
let mut arena = WidgetArena::new();
let outer = arena.insert(Box::new(FillWidget::new()));
let inner = arena.insert_child(outer, Box::new(FillWidget::new()));
{
let n = arena.get_mut(outer).unwrap();
n.bounds = Rect::new(0.0, 0.0, 200.0, 200.0);
n.clips_children = true;
n.content_transform = true;
n.transform_prop = Some(Prop::Static(Transform2D::translate(20.0, 20.0)));
}
{
let n = arena.get_mut(inner).unwrap();
// Inner viewport expressed in the OUTER's content space.
n.bounds = Rect::new(10.0, 10.0, 50.0, 50.0);
n.clips_children = true;
n.content_transform = true;
n.transform_prop = Some(Prop::Static(Transform2D::translate(5.0, 5.0)));
}
// Screen (40,40) → outer-content (20,20) ∈ inner viewport → reaches inner.
assert_eq!(arena.hit_test_at(Point::new(40.0, 40.0), None), Some(inner));
// Screen (5,5) → outer-content (-15,-15) ∉ inner viewport → reaches outer.
assert_eq!(arena.hit_test_at(Point::new(5.0, 5.0), None), Some(outer));
}
/// Accepts only the right half of its bounds via `hit_shape`; the left
/// half is rejected so a click there falls through to a sibling beneath.
#[derive(Debug)]
struct RightHalfWidget;
impl crate::widget::Widget for RightHalfWidget {
fn layout_response(
&self,
proposal: teksilo_canvas::SizeProposal,
_ctx: &crate::widget::LayoutContext,
) -> crate::widget::LayoutResponse {
proposal.resolve(0.0, 0.0).into()
}
fn hit_shape(
&self,
local_point: teksilo_canvas::Point,
bounds: teksilo_canvas::Rect,
) -> bool {
local_point.x >= bounds.x + bounds.width / 2.0
}
}
#[test]
fn hit_shape_rejection_falls_through_to_sibling_underneath() {
// Two overlapping siblings under a common parent. `lower` is a
// full-rect FillWidget; `upper` (inserted later → painted on top,
// hit-tested first) rejects its left half via `hit_shape`. A click in
// the rejected left half must reach `lower` underneath; a click in the
// accepted right half must hit `upper`.
use teksilo_canvas::{Point, Rect};
let mut arena = WidgetArena::new();
let parent = arena.insert(Box::new(FillWidget::new()));
let lower = arena.insert_child(parent, Box::new(FillWidget::new()));
let upper = arena.insert_child(parent, Box::new(RightHalfWidget));
for id in [parent, lower, upper] {
arena.get_mut(id).unwrap().bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
}
// Right half: upper accepts → hit upper.
assert_eq!(arena.hit_test_at(Point::new(75.0, 50.0), None), Some(upper));
// Left half: upper rejects via hit_shape → falls through to lower.
assert_eq!(arena.hit_test_at(Point::new(25.0, 50.0), None), Some(lower));
}
}