fret-ui 0.1.0

Mechanism-layer UI engine for Fret with tree, layout, focus, routing, and interaction contracts.
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
use crate::{Theme, UiHost};
use fret_core::{
    AppWindowId, Corners, Event, NodeId, Point, Rect, Scene, SemanticsCheckedState, SemanticsFlags,
    SemanticsInvalid, SemanticsLive, SemanticsOrientation, SemanticsPressedState, SemanticsRole,
    Size, Transform2D, UiServices,
};
use fret_runtime::{
    CommandId, DefaultAction, DefaultActionSet, Effect, InputContext, Model, ModelId,
};
use std::any::{Any, TypeId};
use std::collections::HashMap;

use crate::layout_constraints::LayoutConstraints;
use crate::layout_pass::LayoutPassKind;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Invalidation {
    Layout,
    Paint,
    HitTest,
    /// Recompute hit-testing and repaint, without forcing a layout pass.
    ///
    /// This is intended for state changes that affect coordinate mapping (e.g. scrolling) but do
    /// not change layout geometry.
    HitTestOnly,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UiSourceLocation {
    pub file: &'static str,
    pub line: u32,
    pub column: u32,
}

pub struct EventCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub services: &'a mut dyn UiServices,
    pub node: NodeId,
    pub layer_root: Option<NodeId>,
    pub window: Option<AppWindowId>,
    pub pointer_id: Option<fret_core::PointerId>,
    /// Window scale factor recorded by the UI tree on the most recent layout pass.
    ///
    /// This is best-effort: events may arrive before the first layout, in which case the value
    /// defaults to `1.0`.
    pub scale_factor: f32,
    /// The incoming pointer position in window-local logical pixels (before any transform-aware
    /// mapping performed by the UI runtime).
    ///
    /// When an event does not carry a pointer position, this is `None`.
    pub event_window_position: Option<Point>,
    /// The incoming wheel delta in window-local logical pixels (before any transform-aware
    /// mapping performed by the UI runtime).
    ///
    /// When the current event is not a wheel event, this is `None`.
    pub event_window_wheel_delta: Option<Point>,
    pub input_ctx: InputContext,
    /// `true` when the pointer hit-test target is (or is inside) a text input element subtree
    /// (`TextInput`, `TextArea`, or `TextInputRegion`).
    ///
    /// This is computed by the UI runtime during dispatch and is available to mechanism widgets
    /// (e.g. `PointerRegion`) so action payloads can carry enough information for policy-level
    /// gesture arbitration without exposing widget internals.
    pub pointer_hit_is_text_input: bool,
    /// `true` when the pointer hit-test target is (or is inside) a pressable element subtree
    /// (`Pressable`).
    ///
    /// This is computed by the UI runtime during dispatch and is available to mechanism widgets
    /// (e.g. `PointerRegion`) so action payloads can carry enough information for policy-level
    /// gesture arbitration without exposing widget internals.
    pub pointer_hit_is_pressable: bool,
    /// The deepest pressable element in the pointer-down hit-test chain (if any).
    ///
    /// This is computed by the UI runtime during dispatch and is available to mechanism widgets
    /// (e.g. `PointerRegion`, `Pressable`) so policy-level hooks can distinguish nested pressable
    /// targets (e.g. "row click" vs "button inside row").
    pub pointer_hit_pressable_target: Option<crate::GlobalElementId>,
    /// `true` when `pointer_hit_pressable_target` is a strict descendant of the current event
    /// target in the hit-test chain.
    ///
    /// This excludes ambient ancestor pressables and the current target itself, so policy hooks
    /// can suppress forwarding only for truly nested interactive descendants.
    pub pointer_hit_pressable_target_in_descendant_subtree: bool,
    pub prevented_default_actions: &'a mut DefaultActionSet,
    pub children: &'a [NodeId],
    pub focus: Option<NodeId>,
    pub captured: Option<NodeId>,
    pub bounds: Rect,
    pub invalidations: Vec<(NodeId, Invalidation)>,
    pub(crate) scroll_handle_invalidations: Vec<ScrollHandleInvalidationRequest>,
    pub(crate) scroll_target_invalidations: Vec<crate::GlobalElementId>,
    pub requested_focus: Option<NodeId>,
    pub requested_focus_target: Option<crate::GlobalElementId>,
    pub requested_capture: Option<Option<NodeId>>,
    pub requested_cursor: Option<fret_core::CursorIcon>,
    pub notify_requested: bool,
    pub notify_requested_location: Option<UiSourceLocation>,
    pub stop_propagation: bool,
}

impl<'a, H: UiHost> EventCx<'a, H> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        app: &'a mut H,
        services: &'a mut dyn UiServices,
        node: NodeId,
        layer_root: Option<NodeId>,
        window: Option<AppWindowId>,
        input_ctx: InputContext,
        pointer_id: Option<fret_core::PointerId>,
        scale_factor: f32,
        event_window_position: Option<Point>,
        event_window_wheel_delta: Option<Point>,
        pointer_hit_is_text_input: bool,
        pointer_hit_is_pressable: bool,
        pointer_hit_pressable_target: Option<crate::GlobalElementId>,
        pointer_hit_pressable_target_in_descendant_subtree: bool,
        prevented_default_actions: &'a mut DefaultActionSet,
        children: &'a [NodeId],
        focus: Option<NodeId>,
        captured: Option<NodeId>,
        bounds: Rect,
    ) -> Self {
        Self {
            app,
            services,
            node,
            layer_root,
            window,
            pointer_id,
            scale_factor,
            event_window_position,
            event_window_wheel_delta,
            input_ctx,
            pointer_hit_is_text_input,
            pointer_hit_is_pressable,
            pointer_hit_pressable_target,
            pointer_hit_pressable_target_in_descendant_subtree,
            prevented_default_actions,
            children,
            focus,
            captured,
            bounds,
            invalidations: Vec::new(),
            scroll_handle_invalidations: Vec::new(),
            scroll_target_invalidations: Vec::new(),
            requested_focus: None,
            requested_focus_target: None,
            requested_capture: None,
            requested_cursor: None,
            notify_requested: false,
            notify_requested_location: None,
            stop_propagation: false,
        }
    }

    pub fn theme(&self) -> &Theme {
        Theme::global(&*self.app)
    }

    /// Returns the pointer position in the current widget's local coordinate space (origin at
    /// `(0, 0)`), derived from the mapped event position.
    ///
    /// Notes:
    /// - The UI runtime maps pointer event positions into each widget's untransformed layout
    ///   space (ADR 0238), so `event.position` is in the same space as `self.bounds`.
    /// - This helper is purely derived and does not introduce state.
    pub fn pointer_position_local(&self, event: &Event) -> Option<Point> {
        let pos = Self::pointer_position_mapped(event)?;
        Some(Point::new(
            fret_core::Px(pos.x.0 - self.bounds.origin.x.0),
            fret_core::Px(pos.y.0 - self.bounds.origin.y.0),
        ))
    }

    /// Returns the pointer position in window-local logical pixels (pre-mapping).
    pub fn pointer_position_window(&self, event: &Event) -> Option<Point> {
        Self::pointer_position_mapped(event).and(self.event_window_position)
    }

    /// Returns the wheel delta in the current widget's local coordinate space (origin at
    /// `(0, 0)`), derived from the mapped event delta.
    pub fn pointer_delta_local(&self, event: &Event) -> Option<Point> {
        match event {
            Event::Pointer(fret_core::PointerEvent::Wheel { delta, .. }) => Some(*delta),
            _ => None,
        }
    }

    /// Returns the wheel delta in window-local logical pixels (pre-mapping).
    pub fn pointer_delta_window(&self, event: &Event) -> Option<Point> {
        self.pointer_delta_local(event)
            .and(self.event_window_wheel_delta)
    }

    fn pointer_position_mapped(event: &Event) -> Option<Point> {
        match event {
            Event::Pointer(e) => match e {
                fret_core::PointerEvent::Move { position, .. }
                | fret_core::PointerEvent::Down { position, .. }
                | fret_core::PointerEvent::Up { position, .. }
                | fret_core::PointerEvent::Wheel { position, .. }
                | fret_core::PointerEvent::PinchGesture { position, .. } => Some(*position),
            },
            Event::PointerCancel(e) => e.position,
            Event::ExternalDrag(e) => Some(e.position),
            Event::InternalDrag(e) => Some(e.position),
            _ => None,
        }
    }

    /// Best-effort frame clock snapshot for the current window (ADR 0240).
    ///
    /// This is intentionally a plain read (non-reactive): it does not participate in view-cache
    /// dependency tracking.
    pub fn frame_clock(&self) -> Option<fret_core::WindowFrameClockSnapshot> {
        let window = self.window?;
        self.app
            .global::<fret_core::WindowFrameClockService>()
            .and_then(|svc| svc.snapshot(window))
    }

    /// Best-effort reduced-motion preference for the current window (ADR 0232 / ADR 0240).
    pub fn prefers_reduced_motion(&self) -> Option<bool> {
        let window = self.window?;
        self.app
            .global::<fret_core::WindowMetricsService>()
            .and_then(|svc| {
                svc.prefers_reduced_motion_is_known(window)
                    .then(|| svc.prefers_reduced_motion(window))
                    .flatten()
            })
    }

    /// Latest pointer position snapshot in window-local logical pixels (ADR 0243).
    pub fn pointer_position_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.position_window(window, pointer_id))
    }

    /// Latest pointer velocity snapshot in window-local logical pixels per second (ADR 0243).
    pub fn pointer_velocity_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.velocity_window(window, pointer_id))
    }

    pub fn invalidate(&mut self, node: NodeId, kind: Invalidation) {
        self.invalidations.push((node, kind));
    }

    /// Request invalidation for all live nodes currently bound to a scroll handle.
    ///
    /// Resolution is deferred until the dispatch runtime regains access to `UiTree`, so widgets
    /// do not need to reason about stale registry bindings or attachment state.
    pub fn invalidate_scroll_handle_bindings(&mut self, handle_key: usize, kind: Invalidation) {
        self.scroll_handle_invalidations
            .push(ScrollHandleInvalidationRequest { handle_key, kind });
    }

    /// Request invalidation for the live attached node currently associated with an element-backed
    /// scroll target.
    ///
    /// Resolution is deferred until the dispatch runtime regains access to `UiTree`, so widgets
    /// do not need to interpret same-frame retained bookkeeping directly.
    pub(crate) fn invalidate_scroll_target(&mut self, element: crate::GlobalElementId) {
        self.scroll_target_invalidations.push(element);
    }

    pub fn invalidate_self(&mut self, kind: Invalidation) {
        self.invalidate(self.node, kind);
    }

    pub fn dispatch_command(&mut self, command: CommandId) {
        self.app.push_effect(Effect::Command {
            window: self.window,
            command,
        });
    }

    pub fn request_focus(&mut self, node: NodeId) {
        self.requested_focus = Some(node);
    }

    pub fn capture_pointer(&mut self, node: NodeId) {
        if self.pointer_id.is_none() {
            return;
        }
        self.requested_capture = Some(Some(node));
    }

    pub fn release_pointer_capture(&mut self) {
        if self.pointer_id.is_none() {
            return;
        }
        self.requested_capture = Some(None);
    }

    pub fn stop_propagation(&mut self) {
        self.stop_propagation = true;
    }

    pub fn prevent_default(&mut self, action: DefaultAction) {
        self.prevented_default_actions.insert(action);
    }

    pub fn default_prevented(&self, action: DefaultAction) -> bool {
        self.prevented_default_actions.contains(action)
    }

    /// Request a window redraw (one-shot).
    ///
    /// Use this for one-shot updates after state changes (e.g. responding to input).
    ///
    /// Notes:
    /// - A redraw does not necessarily imply a fresh widget `paint()` pass if the UI tree can
    ///   replay a valid paint cache entry. If you need frame-driven updates, prefer
    ///   `request_animation_frame()` (from `LayoutCx`/`PaintCx`/`MeasureCx`) which also ensures
    ///   `Invalidation::Paint` is set.
    /// - `request_redraw()` is not a timer. If you need continuous progression without input
    ///   (animations, progressive rendering), you must request the next frame via
    ///   `request_animation_frame()` (or a higher-level continuous-frames helper).
    /// - A redraw request may be coalesced and does not necessarily wake a sleeping event loop on
    ///   all platforms. Prefer `request_animation_frame()` for frame-driven progression.
    pub fn request_redraw(&mut self) {
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Mark the current view as dirty and schedule a redraw.
    ///
    /// In view-cache mode, this forces the nearest cache root to rerender (skip view-cache reuse)
    /// and prevents paint replay of stale recorded ranges.
    #[track_caller]
    pub fn notify(&mut self) {
        self.notify_requested = true;
        if self.notify_requested_location.is_none() {
            let caller = std::panic::Location::caller();
            self.notify_requested_location = Some(UiSourceLocation {
                file: caller.file(),
                line: caller.line(),
                column: caller.column(),
            });
        }
    }

    pub fn set_cursor_icon(&mut self, icon: fret_core::CursorIcon) {
        if !self.input_ctx.caps.ui.cursor_icons {
            return;
        }
        self.requested_cursor = Some(icon);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ScrollHandleInvalidationRequest {
    pub(crate) handle_key: usize,
    pub(crate) kind: Invalidation,
}

/// Observer-only event context for the `InputDispatchPhase::Preview` pass.
///
/// This pass exists to support "click-through outside-press" policies (ADR 0069) without allowing
/// widgets to mutate input routing state (focus / capture / propagation / default actions).
pub struct ObserverCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub services: &'a mut dyn UiServices,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub pointer_id: Option<fret_core::PointerId>,
    pub input_ctx: InputContext,
    pub children: &'a [NodeId],
    pub focus: Option<NodeId>,
    pub captured: Option<NodeId>,
    pub bounds: Rect,
    pub invalidations: Vec<(NodeId, Invalidation)>,
    pub notify_requested: bool,
    pub notify_requested_location: Option<UiSourceLocation>,
}

impl<'a, H: UiHost> ObserverCx<'a, H> {
    pub fn theme(&self) -> &Theme {
        Theme::global(&*self.app)
    }

    pub fn invalidate(&mut self, node: NodeId, kind: Invalidation) {
        self.invalidations.push((node, kind));
    }

    pub fn invalidate_self(&mut self, kind: Invalidation) {
        self.invalidate(self.node, kind);
    }

    pub fn dispatch_command(&mut self, command: CommandId) {
        self.app.push_effect(Effect::Command {
            window: self.window,
            command,
        });
    }

    /// Request a window redraw (one-shot).
    pub fn request_redraw(&mut self) {
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Mark the current view as dirty and schedule a redraw.
    ///
    /// In view-cache mode, this forces the nearest cache root to rerender (skip view-cache reuse)
    /// and prevents paint replay of stale recorded ranges.
    #[track_caller]
    pub fn notify(&mut self) {
        self.notify_requested = true;
        if self.notify_requested_location.is_none() {
            let caller = std::panic::Location::caller();
            self.notify_requested_location = Some(UiSourceLocation {
                file: caller.file(),
                line: caller.line(),
                column: caller.column(),
            });
        }
    }
}

pub struct CommandCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub services: &'a mut dyn UiServices,
    pub tree: &'a mut crate::tree::UiTree<H>,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub input_ctx: InputContext,
    pub focus: Option<NodeId>,
    pub invalidations: Vec<(NodeId, Invalidation)>,
    pub requested_focus: Option<NodeId>,
    pub notify_requested: bool,
    pub notify_requested_location: Option<UiSourceLocation>,
    pub stop_propagation: bool,
}

impl<'a, H: UiHost> CommandCx<'a, H> {
    pub fn theme(&self) -> &Theme {
        Theme::global(&*self.app)
    }

    pub fn invalidate(&mut self, node: NodeId, kind: Invalidation) {
        self.invalidations.push((node, kind));
    }

    pub fn invalidate_self(&mut self, kind: Invalidation) {
        self.invalidate(self.node, kind);
    }

    pub fn request_focus(&mut self, node: NodeId) {
        self.requested_focus = Some(node);
    }

    pub fn stop_propagation(&mut self) {
        self.stop_propagation = true;
    }

    /// Request a window redraw.
    ///
    /// Use this for one-shot updates after state changes. For frame-driven updates (animations,
    /// progressive rendering), prefer `request_animation_frame()` when available.
    pub fn request_redraw(&mut self) {
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Mark the current view as dirty and schedule a redraw.
    ///
    /// In view-cache mode, this forces the nearest cache root to rerender (skip view-cache reuse)
    /// and prevents paint replay of stale recorded ranges.
    #[track_caller]
    pub fn notify(&mut self) {
        self.notify_requested = true;
        if self.notify_requested_location.is_none() {
            let caller = std::panic::Location::caller();
            self.notify_requested_location = Some(UiSourceLocation {
                file: caller.file(),
                line: caller.line(),
                column: caller.column(),
            });
        }
    }
}

/// Command availability query result used by `UiTree::is_command_available` (ADR 0218).
///
/// This is a pure query signal (no side effects). Consumers typically interpret:
/// - `Available`: command should be treated as enabled for the current dispatch path.
/// - `Blocked`: command must not bubble further to ancestors for availability purposes.
/// - `NotHandled`: this node does not participate in availability for this command.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum CommandAvailability {
    #[default]
    NotHandled,
    Available,
    Blocked,
}

/// Context passed to `Widget::command_availability`.
///
/// This is intentionally read-only (no `UiServices`, no invalidations) to keep availability a pure
/// query.
pub struct CommandAvailabilityCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub tree: &'a crate::tree::UiTree<H>,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub input_ctx: InputContext,
    pub focus: Option<NodeId>,
}

pub struct LayoutCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub tree: &'a mut crate::tree::UiTree<H>,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub focus: Option<NodeId>,
    pub children: &'a [NodeId],
    pub bounds: Rect,
    pub available: Size,
    pub pass_kind: LayoutPassKind,
    pub overflow_ctx: crate::layout::overflow::LayoutOverflowContext,
    pub scale_factor: f32,
    pub services: &'a mut dyn UiServices,
    pub observe_model: &'a mut dyn FnMut(ModelId, Invalidation),
    pub observe_global: &'a mut dyn FnMut(TypeId, Invalidation),
}

impl<'a, H: UiHost> LayoutCx<'a, H> {
    pub fn probe_constraints_for_size(&self, size: Size) -> LayoutConstraints {
        self.overflow_ctx.probe_constraints_for_size(size)
    }

    pub fn with_overflow_context<R>(
        &mut self,
        overflow_ctx: crate::layout::overflow::LayoutOverflowContext,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let prev = self.overflow_ctx;
        self.overflow_ctx = overflow_ctx;
        let out = f(self);
        self.overflow_ctx = prev;
        out
    }

    pub fn theme(&mut self) -> &Theme {
        self.observe_global::<Theme>(Invalidation::Layout);
        Theme::global(&*self.app)
    }

    /// Request a window redraw (one-shot).
    ///
    /// This schedules a paint of the current UI state. If you need continuous frame progression
    /// (e.g. animations or progressive rendering without input), use `request_animation_frame()`.
    pub fn request_redraw(&mut self) {
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Request the next animation frame for this window.
    ///
    /// Use this for frame-driven behaviors (animations, progress indicators, progressive
    /// rendering) where the UI must keep repainting even if there are no incoming events.
    ///
    /// This is a one-shot request. Code that animates should re-issue
    /// `request_animation_frame()` each frame while it remains active.
    ///
    /// This method also ensures `Invalidation::Paint` is set for the calling node so paint caching
    /// cannot short-circuit the widget `paint()` pass on the next frame.
    pub fn request_animation_frame(&mut self) {
        // Ensure animation-frame requests trigger a paint pass even when paint caching is enabled.
        self.tree.invalidate_with_source_and_detail(
            self.node,
            Invalidation::Paint,
            crate::tree::UiDebugInvalidationSource::Notify,
            crate::tree::UiDebugInvalidationDetail::AnimationFrameRequest,
        );
        let Some(window) = self.window else {
            return;
        };
        self.app.push_effect(Effect::RequestAnimationFrame(window));
    }

    /// Best-effort frame clock snapshot for the current window (ADR 0240).
    ///
    /// This is intentionally a plain read (non-reactive): it does not participate in view-cache
    /// dependency tracking.
    pub fn frame_clock(&self) -> Option<fret_core::WindowFrameClockSnapshot> {
        let window = self.window?;
        self.app
            .global::<fret_core::WindowFrameClockService>()
            .and_then(|svc| svc.snapshot(window))
    }

    /// Latest pointer position snapshot in window-local logical pixels (ADR 0243).
    pub fn pointer_position_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.position_window(window, pointer_id))
    }

    /// Latest pointer velocity snapshot in window-local logical pixels per second (ADR 0243).
    pub fn pointer_velocity_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.velocity_window(window, pointer_id))
    }

    /// Latest pointer position snapshot mapped into this node's local coordinate space
    /// (origin at `(0, 0)`), transform-aware (ADR 0238 / ADR 0243).
    pub fn pointer_position_local_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window_pos = self.pointer_position_window_snapshot(pointer_id)?;
        let mapped = self
            .tree
            .map_window_point_to_node_layout_space(self.node, window_pos)?;
        Some(Point::new(
            fret_core::Px(mapped.x.0 - self.bounds.origin.x.0),
            fret_core::Px(mapped.y.0 - self.bounds.origin.y.0),
        ))
    }

    /// Latest pointer velocity snapshot mapped into this node's local coordinate space (ADR 0238 / ADR 0243).
    pub fn pointer_velocity_local_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window_vec = self.pointer_velocity_window_snapshot(pointer_id)?;
        self.tree
            .map_window_vector_to_node_layout_space(self.node, window_vec)
    }

    pub fn observe_model<T>(&mut self, model: &Model<T>, invalidation: Invalidation) {
        (self.observe_model)(model.id(), invalidation);
    }

    pub fn observe_global<T: Any>(&mut self, invalidation: Invalidation) {
        (self.observe_global)(TypeId::of::<T>(), invalidation);
    }

    pub fn layout(&mut self, child: NodeId, available: Size) -> Size {
        let rect = Rect::new(self.bounds.origin, available);
        self.layout_in(child, rect)
    }

    pub fn layout_in(&mut self, child: NodeId, bounds: Rect) -> Size {
        self.tree.layout_in_with_pass_kind(
            self.app,
            self.services,
            child,
            bounds,
            self.scale_factor,
            self.pass_kind,
            self.overflow_ctx,
        )
    }

    pub fn layout_in_probe(&mut self, child: NodeId, bounds: Rect) -> Size {
        self.tree.layout_in_with_pass_kind(
            self.app,
            self.services,
            child,
            bounds,
            self.scale_factor,
            LayoutPassKind::Probe,
            self.overflow_ctx,
        )
    }

    pub fn layout_engine_child_bounds(&mut self, child: NodeId) -> Option<Rect> {
        let local = self
            .tree
            .layout_engine_child_local_rect_profiled(self.node, child)?;
        Some(Rect::new(
            Point::new(
                fret_core::Px(self.bounds.origin.x.0 + local.origin.x.0),
                fret_core::Px(self.bounds.origin.y.0 + local.origin.y.0),
            ),
            local.size,
        ))
    }

    pub fn layout_viewport_root(&mut self, child: NodeId, bounds: Rect) -> Size {
        if self.pass_kind == LayoutPassKind::Probe {
            return bounds.size;
        }
        self.tree.register_viewport_root(child, bounds);
        bounds.size
    }

    pub fn solve_barrier_child_root(&mut self, child: NodeId, bounds: Rect) {
        if self.pass_kind != LayoutPassKind::Final {
            return;
        }
        self.tree.solve_barrier_flow_root(
            self.app,
            self.services,
            child,
            bounds,
            self.scale_factor,
        );
    }

    pub fn solve_barrier_child_root_if_needed(&mut self, child: NodeId, bounds: Rect) {
        if self.pass_kind != LayoutPassKind::Final {
            return;
        }
        self.tree.solve_barrier_flow_root_if_needed(
            self.app,
            self.services,
            child,
            bounds,
            self.scale_factor,
        );
    }

    pub fn solve_barrier_child_roots_if_needed(&mut self, roots: &[(NodeId, Rect)]) {
        if self.pass_kind != LayoutPassKind::Final {
            return;
        }
        self.tree.solve_barrier_flow_roots_if_needed(
            self.app,
            self.services,
            roots,
            self.scale_factor,
        );
    }
    pub fn measure_in(&mut self, child: NodeId, constraints: LayoutConstraints) -> Size {
        self.tree.measure_in(
            self.app,
            self.services,
            child,
            constraints,
            self.scale_factor,
        )
    }
}

pub struct MeasureCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub tree: &'a mut crate::tree::UiTree<H>,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub focus: Option<NodeId>,
    pub children: &'a [NodeId],
    pub constraints: LayoutConstraints,
    pub scale_factor: f32,
    pub services: &'a mut dyn UiServices,
    pub observe_model: &'a mut dyn FnMut(ModelId, Invalidation),
    pub observe_global: &'a mut dyn FnMut(TypeId, Invalidation),
}

impl<'a, H: UiHost> MeasureCx<'a, H> {
    pub fn theme(&mut self) -> &Theme {
        self.observe_global::<Theme>(Invalidation::Layout);
        Theme::global(&*self.app)
    }

    /// Request a window redraw (one-shot).
    ///
    /// This is typically used after mutating model/state in response to user input. For
    /// frame-driven updates, use `request_animation_frame()`.
    pub fn request_redraw(&mut self) {
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Request the next animation frame for this window.
    ///
    /// Use this for animations/progressive rendering that must advance without input events.
    ///
    /// This is a one-shot request. Callers should re-issue `request_animation_frame()` each frame
    /// while it remains active.
    /// This also sets `Invalidation::Paint` for the current node so paint caching cannot skip
    /// widget `paint()` on the next frame.
    pub fn request_animation_frame(&mut self) {
        // Ensure animation-frame requests trigger a paint pass even when paint caching is enabled.
        self.tree.invalidate_with_source_and_detail(
            self.node,
            Invalidation::Paint,
            crate::tree::UiDebugInvalidationSource::Notify,
            crate::tree::UiDebugInvalidationDetail::AnimationFrameRequest,
        );
        let Some(window) = self.window else {
            return;
        };
        self.app.push_effect(Effect::RequestAnimationFrame(window));
    }

    /// Best-effort frame clock snapshot for the current window (ADR 0240).
    ///
    /// This is intentionally a plain read (non-reactive): it does not participate in view-cache
    /// dependency tracking.
    pub fn frame_clock(&self) -> Option<fret_core::WindowFrameClockSnapshot> {
        let window = self.window?;
        self.app
            .global::<fret_core::WindowFrameClockService>()
            .and_then(|svc| svc.snapshot(window))
    }

    /// Latest pointer position snapshot in window-local logical pixels (ADR 0243).
    pub fn pointer_position_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.position_window(window, pointer_id))
    }

    /// Latest pointer velocity snapshot in window-local logical pixels per second (ADR 0243).
    pub fn pointer_velocity_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.velocity_window(window, pointer_id))
    }

    /// Latest pointer position snapshot mapped into this node's local coordinate space
    /// (origin at `(0, 0)`), transform-aware (ADR 0238 / ADR 0243).
    pub fn pointer_position_local_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window_pos = self.pointer_position_window_snapshot(pointer_id)?;
        let bounds = self.tree.node_bounds(self.node)?;
        let mapped = self
            .tree
            .map_window_point_to_node_layout_space(self.node, window_pos)?;
        Some(Point::new(
            fret_core::Px(mapped.x.0 - bounds.origin.x.0),
            fret_core::Px(mapped.y.0 - bounds.origin.y.0),
        ))
    }

    /// Latest pointer velocity snapshot mapped into this node's local coordinate space (ADR 0238 / ADR 0243).
    pub fn pointer_velocity_local_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window_vec = self.pointer_velocity_window_snapshot(pointer_id)?;
        self.tree
            .map_window_vector_to_node_layout_space(self.node, window_vec)
    }

    pub fn observe_model<T>(&mut self, model: &Model<T>, invalidation: Invalidation) {
        (self.observe_model)(model.id(), invalidation);
    }

    pub fn observe_global<T: Any>(&mut self, invalidation: Invalidation) {
        (self.observe_global)(TypeId::of::<T>(), invalidation);
    }

    pub fn measure_in(&mut self, child: NodeId, constraints: LayoutConstraints) -> Size {
        if !self.tree.debug_enabled() {
            return self.tree.measure_in(
                self.app,
                self.services,
                child,
                constraints,
                self.scale_factor,
            );
        }

        let started = fret_core::time::Instant::now();
        let size = self.tree.measure_in(
            self.app,
            self.services,
            child,
            constraints,
            self.scale_factor,
        );
        let elapsed = started.elapsed();
        self.tree
            .debug_record_measure_child(self.node, child, elapsed);
        size
    }
}

/// Prepaint context invoked after layout, before paint.
///
/// This is intentionally narrow: it exists to support GPUI-aligned "ephemeral prepaint items"
/// workflows (ADR 0167 / ADR 0175) without forcing a full rerender/relayout of a cache root.
///
/// Notes:
/// - Prepaint runs after layout bounds are known.
/// - Prepaint may request redraw/animation frames, but should avoid structural tree mutations.
pub struct PrepaintCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub tree: &'a mut crate::tree::UiTree<H>,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub bounds: Rect,
    pub scale_factor: f32,
}

impl<'a, H: UiHost> PrepaintCx<'a, H> {
    pub fn set_output<T: std::any::Any>(&mut self, value: T) {
        self.tree.set_prepaint_output(self.node, value);
    }

    pub fn output<T: std::any::Any>(&mut self) -> Option<&T> {
        self.tree.prepaint_output(self.node)
    }

    pub fn output_mut<T: std::any::Any>(&mut self) -> Option<&mut T> {
        self.tree.prepaint_output_mut(self.node)
    }

    /// Mark an invalidation on `node` for the next frame.
    ///
    /// Prefer `Invalidation::Paint` / `Invalidation::HitTest` here. Invalidating `Layout` from
    /// prepaint is allowed but can easily introduce avoidable churn.
    pub fn invalidate(&mut self, node: NodeId, kind: Invalidation) {
        self.tree
            .debug_record_prepaint_action(crate::tree::UiDebugPrepaintAction {
                node: self.node,
                target: Some(node),
                kind: crate::tree::UiDebugPrepaintActionKind::Invalidate,
                invalidation: Some(kind),
                element: None,
                virtual_list_window_shift_kind: None,
                virtual_list_window_shift_reason: None,
                chart_sampling_window_key: None,
                node_graph_cull_window_key: None,
                frame_id: self.app.frame_id(),
            });
        self.tree.invalidate_with_detail(
            node,
            kind,
            crate::tree::UiDebugInvalidationDetail::Unknown,
        );
    }

    /// Mark an invalidation on the current node for the next frame.
    pub fn invalidate_self(&mut self, kind: Invalidation) {
        self.invalidate(self.node, kind);
    }

    /// Request a window redraw (one-shot).
    ///
    /// Use this for one-shot updates after prepaint-driven state changes.
    pub fn request_redraw(&mut self) {
        self.tree
            .debug_record_prepaint_action(crate::tree::UiDebugPrepaintAction {
                node: self.node,
                target: None,
                kind: crate::tree::UiDebugPrepaintActionKind::RequestRedraw,
                invalidation: None,
                element: None,
                virtual_list_window_shift_kind: None,
                virtual_list_window_shift_reason: None,
                chart_sampling_window_key: None,
                node_graph_cull_window_key: None,
                frame_id: self.app.frame_id(),
            });
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Request the next animation frame for this window.
    ///
    /// Prefer this over `request_redraw()` when you need frame-driven progression (animations,
    /// progressive rendering). This also sets `Invalidation::Paint` for the current node so paint
    /// caching cannot skip widget `paint()` on the next frame.
    pub fn request_animation_frame(&mut self) {
        self.tree
            .debug_record_prepaint_action(crate::tree::UiDebugPrepaintAction {
                node: self.node,
                target: Some(self.node),
                kind: crate::tree::UiDebugPrepaintActionKind::RequestAnimationFrame,
                invalidation: Some(Invalidation::Paint),
                element: None,
                virtual_list_window_shift_kind: None,
                virtual_list_window_shift_reason: None,
                chart_sampling_window_key: None,
                node_graph_cull_window_key: None,
                frame_id: self.app.frame_id(),
            });
        // Ensure animation-frame requests trigger a paint pass even when paint caching is enabled.
        self.tree.invalidate_with_source_and_detail(
            self.node,
            Invalidation::Paint,
            crate::tree::UiDebugInvalidationSource::Notify,
            crate::tree::UiDebugInvalidationDetail::AnimationFrameRequest,
        );
        let Some(window) = self.window else {
            return;
        };
        self.app.push_effect(Effect::RequestAnimationFrame(window));
    }

    /// Records a debug-only "sampling window shift" prepaint action.
    ///
    /// This is intended for ecosystem canvases (charts/plots) that maintain an explicit sampling
    /// window contract and want to expose a stable output key in diagnostics bundles.
    pub fn debug_record_chart_sampling_window_shift(&mut self, sampling_window_key: u64) {
        self.tree
            .debug_record_prepaint_action(crate::tree::UiDebugPrepaintAction {
                node: self.node,
                target: None,
                kind: crate::tree::UiDebugPrepaintActionKind::ChartSamplingWindowShift,
                invalidation: None,
                element: None,
                virtual_list_window_shift_kind: None,
                virtual_list_window_shift_reason: None,
                chart_sampling_window_key: Some(sampling_window_key),
                node_graph_cull_window_key: None,
                frame_id: self.app.frame_id(),
            });
    }

    /// Records a debug-only "cull window shift" prepaint action.
    ///
    /// This is intended for ecosystem canvases (e.g. node graphs) that maintain a windowed
    /// viewport culling contract and want to expose a stable output key in diagnostics bundles.
    pub fn debug_record_node_graph_cull_window_shift(&mut self, cull_window_key: u64) {
        self.tree
            .debug_record_prepaint_action(crate::tree::UiDebugPrepaintAction {
                node: self.node,
                target: None,
                kind: crate::tree::UiDebugPrepaintActionKind::NodeGraphCullWindowShift,
                invalidation: None,
                element: None,
                virtual_list_window_shift_kind: None,
                virtual_list_window_shift_reason: None,
                chart_sampling_window_key: None,
                node_graph_cull_window_key: Some(cull_window_key),
                frame_id: self.app.frame_id(),
            });
    }
}

pub struct PaintCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub tree: &'a mut crate::tree::UiTree<H>,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub focus: Option<NodeId>,
    pub children: &'a [NodeId],
    pub bounds: Rect,
    pub scale_factor: f32,
    pub(crate) paint_style: crate::tree::paint_style::PaintStyleState,
    pub accumulated_transform: Transform2D,
    pub children_render_transform: Option<Transform2D>,
    pub services: &'a mut dyn UiServices,
    pub observe_model: &'a mut dyn FnMut(ModelId, Invalidation),
    pub observe_global: &'a mut dyn FnMut(TypeId, Invalidation),
    pub scene: &'a mut Scene,
}

impl<'a, H: UiHost> PaintCx<'a, H> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        app: &'a mut H,
        tree: &'a mut crate::tree::UiTree<H>,
        node: NodeId,
        window: Option<AppWindowId>,
        focus: Option<NodeId>,
        children: &'a [NodeId],
        bounds: Rect,
        scale_factor: f32,
        accumulated_transform: Transform2D,
        children_render_transform: Option<Transform2D>,
        services: &'a mut dyn UiServices,
        observe_model: &'a mut dyn FnMut(ModelId, Invalidation),
        observe_global: &'a mut dyn FnMut(TypeId, Invalidation),
        scene: &'a mut Scene,
    ) -> Self {
        Self {
            app,
            tree,
            node,
            window,
            focus,
            children,
            bounds,
            scale_factor,
            paint_style: Default::default(),
            accumulated_transform,
            children_render_transform,
            services,
            observe_model,
            observe_global,
            scene,
        }
    }

    /// Returns the nearest inherited foreground color for the current paint traversal (v2).
    pub fn inherited_foreground(&self) -> Option<fret_core::Color> {
        self.paint_style.foreground
    }

    pub fn prepaint_output<T: std::any::Any>(&mut self) -> Option<&T> {
        self.tree.prepaint_output(self.node)
    }

    pub fn prepaint_output_mut<T: std::any::Any>(&mut self) -> Option<&mut T> {
        self.tree.prepaint_output_mut(self.node)
    }

    pub fn theme(&mut self) -> &Theme {
        self.observe_global::<Theme>(Invalidation::Paint);
        Theme::global(&*self.app)
    }

    /// Best-effort frame clock snapshot for the current window (ADR 0240).
    ///
    /// This is intentionally a plain read (non-reactive): it does not participate in view-cache
    /// dependency tracking.
    pub fn frame_clock(&self) -> Option<fret_core::WindowFrameClockSnapshot> {
        let window = self.window?;
        self.app
            .global::<fret_core::WindowFrameClockService>()
            .and_then(|svc| svc.snapshot(window))
    }

    /// Latest pointer position snapshot in window-local logical pixels (ADR 0243).
    pub fn pointer_position_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.position_window(window, pointer_id))
    }

    /// Latest pointer velocity snapshot in window-local logical pixels per second (ADR 0243).
    pub fn pointer_velocity_window_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window = self.window?;
        self.app
            .global::<crate::pointer_motion::WindowPointerMotionService>()
            .and_then(|svc| svc.velocity_window(window, pointer_id))
    }

    /// Latest pointer position snapshot mapped into this node's local coordinate space
    /// (origin at `(0, 0)`), transform-aware (ADR 0238 / ADR 0243).
    pub fn pointer_position_local_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window_pos = self.pointer_position_window_snapshot(pointer_id)?;
        let mapped = self
            .tree
            .map_window_point_to_node_layout_space(self.node, window_pos)?;
        Some(Point::new(
            fret_core::Px(mapped.x.0 - self.bounds.origin.x.0),
            fret_core::Px(mapped.y.0 - self.bounds.origin.y.0),
        ))
    }

    /// Latest pointer velocity snapshot mapped into this node's local coordinate space (ADR 0238 / ADR 0243).
    pub fn pointer_velocity_local_snapshot(
        &self,
        pointer_id: fret_core::PointerId,
    ) -> Option<Point> {
        let window_vec = self.pointer_velocity_window_snapshot(pointer_id)?;
        self.tree
            .map_window_vector_to_node_layout_space(self.node, window_vec)
    }

    /// Convert a layout-space rect into the visual rect (AABB) after accumulated render transforms.
    ///
    /// This is useful for platform integrations (e.g. IME candidate positioning), where the OS
    /// expects coordinates in the same space the user sees on screen.
    pub fn visual_rect_aabb(&self, rect: Rect) -> Rect {
        let t = self.accumulated_transform;
        if t == Transform2D::IDENTITY {
            return rect;
        }

        let x0 = rect.origin.x.0;
        let y0 = rect.origin.y.0;
        let x1 = x0 + rect.size.width.0;
        let y1 = y0 + rect.size.height.0;

        let p00 = t.apply_point(Point::new(fret_core::Px(x0), fret_core::Px(y0)));
        let p10 = t.apply_point(Point::new(fret_core::Px(x1), fret_core::Px(y0)));
        let p01 = t.apply_point(Point::new(fret_core::Px(x0), fret_core::Px(y1)));
        let p11 = t.apply_point(Point::new(fret_core::Px(x1), fret_core::Px(y1)));

        let min_x = p00.x.0.min(p10.x.0).min(p01.x.0).min(p11.x.0);
        let max_x = p00.x.0.max(p10.x.0).max(p01.x.0).max(p11.x.0);
        let min_y = p00.y.0.min(p10.y.0).min(p01.y.0).min(p11.y.0);
        let max_y = p00.y.0.max(p10.y.0).max(p01.y.0).max(p11.y.0);

        if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() {
            return rect;
        }

        Rect::new(
            Point::new(fret_core::Px(min_x), fret_core::Px(min_y)),
            Size::new(
                fret_core::Px((max_x - min_x).max(0.0)),
                fret_core::Px((max_y - min_y).max(0.0)),
            ),
        )
    }

    /// Request a window redraw (one-shot).
    ///
    /// Use this for one-shot updates. For frame-driven updates that must repaint continuously,
    /// use `request_animation_frame()`.
    pub fn request_redraw(&mut self) {
        let Some(window) = self.window else {
            return;
        };
        self.app.request_redraw(window);
    }

    /// Request the next animation frame for this window.
    ///
    /// Prefer this over `request_redraw()` when you need frame-driven progression (animations,
    /// progressive rendering). This also sets `Invalidation::Paint` for the current node so paint
    /// caching cannot skip widget `paint()` on the next frame.
    ///
    /// This is a one-shot request. Callers should re-issue `request_animation_frame()` each frame
    /// while it remains active.
    pub fn request_animation_frame(&mut self) {
        // Ensure animation-frame requests trigger a paint pass even when paint caching is enabled.
        self.tree.invalidate_with_source_and_detail(
            self.node,
            Invalidation::Paint,
            crate::tree::UiDebugInvalidationSource::Notify,
            crate::tree::UiDebugInvalidationDetail::AnimationFrameRequest,
        );
        let Some(window) = self.window else {
            return;
        };
        self.app.push_effect(Effect::RequestAnimationFrame(window));
    }

    /// Request the next animation frame for this window without marking the nearest cache root as
    /// dirty.
    ///
    /// This is intended for paint-only chrome (hover fades, drag indicators, caret blink) that
    /// must repaint every frame but should remain structurally reusable under view caching.
    pub fn request_animation_frame_paint_only(&mut self) {
        self.tree.invalidate_with_source_and_detail(
            self.node,
            Invalidation::Paint,
            crate::tree::UiDebugInvalidationSource::Other,
            crate::tree::UiDebugInvalidationDetail::AnimationFrameRequest,
        );
        let Some(window) = self.window else {
            return;
        };
        self.app.push_effect(Effect::RequestAnimationFrame(window));
    }

    pub fn observe_model<T>(&mut self, model: &Model<T>, invalidation: Invalidation) {
        (self.observe_model)(model.id(), invalidation);
    }

    pub fn observe_global<T: Any>(&mut self, invalidation: Invalidation) {
        (self.observe_global)(TypeId::of::<T>(), invalidation);
    }

    pub fn paint(&mut self, child: NodeId, bounds: Rect) {
        let was_widget_timer_running = self.tree.debug_paint_widget_exclusive_pause();
        let child_transform = self.children_render_transform;
        if let Some(transform) = child_transform {
            self.scene
                .push(fret_core::SceneOp::PushTransform { transform });
        }

        let accumulated = child_transform
            .map(|t| self.accumulated_transform.compose(t))
            .unwrap_or(self.accumulated_transform);

        self.tree.paint_node(
            self.app,
            self.services,
            child,
            bounds,
            self.scene,
            self.scale_factor,
            self.paint_style,
            accumulated,
        );

        if child_transform.is_some() {
            self.scene.push(fret_core::SceneOp::PopTransform);
        }
        if was_widget_timer_running {
            self.tree.debug_paint_widget_exclusive_resume();
        }
    }

    /// Paint all child nodes using their last computed layout bounds.
    ///
    /// This is the default behavior of `Widget::paint()`.
    pub fn paint_children(&mut self) {
        for &child in self.children {
            if let Some(bounds) = self.child_bounds(child) {
                self.paint(child, bounds);
            } else {
                self.paint(child, self.bounds);
            }
        }
    }

    pub fn child_bounds(&self, child: NodeId) -> Option<Rect> {
        self.tree.node_bounds(child)
    }
}

pub struct SemanticsCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub element_id_map: Option<&'a HashMap<u64, NodeId>>,
    pub bounds: Rect,
    pub children: &'a [NodeId],
    pub focus: Option<NodeId>,
    pub captured: Option<NodeId>,
    pub(crate) role: &'a mut SemanticsRole,
    pub(crate) flags: &'a mut SemanticsFlags,
    pub(crate) label: &'a mut Option<String>,
    pub(crate) value: &'a mut Option<String>,
    pub(crate) test_id: &'a mut Option<String>,
    pub(crate) extra: &'a mut fret_core::SemanticsNodeExtra,
    pub(crate) text_selection: &'a mut Option<(u32, u32)>,
    pub(crate) text_composition: &'a mut Option<(u32, u32)>,
    pub(crate) actions: &'a mut fret_core::SemanticsActions,
    pub(crate) active_descendant: &'a mut Option<NodeId>,
    pub(crate) pos_in_set: &'a mut Option<u32>,
    pub(crate) set_size: &'a mut Option<u32>,
    pub(crate) labelled_by: &'a mut Vec<NodeId>,
    pub(crate) described_by: &'a mut Vec<NodeId>,
    pub(crate) controls: &'a mut Vec<NodeId>,
    pub(crate) inline_spans: &'a mut Vec<fret_core::SemanticsInlineSpan>,
}

impl<'a, H: UiHost> SemanticsCx<'a, H> {
    pub fn resolve_declarative_element(&mut self, element: u64) -> Option<NodeId> {
        if let Some(node) = self.element_id_map.and_then(|m| m.get(&element).copied()) {
            return Some(node);
        }

        let window = self.window?;
        crate::elements::live_node_for_element(
            self.app,
            window,
            crate::elements::GlobalElementId(element),
        )
    }

    pub fn set_role(&mut self, role: SemanticsRole) {
        *self.role = role;
    }

    pub fn set_label(&mut self, label: impl Into<String>) {
        *self.label = Some(label.into());
    }

    pub fn set_test_id(&mut self, id: impl Into<String>) {
        *self.test_id = Some(id.into());
    }

    pub fn clear_test_id(&mut self) {
        *self.test_id = None;
    }

    pub fn set_value(&mut self, value: impl Into<String>) {
        *self.value = Some(value.into());
    }

    pub fn set_placeholder<T: Into<String>>(&mut self, placeholder: Option<T>) {
        self.extra.placeholder = placeholder.map(Into::into);
    }

    pub fn set_url<T: Into<String>>(&mut self, url: Option<T>) {
        self.extra.url = url.map(Into::into);
    }

    pub fn set_role_description<T: Into<String>>(&mut self, role_description: Option<T>) {
        self.extra.role_description = role_description.map(Into::into);
    }

    pub fn clear_role_description(&mut self) {
        self.extra.role_description = None;
    }

    pub fn set_level(&mut self, level: Option<u32>) {
        self.extra.level = level;
    }

    pub fn set_orientation(&mut self, orientation: Option<SemanticsOrientation>) {
        self.extra.orientation = orientation;
    }

    pub fn clear_orientation(&mut self) {
        self.extra.orientation = None;
    }

    pub fn set_numeric_value(&mut self, value: Option<f64>) {
        self.extra.numeric.value = value;
    }

    pub fn set_numeric_range(&mut self, min: Option<f64>, max: Option<f64>) {
        self.extra.numeric.min = min;
        self.extra.numeric.max = max;
    }

    pub fn set_numeric_step(&mut self, step: Option<f64>) {
        self.extra.numeric.step = step;
    }

    pub fn set_numeric_jump(&mut self, jump: Option<f64>) {
        self.extra.numeric.jump = jump;
    }

    pub fn set_scroll_x(&mut self, x: Option<f64>, min: Option<f64>, max: Option<f64>) {
        self.extra.scroll.x = x;
        self.extra.scroll.x_min = min;
        self.extra.scroll.x_max = max;
    }

    pub fn set_scroll_y(&mut self, y: Option<f64>, min: Option<f64>, max: Option<f64>) {
        self.extra.scroll.y = y;
        self.extra.scroll.y_min = min;
        self.extra.scroll.y_max = max;
    }

    pub fn set_text_selection(&mut self, anchor: u32, focus: u32) {
        *self.text_selection = Some((anchor, focus));
    }

    pub fn clear_text_selection(&mut self) {
        *self.text_selection = None;
    }

    pub fn set_text_composition(&mut self, start: u32, end: u32) {
        *self.text_composition = Some((start, end));
    }

    pub fn clear_text_composition(&mut self) {
        *self.text_composition = None;
    }

    pub fn set_focusable(&mut self, focusable: bool) {
        self.actions.focus = focusable;
    }

    pub fn set_invokable(&mut self, invokable: bool) {
        self.actions.invoke = invokable;
    }

    pub fn set_value_editable(&mut self, editable: bool) {
        match *self.role {
            // Text controls use AccessKit's `SetValue` / `ReplaceSelectedText` action surfaces.
            SemanticsRole::TextField => {
                self.actions.set_value = editable;
            }
            // Range controls generally surface as stepper semantics on platforms. Prefer
            // Increment/Decrement for sliders, spin buttons, and splitters.
            SemanticsRole::Slider | SemanticsRole::SpinButton | SemanticsRole::Splitter => {
                self.actions.increment = editable;
                self.actions.decrement = editable;
            }
            _ => {
                self.actions.set_value = editable;
            }
        }
    }

    pub fn set_increment_supported(&mut self, supported: bool) {
        self.actions.increment = supported;
    }

    pub fn set_decrement_supported(&mut self, supported: bool) {
        self.actions.decrement = supported;
    }

    pub fn set_scroll_by_supported(&mut self, supported: bool) {
        self.actions.scroll_by = supported;
    }

    pub fn set_text_selection_supported(&mut self, supported: bool) {
        self.actions.set_text_selection = supported;
    }

    pub fn set_disabled(&mut self, disabled: bool) {
        self.flags.disabled = disabled;
    }

    pub fn set_read_only(&mut self, read_only: bool) {
        self.flags.read_only = read_only;
    }

    pub fn set_hidden(&mut self, hidden: bool) {
        self.flags.hidden = hidden;
    }

    pub fn set_visited(&mut self, visited: bool) {
        self.flags.visited = visited;
    }

    pub fn set_multiselectable(&mut self, multiselectable: bool) {
        self.flags.multiselectable = multiselectable;
    }

    pub fn set_selected(&mut self, selected: bool) {
        self.flags.selected = selected;
    }

    pub fn set_expanded(&mut self, expanded: bool) {
        self.flags.expanded = expanded;
    }

    pub fn set_checked(&mut self, checked: Option<bool>) {
        self.flags.checked = checked;
    }

    pub fn set_checked_state(&mut self, checked: Option<SemanticsCheckedState>) {
        self.flags.checked_state = checked;
        match checked {
            Some(SemanticsCheckedState::True) => self.flags.checked = Some(true),
            Some(SemanticsCheckedState::False) => self.flags.checked = Some(false),
            Some(SemanticsCheckedState::Mixed) => self.flags.checked = None,
            None => {}
            _ => {}
        }
    }

    pub fn clear_checked_state(&mut self) {
        self.flags.checked_state = None;
    }

    pub fn set_pressed_state(&mut self, pressed: Option<SemanticsPressedState>) {
        self.flags.pressed_state = pressed;
    }

    pub fn clear_pressed_state(&mut self) {
        self.flags.pressed_state = None;
    }

    pub fn set_required(&mut self, required: bool) {
        self.flags.required = required;
    }

    pub fn set_invalid(&mut self, invalid: Option<SemanticsInvalid>) {
        self.flags.invalid = invalid;
    }

    pub fn clear_invalid(&mut self) {
        self.flags.invalid = None;
    }

    pub fn set_busy(&mut self, busy: bool) {
        self.flags.busy = busy;
    }

    pub fn set_live(&mut self, live: Option<SemanticsLive>) {
        self.flags.live = live;
    }

    pub fn clear_live(&mut self) {
        self.flags.live = None;
    }

    pub fn set_live_atomic(&mut self, live_atomic: bool) {
        self.flags.live_atomic = live_atomic;
    }

    pub fn set_active_descendant(&mut self, node: Option<NodeId>) {
        *self.active_descendant = node;
    }

    pub fn set_pos_in_set(&mut self, pos_in_set: Option<u32>) {
        *self.pos_in_set = pos_in_set;
    }

    pub fn set_set_size(&mut self, set_size: Option<u32>) {
        *self.set_size = set_size;
    }

    pub fn set_collection_position(&mut self, pos_in_set: Option<u32>, set_size: Option<u32>) {
        *self.pos_in_set = pos_in_set;
        *self.set_size = set_size;
    }

    pub fn push_labelled_by(&mut self, node: NodeId) {
        if self.labelled_by.contains(&node) {
            return;
        }
        self.labelled_by.push(node);
    }

    pub fn clear_labelled_by(&mut self) {
        self.labelled_by.clear();
    }

    pub fn push_described_by(&mut self, node: NodeId) {
        if self.described_by.contains(&node) {
            return;
        }
        self.described_by.push(node);
    }

    pub fn clear_described_by(&mut self) {
        self.described_by.clear();
    }

    pub fn push_controlled(&mut self, node: NodeId) {
        if self.controls.contains(&node) {
            return;
        }
        self.controls.push(node);
    }

    pub fn push_inline_span(&mut self, span: fret_core::SemanticsInlineSpan) {
        self.inline_spans.push(span);
    }

    pub fn push_inline_link_span(&mut self, start_utf8: u32, end_utf8: u32, tag: Option<String>) {
        self.push_inline_span(fret_core::SemanticsInlineSpan {
            range_utf8: (start_utf8, end_utf8),
            role: SemanticsRole::Link,
            tag,
        });
    }

    pub fn clear_controls(&mut self) {
        self.controls.clear();
    }
}

pub trait Widget<H: UiHost> {
    /// Capture-phase event dispatch (root → target).
    ///
    /// Default is no-op so existing widgets keep their current bubble-only behavior.
    fn event_capture(&mut self, _cx: &mut EventCx<'_, H>, _event: &Event) {}

    /// Observer-phase event dispatch (`InputDispatchPhase::Preview`).
    ///
    /// This pass must not mutate input routing state (focus / capture / propagation / default
    /// actions). It exists to support outside-press dismissal and click-through overlay policies
    /// (ADR 0069).
    fn event_observer(&mut self, _cx: &mut ObserverCx<'_, H>, _event: &Event) {}

    fn debug_type_name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    fn event(&mut self, _cx: &mut EventCx<'_, H>, _event: &Event) {}
    fn command(&mut self, _cx: &mut CommandCx<'_, H>, _command: &CommandId) -> bool {
        false
    }

    /// Pure query: does this node participate in availability for `command`?
    fn command_availability(
        &self,
        _cx: &mut CommandAvailabilityCx<'_, H>,
        _command: &CommandId,
    ) -> CommandAvailability {
        CommandAvailability::NotHandled
    }
    fn cleanup_resources(&mut self, _services: &mut dyn UiServices) {}
    /// Optional affine transform applied to both paint and input for the subtree rooted at this node.
    ///
    /// This is a "render transform" (not a layout transform):
    /// - Layout bounds remain authoritative for measurement and positioning.
    /// - The transform is expressed in the same coordinate space as `bounds` (logical px, window-local).
    /// - Hit-testing and pointer event positions are mapped through the inverse transform so input stays
    ///   consistent with the rendered output.
    ///
    /// Notes:
    /// - If the transform is not invertible, hit-testing and pointer event mapping fall back to the
    ///   untransformed behavior.
    /// - Paint caching may be disabled for nodes that return a transform, depending on runtime policy.
    fn render_transform(&self, _bounds: Rect) -> Option<Transform2D> {
        None
    }
    /// Optional affine transform applied to children only (not to this node's own bounds).
    ///
    /// This is intended for behaviors like scrolling where the viewport bounds are fixed, but the
    /// content subtree is translated.
    ///
    /// The transform is expressed in the same coordinate space as `bounds` (logical px,
    /// window-local).
    fn children_render_transform(&self, _bounds: Rect) -> Option<Transform2D> {
        None
    }
    /// Optional cursor icon request for a pointer position.
    ///
    /// This is a pure query used to build an interaction stream that can be reused on cache-hit
    /// frames (ADR 0167). Prefer this over setting cursor icons via pointer-move event handlers
    /// when the cursor choice is a function of the current input state only.
    ///
    /// The provided `position` is already mapped into this node's coordinate space (including
    /// ancestor `render_transform` and `children_render_transform`), matching what the widget sees
    /// during pointer event dispatch.
    fn cursor_icon_at(
        &self,
        _bounds: Rect,
        _position: Point,
        _input_ctx: &fret_runtime::InputContext,
    ) -> Option<fret_core::CursorIcon> {
        None
    }
    /// Whether hit-testing should be clipped to `bounds`.
    ///
    /// When `false`, children can receive pointer input even if they are positioned outside the
    /// parent's bounds (useful for `overflow: visible` + absolute-positioned badges/icons).
    ///
    /// Default: `true`.
    fn clips_hit_test(&self, _bounds: Rect) -> bool {
        true
    }
    /// Optional rounded-rectangle clip shape for hit-testing.
    ///
    /// When provided and `clips_hit_test(...)` is `true`, the runtime additionally clips pointer
    /// targeting to the rounded-rectangle defined by `bounds` + these corner radii. This keeps
    /// hit-testing consistent with `overflow: clip` + rounded corners.
    ///
    /// Default: `None` (rectangular clipping only).
    fn clip_hit_test_corner_radii(&self, _bounds: Rect) -> Option<Corners> {
        None
    }
    /// Hit-test predicate for pointer input targeting.
    ///
    /// Returning `false` makes the node "transparent" to hit-testing (events fall through to
    /// underlay layers / widgets).
    ///
    /// Default: `true` (bounds-based hit testing).
    fn hit_test(&self, _bounds: Rect, _position: Point) -> bool {
        true
    }
    /// Whether the node's children participate in hit-testing.
    ///
    /// When `false`, the entire subtree behaves like CSS `pointer-events: none` (useful for
    /// disabled controls that must not intercept events).
    ///
    /// Default: `true`.
    fn hit_test_children(&self, _bounds: Rect, _position: Point) -> bool {
        true
    }
    /// Whether this node should be included in the semantics snapshot.
    ///
    /// This is a mechanism-only gate used to model `present=false` (display-none) subtrees that
    /// should not be exposed to assistive tech, while still keeping element state alive (e.g.
    /// Radix-style `forceMount`).
    ///
    /// Default: `true`.
    fn semantics_present(&self) -> bool {
        true
    }
    /// Whether semantics snapshot traversal should recurse into this node's children.
    ///
    /// Default: `true`.
    fn semantics_children(&self) -> bool {
        true
    }
    /// Optional synchronization hook for declarative `InteractivityGate` nodes.
    ///
    /// Declarative `InteractivityGate` is allowed to short-circuit layout when `present == false`
    /// (display-none behavior). In those frames the layout engine may skip calling `layout()` for
    /// the gate node, leaving cached widget gates stale. Declarative host widgets can override
    /// this hook so the mount pipeline can keep semantics/hit-test traversal consistent even when
    /// layout is skipped.
    fn sync_interactivity_gate(&mut self, _present: bool, _interactive: bool) {}

    /// Optional synchronization hook for declarative `HitTestGate` nodes.
    ///
    /// Declarative `HitTestGate` toggles whether pointer hit-testing should recurse into the
    /// subtree. Host widgets can override this hook so the mount pipeline can update cached
    /// hit-test traversal flags without requiring a full layout pass.
    fn sync_hit_test_gate(&mut self, _hit_test: bool) {}

    /// Optional synchronization hook for declarative `FocusTraversalGate` nodes.
    ///
    /// Declarative `FocusTraversalGate` toggles whether focus traversal should recurse into the
    /// subtree. Host widgets can override this hook so the mount pipeline can update cached
    /// traversal flags without requiring a full layout pass.
    fn sync_focus_traversal_gate(&mut self, _traverse: bool) {}
    /// Whether focus traversal should recurse into this node's children.
    ///
    /// This is a mechanism-only gate used by `UiTree` to model "inert" subtrees during
    /// transitions (e.g. `present=true` but `interactive=false`), without requiring every focusable
    /// widget to thread an "interactive" flag into its own `is_focusable()` logic.
    ///
    /// Default: `true`.
    fn focus_traversal_children(&self) -> bool {
        true
    }
    fn is_focusable(&self) -> bool {
        false
    }
    fn is_text_input(&self) -> bool {
        false
    }

    /// Optional platform-facing text input snapshot for the focused widget.
    ///
    /// This exists to support editor-grade IME and accessibility bridges that need UTF-16 ranges
    /// and an IME cursor anchor, without depending on widget internals.
    ///
    /// Coordinate model: UTF-16 code units over the widget's "composed view" (base text with the
    /// active preedit spliced at the caret).
    fn platform_text_input_snapshot(&self) -> Option<fret_runtime::WindowTextInputSnapshot> {
        None
    }

    /// Returns the focused selection range (UTF-16 code units over the composed view).
    fn platform_text_input_selected_range_utf16(&self) -> Option<fret_runtime::Utf16Range> {
        None
    }

    /// Returns the marked (preedit) range (UTF-16 code units over the composed view).
    fn platform_text_input_marked_range_utf16(&self) -> Option<fret_runtime::Utf16Range> {
        None
    }

    fn platform_text_input_text_for_range_utf16(
        &self,
        _range: fret_runtime::Utf16Range,
    ) -> Option<String> {
        None
    }

    fn platform_text_input_bounds_for_range_utf16(
        &mut self,
        _cx: &mut PlatformTextInputCx<'_, H>,
        _range: fret_runtime::Utf16Range,
    ) -> Option<Rect> {
        None
    }

    fn platform_text_input_character_index_for_point_utf16(
        &mut self,
        _cx: &mut PlatformTextInputCx<'_, H>,
        _point: Point,
    ) -> Option<u32> {
        None
    }

    fn platform_text_input_replace_text_in_range_utf16(
        &mut self,
        _cx: &mut PlatformTextInputCx<'_, H>,
        _range: fret_runtime::Utf16Range,
        _text: &str,
    ) -> bool {
        false
    }

    fn platform_text_input_replace_and_mark_text_in_range_utf16(
        &mut self,
        _cx: &mut PlatformTextInputCx<'_, H>,
        _range: fret_runtime::Utf16Range,
        _text: &str,
        _marked: Option<fret_runtime::Utf16Range>,
        _selected: Option<fret_runtime::Utf16Range>,
    ) -> bool {
        false
    }
    /// Whether this node supports direct "scroll-by" requests (typically for accessibility).
    fn can_scroll_by(&self) -> bool {
        false
    }
    fn scroll_by(&mut self, _cx: &mut ScrollByCx<'_, H>, _delta: Point) -> ScrollByResult {
        ScrollByResult::NotHandled
    }
    /// Whether this node can scroll a focused descendant into view.
    ///
    /// This is a mechanism-only capability used by `UiTree` to implement a minimal
    /// "scroll-into-view" contract for focus traversal (ADR 0068) without coupling focus traversal
    /// policy into component crates.
    fn can_scroll_descendant_into_view(&self) -> bool {
        false
    }
    fn scroll_descendant_into_view(
        &mut self,
        _cx: &mut ScrollIntoViewCx<'_, H>,
        _descendant_bounds: Rect,
    ) -> ScrollIntoViewResult {
        ScrollIntoViewResult::NotHandled
    }
    fn measure(&mut self, _cx: &mut MeasureCx<'_, H>) -> Size {
        Size::default()
    }
    fn layout(&mut self, _cx: &mut LayoutCx<'_, H>) -> Size {
        Size::default()
    }
    /// Prepaint hook invoked after layout, before paint.
    ///
    /// Default is no-op so existing widgets keep their current behavior.
    fn prepaint(&mut self, _cx: &mut PrepaintCx<'_, H>) {}
    fn paint(&mut self, cx: &mut PaintCx<'_, H>) {
        cx.paint_children();
    }
    fn semantics(&mut self, _cx: &mut SemanticsCx<'_, H>) {}
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ScrollByResult {
    #[default]
    NotHandled,
    Handled {
        did_scroll: bool,
    },
}

pub struct ScrollByCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub bounds: Rect,
}

#[derive(Debug, Default, Clone, Copy)]
pub enum ScrollIntoViewResult {
    #[default]
    NotHandled,
    Handled {
        did_scroll: bool,
        // Bounds outer scroll ancestors should treat as the descendant after this widget handles
        // the request. Scroll surfaces use this to propagate their effective viewport rect instead
        // of the original deep descendant bounds.
        propagated_bounds: Option<Rect>,
    },
}

pub struct ScrollIntoViewCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub node: NodeId,
    pub window: Option<AppWindowId>,
    pub bounds: Rect,
}

pub struct PlatformTextInputCx<'a, H: UiHost> {
    pub app: &'a mut H,
    pub services: &'a mut dyn UiServices,
    pub window: Option<AppWindowId>,
    pub node: NodeId,
    pub bounds: Rect,
    pub scale_factor: f32,
}

impl<'a, H: UiHost> PlatformTextInputCx<'a, H> {
    pub fn theme(&self) -> &Theme {
        Theme::global(&*self.app)
    }
}