incular-runtime 0.1.1

Application runtime and scheduling foundations for Incular
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
use crate::application_types::{
    ApplicationLifecycle, LifecycleTransition, RuntimeErrorReport, WindowError,
};
#[cfg(feature = "devtools")]
use crate::environment::DEV_TASK_COMPLETION;
#[cfg(feature = "devtools")]
use crate::environment::ReactiveRootId;
use crate::environment::{
    BuildScope, BuildScopeGuard, EnvironmentFields, InitialBuildDependencies, ReactiveQueue,
    environment_change_mask, install_focus_scope_watch,
};
use crate::profiling;
use crate::profiling::FrameTimings;
#[cfg(not(target_arch = "wasm32"))]
use crate::tasks::TokioHandle;
use crate::tasks::{
    self, RuntimeDiagnostics, RuntimeSpawner, RuntimeWake, Task, TaskFailure, TaskHandle,
    TaskScope, UiDispatcher,
};
use crate::text_shortcuts::TextShortcutPlatform;
use crate::undo::UndoHistoryController;
use crate::window_commands::{WindowHandle, WindowOpener};
use crate::window_state::WindowManager;
use incular_config::{Constraints, RuntimeEnvironment};
use incular_core::time::Instant;
use incular_core::{
    Code, ImeEvent, InputEvent, KeyboardEvent, Offset, PRIMARY_POINTER_BUTTON, PointerPhase,
    PointerSampleMetadata, Rect,
};
use incular_platform::{
    Clipboard, ClipboardCapabilities, ClipboardError, ClipboardWriteReport, DataTransfer,
    ExternalDragEvent, ExternalDragResponse, MemoryClipboard, PlatformEvent, PlatformLifecycle,
    TextInputAction, TextInputClientId, TextInputCommand, TextInputConfiguration, TextInputState,
    TextInputType, TransferReadRequest, WindowId, WindowMetrics, WindowOperation, WindowOptions,
};
use incular_rendering::DisplayList;
use incular_semantics::{SemanticAction, SemanticNodeId};
use incular_text::TextEditingValue;
#[cfg(feature = "devtools")]
use incular_widgets::internal::InvalidationCause;
use incular_widgets::internal::{
    ActionId, Diagnostics, ElementId, MouseCursor, PlatformMenuBinding, PointerDeviceKind,
    PointerEvent, PointerHitTest, RawPointerEvent, TextEditingController, TextRange, TextSelection,
    TreeError, WidgetTree, WindowInteraction,
};
use incular_widgets::{TextInputActionHint, TextInputTypeHint, Widget};
use std::{
    cell::{Cell, RefCell},
    collections::{HashMap, VecDeque},
    rc::{Rc, Weak},
    sync::atomic::{AtomicU64, Ordering},
};

mod text_actions;
mod text_gestures;

/// Sequence numbering runtime driver domains so outlet ownership errors
/// can name the runtimes involved.
static RUNTIME_SEQUENCE: AtomicU64 = AtomicU64::new(1);

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FrameStats {
    pub updated_elements: usize,
    pub rebuilt_elements: u64,
    pub laid_out_render_objects: u64,
    pub repainted_render_objects: u64,
    pub composited: u64,
    pub active_animations: u64,
    pub display_list_commands: usize,
    pub requested_another_frame: bool,
    /// Monotonic per-phase CPU durations. Phases never nest.
    pub timings: FrameTimings,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EventTarget {
    pub element: ElementId,
    pub action: Option<ActionId>,
}
/// Debug-facing focus state without exposing native event-loop details.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FocusDiagnostics {
    pub focused_element: Option<ElementId>,
    pub text_pointer_capture: Option<ElementId>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EditingDiagnostics {
    pub key_down_received: u64,
    pub key_up_received: u64,
    pub backspace_commands: u64,
    pub delete_commands: u64,
    pub text_commits: u64,
    pub ime_events: u64,
}

/// Open IME composition. Native IME events carry no session identity,
/// so the field and controller that received the latest Preedit are
/// the only routing authority for the matching Commit/End. The
/// controller handle is retained so cleanup always addresses the
/// composition's own editor, never the currently focused one.
///
/// Preedit → update → Commit → End: Commit retires the owner; End is ignored.
/// Preedit → End: cancellation; the owner's preedit clears, no text changes.
/// Preedit → focus moves: focus change cancels first; later events start fresh.
/// Preedit → controller replaced, field unmounted, or field no longer
///   editable: the owner stops validating and is cancelled, never committed.
/// Commit without Preedit: ownerless, applies to the focused field directly.
struct ImeCompositionOwner {
    field: ElementId,
    controller: TextEditingController,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum InitialFocus {
    AwaitingLayout,
    Settled,
}

/// Retained application execution, input dispatch and frame coordination.
pub struct Runtime {
    pub(crate) tree: WidgetTree,
    /// Input-dispatch time accumulated since the last frame consumed it.
    pub(crate) pending_event_processing_us: u32,
    pub(crate) pending: HashMap<ElementId, Widget>,
    pub(crate) order: VecDeque<ElementId>,
    pub(crate) reactive: Rc<RefCell<ReactiveQueue>>,
    pub(crate) builders: HashMap<ElementId, Box<dyn FnMut() -> Widget>>,
    pub(crate) handlers: HashMap<ActionId, Rc<dyn Fn()>>,
    /// Set when handlers were bound or elements unmounted, so the next
    /// prune scans the tree for live actions; otherwise none can be stale.
    handlers_stale: bool,
    pub(crate) legacy_action_handler: Option<Box<dyn FnMut(ActionId)>>,
    pub(crate) hovered_button: Option<ElementId>,
    pub(crate) pressed_button: Option<ElementId>,
    /// The contact currently allowed to drive single-contact controls. Other
    /// contacts still reach retained gesture regions for scale/pan input.
    pub(crate) legacy_pointer: Option<(u64, u64)>,
    pub(crate) last_pointer: Offset,
    pub(crate) pointer_inside: bool,
    pub(crate) pointer_position_known: bool,
    /// Latest positioned sample from a hover-capable device, replayed at
    /// `last_pointer` when layout or scrolling moves content under it.
    last_hover_sample: Option<RawPointerEvent>,
    pub(crate) focused: Option<ElementId>,
    initial_focus: InitialFocus,
    pub(crate) captured_text_field: Option<ElementId>,
    pub(crate) captured_selectable_text: Option<ElementId>,
    pub(crate) secondary_text_press: Option<text_gestures::SecondaryTextPress>,
    /// `SelectableRegionState._lastSecondaryTapDownPosition`.
    pub(crate) last_selectable_secondary: Option<Offset>,
    /// Consecutive primary taps on a text field (`TapAndPanGestureRecognizer`).
    pub(crate) text_taps: Option<text_gestures::TextTapRun>,
    /// Modifier keys held, from the latest key event (`HardwareKeyboard`).
    pub(crate) keyboard_modifiers: incular_core::Modifiers,
    /// The focused field, content revision and selection whose caret was
    /// last shown on screen (Flutter's `_scheduleShowCaretOnScreen`).
    pub(crate) caret_reveal_key: Option<(ElementId, u64, TextSelection)>,
    ime_composition: Option<ImeCompositionOwner>,
    pub(crate) text_histories: HashMap<ElementId, UndoHistoryController>,
    pub(crate) text_input_commands: VecDeque<TextInputCommand>,
    pub(crate) text_input_client: Option<TextInputClientId>,
    pub(crate) text_input_configuration: Option<TextInputConfiguration>,
    pub(crate) text_input_state: Option<TextInputState>,
    pub(crate) text_input_caret_rect: Option<Rect>,
    pub(crate) clipboard: Box<dyn Clipboard>,
    pub(crate) editing_diagnostics: EditingDiagnostics,
    /// Which platform's `DefaultTextEditingShortcuts` table applies.
    pub(crate) text_shortcut_platform: TextShortcutPlatform,
    pub(crate) frame_requested: bool,
    pub(crate) scheduler: Rc<RefCell<tasks::TaskScheduler>>,
    pub(crate) environment: Rc<RefCell<RuntimeEnvironment>>,
    pub(crate) lifecycle: ApplicationLifecycle,
    pub(crate) lifecycle_observers: Vec<Rc<dyn Fn(LifecycleTransition)>>,
    pub(crate) error_observers: Vec<Rc<dyn Fn(RuntimeErrorReport)>>,
    pub(crate) environment_generation: u64,
    pub(crate) environment_dependencies: Rc<Cell<EnvironmentFields>>,
    pub(crate) application_root: Option<ElementId>,
    pub(crate) owner_scopes: HashMap<ElementId, TaskScope>,
    pub(crate) window_id: Option<WindowId>,
    pub(crate) window_scope: TaskScope,
    pub(crate) window_manager: Option<WindowManager>,
    /// Stable driver identity shared with outlet ownership claims: the id
    /// names this runtime in [`OutletError`](super::route_outlet::OutletError)s,
    /// while the shared ownership doubles as a liveness token — dropping
    /// the runtime releases every claim without a global registry.
    driver_domain: Rc<u64>,
}

pub(crate) fn diagnostic_input_trigger(event: &InputEvent) -> String {
    match event {
        InputEvent::Pointer { phase, position } => {
            format!("pointer({phase:?}, {:.1}, {:.1})", position.x, position.y)
        }
        InputEvent::PointerWithId {
            pointer,
            phase,
            position,
        } => format!(
            "pointer({pointer}, {phase:?}, {:.1}, {:.1})",
            position.x, position.y
        ),
        InputEvent::PointerWithMetadata {
            pointer,
            device,
            kind,
            buttons,
            button,
            sample: _,
            phase,
            position,
        } => format!(
            "pointer({pointer}, device={device}, {kind:?}, buttons={buttons:#x}, changed={button:?}, {phase:?}, {:.1}, {:.1})",
            position.x, position.y
        ),
        InputEvent::TrackpadGesture(event) => format!(
            "trackpad(device={}, kind={:?}, phase={:?})",
            event.device(),
            event.kind(),
            event.phase()
        ),
        InputEvent::Scroll { delta } => format!("scroll({:.1}, {:.1})", delta.x, delta.y),
        InputEvent::Key(event) => format!("key({:?}, {:?})", event.state, event.code),
        InputEvent::Text(text) => format!("text_input(chars={})", text.chars().count()),
        InputEvent::Ime(ImeEvent::Preedit { text, .. }) => {
            format!("ime_preedit(chars={})", text.chars().count())
        }
        InputEvent::Ime(ImeEvent::Commit(text)) => {
            format!("ime_commit(chars={})", text.chars().count())
        }
        InputEvent::Ime(ImeEvent::End) => "ime_end".to_owned(),
        InputEvent::WindowResized { size, scale_factor } => format!(
            "window_resize({:.1}x{:.1}, scale={scale_factor:.2})",
            size.width, size.height
        ),
    }
}

impl Runtime {
    pub fn new(root: Widget) -> Result<Self, TreeError> {
        Self::with_scheduler(root, tasks::TaskScheduler::new())
    }
    fn with_scheduler(
        root: Widget,
        scheduler: Rc<RefCell<tasks::TaskScheduler>>,
    ) -> Result<Self, TreeError> {
        let window_scope = tasks::TaskScheduler::spawner(&scheduler).scope();
        Self::with_window(root, scheduler, None, window_scope, None)
    }

    pub(crate) fn with_window(
        root: Widget,
        scheduler: Rc<RefCell<tasks::TaskScheduler>>,
        window_id: Option<WindowId>,
        window_scope: TaskScope,
        window_manager: Option<WindowManager>,
    ) -> Result<Self, TreeError> {
        Self::with_window_and_reactive(
            root,
            scheduler,
            window_id,
            window_scope,
            window_manager,
            ReactiveQueue::new(),
        )
    }
    pub(crate) fn with_window_and_reactive(
        mut root: Widget,
        scheduler: Rc<RefCell<tasks::TaskScheduler>>,
        window_id: Option<WindowId>,
        window_scope: TaskScope,
        window_manager: Option<WindowManager>,
        reactive: Rc<RefCell<ReactiveQueue>>,
    ) -> Result<Self, TreeError> {
        let mut tree = WidgetTree::new();
        let mut handlers = HashMap::new();
        root.bind_callbacks(&mut |callback| {
            let action = tree.allocate_action();
            handlers.insert(action, callback);
            action
        });
        tree.mount(root)?;
        for (action, handler) in tree.take_pending_handlers() {
            handlers.insert(action, handler);
        }
        let mut runtime = Self {
            pending_event_processing_us: 0,
            tree,
            pending: HashMap::new(),
            order: VecDeque::new(),
            reactive,
            builders: HashMap::new(),
            handlers,
            handlers_stale: false,
            legacy_action_handler: None,
            hovered_button: None,
            pressed_button: None,
            legacy_pointer: None,
            last_pointer: Offset::ZERO,
            pointer_inside: false,
            pointer_position_known: false,
            last_hover_sample: None,
            focused: None,
            initial_focus: InitialFocus::AwaitingLayout,
            captured_text_field: None,
            captured_selectable_text: None,
            secondary_text_press: None,
            last_selectable_secondary: None,
            text_taps: None,
            keyboard_modifiers: incular_core::Modifiers::empty(),
            caret_reveal_key: None,
            ime_composition: None,
            text_histories: HashMap::new(),
            text_input_commands: VecDeque::new(),
            text_input_client: None,
            text_input_configuration: None,
            text_input_state: None,
            text_input_caret_rect: None,
            clipboard: Box::new(MemoryClipboard::default()),
            editing_diagnostics: EditingDiagnostics::default(),
            text_shortcut_platform: TextShortcutPlatform::current(),
            frame_requested: true,
            scheduler,
            environment: Rc::new(RefCell::new(RuntimeEnvironment::default())),
            lifecycle: ApplicationLifecycle::Starting,
            lifecycle_observers: Vec::new(),
            error_observers: Vec::new(),
            environment_generation: 0,
            environment_dependencies: Rc::new(Cell::new(EnvironmentFields::empty())),
            application_root: None,
            owner_scopes: HashMap::new(),
            window_id,
            window_scope,
            window_manager,
            driver_domain: Rc::new(
                RUNTIME_SEQUENCE
                    .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
                    .expect("runtime driver identity space exhausted"),
            ),
        };
        // Focus nodes live outside the retained tree so they may be shared by
        // rebuildable descriptors. Resolve the first mounted autofocus listener
        // once the element IDs exist, then keep runtime and node focus mirrored
        // for subsequent keyboard traversal.
        if let Some(autofocus) = runtime.tree.autofocus_element() {
            runtime.set_focus(Some(autofocus));
        }
        Ok(runtime)
    }
    /// Stable identity of this runtime's driver domain, for outlet
    /// ownership diagnostics: pairs with the outlet id to name both sides
    /// of a driver conflict.
    #[must_use]
    pub fn id(&self) -> u64 {
        *self.driver_domain
    }

    /// Liveness token for outlet driver claims. Dies with the runtime, so
    /// teardown releases outlet ownership without any registry.
    pub(crate) fn driver_token(&self) -> Weak<u64> {
        Rc::downgrade(&self.driver_domain)
    }

    /// Starts work owned by this retained root. Component code should prefer
    /// the build context's spawn API so completion lifetime follows its owner.
    #[must_use]
    pub fn spawner(&self) -> RuntimeSpawner {
        self.window_id.map_or_else(
            || tasks::TaskScheduler::spawner(&self.scheduler),
            |window_id| tasks::TaskScheduler::spawner_for(&self.scheduler, window_id),
        )
    }
    /// Sends a `Send` callback from any worker thread to the UI owner. The
    /// callback is never run concurrently with retained-tree mutation.
    #[must_use]
    pub fn dispatcher(&self) -> UiDispatcher {
        self.scheduler.borrow().dispatcher_for(self.window_id)
    }
    /// Returns the application's Tokio handle for advanced libraries. Direct
    /// Tokio tasks have Tokio/application lifetime and are not component-owned.
    #[must_use]
    #[cfg(not(target_arch = "wasm32"))]
    pub fn tokio_handle(&self) -> TokioHandle {
        self.scheduler.borrow().tokio_handle()
    }
    pub fn set_wake_handler(&mut self, wake: std::sync::Arc<dyn RuntimeWake>) {
        self.scheduler.borrow_mut().set_wake(wake);
    }

    /// Returns the owning normalized window when this runtime is managed by a
    /// multi-window application. Standalone runtimes remain windowless.
    #[must_use]
    pub const fn window_id(&self) -> Option<WindowId> {
        self.window_id
    }

    /// Returns default application-menu bridges retained by this window root.
    /// Native desktop adapters use these after native window creation; normal
    /// application code should use `PlatformMenuBar` instead.
    #[doc(hidden)]
    #[must_use]
    pub fn platform_menu_bindings(&self) -> Vec<PlatformMenuBinding> {
        self.tree.platform_menu_bindings()
    }

    /// Marks only this retained root for a future presentation.
    pub fn request_frame(&mut self) {
        self.frame_requested = true;
    }

    /// Drains native text-input commands produced since the last platform
    /// event-loop turn. A desktop runner applies these to Winit; mobile hosts
    /// can translate the same data to their platform text services.
    pub fn take_text_input_commands(&mut self) -> Vec<TextInputCommand> {
        self.text_input_commands.drain(..).collect()
    }

    /// Opens a second retained root through the owning application. This can
    /// be called from a build or a UI completion; native creation is queued
    /// for the desktop event-loop callback.
    pub fn open_window(
        &mut self,
        options: WindowOptions,
        root: Widget,
    ) -> Result<WindowHandle, WindowError> {
        self.window_manager
            .as_ref()
            .ok_or(WindowError::ApplicationStopped)?
            .open_window(options, root)
    }

    /// Returns a retained UI capability that callbacks may use to open a
    /// window after this build has returned.
    #[must_use]
    pub fn window_opener(&self) -> Option<WindowOpener> {
        self.window_manager
            .as_ref()
            .cloned()
            .map(|manager| WindowOpener { manager })
    }

    /// Returns a command handle for this retained root's owning native window.
    #[must_use]
    pub fn window_handle(&self) -> Option<WindowHandle> {
        let id = self.window_id?;
        self.window_manager.as_ref()?.handle(id)
    }

    /// Returns the scope cancelled as soon as this window closes. Child
    /// component scopes inherit from it automatically.
    #[must_use]
    pub fn window_task_scope(&self) -> TaskScope {
        self.window_scope.clone()
    }

    /// Starts bounded blocking work. Its completion callback runs later on the
    /// UI thread, so it may safely update a local `Signal` or schedule a build.
    pub fn spawn_blocking<T>(
        &self,
        work: impl FnOnce() -> T + Send + 'static,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        T: Send + 'static,
    {
        self.spawner()
            .spawn_blocking_in(&self.window_scope, work, complete)
    }
    /// Starts Tokio work cancelled with this window. Use a `BuildContext` for
    /// work whose completion must be tied to a mounted declarative owner.
    pub fn spawn<F, T>(&self, future: F) -> Task<T>
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.spawner().spawn_in(&self.window_scope, future)
    }
    /// Starts window-scoped Tokio work with a UI-thread completion.
    pub fn spawn_into<F, T>(
        &self,
        future: F,
        complete: impl FnOnce(Result<T, TaskFailure>, &mut Runtime) + 'static,
    ) -> TaskHandle
    where
        F: std::future::Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        self.spawner()
            .spawn_into_in(&self.window_scope, future, complete)
    }
    /// Processes a bounded batch of UI-relevant Tokio completion messages and
    /// dispatch callbacks. Native runners call this only from their user-event
    /// path; it never polls Tokio or implies a redraw.
    pub fn process_runtime_work_at(&mut self, _now: Instant) {
        let scheduler = self.scheduler.clone();
        // Take message-owned work while borrowing the local scheduler, then
        // release that borrow before any UI callback runs. A completion may
        // safely start its next Tokio task without re-entering `RefCell`.
        let work = scheduler.borrow_mut().take_turn();
        for work in work {
            self.process_ui_work(&scheduler, work);
        }
        // A UI completion may also complete a value a widget build reads,
        // such as a `UiFuture` behind a `FutureBuilder`.
        if self.reactive.borrow().has_work()
            || !self.pending.is_empty()
            || self.tree.has_dirty_dependencies()
        {
            self.frame_requested = true;
        }
    }

    pub(crate) fn process_ui_work(
        &mut self,
        scheduler: &Rc<RefCell<tasks::TaskScheduler>>,
        work: tasks::UiWork,
    ) {
        let mut failures = Vec::new();
        match work {
            tasks::UiWork::Dispatch { callback, .. } => {
                if scheduler.borrow().accepting()
                    && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| callback(self)))
                        .is_err()
                {
                    failures.push(TaskFailure::Panicked);
                }
            }
            tasks::UiWork::Task(pending) => {
                scheduler.borrow().detach_scope(&pending.control);
                let stale_owner = pending.control.owner_is_stale(self);
                if !scheduler.borrow().accepting() || pending.control.is_cancelled() || stale_owner
                {
                    (pending.discard)();
                    scheduler
                        .borrow_mut()
                        .record_discard(pending.blocking, stale_owner);
                } else {
                    #[cfg(feature = "devtools")]
                    let previous_task_context = DEV_TASK_COMPLETION.with(|context| {
                        let previous = context.get();
                        context.set(true);
                        previous
                    });
                    let failure = (pending.finish)(self);
                    #[cfg(feature = "devtools")]
                    DEV_TASK_COMPLETION.with(|context| context.set(previous_task_context));
                    if let Some(failure) = scheduler
                        .borrow_mut()
                        .record_completion(pending.blocking, failure)
                    {
                        failures.push(failure);
                    }
                }
            }
        }
        for failure in failures {
            if self.error_observers.is_empty() {
                // Flutter's default FlutterError.onError (presentError) reports
                // the error instead of dropping it; registered observers replace
                // that default.
                eprintln!("Incular runtime error: {failure:?}");
            }
            for observer in &self.error_observers {
                observer(RuntimeErrorReport {
                    failure: failure.clone(),
                });
            }
        }
        // A UI completion may also complete a value a widget build reads,
        // such as a `UiFuture` behind a `FutureBuilder`.
        if self.reactive.borrow().has_work()
            || !self.pending.is_empty()
            || self.tree.has_dirty_dependencies()
        {
            self.frame_requested = true;
        }
    }
    pub fn process_runtime_work(&mut self) {
        self.process_runtime_work_at(Instant::now());
    }
    #[must_use]
    pub fn runtime_diagnostics(&self) -> RuntimeDiagnostics {
        self.scheduler.borrow().diagnostics()
    }
    /// Compact ownership-facing state for framework diagnostics. Tokio's own
    /// tracing ecosystem remains the source of executor-level telemetry.
    #[must_use]
    pub fn debug_dump(&self) -> String {
        let diagnostics = self.runtime_diagnostics();
        let (application_tasks, owner_tasks) = self.scheduler.borrow().active_ownership();
        format!(
            "Lifecycle: {:?}\nTokio tasks tracked: {}\n  application: {}\n  owner-scoped: {}\nPending UI messages: {}\nEnvironment generation: {}",
            self.lifecycle,
            diagnostics.active_tracked_tasks,
            application_tasks,
            owner_tasks,
            diagnostics
                .ui_messages_enqueued
                .saturating_sub(diagnostics.ui_messages_processed),
            self.environment_generation,
        )
    }
    #[must_use]
    pub fn environment(&self) -> RuntimeEnvironment {
        self.environment.borrow().clone()
    }
    #[must_use]
    pub const fn lifecycle(&self) -> ApplicationLifecycle {
        self.lifecycle
    }
    #[must_use]
    pub const fn environment_generation(&self) -> u64 {
        self.environment_generation
    }
    /// Replaces normalized runtime values from a platform event. Rebuild is
    /// requested only when the declarative root read a changed value.
    pub fn set_environment(&mut self, environment: RuntimeEnvironment) -> bool {
        let environment = environment.normalized();
        let previous = self.environment.borrow().clone();
        if previous == environment {
            return false;
        }
        let changed = environment_change_mask(&previous, &environment);
        *self.environment.borrow_mut() = environment.clone();
        // WidgetTree owns renderer-neutral runtime geometry and direction used
        // by retained policies such as SafeArea and transient placement. Keep
        // that snapshot synchronized even when no declarative environment
        // dependency requires rebuilding the application root.
        let retained_environment_dirty = self.tree.set_environment(environment);
        self.environment_generation = self
            .environment_generation
            .checked_add(1)
            .expect("runtime environment generation exhausted");
        if retained_environment_dirty {
            self.frame_requested = true;
        }
        if self.environment_dependencies.get().intersects(changed)
            && let Some(root) = self.application_root
        {
            #[cfg(feature = "devtools")]
            self.tree
                .note_invalidation(root, InvalidationCause::EnvironmentChanged);
            let _ = self.rebuild_from_builder(root);
            self.frame_requested = true;
        }
        true
    }
    pub fn transition_lifecycle(&mut self, lifecycle: ApplicationLifecycle) -> bool {
        if self.lifecycle == lifecycle {
            return false;
        }
        let transition = LifecycleTransition {
            previous: self.lifecycle,
            current: lifecycle,
        };
        self.lifecycle = lifecycle;
        for observer in &self.lifecycle_observers {
            observer(transition);
        }
        if matches!(
            lifecycle,
            ApplicationLifecycle::Stopping | ApplicationLifecycle::Terminated
        ) {
            self.reactive.borrow_mut().clear();
            self.scheduler.borrow_mut().shutdown();
        }
        true
    }
    pub fn observe_lifecycle(&mut self, observer: impl Fn(LifecycleTransition) + 'static) {
        self.lifecycle_observers.push(Rc::new(observer));
    }
    pub fn observe_runtime_error(&mut self, observer: impl Fn(RuntimeErrorReport) + 'static) {
        self.error_observers.push(Rc::new(observer));
    }
    /// Cancels runtime-owned work and prevents later queued callbacks from
    /// touching retained state. Native runners should call this before their
    /// renderer/window teardown.
    pub fn shutdown(&mut self) {
        if self.focused.is_some() {
            self.set_focus(None);
        } else {
            self.cancel_ime_composition();
            self.sync_text_input_client();
        }
        self.tree.cancel_all_gesture_streams();
        self.captured_text_field = None;
        self.captured_selectable_text = None;
        self.hovered_button = None;
        self.pressed_button = None;
        self.legacy_pointer = None;
        self.text_histories.clear();
        self.tree.release_edit_subscriptions();
        let _ = self.transition_lifecycle(ApplicationLifecycle::Stopping);
        for (_, scope) in self.owner_scopes.drain() {
            scope.cancel();
        }
        self.scheduler.borrow_mut().shutdown();
        self.lifecycle = ApplicationLifecycle::Terminated;
    }

    /// Releases window-owned subscriptions and callback state without
    /// stopping the shared application scheduler. `Application` calls this
    /// before dropping a closed retained root.
    pub(crate) fn dispose_window(&mut self) {
        if self.focused.is_some() {
            self.set_focus(None);
        } else {
            self.cancel_ime_composition();
            self.sync_text_input_client();
        }
        self.tree.cancel_all_gesture_streams();
        self.tree.release_edit_subscriptions();
        self.legacy_pointer = None;
        self.window_scope.cancel();
        for (_, scope) in self.owner_scopes.drain() {
            scope.cancel();
        }
        self.reactive.borrow_mut().clear();
        self.builders.clear();
        self.pending.clear();
        self.order.clear();
        self.handlers.clear();
        self.legacy_action_handler = None;
        self.text_histories.clear();
        self.text_input_commands.clear();
        self.text_input_client = None;
        self.text_input_configuration = None;
        self.text_input_state = None;
        self.text_input_caret_rect = None;
        self.captured_text_field = None;
        self.captured_selectable_text = None;
        self.hovered_button = None;
        self.pressed_button = None;
    }
    #[must_use]
    pub fn tree(&self) -> &WidgetTree {
        &self.tree
    }

    #[cfg(feature = "devtools")]
    pub(crate) fn devtools_reactive_root(&self) -> ReactiveRootId {
        self.reactive.borrow().root
    }
    #[must_use]
    pub fn tree_mut(&mut self) -> &mut WidgetTree {
        &mut self.tree
    }

    /// Returns the effective capture-protection policy contributed by the
    /// mounted retained tree. The window/application boundary is responsible
    /// for forwarding changes to its native adapter.
    #[must_use]
    pub fn content_sensitivity(&self) -> incular_config::ContentSensitivity {
        self.tree.content_sensitivity()
    }

    /// Visible transient portals after the latest layout. Desktop adapters use
    /// this retained snapshot to bind popup presentation to the owning window
    /// without coupling controls to a native event loop.
    #[must_use]
    pub fn transient_surfaces(&self) -> Vec<incular_widgets::TransientSurfaceSnapshot> {
        self.tree.transient_surfaces()
    }

    /// Updates the parent-local logical rectangle that confirmed native
    /// transient hosts may use for collision placement.
    pub fn set_native_transient_bounds(&mut self, bounds: Option<incular_core::Rect>) -> bool {
        let changed = self.tree.set_native_transient_bounds(bounds);
        self.frame_requested |= changed;
        changed
    }

    /// Updates the set of retained transients whose native hosts have completed
    /// negotiation. A presentation change requests a frame so placement,
    /// semantics, hit testing, and rendering switch coordinate spaces together.
    pub fn set_native_transient_presentations(
        &mut self,
        ids: impl IntoIterator<Item = incular_widgets::TransientSurfaceId>,
    ) -> bool {
        let changed = self.tree.set_native_transient_presentations(ids);
        self.frame_requested |= changed;
        changed
    }

    /// Applies a framework-level transient dismissal cause without changing
    /// native focus ownership. Controllers receive the callback and the normal
    /// retained rebuild path removes their popup subtree.
    pub fn dismiss_transients(&mut self, reason: incular_widgets::TransientDismissReason) -> bool {
        let dismissed = self.tree.dismiss_transients(reason) > 0;
        self.frame_requested |= dismissed;
        dismissed
    }
    #[cfg(feature = "devtools")]
    pub(crate) fn devtools_edit_property(
        &mut self,
        id: incular_devtools_protocol::DevWidgetId,
        name: &str,
        value: &incular_devtools_protocol::DebugValue,
    ) -> bool {
        let edit = self.tree.devtools_edit_property(id, name, value);
        self.frame_requested |= edit == incular_widgets::devtools::DevEdit::Applied;
        edit != incular_widgets::devtools::DevEdit::Rejected
    }
    #[cfg(feature = "devtools")]
    pub(crate) fn devtools_revert_property(
        &mut self,
        id: incular_devtools_protocol::DevWidgetId,
        name: &str,
        original: &incular_devtools_protocol::DebugValue,
    ) -> bool {
        let edit = self.tree.devtools_revert_property(id, name, original);
        self.frame_requested |= edit == incular_widgets::devtools::DevEdit::Applied;
        edit != incular_widgets::devtools::DevEdit::Rejected
    }
    /// Sets the animation-only time scale for this retained root. Runtime
    /// messages, Tokio tasks and profiler wall-clock measurements remain on
    /// the platform monotonic clock.
    pub fn set_animation_time_scale(&mut self, scale: f32) {
        self.tree.set_animation_time_scale(scale);
    }
    #[must_use]
    pub fn focused_element(&self) -> Option<ElementId> {
        self.focused
    }
    /// Dispatches an owned semantic action through the same control state used
    /// by pointer and keyboard input. Native adapters queue these requests;
    /// they never borrow mutable element storage. Eligibility reuses the
    /// existing owners: explicit semantic callbacks always execute;
    /// built-in Activate additionally requires the advertisement predicate
    /// (enabled button with a bound callback), matching the pointer and
    /// keyboard paths, which never see a disabled button past their own
    /// enabled gate. SetText requires an editable field while SetSelection
    /// requires only a controller — selection stays available in read-only
    /// and disabled fields on every input path. Focus accepts only targets
    /// the tree's own focusability owner admits (`can_request_focus`:
    /// enabled controls, selectable text, or a focus node, unobstructed by
    /// `exclude_focus` or a hidden IndexedStack slot), with an
    /// already-focused valid target still reporting success; `set_focus`
    /// remains the single focus owner for all paths.
    pub fn dispatch_semantic_action(
        &mut self,
        node: SemanticNodeId,
        action: SemanticAction,
    ) -> bool {
        let Some(element) = self.tree.element_for_semantic_node(node) else {
            return false;
        };
        self.tree.note_semantic_action();
        let handled = match action {
            SemanticAction::Focus => {
                if self.tree.can_request_focus(element) {
                    self.set_focus(Some(element));
                    true
                } else {
                    false
                }
            }
            SemanticAction::Activate => {
                if let Some(callback) = self.tree.semantic_action_callback(
                    element,
                    incular_semantics::SemanticActionKind::Activate,
                ) {
                    callback();
                    true
                } else if self.tree.semantic_activate_executable(element) {
                    self.tree
                        .action_for_element(element)
                        .map(|action| self.activate_action(action))
                        .unwrap_or(false)
                } else {
                    false
                }
            }
            SemanticAction::SetText(text) => {
                if !self.tree.text_field_is_editable(element) {
                    false
                } else {
                    self.tree
                        .text_controller(element)
                        .map(|controller| {
                            controller.set_text(text);
                            true
                        })
                        .unwrap_or(false)
                }
            }
            SemanticAction::SetSelection { base, extent } => self
                .tree
                .text_controller(element)
                .map(|controller| {
                    let length = controller.text().len();
                    controller.set_selection(TextSelection {
                        base: base.min(length),
                        extent: extent.min(length),
                    });
                    true
                })
                .unwrap_or(false),
            SemanticAction::ScrollForward => self
                .tree
                .semantic_action_callback(
                    element,
                    incular_semantics::SemanticActionKind::ScrollForward,
                )
                .map(|callback| {
                    callback();
                    true
                })
                .unwrap_or_else(|| self.tree.semantic_scroll(element, true)),
            SemanticAction::ScrollBackward => self
                .tree
                .semantic_action_callback(
                    element,
                    incular_semantics::SemanticActionKind::ScrollBackward,
                )
                .map(|callback| {
                    callback();
                    true
                })
                .unwrap_or_else(|| self.tree.semantic_scroll(element, false)),
            SemanticAction::Increment => self
                .tree
                .semantic_action_callback(element, incular_semantics::SemanticActionKind::Increment)
                .map(|callback| {
                    callback();
                    true
                })
                .unwrap_or_else(|| self.tree.dispatch_semantic_increment(element, true)),
            SemanticAction::Decrement => self
                .tree
                .semantic_action_callback(element, incular_semantics::SemanticActionKind::Decrement)
                .map(|callback| {
                    callback();
                    true
                })
                .unwrap_or_else(|| self.tree.dispatch_semantic_increment(element, false)),
        };
        if handled {
            self.frame_requested = true;
        }
        handled
    }
    #[must_use]
    pub fn focus_diagnostics(&self) -> FocusDiagnostics {
        FocusDiagnostics {
            focused_element: self.focused,
            text_pointer_capture: self.captured_text_field,
        }
    }
    #[must_use]
    pub const fn editing_diagnostics(&self) -> EditingDiagnostics {
        self.editing_diagnostics
    }
    /// Chooses which platform's text-editing shortcut table text fields use
    /// (Flutter's `defaultTargetPlatform`): Option for words and Command for
    /// lines on macOS and iOS, Control for words elsewhere. Defaults to the
    /// platform this build targets.
    pub fn set_text_shortcut_platform(&mut self, platform: TextShortcutPlatform) {
        self.text_shortcut_platform = platform;
    }

    /// The platform whose text-editing shortcuts are active.
    #[must_use]
    pub fn text_shortcut_platform(&self) -> TextShortcutPlatform {
        self.text_shortcut_platform
    }

    pub fn set_clipboard(&mut self, clipboard: Box<dyn Clipboard>) {
        self.clipboard = clipboard;
    }
    /// Returns the capabilities of the clipboard backend currently installed
    /// for this retained window.
    #[must_use]
    pub fn clipboard_capabilities(&self) -> ClipboardCapabilities {
        self.clipboard.capabilities()
    }
    /// Reads rich clipboard data without collapsing it to plain text.
    pub fn read_clipboard(
        &mut self,
        request: TransferReadRequest,
    ) -> Result<DataTransfer, ClipboardError> {
        self.clipboard.read(request)
    }
    /// Writes one rich clipboard transfer. The report distinguishes formats
    /// written atomically by the backend from representations it skipped.
    pub fn write_clipboard(
        &mut self,
        transfer: DataTransfer,
    ) -> Result<ClipboardWriteReport, ClipboardError> {
        self.clipboard.write(transfer)
    }
    pub fn set_clipboard_text(&mut self, text: impl Into<String>) {
        self.clipboard.set_text(text.into());
    }
    /// Routes platform-owned transfer data through external drop targets. This
    /// path is intentionally independent of the local typed gesture arena.
    #[must_use]
    pub fn handle_external_drag(&mut self, event: ExternalDragEvent) -> ExternalDragResponse {
        let response = self.tree.dispatch_external_drag(event);
        self.frame_requested = true;
        response
    }
    /// Processes a normalized platform event without exposing native window or
    /// event-loop types to the runtime API.
    pub fn handle_platform_event(&mut self, event: PlatformEvent) -> Option<EventTarget> {
        match event {
            PlatformEvent::Input(input) => self.handle_input(input),
            PlatformEvent::TextInputAction(action) => {
                self.handle_text_input_action(action);
                None
            }
            PlatformEvent::Metrics(metrics) => {
                self.update_window_metrics(metrics);
                None
            }
            PlatformEvent::Environment(environment) => {
                self.set_environment(environment);
                None
            }
            PlatformEvent::Lifecycle(lifecycle) => {
                self.transition_lifecycle(match lifecycle {
                    PlatformLifecycle::Active => ApplicationLifecycle::Active,
                    PlatformLifecycle::Inactive => ApplicationLifecycle::Inactive,
                    PlatformLifecycle::Suspended => ApplicationLifecycle::Suspended,
                    PlatformLifecycle::Resumed => ApplicationLifecycle::Active,
                    PlatformLifecycle::Stopping => ApplicationLifecycle::Stopping,
                });
                None
            }
            PlatformEvent::ExternalDrag(event) => {
                let _ = self.handle_external_drag(event);
                None
            }
            PlatformEvent::CloseRequested => {
                self.shutdown();
                None
            }
        }
    }
    /// Applies the authoritative logical/physical conversion supplied by the
    /// platform metrics owner. Existing environment values such as locale are
    /// preserved while size and scale change together.
    pub fn update_window_metrics(&mut self, metrics: WindowMetrics) -> bool {
        let mut environment = self.environment();
        environment.viewport = metrics.logical_size();
        environment.physical_width = metrics.physical_size.width;
        environment.physical_height = metrics.physical_size.height;
        environment.scale_factor = metrics.scale_factor;
        self.set_environment(environment)
    }
    pub fn register_builder(
        &mut self,
        id: ElementId,
        builder: impl FnMut() -> Widget + 'static,
    ) -> Result<(), TreeError> {
        self.register_builder_without_rebuild(id, builder)?;
        self.rebuild_from_builder(id)
    }
    pub(crate) fn register_builder_without_rebuild(
        &mut self,
        id: ElementId,
        builder: impl FnMut() -> Widget + 'static,
    ) -> Result<(), TreeError> {
        if !self.tree.element_exists(id) {
            return Err(TreeError::MissingElement(id));
        }
        self.builders.insert(id, Box::new(builder));
        Ok(())
    }
    pub(crate) fn install_initial_dependencies(
        &mut self,
        id: ElementId,
        initial_dependencies: Rc<RefCell<InitialBuildDependencies>>,
    ) {
        let initial_dependencies = std::mem::take(&mut *initial_dependencies.borrow_mut());
        let queue = self.reactive.clone();
        let root = queue.borrow().root;
        let queue_weak = Rc::downgrade(&queue);
        for dependency in initial_dependencies.signals {
            let tracked =
                crate::reactive::subscribe_element(dependency, root, id, queue_weak.clone());
            queue.borrow_mut().record(id, tracked);
        }
        for scope in initial_dependencies.focus_scopes {
            install_focus_scope_watch(&queue, id, &scope);
        }
    }
    pub fn schedule_update(&mut self, id: ElementId, widget: Widget) -> Result<(), TreeError> {
        if !self.tree.element_exists(id) {
            return Err(TreeError::MissingElement(id));
        }
        #[cfg(feature = "devtools")]
        self.tree
            .note_invalidation(id, InvalidationCause::WidgetConfigurationChanged);
        self.tree.mark_build(id)?;
        let mut widget = widget;
        self.prepare_widget(&mut widget);
        if self.pending.insert(id, widget).is_none() {
            self.order.push_back(id);
        }
        self.frame_requested = true;
        Ok(())
    }
    #[must_use]
    pub fn frame_requested(&self) -> bool {
        self.frame_requested
            || self.reactive.borrow().has_work()
            || self.tree.has_pending_application_fonts()
    }
    #[must_use]
    pub fn handle_input(&mut self, event: InputEvent) -> Option<EventTarget> {
        self.tree
            .set_diagnostic_input_trigger(None, &event, diagnostic_input_trigger);
        self.handle_input_timed(event)
    }

    pub(crate) fn handle_input_with_trigger(
        &mut self,
        event: InputEvent,
        trigger: impl Into<String>,
    ) -> Option<EventTarget> {
        self.tree.set_diagnostic_trigger(trigger);
        self.handle_input_timed(event)
    }

    pub(crate) fn handle_input_timed(&mut self, event: InputEvent) -> Option<EventTarget> {
        let started = incular_core::time::Instant::now();
        let target = self.handle_input_inner(event);
        self.pending_event_processing_us = self
            .pending_event_processing_us
            .saturating_add(us_since_instant(started));
        target
    }

    /// Associates subsequent frame work with a higher-level command such as a
    /// semantic simulation click. The trigger survives the input callback so
    /// deferred build/layout failures retain their original cause.
    pub fn set_diagnostic_trigger(&self, trigger: impl Into<String>) {
        self.tree.set_diagnostic_trigger(trigger);
    }
    /// The retained tree's window key for gesture arenas and hover state.
    fn gesture_window(&self) -> u64 {
        self.window_id.map_or(0, |window| {
            (u64::from(window.index()) << 32) | u64::from(window.generation())
        })
    }
    fn handle_input_inner(&mut self, event: InputEvent) -> Option<EventTarget> {
        let gesture_window = self.gesture_window();
        let (pointer, device, kind, buttons, button, sample, phase, position, metadata_rich) =
            match event {
                InputEvent::Pointer { phase, position } => (
                    0,
                    0,
                    PointerDeviceKind::Mouse,
                    0,
                    None,
                    PointerSampleMetadata::default(),
                    phase,
                    position,
                    false,
                ),
                InputEvent::PointerWithId {
                    pointer,
                    phase,
                    position,
                } => (
                    pointer,
                    0,
                    PointerDeviceKind::Mouse,
                    0,
                    None,
                    PointerSampleMetadata::default(),
                    phase,
                    position,
                    false,
                ),
                InputEvent::PointerWithMetadata {
                    pointer,
                    device,
                    kind,
                    buttons,
                    button,
                    sample,
                    phase,
                    position,
                } => (
                    pointer, device, kind, buttons, button, sample, phase, position, true,
                ),
                event => {
                    match event {
                        InputEvent::Scroll { delta } => {
                            // The platform normalizes wheel values to logical pixels. The
                            // latest pointer position selects the nearest viewport.
                            if self.tree.scroll_at(self.last_pointer, delta) {
                                self.frame_requested = true;
                            }
                        }
                        InputEvent::Key(key) => {
                            self.handle_key(key);
                        }
                        InputEvent::Text(text) => {
                            self.insert_text(&text);
                        }
                        InputEvent::Ime(ime) => {
                            self.handle_ime(ime);
                        }
                        InputEvent::TrackpadGesture(gesture) => {
                            // Aggregate gestures do not carry a focal position in
                            // Winit. Use only a genuine cursor position already
                            // observed for this window; never invent a touch point.
                            if self.pointer_position_known
                                && let Some(element) =
                                    self.tree.dispatch_trackpad_gesture_in_window(
                                        gesture_window,
                                        self.last_pointer,
                                        gesture,
                                    )
                            {
                                self.frame_requested = true;
                                return Some(EventTarget {
                                    element,
                                    action: None,
                                });
                            }
                        }
                        InputEvent::WindowResized { .. } => {}
                        InputEvent::Pointer { .. } => unreachable!(),
                        InputEvent::PointerWithId { .. } => unreachable!(),
                        InputEvent::PointerWithMetadata { .. } => unreachable!(),
                    }
                    return None;
                }
            };
        let hover_capable = matches!(
            kind,
            PointerDeviceKind::Mouse
                | PointerDeviceKind::Trackpad
                | PointerDeviceKind::Stylus
                | PointerDeviceKind::InvertedStylus
        );
        if hover_capable {
            match phase {
                PointerPhase::Enter => {
                    self.pointer_inside = true;
                    self.pointer_position_known = false;
                }
                PointerPhase::Exit => {
                    self.pointer_inside = false;
                    self.pointer_position_known = false;
                }
                _ => {
                    self.pointer_inside = true;
                    self.pointer_position_known = true;
                }
            }
        }
        if phase != PointerPhase::Enter {
            self.last_pointer = position;
        }
        if phase == PointerPhase::Down {
            // A held press owns `kPressTimeout` and `kLongPressTimeout`
            // deadlines that fire on the frame clock, so a frame must run.
            self.frame_requested = true;
        }
        let text_menu_was_showing = phase == PointerPhase::Down
            && button == Some(incular_core::SECONDARY_POINTER_BUTTON)
            && self.text_menu_open_at(position);
        if phase == PointerPhase::Down && self.tree.dismiss_transients_for_pointer(position) > 0 {
            self.frame_requested = true;
        }
        let raw_event = RawPointerEvent::new(
            pointer,
            device,
            kind,
            buttons,
            position,
            phase,
            Instant::now(),
        )
        .with_button(button)
        .with_sample(sample);
        if hover_capable {
            self.last_hover_sample =
                (!matches!(phase, PointerPhase::Enter | PointerPhase::Exit)).then_some(raw_event);
        }
        // One hit test serves the whole event: raw regions and listeners,
        // retained gestures, text editing and buttons.
        let hit = if matches!(phase, PointerPhase::Enter | PointerPhase::Exit) {
            PointerHitTest::default()
        } else {
            self.tree.pointer_hit_test(position)
        };
        let raw_target = self
            .tree
            .dispatch_raw_pointer_with_hit(gesture_window, raw_event, &hit);
        if metadata_rich
            && self.text_secondary_pointer(
                phase,
                button,
                device,
                pointer,
                position,
                &hit,
                text_menu_was_showing,
            )
        {
            self.frame_requested = true;
        }
        if matches!(phase, PointerPhase::Enter | PointerPhase::Exit) {
            if phase == PointerPhase::Exit {
                self.set_hover(None);
                if self.tree.scrollbar_pointer(PointerPhase::Exit, position) {
                    self.frame_requested = true;
                }
            }
            return None;
        }

        let primary_changed = !metadata_rich || button == Some(PRIMARY_POINTER_BUTTON);
        let stream = (device, pointer);
        let active_primary = self.legacy_pointer == Some(stream);
        let legacy_pointer = match phase {
            PointerPhase::Down if primary_changed && self.legacy_pointer.is_none() => {
                self.legacy_pointer = Some(stream);
                true
            }
            PointerPhase::Down => primary_changed && active_primary,
            PointerPhase::Move => {
                active_primary || (hover_capable && self.legacy_pointer.is_none())
            }
            PointerPhase::Up => primary_changed && active_primary,
            PointerPhase::Cancel => active_primary,
            PointerPhase::Enter | PointerPhase::Exit => false,
        };

        if let Some(element) = raw_target {
            self.frame_requested = true;
            self.release_legacy_pointer(device, pointer, phase, primary_changed);
            return Some(EventTarget {
                element,
                action: None,
            });
        }
        let ordinary_gesture_allowed = legacy_pointer || !metadata_rich || !hover_capable;
        if ordinary_gesture_allowed
            && let Some(element) = self.tree.dispatch_pointer_gesture_with_hit(
                gesture_window,
                device,
                kind,
                PointerEvent {
                    pointer,
                    position,
                    phase,
                    time: Instant::now(),
                },
                &hit,
            )
        {
            self.frame_requested = true;
            self.release_legacy_pointer(device, pointer, phase, primary_changed);
            return Some(EventTarget {
                element,
                action: None,
            });
        }
        // Legacy controls and scrollbars admit just the primary contact.
        // Additional contacts remain available to retained gesture regions.
        if !legacy_pointer {
            return None;
        }
        if self.tree.scrollbar_pointer_with_kind(phase, position, kind) {
            self.frame_requested = true;
            self.release_legacy_pointer(device, pointer, phase, primary_changed);
            return None;
        }
        let text_target = self.tree.text_field_for_hit(&hit);
        let selectable_target = self.tree.selectable_text_for_hit(&hit);
        let target = self.button_target(&hit);
        let result = match phase {
            PointerPhase::Enter | PointerPhase::Exit => {
                unreachable!("pointer boundary handled above")
            }
            PointerPhase::Move => {
                if let Some(field) = self.captured_text_field {
                    self.text_field_primary_drag(field, position);
                    self.frame_requested = true;
                }
                if let Some(label) = self.captured_selectable_text {
                    if let Some(target) = selectable_target {
                        if self
                            .tree
                            .selectable_text_set_selection(target, position, true)
                        {
                            self.captured_selectable_text = Some(target);
                            self.set_focus(Some(target));
                            self.frame_requested = true;
                        }
                    } else if self.tree.is_selectable_text(label) {
                        self.frame_requested = true;
                    }
                }
                self.set_hover(target.map(|(element, _)| element));
                target.map(|(element, action)| EventTarget { element, action })
            }
            PointerPhase::Down => {
                if let Some(label) = selectable_target {
                    self.set_focus(Some(label));
                    self.captured_selectable_text = Some(label);
                    if self
                        .tree
                        .selectable_text_set_selection(label, position, false)
                    {
                        self.frame_requested = true;
                        return Some(EventTarget {
                            element: label,
                            action: None,
                        });
                    }
                }
                if selectable_target.is_none()
                    && text_target.is_none()
                    && target.is_none()
                    && let Some((element, interaction)) = self.tree.window_interaction_at(position)
                    && let (Some(window_id), Some(manager)) =
                        (self.window_id, self.window_manager.as_ref())
                {
                    let operation = match interaction {
                        WindowInteraction::Move => WindowOperation::BeginMoveDrag,
                        WindowInteraction::Resize(direction) => {
                            WindowOperation::BeginResizeDrag(direction)
                        }
                    };
                    if manager.send_window_operation(window_id, operation) {
                        self.release_legacy_pointer(device, pointer, phase, primary_changed);
                        return Some(EventTarget {
                            element,
                            action: None,
                        });
                    }
                }
                let text_target_was_focused =
                    text_target.is_some_and(|field| self.focused == Some(field));
                let keep_text_field_focus = self
                    .focused
                    .is_some_and(|focused| self.tree.is_text_field(focused))
                    && self.tree.preserves_text_field_focus(position);
                self.set_focus(if keep_text_field_focus {
                    self.focused
                } else {
                    text_target
                });
                // Flutter's EditableText only installs its selection gestures
                // while `_userSelectionEnabled` (`!readOnly || !obscureText`)
                // holds; a read-only obscured field keeps focus but no caret.
                self.captured_text_field =
                    text_target.filter(|field| self.text_field_pointer_selection_enabled(*field));
                if let Some(field) = text_target {
                    if self.captured_text_field.is_some() {
                        self.text_field_primary_down(field, position, text_target_was_focused);
                    }
                    self.frame_requested = true;
                    return Some(EventTarget {
                        element: field,
                        action: None,
                    });
                }
                self.set_hover(target.map(|(element, _)| element));
                self.pressed_button = target.map(|(element, _)| element);
                if let Some(element) = self.pressed_button {
                    let _ = self
                        .tree
                        .set_button_interaction(element, None, Some(true), None);
                    self.frame_requested = true;
                }
                target.map(|(element, action)| EventTarget { element, action })
            }
            PointerPhase::Up => {
                if self.captured_text_field.take().is_some() {
                    self.text_field_primary_up();
                }
                self.captured_selectable_text = None;
                let pressed = self.pressed_button.take();
                let valid = pressed
                    .zip(target)
                    .filter(|(pressed, (target, _))| pressed == target)
                    .map(|(_, target)| target);
                if let Some(element) = pressed {
                    let _ = self
                        .tree
                        .set_button_interaction(element, None, Some(false), None);
                }
                if let Some((element, action)) = valid {
                    if let Some(action) = action {
                        self.activate_action(action);
                    }
                    Some(EventTarget { element, action })
                } else {
                    None
                }
            }
            PointerPhase::Cancel => {
                self.captured_text_field = None;
                self.captured_selectable_text = None;
                if let Some(element) = self.pressed_button.take() {
                    let _ = self
                        .tree
                        .set_button_interaction(element, None, Some(false), None);
                    self.frame_requested = true;
                }
                None
            }
        };
        self.release_legacy_pointer(device, pointer, phase, primary_changed);
        result
    }
    fn button_target(&self, hit: &PointerHitTest) -> Option<(ElementId, Option<ActionId>)> {
        hit.target()
            .and_then(|render| self.tree.element_for_render(render))
            .and_then(|element| self.tree.button_ancestor(element))
    }
    /// Flutter's `MouseTracker.updateAllDevices` after layout: a still
    /// pointer over content that moved (a programmatic or wheel scroll, a
    /// relayout) hovers whatever is under it now. Mouse regions get their
    /// enter and exit callbacks, and button hover follows unless a press
    /// owns the single-contact controls.
    fn refresh_hover_after_layout(&mut self) {
        if !self.pointer_inside || !self.pointer_position_known {
            return;
        }
        let Some(sample) = self.last_hover_sample else {
            return;
        };
        let event = RawPointerEvent {
            position: self.last_pointer,
            local_position: self.last_pointer,
            delta: incular_core::Offset::ZERO,
            local_delta: incular_core::Offset::ZERO,
            time: Instant::now(),
            ..sample
        };
        let hit = self.tree.pointer_hit_test(self.last_pointer);
        let window = self.gesture_window();
        self.tree.refresh_mouse_hover_in_window(window, event, &hit);
        if self.legacy_pointer.is_none() {
            let target = self.button_target(&hit);
            self.set_hover(target.map(|(element, _)| element));
        }
    }
    fn release_legacy_pointer(
        &mut self,
        device: u64,
        pointer: u64,
        phase: PointerPhase,
        primary_changed: bool,
    ) {
        if (phase == PointerPhase::Cancel || (phase == PointerPhase::Up && primary_changed))
            && self.legacy_pointer == Some((device, pointer))
        {
            self.legacy_pointer = None;
        }
    }

    /// Cursor selected by the current retained hover route. `Defer` is resolved
    /// to the ordinary platform cursor before crossing the native boundary.
    #[must_use]
    pub fn effective_mouse_cursor(&self) -> MouseCursor {
        if !self.pointer_inside || !self.pointer_position_known {
            return MouseCursor::Basic;
        }
        match self.tree.mouse_cursor_at(self.last_pointer) {
            MouseCursor::Defer => MouseCursor::Basic,
            cursor => cursor,
        }
    }
    pub(crate) fn set_focus(&mut self, next: Option<ElementId>) {
        // Explicit input (including clearing focus) wins over a pending initial
        // autofocus request, even when it leaves the focused element unchanged.
        self.initial_focus = InitialFocus::Settled;
        if self.focused == next {
            return;
        }
        // A focus change retires the native client behind any open
        // composition: without a session id later IME events are
        // unattributable, so the old composition ends here and later
        // events start fresh on the newly focused field.
        self.cancel_ime_composition();
        if let Some(next) = next
            && self.tree.dismiss_transients_for_focus(next) > 0
        {
            self.frame_requested = true;
        }
        if let Some(previous) = self.focused {
            self.tree.set_keyboard_focus(previous, false);
            let _ = self.tree.set_focused(previous, false, Instant::now());
        }
        self.focused = next;
        if let Some(current) = next {
            let _ = self.tree.set_focused(current, true, Instant::now());
            self.tree.set_keyboard_focus(current, true);
            if self.tree.is_text_field(current) {
                let _ = self.ensure_text_history(current);
            }
        }
        self.frame_requested = true;
        self.sync_text_input_client();
    }

    fn reconcile_focus_and_selection_captures(&mut self) {
        if self.captured_text_field.is_some_and(|field| {
            !self.tree.is_text_field(field) || !self.tree.can_request_focus(field)
        }) {
            self.captured_text_field = None;
        }
        if self.captured_selectable_text.is_some_and(|label| {
            !self.tree.is_selectable_text(label) || !self.tree.can_request_focus(label)
        }) {
            self.captured_selectable_text = None;
        }
        if self
            .focused
            .is_some_and(|focused| !self.tree.can_request_focus(focused))
        {
            self.set_focus(None);
        }
        self.reconcile_button_tenure();
    }

    fn reconcile_button_tenure(&mut self) {
        // Pressed tenure belongs to a still-pressable button element.
        // `button_ancestor` already filters disabled and missing elements,
        // so reuse it instead of restating button liveness here. A stale
        // press clears its visual when still mounted and never activates.
        if self.pressed_button.is_some_and(|pressed| {
            self.tree
                .button_ancestor(pressed)
                .map(|(ancestor, _)| ancestor)
                != Some(pressed)
        }) && let Some(pressed) = self.pressed_button.take()
        {
            let _ = self
                .tree
                .set_button_interaction(pressed, None, Some(false), None);
            self.frame_requested = true;
        }
        // Hover tenure reuses the single `set_hover` owner so exit callbacks
        // fire for still-mounted buttons; pruned handlers make unmounted exit
        // a silent visual release.
        if self.hovered_button.is_some_and(|hovered| {
            self.tree
                .button_ancestor(hovered)
                .map(|(ancestor, _)| ancestor)
                != Some(hovered)
        }) {
            self.set_hover(None);
        }
    }

    fn ensure_text_history(&mut self, field: ElementId) -> Option<UndoHistoryController> {
        let editor = self.tree.text_controller(field)?;
        let replace = self
            .text_histories
            .get(&field)
            .is_none_or(|history| history.editor() != editor);
        if replace {
            self.text_histories
                .insert(field, UndoHistoryController::new(editor));
        }
        let history = self.text_histories.get(&field).cloned()?;
        if let Some(max_entries) = self.tree.text_field_history_max_entries(field)
            && history.max_entries() != max_entries
        {
            history.set_max_entries(max_entries);
        }
        Some(history)
    }

    /// Flutter's `EditableTextState._scheduleShowCaretOnScreen`: when the
    /// focused field gains focus or its value or selection changes, its
    /// ancestor viewports scroll its caret, with `scrollPadding`, into view.
    fn show_focused_caret_on_screen(&mut self) -> bool {
        let Some(field) = self.focused.filter(|id| self.tree.is_text_field(*id)) else {
            self.caret_reveal_key = None;
            return false;
        };
        let Some(controller) = self.tree.text_controller(field) else {
            return false;
        };
        let key = (field, controller.revisions().0, controller.selection());
        if self.caret_reveal_key == Some(key) {
            return false;
        }
        self.caret_reveal_key = Some(key);
        self.tree.text_field_show_caret_on_screen(field)
    }

    fn sync_text_input_client(&mut self) {
        let snapshot = self
            .focused
            .and_then(|id| self.tree.text_field_input_snapshot(id));
        let Some(snapshot) = snapshot else {
            if let Some(client) = self.text_input_client.take() {
                self.text_input_commands
                    .push_back(TextInputCommand::Hide { client });
                self.text_input_commands
                    .push_back(TextInputCommand::Clear { client });
            }
            self.text_input_configuration = None;
            self.text_input_state = None;
            self.text_input_caret_rect = None;
            return;
        };

        let client = TextInputClientId::new(snapshot.client_id);
        let input_type = match snapshot.input_type {
            TextInputTypeHint::Text if snapshot.multiline => TextInputType::Multiline,
            TextInputTypeHint::Text => TextInputType::Text,
            TextInputTypeHint::Multiline => TextInputType::Multiline,
            TextInputTypeHint::Number => TextInputType::Number,
            TextInputTypeHint::Phone => TextInputType::Phone,
            TextInputTypeHint::Email => TextInputType::Email,
            TextInputTypeHint::Url => TextInputType::Url,
            TextInputTypeHint::Password => TextInputType::Password,
        };
        let action = match snapshot.input_action {
            TextInputActionHint::Unspecified => {
                if snapshot.multiline {
                    TextInputAction::Newline
                } else {
                    TextInputAction::Done
                }
            }
            TextInputActionHint::None => TextInputAction::None,
            TextInputActionHint::Done => TextInputAction::Done,
            TextInputActionHint::Go => TextInputAction::Go,
            TextInputActionHint::Search => TextInputAction::Search,
            TextInputActionHint::Send => TextInputAction::Send,
            TextInputActionHint::Next => TextInputAction::Next,
            TextInputActionHint::Previous => TextInputAction::Previous,
            TextInputActionHint::Newline => TextInputAction::Newline,
        };
        let configuration = TextInputConfiguration {
            client,
            input_type: if snapshot.obscure_text {
                TextInputType::Password
            } else {
                input_type
            },
            action,
            multiline: snapshot.multiline,
            enabled: snapshot.enabled,
            read_only: snapshot.read_only,
            obscure_text: snapshot.obscure_text,
            traits: snapshot.traits,
        };
        let state = TextInputState {
            text: snapshot.text,
            selection_start: snapshot.selection.base,
            selection_end: snapshot.selection.extent,
            composing: snapshot.composing.map(|range| (range.start, range.end)),
        };
        let client_changed = self.text_input_client != Some(client);
        let configuration_changed = self.text_input_configuration.as_ref() != Some(&configuration);
        if client_changed || configuration_changed {
            self.text_input_commands
                .push_back(TextInputCommand::SetClient {
                    configuration: configuration.clone(),
                    state: state.clone(),
                    caret_rect: snapshot.caret_rect,
                });
        } else if self.text_input_state.as_ref() != Some(&state) {
            self.text_input_commands
                .push_back(TextInputCommand::Update {
                    client,
                    state: state.clone(),
                });
        }
        if !client_changed
            && self.text_input_caret_rect != Some(snapshot.caret_rect)
            && !configuration_changed
        {
            self.text_input_commands
                .push_back(TextInputCommand::SetCaretRect {
                    client,
                    rect: snapshot.caret_rect,
                });
        }
        self.text_input_client = Some(client);
        self.text_input_configuration = Some(configuration);
        self.text_input_state = Some(state);
        self.text_input_caret_rect = Some(snapshot.caret_rect);
    }
    fn focus_next(&mut self, reverse: bool) {
        let fields = self.tree.focusable_elements();
        if fields.is_empty() {
            return;
        }
        let index = self
            .focused
            .and_then(|focused| fields.iter().position(|id| *id == focused));
        let next = match index {
            Some(index) if reverse => fields[(index + fields.len() - 1) % fields.len()],
            Some(index) => fields[(index + 1) % fields.len()],
            None if reverse => *fields.last().expect("not empty"),
            None => fields[0],
        };
        self.set_focus(Some(next));
    }
    fn handle_key(&mut self, event: KeyboardEvent) {
        self.track_keyboard_modifiers(&event);
        // Widgets that show held modifiers (menu accelerator underlines)
        // rebuild when one is pressed or released.
        if matches!(
            event.code,
            Code::AltLeft
                | Code::AltRight
                | Code::ControlLeft
                | Code::ControlRight
                | Code::ShiftLeft
                | Code::ShiftRight
                | Code::MetaLeft
                | Code::MetaRight
        ) {
            self.frame_requested = true;
        }
        if event.state.is_down() {
            self.editing_diagnostics.key_down_received += 1;
        } else {
            self.editing_diagnostics.key_up_received += 1;
        }

        // A FocusNode may be requested by application code or a FocusScopeNode
        // without going through runtime pointer/Tab handling. Adopt that
        // external selection before routing the event through retained parents.
        if let Some(external) = self.tree.focused_keyboard_element()
            && self.focused != Some(external)
        {
            self.set_focus(Some(external));
        }

        // KeyboardListener/Shortcuts are the nearest retained command scopes.
        // Give them first refusal for every transition, including key-up and
        // auto-repeat; text editing and Tab traversal remain fallthrough paths.
        if self.tree.dispatch_keyboard(self.focused, event.clone()) {
            self.frame_requested = true;
            return;
        }
        if !event.state.is_down() {
            return;
        }
        if event.code == Code::Escape
            && self
                .tree
                .dismiss_transients(incular_widgets::TransientDismissReason::Escape)
                > 0
        {
            self.frame_requested = true;
            return;
        }
        if matches!(
            event.code,
            Code::ArrowUp | Code::ArrowDown | Code::ArrowLeft | Code::ArrowRight
        ) && let Some(focused) = self.focused
            && let Some(next) = self.tree.menu_directional_focus_target(focused, event.code)
        {
            self.set_focus(Some(next));
            return;
        }
        // Activate the focused surface itself. Only menus delegate activation
        // from a focused descendant; nested editors retain their own keys.
        if matches!(event.code, Code::Enter | Code::NumpadEnter | Code::Space)
            && let Some(focused) = self.focused
            && let Some((owner, Some(action))) = self.tree.button_ancestor(focused)
            && (owner == focused || self.tree.is_menu_item_focus(focused))
            && self.activate_action(action)
        {
            return;
        }
        // Flutter's NextFocusIntent/PreviousFocusIntent activators require
        // control, alt and meta to be released; Ctrl+Tab matches nothing.
        if event.code == Code::Tab
            && !event.modifiers.ctrl()
            && !event.modifiers.alt()
            && !event.modifiers.meta()
        {
            self.focus_next(event.modifiers.shift());
            return;
        }
        if let Some(label) = self.focused.filter(|id| self.tree.is_selectable_text(*id)) {
            if self.run_selectable_text_key(label, &event) {
                self.frame_requested = true;
            }
            return;
        }
        let Some(field) = self.focused.filter(|id| self.tree.is_text_field(*id)) else {
            return;
        };
        let Some(controller) = self.tree.text_controller(field) else {
            return;
        };
        // Flutter's `DefaultTextEditingShortcuts` pick the intent for the
        // chord on the target platform and the field's actions run it.
        if !self.run_text_field_key(field, &controller, &event) {
            return;
        }
        self.hide_text_field_menu(field);
        controller.reset_caret(Instant::now());
        self.frame_requested = true;
    }
    /// Whether the field hides its text (Flutter `obscureText`).
    fn text_field_obscured(&self, field: ElementId) -> bool {
        self.tree
            .text_field_input_snapshot(field)
            .is_some_and(|snapshot| snapshot.obscure_text)
    }

    /// Flutter's `EditableText._userSelectionEnabled` with the default
    /// `enableInteractiveSelection`: `!readOnly || !obscureText`.
    fn text_field_pointer_selection_enabled(&self, field: ElementId) -> bool {
        self.tree
            .text_field_input_snapshot(field)
            .is_none_or(|snapshot| !(snapshot.read_only && snapshot.obscure_text))
    }

    /// Flutter's `copySelection` gate: a collapsed selection or obscured text
    /// copies nothing and leaves the clipboard untouched.
    fn text_field_copy_allowed(
        &self,
        field: ElementId,
        controller: &TextEditingController,
    ) -> bool {
        !controller.value().selection.is_collapsed() && !self.text_field_obscured(field)
    }

    /// Flutter's `cutSelection` gate: read-only or obscured fields and collapsed
    /// selections leave both the clipboard and the text unchanged.
    fn cut_text_field_selection(
        &mut self,
        field: ElementId,
        controller: &TextEditingController,
    ) -> bool {
        if !self.tree.text_field_is_editable(field)
            || !self.text_field_copy_allowed(field, controller)
        {
            return false;
        }
        self.clipboard.set_text(controller.selected_text());
        controller.replace_selection("");
        true
    }

    fn insert_text(&mut self, text: &str) {
        let Some(field) = self.focused.filter(|id| self.tree.is_text_field(*id)) else {
            return;
        };
        if !self.tree.text_field_is_editable(field) {
            return;
        }
        if text.chars().any(char::is_control) {
            return;
        }
        if let Some(controller) = self.tree.text_controller(field) {
            controller.insert(text);
            self.editing_diagnostics.text_commits += 1;
            controller.reset_caret(Instant::now());
            self.frame_requested = true;
        }
    }

    /// Handles the action chosen by a native software keyboard. Desktop
    /// Winit backends reach the same code path through Enter, while mobile
    /// hosts can preserve the IME's explicit Done/Next/Search intent.
    pub fn handle_text_input_action(&mut self, action: TextInputAction) -> bool {
        let Some(field) = self.focused.filter(|id| self.tree.is_text_field(*id)) else {
            return false;
        };
        let editable = self.tree.text_field_is_editable(field);
        if !editable {
            return false;
        }
        let handled = match action {
            TextInputAction::Newline => {
                if self.tree.is_multiline_text_field(field) {
                    self.tree.text_controller(field).is_some_and(|controller| {
                        controller.insert("\n");
                        controller.reset_caret(Instant::now());
                        true
                    })
                } else {
                    self.tree.submit_text_field(field)
                }
            }
            TextInputAction::Next => {
                let submitted = self.tree.submit_text_field(field);
                self.focus_next(false);
                submitted
            }
            TextInputAction::Previous => {
                let submitted = self.tree.submit_text_field(field);
                self.focus_next(true);
                submitted
            }
            TextInputAction::Done
            | TextInputAction::Go
            | TextInputAction::Search
            | TextInputAction::Send => self.tree.submit_text_field(field),
            TextInputAction::Unspecified | TextInputAction::None => false,
        };
        if handled {
            self.frame_requested = true;
        }
        handled
    }
    /// Drops the open composition, clearing the owner's stale preedit.
    /// Single cleanup path: the owner's own controller is the only
    /// writer, so cleanup never lands in another editor. Clearing an
    /// unset preedit notifies nothing.
    fn cancel_ime_composition(&mut self) {
        let owner = self.ime_composition.take();
        if let Some(owner) = owner {
            owner.controller.clear_preedit();
        }
    }

    /// Whether the retained owner still names the live editing target:
    /// the focused field, with the same controller identity, still
    /// editable. Anything else means the composition's client is gone.
    fn ime_owner_current(&self) -> bool {
        self.ime_composition.as_ref().is_some_and(|owner| {
            self.focused == Some(owner.field)
                && self.tree.is_text_field(owner.field)
                && self.tree.text_field_is_editable(owner.field)
                && self
                    .tree
                    .text_controller(owner.field)
                    .is_some_and(|current| current == owner.controller)
        })
    }

    fn ime_focused_target(&self) -> Option<ImeCompositionOwner> {
        let field = self
            .focused
            .filter(|id| self.tree.text_field_is_editable(*id))?;
        Some(ImeCompositionOwner {
            field,
            controller: self.tree.text_controller(field)?,
        })
    }

    fn validate_ime_composition(&mut self) {
        if !self.ime_owner_current() {
            self.cancel_ime_composition();
        }
    }

    /// Routes one native IME event. An owner that no longer validates
    /// (focus moved off-path, controller replaced, field unmounted or
    /// no longer editable) is cancelled before routing, so its preedit
    /// clears on its own controller and is never committed elsewhere.
    /// Owned events address the owner; only ownerless Commits fall back
    /// to the focused field, and only ownerless Preedits adopt a target.
    fn handle_ime(&mut self, event: ImeEvent) {
        self.editing_diagnostics.ime_events += 1;
        self.validate_ime_composition();
        let target = match &event {
            ImeEvent::Preedit { .. } => {
                if self.ime_composition.is_none() {
                    self.ime_composition = self.ime_focused_target();
                }
                self.ime_composition
                    .as_ref()
                    .map(|owner| owner.controller.clone())
            }
            ImeEvent::Commit(_) => self
                .ime_composition
                .take()
                .or_else(|| self.ime_focused_target())
                .map(|owner| owner.controller),
            ImeEvent::End => self.ime_composition.take().map(|owner| owner.controller),
        };
        let Some(controller) = target else {
            return;
        };
        match event {
            ImeEvent::Preedit { text, selection } => {
                controller.set_preedit(
                    text,
                    selection.map(|(start, end)| TextRange::new(start, end)),
                );
            }
            ImeEvent::Commit(text) => {
                // Ownerless commit policy: without a session or client
                // identity, a late Commit after focus changes cannot be
                // distinguished from a legitimate direct commit, so it
                // applies to the focused editable field. This is a routing
                // policy, not stale-commit protection.
                controller.commit_preedit(&text);
            }
            ImeEvent::End => {
                controller.clear_preedit();
            }
        }
        controller.reset_caret(Instant::now());
        self.frame_requested = true;
    }
    pub fn run_frame(
        &mut self,
        constraints: Constraints,
    ) -> Result<(DisplayList, FrameStats), TreeError> {
        self.run_frame_at(constraints, Instant::now())
    }
    /// Deterministic frame entry point used by animation tests and embedders
    /// with an existing monotonic clock.
    pub fn run_frame_at(
        &mut self,
        constraints: Constraints,
        now: Instant,
    ) -> Result<(DisplayList, FrameStats), TreeError> {
        let message_guard = tracing::info_span!("incular.messages").entered();
        let message_span = profiling::PhaseSpan::start();
        self.process_runtime_work_at(now);
        let runtime_messages = message_span.elapsed_us();
        drop(message_guard);
        let before = self.tree.diagnostics();
        let build_guard =
            tracing::info_span!("incular.build", elements_updated = tracing::field::Empty,)
                .entered();
        let build_span = profiling::PhaseSpan::start();
        let mut updated = 0;
        while let Some(id) = self.order.pop_front() {
            if let Some(widget) = self.pending.remove(&id)
                && self.tree.element_exists(id)
            {
                self.tree.update(id, widget)?;
                updated += 1;
            }
        }
        loop {
            while let Some((root, node)) = { self.reactive.borrow_mut().take_node() } {
                if let Some(node) = node.upgrade() {
                    node.run(root);
                }
            }
            while let Some(id) = { self.reactive.borrow_mut().take() } {
                if self.tree.element_exists(id) && self.builders.contains_key(&id) {
                    #[cfg(feature = "devtools")]
                    for cause in self.reactive.borrow_mut().take_causes(id) {
                        self.tree.note_invalidation(id, cause);
                    }
                    self.rebuild_from_builder(id)?;
                    updated += 1;
                }
            }
            if !self.reactive.borrow().has_work() {
                break;
            }
        }
        for id in self.tree.take_unmounted() {
            self.handlers_stale = true;
            self.builders.remove(&id);
            self.reactive.borrow_mut().forget(id);
            if let Some(scope) = self.owner_scopes.remove(&id) {
                scope.cancel();
            }
            self.text_histories.remove(&id);
        }
        self.reconcile_focus_and_selection_captures();
        self.validate_ime_composition();
        self.prune_handlers();
        let build = build_span.elapsed_us();
        drop(build_guard);
        // Ballistic tenures pump on the frame clock before layout, so
        // pumped offsets lay out and paint in the same frame. The pump
        // reports live drivers; that liveness is captured here and
        // ORed into the end-of-frame demand below, so the reset point
        // cannot discard it — the scheduler stays awake while a driver
        // lives and idles otherwise. No timer loop, just frame demand.
        let reduced_motion = self.environment.borrow().reduced_motion;
        let fling_live = self.tree.pump_scroll_flings(now, reduced_motion);
        // The overlay scrollbar's reveal/fade-out follows scrolling and hover,
        // so it steps after flings and before paint.
        let scrollbar_live = self.tree.pump_scrollbar_fades(now);
        // Press and long-press deadlines (`kPressTimeout`, `kLongPressTimeout`)
        // fire on the frame clock while a pointer is held without moving.
        let gesture_timers_live = self.tree.pump_gesture_timers(now);
        let _layout_guard = tracing::info_span!("incular.layout").entered();
        let layout_span = profiling::PhaseSpan::start();
        self.tree.layout(constraints)?;
        let layout = layout_span.elapsed_us();
        drop(_layout_guard);
        for (action, handler) in self.tree.take_pending_handlers() {
            self.handlers_stale = true;
            self.handlers.insert(action, handler);
        }
        // Lazy viewport expiry occurs during layout, after the ordinary dirty
        // queue drain above. Release those builder subscriptions and callbacks
        // in the same frame rather than retaining one stale cache generation.
        for id in self.tree.take_unmounted() {
            self.handlers_stale = true;
            self.builders.remove(&id);
            self.reactive.borrow_mut().forget(id);
            if let Some(scope) = self.owner_scopes.remove(&id) {
                scope.cancel();
            }
            self.text_histories.remove(&id);
        }
        self.reconcile_focus_and_selection_captures();
        self.validate_ime_composition();
        self.prune_handlers();
        // Layout builders create their retained controls during the first
        // layout. Resolve initial autofocus once those controls exist, without
        // reclaiming focus on later frames or after an explicit input decision.
        if self.initial_focus == InitialFocus::AwaitingLayout {
            self.set_focus(self.tree.autofocus_element());
        }
        let _composite_guard = tracing::info_span!("incular.composite").entered();
        let composite_span = profiling::PhaseSpan::start();
        let (composited, animations_active) = self.tree.update_compositor(now)?;
        let composite = composite_span.elapsed_us();
        drop(_composite_guard);
        // Layout and the compositor's scroll translations are final here,
        // so hover catches up with content that moved under the pointer
        // and its paint lands in this frame.
        let geometry = self.tree.diagnostics();
        if geometry.layouts != before.layouts
            || geometry.scroll_offset_updates != before.scroll_offset_updates
        {
            self.refresh_hover_after_layout();
        }
        let _semantics_guard = tracing::info_span!("incular.semantics").entered();
        let semantics_span = profiling::PhaseSpan::start();
        self.tree.update_semantics();
        let semantics = semantics_span.elapsed_us();
        drop(_semantics_guard);
        let _paint_guard = tracing::info_span!("incular.paint").entered();
        let paint_span = profiling::PhaseSpan::start();
        let display_list = self.tree.paint();
        let paint = paint_span.elapsed_us();
        drop(_paint_guard);
        self.sync_text_input_client();
        // A focused field whose value or selection changed scrolls its
        // ancestors to show the caret; the next frame lays that out.
        let caret_revealed = self.show_focused_caret_on_screen();
        // End-of-frame reset: recomputed from every demand source, not
        // blindly cleared. `fling_live` above is one source — a write
        // before layout alone would not survive this assignment, so it
        // is ORed back in. Nothing else in this frame clears the flag:
        // intermediate paths only ever set it.
        self.frame_requested = fling_live
            || caret_revealed
            || gesture_timers_live
            || scrollbar_live
            || !self.pending.is_empty()
            || self.reactive.borrow().has_work()
            || animations_active;
        let after = self.tree.diagnostics();
        let timings = FrameTimings {
            event_processing: std::mem::take(&mut self.pending_event_processing_us),
            runtime_messages,
            build,
            layout,
            composite,
            semantics,
            paint,
            cpu_total: runtime_messages + build + layout + composite + semantics + paint,
        };
        tracing::debug!(
            target: "incular::frame",
            cpu_total_us = timings.cpu_total,
            build_us = timings.build,
            layout_us = timings.layout,
            paint_us = timings.paint,
        );
        Ok((
            display_list.clone(),
            FrameStats {
                updated_elements: updated,
                rebuilt_elements: after.rebuilds - before.rebuilds,
                laid_out_render_objects: after.layouts - before.layouts,
                repainted_render_objects: after.paints - before.paints,
                composited: u64::from(composited),
                active_animations: u64::from(animations_active),
                display_list_commands: display_list.len(),
                requested_another_frame: self.frame_requested,
                timings,
            },
        ))
    }
    #[must_use]
    pub fn diagnostics(&self) -> Diagnostics {
        self.tree.diagnostics()
    }
    /// Queues every registered builder for the next frame's build drain,
    /// application root first so descendants it unmounts are skipped.
    #[cfg(feature = "hot-reload")]
    pub(crate) fn reassemble(&mut self) {
        let root = self.application_root;
        let ids = root
            .into_iter()
            .chain(self.builders.keys().copied().filter(|id| Some(*id) != root))
            .collect::<Vec<_>>();
        let mut reactive = self.reactive.borrow_mut();
        for id in ids {
            #[cfg(feature = "devtools")]
            reactive.note_cause(id, InvalidationCause::Manual);
            reactive.enqueue(id);
        }
        drop(reactive);
        self.frame_requested = true;
    }
    /// Rebuilds one registered builder outside the frame drain. Route
    /// outlets use this to refresh mounted content deterministically
    /// before framing, rather than only when reactive dependencies fire.
    pub(crate) fn rebuild_from_builder(&mut self, id: ElementId) -> Result<(), TreeError> {
        self.reactive.borrow_mut().refresh(id);
        let widget = {
            let _build_scope = BuildScopeGuard::enter(BuildScope {
                root: self.reactive.borrow().root,
                element: Some(id),
                queue: Rc::downgrade(&self.reactive),
                initial_dependencies: None,
                spawner: self.spawner(),
                owner_scope: self
                    .owner_scopes
                    .get(&id)
                    .cloned()
                    .unwrap_or_else(|| self.window_scope.clone()),
            });
            self.builders.get_mut(&id).expect("registered builder")()
        };
        let mut widget = widget;
        self.prepare_widget(&mut widget);
        self.tree.update(id, widget)?;
        Ok(())
    }
    fn prepare_widget(&mut self, widget: &mut Widget) {
        self.handlers_stale = true;
        let handlers = &mut self.handlers;
        let tree = &mut self.tree;
        widget.bind_callbacks(&mut |callback| {
            let id = tree.allocate_action();
            handlers.insert(id, callback);
            id
        });
    }
    fn activate_action(&mut self, action: ActionId) -> bool {
        let mut handled = false;
        if let Some(callback) = self.handlers.get(&action).cloned() {
            callback();
            handled = true;
        }
        if let Some(callback) = self.legacy_action_handler.as_mut() {
            callback(action);
            handled = true;
        }
        self.frame_requested |= handled;
        handled
    }

    fn prune_handlers(&mut self) {
        if !std::mem::take(&mut self.handlers_stale) {
            return;
        }
        let active = self.tree.action_ids();
        self.handlers.retain(|id, _| active.contains(id));
    }
    fn set_hover(&mut self, next: Option<ElementId>) {
        if self.hovered_button == next {
            return;
        }
        if let Some(previous) = self.hovered_button {
            let _ = self
                .tree
                .set_button_interaction(previous, Some(false), None, None);
            if let Some(action) = self.tree.hover_actions_for_element(previous).1
                && let Some(callback) = self.handlers.get(&action).cloned()
            {
                callback();
            }
        }
        self.hovered_button = next;
        if let Some(current) = next {
            if self.pressed_button != Some(current) {
                let _ = self
                    .tree
                    .set_button_interaction(current, Some(true), None, None);
            }
            if let Some(action) = self.tree.hover_actions_for_element(current).0
                && let Some(callback) = self.handlers.get(&action).cloned()
            {
                callback();
            }
        }
        self.frame_requested = true;
    }
}

/// Framework-controlled build scope for declarative roots. It intentionally
/// exposes no element IDs or scheduler handles. Signals use the runtime's
/// scoped collector while a builder executes; reads outside a build simply
/// do not create dependencies.
fn us_since_instant(started: incular_core::time::Instant) -> u32 {
    started.elapsed().as_micros().try_into().unwrap_or(u32::MAX)
}