teksilo-core 0.13.1

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

use super::*;

use crate::event::ButtonMask;
use crate::gesture::{GestureArenaSet, GestureEvent};

/// Which recognizers a node's handler set asks for, and on which buttons.
///
/// Read once and used twice: [`WidgetTree::ensure_gesture_arena`] installs the
/// arena from it, and [`WidgetTree::press_buttons`] decides from the very same
/// reading which buttons may raise the node's press visual. One reader, so the
/// arena and the visual cannot come to disagree about what this node acts on.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ArenaRecognizers {
    has_tap: bool,
    has_double_tap: bool,
    has_triple_tap: bool,
    has_long_press: bool,
    has_drag: bool,
    has_swipe: bool,
    /// Per-recognizer overrides, own bucket preferred over external. `None`
    /// leaves the recognizer on its own default, [`ButtonMask::PRIMARY`].
    tap_buttons: Option<ButtonMask>,
    double_tap_buttons: Option<ButtonMask>,
    triple_tap_buttons: Option<ButtonMask>,
    long_press_buttons: Option<ButtonMask>,
}

impl ArenaRecognizers {
    /// Read BOTH handler buckets, so a handler attached via
    /// `apply_self_handlers` and one attached through the `WidgetBuilder`
    /// chain count the same.
    pub(crate) fn read(node: &crate::arena::WidgetNode) -> Self {
        Self {
            has_tap: node.any_handler(|h| h.on_tap.is_some()),
            has_double_tap: node.any_handler(|h| h.on_double_tap.is_some()),
            has_triple_tap: node.any_handler(|h| h.on_triple_tap.is_some()),
            has_long_press: node.any_handler(|h| h.on_long_press.is_some()),
            has_drag: node.any_handler(|h| h.on_drag.is_some()),
            has_swipe: node.any_handler(|h| h.on_swipe.is_some()),
            tap_buttons: node
                .handlers
                .tap_buttons
                .or(node.external_handlers.tap_buttons),
            double_tap_buttons: node
                .handlers
                .double_tap_buttons
                .or(node.external_handlers.double_tap_buttons),
            triple_tap_buttons: node
                .handlers
                .triple_tap_buttons
                .or(node.external_handlers.triple_tap_buttons),
            long_press_buttons: node
                .handlers
                .long_press_buttons
                .or(node.external_handlers.long_press_buttons),
        }
    }

    /// Whether any recognizer at all is wanted — the gate on installing an
    /// arena.
    fn any(self) -> bool {
        self.has_tap
            || self.has_double_tap
            || self.has_triple_tap
            || self.has_drag
            || self.has_long_press
            || self.has_swipe
    }

    /// Whether the plain `TapRecognizer` is one of the installed prototypes.
    ///
    /// A multi-tap recognizer in the arena suppresses it — see the comment at
    /// the install site — so its mask must not speak for a node whose
    /// `TapRecognizer` was never built.
    fn installs_tap(self) -> bool {
        self.has_tap && !(self.has_double_tap || self.has_triple_tap)
    }

    /// The buttons a press on this node could actually act on.
    ///
    /// The four click-style recognizers each carry a [`ButtonMask`], defaulting
    /// to [`ButtonMask::PRIMARY`]; a drag and a swipe carry none and act on
    /// whatever button the press arrived with. So a node whose arena is
    /// click-style throughout answers with the union of those masks, and one
    /// that also drags or swipes — or that carries no recognizer at all,
    /// because it captured the pointer explicitly and drives its own
    /// `on_pointer_event` — has nothing to say against any button and answers
    /// [`ButtonMask::ALL`].
    fn accepted_buttons(self) -> ButtonMask {
        if self.has_drag || self.has_swipe {
            return ButtonMask::ALL;
        }
        let mut mask = ButtonMask::NONE;
        let mut add = |on: bool, declared: Option<ButtonMask>| {
            if on {
                mask = mask.union(declared.unwrap_or(ButtonMask::PRIMARY));
            }
        };
        add(self.installs_tap(), self.tap_buttons);
        add(self.has_double_tap, self.double_tap_buttons);
        add(self.has_triple_tap, self.triple_tap_buttons);
        add(self.has_long_press, self.long_press_buttons);
        if mask.is_empty() {
            ButtonMask::ALL
        } else {
            mask
        }
    }
}

impl WidgetTree {
    /// The buttons on which a press over `id` may raise its press visual.
    ///
    /// The visual says "release here and this control acts", so it must answer
    /// to the same buttons the activation does — otherwise a middle-click, or a
    /// right-click on a node with no context menu, lights a control up for a
    /// press that can never complete. See
    /// [`ArenaRecognizers::accepted_buttons`].
    pub(crate) fn press_buttons(&self, id: WidgetId) -> ButtonMask {
        self.arena.get(id).map_or(ButtonMask::ALL, |node| {
            ArenaRecognizers::read(node).accepted_buttons()
        })
    }

    /// Lazily install a gesture arena set populated with whichever recognizers
    /// the widget's handler set actually needs. Without this, a widget
    /// that wires `on_drag` or `on_double_tap` (but not `on_tap`) would
    /// never get a gesture arena and the handlers would never fire.
    ///
    /// What is installed is a list of *prototypes*, not live recognizers: the
    /// set instantiates an arena per contact as contacts arrive. The node's
    /// tap streak is installed with them and outlives every one of those
    /// arenas — which is what makes a touch double tap, two presses with two
    /// different pointer ids, recognizable at all.
    ///
    /// Checks BOTH handler buckets (own + external) so a recognizer gets
    /// installed whether the handler was attached via
    /// `apply_self_handlers` or via the `WidgetBuilder` chain.
    pub(crate) fn ensure_gesture_arena(
        node: &mut crate::arena::WidgetNode,
        id: WidgetId,
        gesture_owners: &mut std::collections::HashSet<WidgetId>,
    ) {
        if let Some(set) = node.handlers.gesture_arena.as_mut() {
            // Already installed — refresh the policy (a rebuild may have
            // changed it) and make sure the owners set is in sync (covers a
            // widget that re-enters dispatch after a pre-existing arena was
            // carried across rebuild).
            set.set_multi_contact(node.multi_contact);
            gesture_owners.insert(id);
            return;
        }
        // One reading of the handler buckets, shared with `press_buttons` so
        // the arena that fires and the visual that lights up cannot come to
        // disagree about which buttons this node acts on.
        let wanted = ArenaRecognizers::read(node);
        if !wanted.any() {
            return;
        }
        let ArenaRecognizers {
            // `has_tap` alone does not decide: a multi-tap recognizer
            // suppresses the plain one, so the install below asks
            // `installs_tap()`.
            has_tap: _,
            has_double_tap,
            has_triple_tap,
            has_long_press,
            has_drag,
            has_swipe,
            tap_buttons,
            double_tap_buttons,
            triple_tap_buttons,
            long_press_buttons,
        } = wanted;

        let mut set = GestureArenaSet::new();
        set.set_multi_contact(node.multi_contact);
        // Important: install `TapRecognizer` ONLY when the widget actually
        // wired `on_tap` AND no multi-tap recognizer is in the arena. A
        // parallel `TapRecognizer` would let `Tap` win on the first up
        // (it returns `Recognized` while `DoubleTap` / `TripleTap` return
        // `Pending`), and the arena's reset loop would wipe the multi-tap
        // state. Multi-tap recognizers opt out of that reset via
        // `resets_on_peer_recognition = false`, so once we install a
        // multi-tap recognizer, we intentionally skip `TapRecognizer` —
        // callers that need click-1 behaviour under a multi-tap widget
        // use `on_pointer_event::PointerDown` (which fires before the
        // gesture arena and runs regardless of multi-tap state).
        if wanted.installs_tap() {
            set.add(move || {
                let rec = crate::gesture::TapRecognizer::new();
                match tap_buttons {
                    Some(mask) => rec.accept_buttons(mask),
                    None => rec,
                }
            });
        }
        if has_double_tap {
            set.add(move || {
                let rec = crate::gesture::DoubleTapRecognizer::new();
                match double_tap_buttons {
                    Some(mask) => rec.accept_buttons(mask),
                    None => rec,
                }
            });
        }
        if has_triple_tap {
            set.add(move || {
                let rec = crate::gesture::TripleTapRecognizer::new();
                match triple_tap_buttons {
                    Some(mask) => rec.accept_buttons(mask),
                    None => rec,
                }
            });
        }
        if has_drag {
            // No `.threshold(..)`: the drag slop is the active profile's, so a
            // finger gets 18 dp where a mouse keeps its 5.
            set.add(crate::gesture::DragRecognizer::new);
        }
        if has_long_press {
            set.add(move || {
                let rec = crate::gesture::LongPressRecognizer::new();
                match long_press_buttons {
                    Some(mask) => rec.accept_buttons(mask),
                    None => rec,
                }
            });
        }
        if has_swipe {
            set.add(crate::gesture::SwipeRecognizer::new);
        }
        node.handlers.gesture_arena = Some(set);
        gesture_owners.insert(id);
    }

    /// Route a gesture recognized by the arena (or the OS pinch/rotate
    /// stream) to the matching handler on the node.
    pub(crate) fn dispatch_recognized_gesture(
        node: &mut crate::arena::WidgetNode,
        gesture: GestureEvent,
        ctx: &mut EventContext,
    ) {
        use crate::gesture::{DragPhase, PinchPhase};
        // Every gesture handler invocation runs under a
        // `Handler` source label. Any `ctx.send_intent(...)` issued
        // from inside a tap / double-tap / drag / etc. handler
        // emits with `IntentSource::Handler`. The label is restored
        // at the bottom of this fn so nested dispatch doesn't
        // pollute the wrong bucket.
        let saved_source = ctx
            .current_source
            .replace(crate::telemetry::IntentSource::Handler);
        // For every gesture handler, fire BOTH the external and own slot
        // in that order so a widget that wired an on_tap via the
        // WidgetBuilder AND via apply_self_handlers sees both callbacks —
        // and more importantly, so widgets that rely on one bucket don't
        // miss the gesture when the other is empty.
        match gesture {
            GestureEvent::Tap(event) => {
                if let Some(h) = node.external_handlers.on_tap.as_mut() {
                    h(&event, ctx);
                }
                if let Some(h) = node.handlers.on_tap.as_mut() {
                    h(&event, ctx);
                }
            }
            GestureEvent::DoubleTap(event) => {
                if let Some(h) = node.external_handlers.on_double_tap.as_mut() {
                    h(&event, ctx);
                }
                if let Some(h) = node.handlers.on_double_tap.as_mut() {
                    h(&event, ctx);
                }
            }
            GestureEvent::TripleTap(event) => {
                if let Some(h) = node.external_handlers.on_triple_tap.as_mut() {
                    h(&event, ctx);
                }
                if let Some(h) = node.handlers.on_triple_tap.as_mut() {
                    h(&event, ctx);
                }
            }
            GestureEvent::LongPress(event) => {
                if let Some(h) = node.external_handlers.on_long_press.as_mut() {
                    h(&event, ctx);
                }
                if let Some(h) = node.handlers.on_long_press.as_mut() {
                    h(&event, ctx);
                }
            }
            GestureEvent::DragStarted {
                position,
                button,
                pointer,
            } => {
                // Auto-capture the pointer for the duration of the drag so
                // the widget keeps receiving `Moved` / `Ended` even when
                // the cursor leaves its bounds. Released on `DragEnded`.
                // Implicit: the recognizer has already won the arbitration,
                // so this is bookkeeping rather than a fresh claim.
                ctx.capture_pointer_implicit();
                // A drag owns the rest of the press: tell the router so the
                // sequence records this node as its winner and every peer is
                // cancelled exactly once.
                ctx.recognized_owning_gesture = true;
                let phase = DragPhase::Started {
                    position,
                    button,
                    pointer,
                };
                if let Some(h) = node.external_handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
            }
            GestureEvent::DragMoved {
                position,
                delta,
                pointer,
            } => {
                let phase = DragPhase::Moved {
                    position,
                    delta,
                    pointer,
                };
                if let Some(h) = node.external_handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
            }
            GestureEvent::DragEnded { position, pointer } => {
                let phase = DragPhase::Ended { position, pointer };
                if let Some(h) = node.external_handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
                ctx.release_pointer();
            }
            GestureEvent::DragCancelled {
                position,
                pointer,
                reason,
            } => {
                // Same shape as `DragEnded`: the handler is told, then the
                // implicit capture the drag took is given back. A handler that
                // committed as it went unwinds here.
                let phase = DragPhase::Cancelled {
                    position,
                    pointer,
                    reason,
                };
                if let Some(h) = node.external_handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_drag.as_mut() {
                    h(phase, ctx);
                }
                ctx.release_pointer();
            }
            GestureEvent::Swipe {
                direction,
                velocity,
            } => {
                // Like a drag, a swipe owns the press it completes.
                ctx.recognized_owning_gesture = true;
                if let Some(h) = node.external_handlers.on_swipe.as_mut() {
                    h(direction, velocity, ctx);
                }
                if let Some(h) = node.handlers.on_swipe.as_mut() {
                    h(direction, velocity, ctx);
                }
            }
            GestureEvent::PinchStarted { center } => {
                let phase = PinchPhase::Started {
                    center,
                    pointer: ctx.pointer(),
                };
                if let Some(h) = node.external_handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
            }
            GestureEvent::PinchChanged {
                center,
                scale,
                rotation,
            } => {
                let phase = PinchPhase::Changed {
                    center,
                    scale,
                    rotation,
                    pointer: ctx.pointer(),
                };
                if let Some(h) = node.external_handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
            }
            GestureEvent::PinchEnded => {
                let phase = PinchPhase::Ended {
                    pointer: ctx.pointer(),
                };
                if let Some(h) = node.external_handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
            }
            GestureEvent::PinchCancelled { reason } => {
                let phase = PinchPhase::Cancelled {
                    pointer: ctx.pointer(),
                    reason,
                };
                if let Some(h) = node.external_handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
                if let Some(h) = node.handlers.on_pinch.as_mut() {
                    h(phase, ctx);
                }
            }
        }
        // Restore — see the matching `replace` at the
        // top of this function.
        ctx.current_source = saved_source;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_widgets::FillWidget;
    use crate::widget_builder::WidgetBuilder;

    #[test]
    fn gesture_tap_recognized_on_click() {
        use std::cell::Cell;
        use std::rc::Rc;

        let tapped = Rc::new(Cell::new(false));
        let tapped_flag = tapped.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_tap(move |_pos, _ctx| {
            tapped_flag.set(true);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.click(widget);
        assert!(tapped.get());
    }

    #[test]
    fn gesture_drag_recognized_on_drag() {
        use crate::gesture::DragPhase;
        use std::cell::Cell;
        use std::rc::Rc;

        let drag_started = Rc::new(Cell::new(false));
        let drag_ended = Rc::new(Cell::new(false));
        let start_flag = drag_started.clone();
        let end_flag = drag_ended.clone();

        let mut tree = WidgetTree::new();
        let _widget = tree.add(FillWidget::new().on_drag(move |phase, _ctx| match phase {
            DragPhase::Started { .. } => start_flag.set(true),
            DragPhase::Ended { .. } => end_flag.set(true),
            _ => {}
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.drag(Point::new(50.0, 25.0), Point::new(80.0, 25.0));

        assert!(drag_started.get());
        assert!(drag_ended.get());
    }

    #[test]
    fn gesture_handler_called_on_tap() {
        use std::cell::Cell;
        use std::rc::Rc;

        let handler_called = Rc::new(Cell::new(false));
        let handler_flag = handler_called.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_tap(move |_pos, _ctx| {
            handler_flag.set(true);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.click(widget);
        assert!(handler_called.get());
    }

    #[test]
    fn on_swipe_fires_from_platform_gesture_event() {
        use crate::gesture::{GestureEvent, SwipeDirection};
        use std::cell::Cell;
        use std::rc::Rc;

        let observed: Rc<Cell<Option<(SwipeDirection, i32)>>> = Rc::new(Cell::new(None));
        let flag = observed.clone();

        let mut tree = WidgetTree::new();
        tree.add(
            FillWidget::new().on_swipe(move |direction, velocity, _ctx| {
                flag.set(Some((direction, velocity as i32)));
            }),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.pointer_move(Point::new(50.0, 25.0));
        tree.dispatch_event(WidgetEvent::Gesture {
            gesture: GestureEvent::Swipe {
                direction: SwipeDirection::Left,
                velocity: 450.0,
            },
        });

        let got = observed.get();
        assert!(matches!(got, Some((SwipeDirection::Left, 450))));
    }

    #[test]
    fn on_pinch_fires_from_platform_gesture_event() {
        use crate::gesture::{GestureEvent, PinchPhase};
        use std::cell::Cell;
        use std::rc::Rc;

        let started = Rc::new(Cell::new(false));
        let scale_seen = Rc::new(Cell::new(0.0_f32));
        let ended = Rc::new(Cell::new(false));
        let started_flag = started.clone();
        let scale_flag = scale_seen.clone();
        let ended_flag = ended.clone();

        let mut tree = WidgetTree::new();
        tree.add(FillWidget::new().on_pinch(move |phase, _ctx| match phase {
            PinchPhase::Started { .. } => started_flag.set(true),
            PinchPhase::Changed { scale, .. } => scale_flag.set(scale),
            PinchPhase::Ended { .. } => ended_flag.set(true),
            _ => {}
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.pointer_move(Point::new(50.0, 25.0));
        tree.dispatch_event(WidgetEvent::Gesture {
            gesture: GestureEvent::PinchStarted {
                center: Point::new(50.0, 25.0),
            },
        });
        tree.dispatch_event(WidgetEvent::Gesture {
            gesture: GestureEvent::PinchChanged {
                center: Point::new(50.0, 25.0),
                scale: 1.5,
                rotation: 0.0,
            },
        });
        tree.dispatch_event(WidgetEvent::Gesture {
            gesture: GestureEvent::PinchEnded,
        });

        assert!(started.get());
        assert!((scale_seen.get() - 1.5).abs() < 0.001);
        assert!(ended.get());
    }

    #[test]
    fn drag_auto_captures_pointer_until_ended() {
        use crate::gesture::DragPhase;
        use std::cell::Cell;
        use std::rc::Rc;

        let started = Rc::new(Cell::new(false));
        let moved = Rc::new(Cell::new(0));
        let ended = Rc::new(Cell::new(false));
        let started_flag = started.clone();
        let moved_flag = moved.clone();
        let ended_flag = ended.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_drag(move |phase, _ctx| match phase {
            DragPhase::Started { .. } => started_flag.set(true),
            DragPhase::Moved { .. } => moved_flag.set(moved_flag.get() + 1),
            DragPhase::Ended { .. } => ended_flag.set(true),
            _ => {}
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // Press inside, move past the 5px threshold while still inside —
        // DragRecognizer emits DragStarted, and auto-capture kicks in.
        tree.dispatch_event(WidgetEvent::pointer_down(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(70.0, 25.0)));
        assert!(started.get(), "DragStarted must fire");

        // Move the pointer well outside the widget bounds. Without
        // auto-capture this event would hit-test to another widget and
        // the scrollbar would never see it.
        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(500.0, 500.0)));
        assert!(
            moved.get() >= 1,
            "Move outside bounds must still reach drag handler"
        );

        // Release outside bounds — must still fire DragEnded on the
        // original widget, and pointer capture must be released.
        tree.dispatch_event(WidgetEvent::pointer_up(
            Point::new(500.0, 500.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        assert!(ended.get(), "DragEnded must fire on the original widget");
        assert_eq!(
            tree.pointer_captured_by(),
            None,
            "pointer capture must be released after DragEnded"
        );

        // Sanity: the widget we instantiated is the one we hooked.
        let _ = widget;
    }

    #[test]
    fn on_long_press_fires_from_tick_gestures() {
        use std::cell::Cell;
        use std::rc::Rc;
        use std::time::{Duration, Instant};

        let pressed = Rc::new(Cell::new(false));
        let pressed_flag = pressed.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_long_press(move |_pos, _ctx| {
            pressed_flag.set(true);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let center = tree.bounds(widget).center();
        tree.dispatch_event(WidgetEvent::pointer_down(
            center,
            PointerButton::Primary,
            Modifiers::NONE,
        ));

        // Before the timeout, tick does nothing.
        tree.tick_gestures(Instant::now());
        assert!(!pressed.get());

        // After the configured 500ms, tick fires the handler.
        tree.tick_gestures(Instant::now() + Duration::from_millis(600));
        assert!(pressed.get());

        // After firing there is no remaining deadline.
        assert!(tree.next_gesture_deadline().is_none());
    }

    #[test]
    fn multiple_recognizers_on_same_widget() {
        use crate::gesture::DragPhase;
        use std::cell::Cell;
        use std::rc::Rc;

        let tapped = Rc::new(Cell::new(false));
        let dragged = Rc::new(Cell::new(false));
        let tapped_flag = tapped.clone();
        let dragged_flag = dragged.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(
            FillWidget::new()
                .on_tap(move |_pos, _ctx| {
                    tapped_flag.set(true);
                })
                .on_drag(move |phase, _ctx| {
                    if matches!(phase, DragPhase::Started { .. }) {
                        dragged_flag.set(true);
                    }
                }),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.click(widget);
        assert!(tapped.get());
        assert!(!dragged.get());

        tapped.set(false);
        dragged.set(false);

        tree.drag(Point::new(50.0, 25.0), Point::new(80.0, 25.0));
        assert!(dragged.get());
    }

    #[test]
    fn ancestor_drag_starts_through_descendant_tap_capture() {
        // The cross-widget tap-vs-drag disambiguation: a descendant `on_tap`
        // (which captures the pointer on PointerDown) must NOT permanently
        // shadow an ancestor `on_drag`. A plain click fires the descendant tap;
        // a press-then-move starts the ANCESTOR drag instead.
        use crate::gesture::DragPhase;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let tapped = Rc::new(Cell::new(false));
        let drag_started = Rc::new(Cell::new(false));
        let t = tapped.clone();
        let d = drag_started.clone();

        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_tap(move |_p, _c| t.set(true)));
        // Ancestor container carries the drag; child sits on top and taps.
        let _parent = tree.add(StackWidget::new().child(child).on_drag(move |phase, _c| {
            if matches!(phase, DragPhase::Started { .. }) {
                d.set(true);
            }
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // 1) A plain click on the child fires the child's tap, not the drag.
        tree.dispatch_event(WidgetEvent::pointer_down(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        tree.dispatch_event(WidgetEvent::pointer_up(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        assert!(
            tapped.get(),
            "a click on the child fires the descendant tap"
        );
        assert!(
            !drag_started.get(),
            "a click must not start the ancestor drag"
        );

        tapped.set(false);
        drag_started.set(false);

        // 2) Press on the child, then move past threshold → the ANCESTOR drag
        // starts (it competes for the sequence while the child tap holds
        // capture), and the descendant tap does NOT fire.
        tree.dispatch_event(WidgetEvent::pointer_down(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        // The arbitration is observable: exactly one competitor, the ancestor,
        // enrolled as a `Gesture` member and still in the running. This is the
        // migration contract for the deleted `drag_observers`.
        assert_eq!(
            tree.sequence_members(crate::pointer::PointerId::MOUSE),
            vec![(
                _parent,
                crate::gesture::MemberRole::Gesture,
                crate::gesture::MemberState::Possible
            )],
        );
        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(80.0, 25.0)));
        assert!(
            drag_started.get(),
            "dragging from the child must start the ancestor drag"
        );
        assert_eq!(
            tree.sequence_winner(crate::pointer::PointerId::MOUSE),
            Some(_parent),
            "and the ancestor is the sequence's winner"
        );
        tree.dispatch_event(WidgetEvent::pointer_up(
            Point::new(80.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        assert!(!tapped.get(), "a drag must not fire the descendant tap");
    }

    #[test]
    fn ancestor_drag_starts_through_deeply_nested_tap_capture() {
        // The SceneView shape: an `on_drag` container whose child is an
        // `on_tap`-wrapped card with a DEEPER inner leaf (the hit target). The
        // press bubbles up to the card's tap (which captures), and the
        // container's drag must still start on move — proving the disambiguation
        // walks multiple levels, not just an immediate parent.
        use crate::gesture::DragPhase;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let drag_started = Rc::new(Cell::new(false));
        let d = drag_started.clone();

        let mut tree = WidgetTree::new();
        // Deepest leaf — the hit target, no handlers of its own.
        let inner = tree.add(FillWidget::new());
        // Card: an on_tap wrapper around a container holding the inner leaf.
        let card = tree.add(
            StackWidget::new()
                .child(inner)
                .on_tap(move |_p, _c| { /* select */ }),
        );
        // Canvas: an on_drag container holding the card.
        let _canvas = tree.add(StackWidget::new().child(card).on_drag(move |phase, _c| {
            if matches!(phase, DragPhase::Started { .. }) {
                d.set(true);
            }
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.dispatch_event(WidgetEvent::pointer_down(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        // Enrolment walks the whole frozen path, not just the immediate
        // parent: the canvas two levels up is the one competitor.
        assert_eq!(
            tree.sequence_members(crate::pointer::PointerId::MOUSE),
            vec![(
                _canvas,
                crate::gesture::MemberRole::Gesture,
                crate::gesture::MemberState::Possible
            )],
        );
        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(80.0, 25.0)));
        assert!(
            drag_started.get(),
            "dragging a deeply-nested tappable child must start the ancestor drag"
        );
        assert_eq!(
            tree.sequence_winner(crate::pointer::PointerId::MOUSE),
            Some(_canvas),
        );
    }

    #[test]
    fn click_on_tap_child_then_hover_does_not_start_ancestor_drag() {
        // Regression: press+RELEASE on a descendant tap child (no drag), THEN
        // move the mouse with no button held. Arming the ancestor drag on the
        // press fed the ancestor's DragRecognizer a `Down`; the release must
        // clear that armed state, or the *next* hover move crosses the drag
        // threshold and starts a phantom drag. This is the corkboard bug: a
        // card's read-only RichTextEditor captures the press as an interactive
        // child, and a later hover-move dragged the card.
        use crate::gesture::DragPhase;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let drag_started = Rc::new(Cell::new(false));
        let d = drag_started.clone();

        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_tap(move |_p, _c| { /* select */ }));
        let _parent = tree.add(StackWidget::new().child(child).on_drag(move |phase, _c| {
            if matches!(phase, DragPhase::Started { .. }) {
                d.set(true);
            }
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // Click (press then release at the same point — the tap resolves).
        tree.dispatch_event(WidgetEvent::pointer_down(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        tree.dispatch_event(WidgetEvent::pointer_up(
            Point::new(50.0, 25.0),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        // The release sweep closed the sequence, so nothing is competing any
        // more — the state that used to leak was an armed ancestor recognizer.
        assert!(
            tree.sequence_members(crate::pointer::PointerId::MOUSE)
                .is_empty(),
            "the release sweep ends the sequence"
        );
        // Now hover somewhere (no button down). Must NOT start the drag.
        tree.dispatch_event(WidgetEvent::pointer_move(Point::new(85.0, 25.0)));
        assert!(
            !drag_started.get(),
            "a hover after a click must not start a phantom ancestor drag"
        );
    }
    // ---------------------------------------------------------------
    // P06: per-contact arenas, the node tap streak, and the profile
    // ---------------------------------------------------------------

    use crate::pointer::{
        BackendDeviceKey, EventTime, PointerId, PointerIdAllocator, PointerInfo, PointerPhase,
        PointerSample,
    };

    /// A fresh touch contact — the platform mints a new id per press, which is
    /// exactly why the tap streak cannot live inside a recognizer.
    fn new_contact() -> PointerId {
        use std::sync::atomic::{AtomicU64, Ordering};
        static NEXT: AtomicU64 = AtomicU64::new(1);
        PointerIdAllocator::global().begin(
            BackendDeviceKey::DEFAULT,
            NEXT.fetch_add(1, Ordering::Relaxed),
        )
    }

    fn touch_sample(
        id: PointerId,
        phase: PointerPhase,
        position: Point,
        time: EventTime,
    ) -> PointerSample {
        PointerSample {
            pointer: PointerInfo::touch(id, time),
            phase,
            position,
            button: None,
            modifiers: Modifiers::NONE,
            coalesced: Vec::new(),
        }
    }

    /// Press and release one fresh contact at `at`.
    fn touch_tap(tree: &mut WidgetTree, at: Point, down_ms: u64, up_ms: u64) {
        let id = new_contact();
        tree.dispatch_pointer(touch_sample(
            id,
            PointerPhase::Down,
            at,
            EventTime::from_millis(down_ms),
        ));
        tree.dispatch_pointer(touch_sample(
            id,
            PointerPhase::Up,
            at,
            EventTime::from_millis(up_ms),
        ));
    }

    #[test]
    fn a_touch_double_tap_survives_two_pointer_ids_through_the_tree() {
        use std::cell::Cell;
        use std::rc::Rc;

        let doubles = Rc::new(Cell::new(0));
        let flag = doubles.clone();

        let mut tree = WidgetTree::new();
        tree.add(FillWidget::new().on_double_tap(move |_e, _ctx| {
            flag.set(flag.get() + 1);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let at = Point::new(50.0, 25.0);
        touch_tap(&mut tree, at, 0, 40);
        assert_eq!(doubles.get(), 0, "one tap is not a double tap");
        touch_tap(&mut tree, at, 150, 190);
        assert_eq!(
            doubles.get(),
            1,
            "the pair must be recognized across two contacts"
        );
    }

    #[test]
    fn gesture_owners_holds_exactly_the_arena_owning_nodes() {
        use std::cell::Cell;
        use std::rc::Rc;

        let ticks = Rc::new(Cell::new(0));
        let flag = ticks.clone();

        let mut tree = WidgetTree::new();
        // Two nodes, only one of which wires a gesture handler.
        let plain = tree.add(FillWidget::new());
        let gestured = tree.add(FillWidget::new().on_long_press(move |_e, _ctx| {
            flag.set(flag.get() + 1);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // Prototypes are installed on the first press that reaches the node…
        assert!(tree.gesture_owners.is_empty());
        let center = tree.bounds(gestured).center();
        tree.dispatch_event(WidgetEvent::pointer_down(
            center,
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        assert_eq!(
            tree.gesture_owners.iter().copied().collect::<Vec<_>>(),
            vec![gestured],
            "only the node that actually carries recognizers is an owner"
        );
        assert!(!tree.gesture_owners.contains(&plain));

        // …and the install is what the sweep is bounded by, not the live
        // per-contact arenas: the owner is visited and does fire.
        tree.tick_gestures(std::time::Instant::now() + std::time::Duration::from_millis(600));
        assert_eq!(ticks.get(), 1, "the tick sweep must visit the owner");

        // Destroying the widget takes it back out of the set.
        tree.destroy_subtree(gestured);
        assert!(!tree.gesture_owners.contains(&gestured));
    }

    #[test]
    fn under_multi_contact_first_only_one_contact_is_served() {
        use std::cell::Cell;
        use std::rc::Rc;

        let taps = Rc::new(Cell::new(0));
        let flag = taps.clone();

        let mut tree = WidgetTree::new();
        // No `.multi_contact(..)`: `First` is the default, and it is what every
        // widget written before the touch programme assumes.
        tree.add(FillWidget::new().on_tap(move |_e, _ctx| {
            flag.set(flag.get() + 1);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let a = new_contact();
        let b = new_contact();
        tree.dispatch_pointer(touch_sample(
            a,
            PointerPhase::Down,
            Point::new(40.0, 25.0),
            EventTime::from_millis(0),
        ));
        // Second finger while the first is still down: terminated at the node.
        tree.dispatch_pointer(touch_sample(
            b,
            PointerPhase::Down,
            Point::new(60.0, 25.0),
            EventTime::from_millis(5),
        ));
        tree.dispatch_pointer(touch_sample(
            b,
            PointerPhase::Up,
            Point::new(60.0, 25.0),
            EventTime::from_millis(20),
        ));
        tree.dispatch_pointer(touch_sample(
            a,
            PointerPhase::Up,
            Point::new(40.0, 25.0),
            EventTime::from_millis(30),
        ));

        assert_eq!(taps.get(), 1, "the refused contact must produce no tap");
    }

    #[test]
    fn under_multi_contact_all_every_contact_is_served() {
        use crate::gesture::MultiContact;
        use std::cell::Cell;
        use std::rc::Rc;

        let taps = Rc::new(Cell::new(0));
        let flag = taps.clone();

        let mut tree = WidgetTree::new();
        tree.add(
            FillWidget::new()
                .on_tap(move |_e, _ctx| {
                    flag.set(flag.get() + 1);
                })
                .multi_contact(MultiContact::All),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let a = new_contact();
        let b = new_contact();
        // Overlapping presses: a goes down, b goes down, b lifts, a lifts.
        for (id, x, ms) in [(a, 40.0, 0u64), (b, 60.0, 5)] {
            tree.dispatch_pointer(touch_sample(
                id,
                PointerPhase::Down,
                Point::new(x, 25.0),
                EventTime::from_millis(ms),
            ));
        }
        for (id, x, ms) in [(b, 60.0, 20u64), (a, 40.0, 30)] {
            tree.dispatch_pointer(touch_sample(
                id,
                PointerPhase::Up,
                Point::new(x, 25.0),
                EventTime::from_millis(ms),
            ));
        }

        assert_eq!(taps.get(), 2, "both contacts must tap");
    }

    #[test]
    fn a_mouse_drag_still_arms_at_five_pixels_and_a_finger_does_not() {
        use crate::gesture::DragPhase;
        use std::cell::Cell;
        use std::rc::Rc;

        fn armed_after(travel: f32, touch: bool) -> bool {
            let started = Rc::new(Cell::new(false));
            let flag = started.clone();
            let mut tree = WidgetTree::new();
            tree.add(FillWidget::new().on_drag(move |phase, _ctx| {
                if matches!(phase, DragPhase::Started { .. }) {
                    flag.set(true);
                }
            }));
            tree.layout(SizeProposal::exact(200.0, 50.0));

            let from = Point::new(20.0, 25.0);
            let to = Point::new(20.0 + travel, 25.0);
            if touch {
                let id = new_contact();
                tree.dispatch_pointer(touch_sample(
                    id,
                    PointerPhase::Down,
                    from,
                    EventTime::from_millis(0),
                ));
                tree.dispatch_pointer(touch_sample(
                    id,
                    PointerPhase::Move,
                    to,
                    EventTime::from_millis(10),
                ));
            } else {
                tree.dispatch_event(WidgetEvent::pointer_down(
                    from,
                    PointerButton::Primary,
                    Modifiers::NONE,
                ));
                tree.dispatch_event(WidgetEvent::pointer_move(to));
            }
            started.get()
        }

        // The mouse column of `GestureProfile::MOUSE` is byte-for-byte the
        // pre-P06 constant: 5 dp, `>=`.
        assert!(!armed_after(4.0, false), "4 dp is under the mouse slop");
        assert!(armed_after(5.0, false), "5 dp is the mouse slop");

        // The same travel on a finger is nothing — 18 dp of touch slop.
        assert!(!armed_after(5.0, true));
        assert!(!armed_after(17.0, true));
        assert!(armed_after(18.0, true), "18 dp is the touch slop");
    }

    #[test]
    fn a_long_press_fires_on_a_simulated_clock() {
        use crate::pointer::clock::ManualClock;
        use std::cell::Cell;
        use std::rc::Rc;

        let pressed = Rc::new(Cell::new(false));
        let flag = pressed.clone();

        let mut tree = WidgetTree::new();
        let clock = std::rc::Rc::new(ManualClock::new(EventTime::ZERO));
        tree.set_input_clock(clock.clone());
        let widget = tree.add(FillWidget::new().on_long_press(move |_e, _ctx| {
            flag.set(true);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let center = tree.bounds(widget).center();
        tree.dispatch_event(WidgetEvent::pointer_down(
            center,
            PointerButton::Primary,
            Modifiers::NONE,
        ));

        // Not yet: 499 ms is under the mouse profile's 500 ms hold.
        clock.set(EventTime::from_millis(499));
        tree.tick_gestures(std::time::Instant::now());
        assert!(!pressed.get());

        // Exactly at the hold, with no sleeping anywhere.
        clock.set(EventTime::from_millis(500));
        tree.tick_gestures(std::time::Instant::now());
        assert!(pressed.get(), "the hold is 500 ms on the mouse profile");
    }

    /// A press, then one `advance_time` past the hold — and the long press
    /// fires.
    ///
    /// It did not before: `advance_time` moved the simulated clock, the overlay
    /// timers and the flings, and left the gesture arenas alone. A test that
    /// wanted a hold had to install a `ManualClock` *and* call `tick_gestures`
    /// by hand, which is why `advance_time`'s own doc comment promised
    /// long-press recognition it had never delivered.
    #[test]
    fn one_advance_time_past_the_hold_recognises_a_long_press() {
        use std::cell::Cell;
        use std::rc::Rc;

        let pressed = Rc::new(Cell::new(0u32));
        let flag = pressed.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().on_long_press(move |_e, _ctx| {
            flag.set(flag.get() + 1);
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let center = tree.bounds(widget).center();
        tree.dispatch_event(WidgetEvent::pointer_down(
            center,
            PointerButton::Primary,
            Modifiers::NONE,
        ));

        // Short of the mouse profile's 500 ms hold, and nothing has fired.
        tree.advance_time(std::time::Duration::from_millis(400));
        assert_eq!(pressed.get(), 0, "400 ms is under the hold");

        // Past it, on the same clock and with no `tick_gestures` call and no
        // hand-installed clock anywhere.
        tree.advance_time(std::time::Duration::from_millis(150));
        assert_eq!(pressed.get(), 1, "the hold is 500 ms on the mouse profile");

        // …and only once, however long the press is held.
        tree.advance_time(std::time::Duration::from_millis(1000));
        assert_eq!(
            pressed.get(),
            1,
            "a hold recognises once, not once per tick"
        );
    }

    /// What a tick's handlers write is flushed inside the same tick.
    ///
    /// A recognized gesture is a dispatch: its handler writes signals, and
    /// those signals drive rebuilds and dormancy transitions that only happen
    /// in `process_state_changes`. Leaving that to the caller's next `layout`
    /// would make the effect of a hold arrive a frame after the hold — and for
    /// a caller that only advances the clock (the automation settle loop), not
    /// arrive at all.
    #[test]
    fn a_gesture_recognized_by_a_tick_has_its_effect_flushed_by_the_same_tick() {
        use crate::signal::Signal;
        use crate::test_widgets::StackWidget;

        let mut tree = WidgetTree::new();
        let revealed = Signal::new(false);
        let flag = revealed.clone();
        let panel = tree.add(FillWidget::new().visible_when(revealed.clone()));
        let widget = tree.add(FillWidget::new().on_long_press(move |_e, _ctx| {
            flag.set(true);
        }));
        let _root = tree.add(StackWidget::new().child(widget).child(panel));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert!(!tree.is_visible(panel), "precondition: the panel is parked");

        tree.dispatch_event(WidgetEvent::pointer_down(
            tree.bounds(widget).center(),
            PointerButton::Primary,
            Modifiers::NONE,
        ));
        tree.advance_time(std::time::Duration::from_millis(600));

        assert!(
            tree.is_visible(panel),
            "the hold fired and its signal was drained in the same call"
        );
    }

    #[test]
    fn a_mouse_triple_click_still_escalates_through_the_tree() {
        use std::cell::Cell;
        use std::rc::Rc;

        let doubles = Rc::new(Cell::new(0));
        let triples = Rc::new(Cell::new(0));
        let d = doubles.clone();
        let t = triples.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(
            FillWidget::new()
                .on_double_tap(move |_e, _ctx| d.set(d.get() + 1))
                .on_triple_tap(move |_e, _ctx| t.set(t.get() + 1)),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));

        let center = tree.bounds(widget).center();
        for _ in 0..3 {
            tree.dispatch_event(WidgetEvent::pointer_down(
                center,
                PointerButton::Primary,
                Modifiers::NONE,
            ));
            tree.dispatch_event(WidgetEvent::pointer_up(
                center,
                PointerButton::Primary,
                Modifiers::NONE,
            ));
        }
        assert_eq!(doubles.get(), 1, "click 2 fires DoubleTap");
        assert_eq!(triples.get(), 1, "click 3 fires TripleTap");
    }
}

// -------------------------------------------------------------------------
// P08: the arbitration spine — `PointerSequence` and the ordered procedure
// -------------------------------------------------------------------------

#[cfg(test)]
mod arbitration_tests {
    use super::*;
    use crate::event::EventResponse;
    use crate::event::{Modifiers, PointerButton, WidgetEvent};
    use crate::gesture::{DragPhase, MemberRole, MemberState};
    use crate::pointer::touch_action::{PanClaim, TouchAction};
    use crate::pointer::{
        BackendDeviceKey, EventTime, PointerId, PointerIdAllocator, PointerInfo, PointerPhase,
        PointerSample,
    };
    use crate::test_widgets::{FillWidget, StackWidget};
    use crate::widget_builder::WidgetBuilder;
    use std::cell::Cell;
    use std::rc::Rc;
    use std::time::Duration;
    use teksilo_canvas::{Point, SizeProposal};
    use teksilo_tokens::{DragActivation, PointerKind, TargetDensity};

    /// A fresh contact: the platform mints a new id per press.
    fn new_contact() -> PointerId {
        use std::sync::atomic::{AtomicU64, Ordering};
        static NEXT: AtomicU64 = AtomicU64::new(9_000);
        PointerIdAllocator::global().begin(
            BackendDeviceKey::DEFAULT,
            NEXT.fetch_add(1, Ordering::Relaxed),
        )
    }

    fn touch(id: PointerId, phase: PointerPhase, at: Point, ms: u64) -> PointerSample {
        PointerSample {
            pointer: PointerInfo::touch(id, EventTime::from_millis(ms)),
            phase,
            position: at,
            button: None,
            modifiers: Modifiers::NONE,
            coalesced: Vec::new(),
        }
    }

    fn press(tree: &mut WidgetTree, at: Point) {
        tree.dispatch_event(WidgetEvent::pointer_down(
            at,
            PointerButton::Primary,
            Modifiers::NONE,
        ));
    }

    fn moved(tree: &mut WidgetTree, at: Point) {
        tree.dispatch_event(WidgetEvent::pointer_move(at));
    }

    fn release(tree: &mut WidgetTree, at: Point) {
        tree.dispatch_event(WidgetEvent::pointer_up(
            at,
            PointerButton::Primary,
            Modifiers::NONE,
        ));
    }

    /// **The single most important test in the package.** A mouse drag latches
    /// at 5.0 dp whatever the frozen `TouchAction` and whatever the density —
    /// reading `slop_precise` (2.0) for a precise pointer would silently
    /// retune every mouse drag in the framework.
    #[test]
    fn a_mouse_drag_latches_at_five_in_every_configuration() {
        for density in [
            TargetDensity::Compact,
            TargetDensity::Comfortable,
            TargetDensity::Touch,
        ] {
            for action in [
                TouchAction::AUTO,
                TouchAction::NONE,
                TouchAction::PAN,
                TouchAction::PAN_X,
                TouchAction::PAN_Y,
                TouchAction::MANIPULATION,
            ] {
                // `DragPhase::Started` reports the press origin, not the
                // sample that latched it, so measure the latch by *when* the
                // handler fired: walk one pixel at a time and record the
                // travel at the first Started.
                let latched = Rc::new(Cell::new(None::<f32>));
                let travel = Rc::new(Cell::new(0.0_f32));
                let l = latched.clone();
                let t = travel.clone();
                let mut theme = crate::presets::intui::light();
                theme.input = teksilo_tokens::InputTokens::for_density(density);
                let mut tree = WidgetTree::new().with_theme(theme);
                let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
                tree.add(
                    StackWidget::new()
                        .child(child)
                        .touch_action(action)
                        .on_drag(move |phase, _c| {
                            if matches!(phase, DragPhase::Started { .. }) && l.get().is_none() {
                                l.set(Some(t.get()));
                            }
                        }),
                );
                tree.layout(SizeProposal::exact(200.0, 50.0));

                press(&mut tree, Point::new(20.0, 25.0));
                for step in 1..=10 {
                    travel.set(step as f32);
                    moved(&mut tree, Point::new(20.0 + step as f32, 25.0));
                    if latched.get().is_some() {
                        break;
                    }
                }
                let at = latched
                    .get()
                    .unwrap_or_else(|| panic!("no drag latched at {density:?} under {action:?}"));
                assert_eq!(
                    at, 5.0,
                    "a mouse latched after {at} dp of travel under {action:?} at \
                     {density:?}; the mouse drag slop is 5.0 and must stay 5.0"
                );
                release(&mut tree, Point::new(30.0, 25.0));
            }
        }
    }

    /// `slop_precise` reaches only a **direct** pointer under a frozen
    /// `TouchAction::NONE`.
    #[test]
    fn slop_precise_is_direct_pointer_only() {
        use crate::gesture::PointerSequence;

        let tokens = teksilo_tokens::InputTokens::for_density(TargetDensity::Compact);
        let path = Vec::new();
        let mouse = PointerSequence::new(
            PointerInfo::mouse(EventTime::ZERO),
            path.clone(),
            TouchAction::NONE,
            None,
            Point::ZERO,
            EventTime::ZERO,
        );
        assert_eq!(
            mouse.latch_slop(tokens.profile(PointerKind::Mouse)),
            5.0,
            "a mouse under a frozen NONE still latches at 5.0"
        );

        let contact = PointerSequence::new(
            PointerInfo::touch(new_contact(), EventTime::ZERO),
            path,
            TouchAction::NONE,
            None,
            Point::ZERO,
            EventTime::ZERO,
        );
        let touch_profile = tokens.profile(PointerKind::Touch);
        assert_eq!(
            contact.latch_slop(touch_profile),
            touch_profile.slop_precise,
            "a contact under a frozen NONE drops to the jitter floor"
        );
    }

    /// The raw-preview pass runs root-first, and the first `Handled` claims the
    /// press. A nested pair of previewers pins the order.
    #[test]
    fn nested_previewers_run_root_first() {
        let order = Rc::new(std::cell::RefCell::new(Vec::<&'static str>::new()));
        let outer_order = order.clone();
        let inner_order = order.clone();

        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new());
        let inner = tree.add(StackWidget::new().child(leaf).on_pointer_event(
            move |event, _ctx| {
                if matches!(event, WidgetEvent::PointerDown { .. }) {
                    inner_order.borrow_mut().push("inner");
                }
                EventResponse::Ignored
            },
        ));
        let outer = tree.add(StackWidget::new().child(inner).on_pointer_event(
            move |event, _ctx| {
                if matches!(event, WidgetEvent::PointerDown { .. }) {
                    outer_order.borrow_mut().push("outer");
                    // The outer previewer claims: the inner one must never run.
                    return EventResponse::Handled;
                }
                EventResponse::Ignored
            },
        ));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        press(&mut tree, Point::new(50.0, 25.0));
        assert_eq!(
            *order.borrow(),
            vec!["outer"],
            "the preview pass is root-first and the first Handled wins"
        );
        assert_eq!(
            tree.sequence_winner(PointerId::MOUSE),
            Some(outer),
            "and that claim decides the sequence"
        );
        assert_eq!(
            tree.sequence_members(PointerId::MOUSE),
            vec![(outer, MemberRole::RawPreview, MemberState::Won)],
        );
        release(&mut tree, Point::new(50.0, 25.0));
    }

    /// An explicit `capture_pointer()` from an undecided sequence enrols the
    /// caller as a `RawDrag` member and, for a precise pointer, decides the
    /// sequence there and then — the Splitter / dock-handle / column-grip
    /// shape, which owns no recognizer at all.
    #[test]
    fn explicit_capture_enrols_a_raw_drag_and_decides_a_precise_pointer() {
        let dragged = Rc::new(Cell::new(false));
        let d = dragged.clone();

        let mut tree = WidgetTree::new();
        // The handle: captures on Down, answers Ignored, works from Move — the
        // Splitter / dock-handle / column-grip shape. Like the real Splitter it
        // also carries a double-tap handler, so it owns an arena and the press
        // stops bubbling at it.
        let handle = tree.add(
            FillWidget::new()
                .on_double_tap(|_e, _c| {})
                .on_pointer_event(|event, ctx| {
                    if matches!(event, WidgetEvent::PointerDown { .. }) {
                        ctx.capture_pointer();
                    }
                    EventResponse::Ignored
                }),
        );
        let ancestor = tree.add(StackWidget::new().child(handle).on_drag(move |phase, _c| {
            if matches!(phase, DragPhase::Started { .. }) {
                d.set(true);
            }
        }));
        tree.layout(SizeProposal::exact(200.0, 50.0));

        press(&mut tree, Point::new(20.0, 25.0));
        assert_eq!(
            tree.sequence_winner(PointerId::MOUSE),
            Some(handle),
            "the explicit captor owns the press immediately"
        );
        let members = tree.sequence_members(PointerId::MOUSE);
        assert_eq!(members[0], (handle, MemberRole::RawDrag, MemberState::Won));
        assert_eq!(
            members[1],
            (ancestor, MemberRole::Gesture, MemberState::Rejected),
            "the ancestor is still enrolled — as a rejected competitor, which is \
             what keeps its recognizers out of the rest of the press"
        );

        // Drag well past the ancestor's threshold: it must not steal the press.
        for step in 1..=20 {
            moved(&mut tree, Point::new(20.0 + step as f32 * 4.0, 25.0));
        }
        assert!(
            !dragged.get(),
            "a decided sequence keeps the ancestor out of the running"
        );
        release(&mut tree, Point::new(100.0, 25.0));
    }

    /// A touch `RawDrag` does **not** decide at press: it defers to
    /// `drag_slop` (18) and still beats a pan claimant, whose `pan_slop` is 36.
    #[test]
    fn a_touch_raw_drag_defers_to_drag_slop_and_still_beats_a_pan() {
        let mut tree = WidgetTree::new();
        let handle = tree.add(FillWidget::new().on_pointer_event(|event, ctx| {
            if matches!(event, WidgetEvent::PointerDown { .. }) {
                ctx.capture_pointer();
            }
            EventResponse::Ignored
        }));
        let scroller = tree.add(
            StackWidget::new()
                .child(handle)
                .pan_claim(PanClaim::vertical()),
        );
        tree.layout(SizeProposal::exact(200.0, 400.0));

        let id = new_contact();
        let at = Point::new(100.0, 20.0);
        tree.dispatch_pointer(touch(id, PointerPhase::Down, at, 0));
        assert_eq!(
            tree.sequence_winner(id),
            None,
            "a contact's explicit capture does NOT decide at press"
        );
        let members = tree.sequence_members(id);
        assert!(
            members
                .iter()
                .any(|(id, role, _)| *id == handle && *role == MemberRole::RawDrag),
            "the captor competes as a RawDrag: {members:?}"
        );
        assert!(
            members
                .iter()
                .any(|(id, role, _)| *id == scroller && matches!(role, MemberRole::Pan(_))),
            "and the scroller competes as a Pan: {members:?}"
        );

        // 17 dp: below the 18 dp drag slop, so nobody has won.
        tree.dispatch_pointer(touch(id, PointerPhase::Move, Point::new(100.0, 37.0), 20));
        assert_eq!(tree.sequence_winner(id), None, "17 dp is below drag_slop");

        // 19 dp: past drag_slop (18) but well below pan_slop (36) — the
        // innermost RawDrag wins.
        tree.dispatch_pointer(touch(id, PointerPhase::Move, Point::new(100.0, 39.0), 30));
        assert_eq!(
            tree.sequence_winner(id),
            Some(handle),
            "the RawDrag latches at 18 and the pan claimant needs 36"
        );
        tree.dispatch_pointer(touch(id, PointerPhase::Up, Point::new(100.0, 39.0), 40));
    }

    /// `DragActivation::AfterLongPress` cannot win before its timer, and
    /// self-rejects once the press leaves the tap boundary.
    #[test]
    fn after_long_press_defers_and_self_rejects_past_the_tap_boundary() {
        let mut tree = WidgetTree::new();
        let row = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
        let list = tree.add(
            StackWidget::new()
                .child(row)
                .drag_activation(DragActivation::AfterLongPress)
                .on_drag(|_phase, _c| {}),
        );
        tree.layout(SizeProposal::exact(200.0, 50.0));

        press(&mut tree, Point::new(20.0, 25.0));
        let member = tree
            .sequence_members(PointerId::MOUSE)
            .into_iter()
            .find(|(id, ..)| *id == list)
            .expect("the list competes");
        assert_eq!(member.1, MemberRole::Gesture);
        assert_eq!(member.2, MemberState::Possible);

        // Travelling past the tap boundary before the timer withdraws it: that
        // travel is a pan, not a considered grab.
        moved(&mut tree, Point::new(60.0, 25.0));
        assert_eq!(
            tree.sequence_winner(PointerId::MOUSE),
            None,
            "a deferred drag cannot win before its long-press timer"
        );
        let member = tree
            .sequence_members(PointerId::MOUSE)
            .into_iter()
            .find(|(id, ..)| *id == list)
            .expect("the list is still listed");
        assert_eq!(
            member.2,
            MemberState::Rejected,
            "and self-rejects once the press leaves the tap boundary"
        );
        release(&mut tree, Point::new(60.0, 25.0));
    }

    /// Losing the **captor** cancels the whole sequence: the press belongs to
    /// the node that took it, and there is nothing left to arbitrate for.
    ///
    /// Per-member death is the unit-level half of the same rule and is pinned
    /// in `gesture::sequence`'s own tests — in a tree a member is always an
    /// ancestor of the captor, so it cannot die on its own.
    #[test]
    fn losing_the_captor_cancels_the_sequence() {
        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
        let mid = tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
        let outer = tree.add(StackWidget::new().child(mid).on_drag(|_phase, _c| {}));
        tree.layout(SizeProposal::exact(200.0, 50.0));

        press(&mut tree, Point::new(20.0, 25.0));
        let members: Vec<_> = tree
            .sequence_members(PointerId::MOUSE)
            .into_iter()
            .map(|(id, ..)| id)
            .collect();
        assert_eq!(members, vec![mid, outer], "innermost first");

        tree.arena.destroy(child);
        moved(&mut tree, Point::new(21.0, 25.0));
        assert!(
            tree.sequence_members(PointerId::MOUSE).is_empty(),
            "losing the captor cancels the sequence"
        );
        assert_eq!(tree.sequence_winner(PointerId::MOUSE), None);
    }

    /// `hold_gesture` blocks every peer, and auto-releases at
    /// `profile.max_hold` (250 ms) — the framework never trusts a holder to
    /// answer.
    #[test]
    fn a_hold_blocks_peers_and_auto_releases_at_max_hold() {
        use crate::pointer::clock::ManualClock;

        let dragged = Rc::new(Cell::new(false));
        let d = dragged.clone();

        let mut tree = WidgetTree::new();
        let clock = Rc::new(ManualClock::new(EventTime::ZERO));
        tree.set_input_clock(clock.clone());

        // The child holds the sequence on the press, then never answers.
        let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}).on_pointer_event(
            |event, ctx| {
                if matches!(event, WidgetEvent::PointerDown { .. }) {
                    ctx.hold_gesture();
                }
                EventResponse::Ignored
            },
        ));
        tree.add(StackWidget::new().child(child).on_drag(move |phase, _c| {
            if matches!(phase, DragPhase::Started { .. }) {
                d.set(true);
            }
        }));
        tree.layout(SizeProposal::exact(300.0, 50.0));

        press(&mut tree, Point::new(20.0, 25.0));
        assert!(
            tree.sequence_members(PointerId::MOUSE)
                .iter()
                .any(|(id, _, state)| *id == child && *state == MemberState::Held),
            "the holder is listed as Held"
        );

        // Well past the ancestor's 5 dp threshold, but nothing may win.
        clock.set(EventTime::from_millis(100));
        moved(&mut tree, Point::new(80.0, 25.0));
        assert!(!dragged.get(), "no peer wins while a member is holding");

        // 250 ms: the hold expires and the ancestor is free to latch.
        clock.set(EventTime::from_millis(250));
        moved(&mut tree, Point::new(90.0, 25.0));
        assert!(
            dragged.get(),
            "the hold auto-releases at max_hold and the peer latches"
        );
    }

    /// The auto-release is driven by **time**, not by the next sample. A
    /// contact resting perfectly still finds its hold released the moment the
    /// clock reaches `max_hold`, with no move to carry the transition.
    ///
    /// Before the tick knew how to expire a hold this was only true of a
    /// sequence the user happened to move: every reader of `Held` re-reads it
    /// against the timestamp of whatever sample it is serving, so the outcome
    /// of a *later* move was already right — but the framework's promise is
    /// that it stops trusting a holder after `max_hold`, and until then the
    /// holder stayed listed as `Held` for as long as the user kept still.
    #[test]
    fn a_hold_auto_releases_on_the_tick_with_no_movement_at_all() {
        use crate::pointer::clock::ManualClock;

        let mut tree = WidgetTree::new();
        let clock = Rc::new(ManualClock::new(EventTime::ZERO));
        tree.set_input_clock(clock.clone());

        let child = tree.add(FillWidget::new().on_pointer_event(|event, ctx| {
            if matches!(event, WidgetEvent::PointerDown { .. }) {
                ctx.hold_gesture();
            }
            EventResponse::Ignored
        }));
        tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
        tree.layout(SizeProposal::exact(300.0, 50.0));

        let max_hold = teksilo_tokens::GestureProfile::MOUSE.max_hold;
        let state_of = |tree: &WidgetTree, id: WidgetId| {
            tree.sequence_members(PointerId::MOUSE)
                .into_iter()
                .find(|(m, ..)| *m == id)
                .map(|(_, _, state)| state)
        };

        press(&mut tree, Point::new(20.0, 25.0));
        assert_eq!(
            state_of(&tree, child),
            Some(MemberState::Held),
            "the holder is listed as Held"
        );

        // One millisecond short of the promise, and nothing has moved.
        tree.advance_time(max_hold - Duration::from_millis(1));
        assert_eq!(
            state_of(&tree, child),
            Some(MemberState::Held),
            "the hold stands right up to max_hold"
        );

        // …and at it.
        tree.advance_time(Duration::from_millis(1));
        assert_eq!(
            state_of(&tree, child),
            Some(MemberState::Possible),
            "time alone releases the hold — no sample carried it"
        );
    }

    /// …and the event loop is told to come back for it. A transition the tick
    /// can perform but no deadline reports is a frame the loop never wakes for,
    /// which leaves the hold standing exactly as long as it did before.
    #[test]
    fn a_standing_hold_wakes_the_event_loop_for_its_own_expiry() {
        use crate::pointer::clock::ManualClock;

        let mut tree = WidgetTree::new();
        let clock = Rc::new(ManualClock::new(EventTime::ZERO));
        tree.set_input_clock(clock.clone());

        let child = tree.add(FillWidget::new().on_pointer_event(|event, ctx| {
            if matches!(event, WidgetEvent::PointerDown { .. }) {
                ctx.hold_gesture();
            }
            EventResponse::Ignored
        }));
        tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
        tree.layout(SizeProposal::exact(300.0, 50.0));

        let max_hold = teksilo_tokens::GestureProfile::MOUSE.max_hold;
        assert_eq!(
            tree.next_input_deadline(),
            None,
            "nothing is pending before the press"
        );

        press(&mut tree, Point::new(20.0, 25.0));
        let deadline = tree
            .next_input_deadline()
            .expect("a standing hold is an input deadline");
        // The value, not merely its presence: a term reporting some other
        // instant — the member's `eligible_at`, a wrong duration — would leave
        // the assertion below green if it only asked `is_some`.
        let expected = tree.instant_for(EventTime::from_duration(max_hold));
        let skew = deadline
            .saturating_duration_since(expected)
            .max(expected.saturating_duration_since(deadline));
        assert!(
            skew < Duration::from_millis(5),
            "the wake must be the hold's own expiry: expected ~{max_hold:?} out, \
             deadline and expectation differ by {skew:?}"
        );

        // Serving it clears it: one wake, not a spin.
        tree.advance_time(max_hold);
        assert_eq!(
            tree.next_input_deadline(),
            None,
            "the expiry ran, so nothing is pending any more"
        );
    }

    /// The other half of the same decision, stated as a test so it cannot rot
    /// into prose: a deferred member's `eligible_at` is **not** a deadline.
    ///
    /// Eligibility is never stored — it is re-derived against the timestamp of
    /// whatever sample is being arbitrated — so nothing happens at that
    /// instant and waking the loop for it would buy an idle frame with no work
    /// in it. A press that sat still past its `long_press` is already eligible
    /// on its very next move, with no tick in between.
    #[test]
    fn a_deferred_members_eligibility_is_not_a_wake() {
        let mut tree = WidgetTree::new();
        // The row must take the press: the deferral is armed by the ancestor
        // walk that runs *through* a captor, and a row that captures nothing
        // enrols the list by a path that never sets `eligible_at` at all —
        // which would leave this test asserting nothing.
        let row = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
        let list = tree.add(
            StackWidget::new()
                .child(row)
                .drag_activation(DragActivation::AfterLongPress)
                .on_drag(|_phase, _c| {}),
        );
        tree.layout(SizeProposal::exact(200.0, 50.0));

        press(&mut tree, Point::new(20.0, 25.0));
        assert_eq!(
            tree.sequence_members(PointerId::MOUSE)
                .into_iter()
                .find(|(id, ..)| *id == list)
                .map(|(_, _, state)| state),
            Some(MemberState::Possible),
            "the deferred member is enrolled and waiting on its timer"
        );
        assert_eq!(
            tree.next_input_deadline(),
            None,
            "a deferred member asks the loop for nothing: there is no work at \
             its eligibility instant"
        );

        // Proof that the deferral really was armed, and not that this fixture
        // enrolled an ordinary drag member with no timer at all: only a
        // deferred member self-rejects on leaving the tap boundary.
        moved(&mut tree, Point::new(60.0, 25.0));
        assert_eq!(
            tree.sequence_members(PointerId::MOUSE)
                .into_iter()
                .find(|(id, ..)| *id == list)
                .map(|(_, _, state)| state),
            Some(MemberState::Rejected),
            "the member under test is the deferred one"
        );
    }

    /// `claim_gesture` / `reject_gesture` are the explicit forms of the same
    /// decision.
    #[test]
    fn claim_and_reject_are_arbitration_acts() {
        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}).on_pointer_event(
            |event, ctx| {
                if matches!(event, WidgetEvent::PointerDown { .. }) {
                    ctx.claim_gesture();
                }
                EventResponse::Ignored
            },
        ));
        let ancestor = tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
        tree.layout(SizeProposal::exact(200.0, 50.0));

        press(&mut tree, Point::new(20.0, 25.0));
        assert_eq!(tree.sequence_winner(PointerId::MOUSE), Some(child));
        let ancestor_state = tree
            .sequence_members(PointerId::MOUSE)
            .into_iter()
            .find(|(id, ..)| *id == ancestor)
            .map(|(_, _, state)| state);
        assert_eq!(
            ancestor_state,
            Some(MemberState::Rejected),
            "a claim knocks every peer out exactly once"
        );
        release(&mut tree, Point::new(20.0, 25.0));
    }

    /// With the touch kill switch off, a direct-pointer sample forms no
    /// sequence at all — while a mouse on the same tree still does.
    #[test]
    fn touch_disabled_forms_no_sequence() {
        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
        tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
        tree.layout(SizeProposal::exact(200.0, 50.0));
        tree.set_touch_enabled(false);

        let id = new_contact();
        let at = Point::new(20.0, 25.0);
        tree.dispatch_pointer(touch(id, PointerPhase::Down, at, 0));
        assert!(
            tree.sequence_members(id).is_empty(),
            "the kill switch means a contact arbitrates nothing"
        );
        assert_eq!(tree.sequence_winner(id), None);
        tree.dispatch_pointer(touch(id, PointerPhase::Up, at, 10));

        press(&mut tree, at);
        assert!(
            !tree.sequence_members(PointerId::MOUSE).is_empty(),
            "the mouse is unaffected by the touch kill switch"
        );
        release(&mut tree, at);
    }

    /// One [`TapBoundary`](crate::gesture::TapBoundary) predicate, two answers:
    /// a precise pointer keeps its `tap_slop` radius, and a coarse one keeps
    /// its target's **bounds** — a finger's reported centre wanders while
    /// resting on a control, and a tap that never left its target is a tap.
    #[test]
    fn a_coarse_tap_survives_inside_its_bounds_where_a_mouse_would_not() {
        let taps = Rc::new(Cell::new(0));
        let t = taps.clone();

        let mut tree = WidgetTree::new();
        let row = tree.add(FillWidget::new().on_tap(move |_e, _c| t.set(t.get() + 1)));
        tree.layout(SizeProposal::exact(200.0, 60.0));

        // 30 dp of travel: past the touch profile's 18 dp tap_slop, but well
        // inside the 200 x 60 row.
        let down = Point::new(40.0, 30.0);
        let up = Point::new(70.0, 30.0);

        let id = new_contact();
        tree.dispatch_pointer(touch(id, PointerPhase::Down, down, 0));
        tree.dispatch_pointer(touch(id, PointerPhase::Move, up, 10));
        tree.dispatch_pointer(touch(id, PointerPhase::Up, up, 20));
        assert_eq!(taps.get(), 1, "a finger that stayed on the row tapped it");

        // The same travel on a mouse is 30 dp past a 5 dp radius: not a tap.
        taps.set(0);
        press(&mut tree, down);
        moved(&mut tree, up);
        release(&mut tree, up);
        assert_eq!(taps.get(), 0, "a mouse keeps its tap_slop radius");

        // And a finger that leaves the row is not a tap either.
        taps.set(0);
        let id = new_contact();
        let out = Point::new(40.0, 200.0);
        tree.dispatch_pointer(touch(id, PointerPhase::Down, down, 30));
        tree.dispatch_pointer(touch(id, PointerPhase::Move, out, 40));
        tree.dispatch_pointer(touch(id, PointerPhase::Up, out, 50));
        assert_eq!(taps.get(), 0, "sliding off the row abandons the activation");
        let _ = row;
    }

    /// Sliding off a control revokes its **tap family** once — WCAG 2.2
    /// SC 2.5.2's "slide off to abort" — while a drag the same press started
    /// runs on.
    #[test]
    fn leaving_the_tap_boundary_revokes_the_tap_family_but_not_the_drag() {
        let tapped = Rc::new(Cell::new(false));
        let dragged = Rc::new(Cell::new(0));
        let ta = tapped.clone();
        let dr = dragged.clone();

        let mut tree = WidgetTree::new();
        let control = tree.add(
            FillWidget::new()
                .on_tap(move |_e, _c| ta.set(true))
                .on_drag(move |phase, _c| {
                    if matches!(phase, DragPhase::Started { .. }) {
                        dr.set(dr.get() + 1);
                    }
                }),
        );
        tree.layout(SizeProposal::exact(200.0, 60.0));

        press(&mut tree, Point::new(40.0, 30.0));
        moved(&mut tree, Point::new(120.0, 30.0));
        release(&mut tree, Point::new(120.0, 30.0));

        assert!(!tapped.get(), "the activation is abandoned");
        assert_eq!(dragged.get(), 1, "the drag the same press started is not");
        let _ = control;
    }

    /// The frozen `TouchAction` is readable from inside the press handler, and
    /// is the intersection of the whole root-to-target chain.
    #[test]
    fn the_frozen_touch_action_reaches_the_press_handler() {
        let seen = Rc::new(Cell::new(TouchAction::AUTO));
        let s = seen.clone();

        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new().on_pointer_event(move |event, ctx| {
            if matches!(event, WidgetEvent::PointerDown { .. }) {
                s.set(ctx.touch_action());
            }
            EventResponse::Ignored
        }));
        let inner = tree.add(
            StackWidget::new()
                .child(leaf)
                .touch_action(TouchAction::PAN),
        );
        tree.add(
            StackWidget::new()
                .child(inner)
                .touch_action(TouchAction::PAN_Y),
        );
        tree.layout(SizeProposal::exact(200.0, 50.0));

        let id = new_contact();
        let at = Point::new(20.0, 25.0);
        tree.dispatch_pointer(touch(id, PointerPhase::Down, at, 0));
        assert_eq!(
            seen.get(),
            TouchAction::PAN_Y,
            "PAN ∩ PAN_Y = PAN_Y, frozen at press and readable from the handler"
        );
        assert_eq!(tree.sequence_touch_action(id), TouchAction::PAN_Y);
        tree.dispatch_pointer(touch(id, PointerPhase::Up, at, 10));
    }
}