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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! One arbitration object per live pointer: who is competing for this press,
//! and which of them owns it.
//!
//! # What this replaces
//!
//! Before this module the framework had exactly one piece of cross-widget
//! arbitration: `drag_observers`, a `Vec<WidgetId>` on the tree holding the
//! draggable ancestors armed by the current press. It was single-pointer (one
//! `Vec` for the whole tree), drag-only (a scrollable, a previewer or an
//! explicit captor could not be a competitor at all), and its decision
//! procedure was implicit in the order of three helper functions.
//!
//! A [`PointerSequence`] is the same idea made explicit and made plural: one
//! per live [`PointerId`](crate::pointer::PointerId), stored on that pointer's
//! [`PointerEntry`](crate::pointer::table::PointerEntry), carrying the frozen hit
//! path, the frozen [`TouchAction`], every enrolled [`SequenceMember`], and the
//! winner once one is decided.
//!
//! # The ordered decision procedure
//!
//! Stated once here, implemented in `widget_tree/pointer_router.rs`:
//!
//! 1. **At press**: hit-test to a target, freeze the hit path (target → root),
//!    intersect and freeze [`TouchAction`] root-to-target, and record the
//!    innermost `gesture_dead_zone` node on that path as the enrolment
//!    boundary.
//! 2. **The raw-preview pass runs first, root-first.** The first ancestor whose
//!    `on_pointer_event` answers `Handled` claims the sequence outright as a
//!    [`MemberRole::RawPreview`] winner. This order is load-bearing —
//!    `rich_text/mouse.rs` documents relying on an outer wrapper seeing a press
//!    before an inner one — so previewers are deliberately **not** folded into
//!    the innermost-first member order below.
//! 3. **An explicit [`capture_pointer`](crate::widget::EventContext::capture_pointer)
//!    from an undecided sequence is an arbitration act**, not plumbing: the
//!    caller is enrolled as [`MemberRole::RawDrag`], and for a precise pointer
//!    with no eligible pan competitor the sequence is decided there and then.
//!    Three shipped widgets drive their whole interaction this way — the
//!    splitter handle, the dock resize handle and the table column grip all
//!    return `Ignored` from `on_pointer_event`, capture, and work from
//!    `PointerMove` with no recognizer at all.
//! 4. **On move while undecided**: timers before positional thresholds, then
//!    members innermost-first. A `RawDrag` wins past `drag_slop`; a `Gesture`
//!    wins when its own recognizer recognizes; a [`MemberRole::Pan`] wins only
//!    on an axis the frozen `TouchAction` permits and only past `pan_slop`.
//! 5. **On up**: the release sweep — the innermost still-`Possible` member with
//!    a completable gesture wins, which is the pre-existing
//!    `arena.process(Up) -> Tap`.
//!
//! # A node with two roles
//!
//! One node holds exactly **one** member — [`PointerSequence::decide`],
//! [`PointerSequence::reject`] and [`PointerSequence::hold`] are all keyed on
//! that, and [`PointerSequence::enrol`] refuses a second. A node can still want
//! two roles: a scene viewport declares a [`PanClaim`] *and* carries `on_drag`
//! on the same `HandlerSet`, because its surface is both the camera and the
//! marquee. Step 1 enrols it as the pan claimant before any handler runs, so
//! the drag half arrives at an already-taken slot.
//!
//! [`PointerSequence::defer_own_drag`] is that half's door: it attaches the
//! drag's [`DragActivation`] to the member the node already has. The member goes
//! on competing as a pan at `pan_slop`, while the node's own recognizers are
//! silenced until the activation allows them — `Auto` on a direct pointer with
//! an eligible pan resolving, as everywhere else, to a hold. Whichever half
//! ripens first takes the other out: a won pan withdraws the self-drag
//! ([`PointerSequence::withdraw_own_drag`]), a recognized self-drag flips the
//! member's reported role ([`PointerSequence::promote_own_drag`]) so
//! [`WidgetTree::sequence_members`](crate::WidgetTree::sequence_members) names
//! the half that actually won.
//!
//! The deferral is a **hold**, not a timer. A press that has already travelled
//! past `long_press_slop` when the deadline arrives was never a hold, so its
//! self-drag is withdrawn rather than armed — the rule
//! [`LongPressRecognizer`](super::LongPressRecognizer) applies to itself.
//! Without it a slow, deliberate pan would arm the grab simply by outlasting
//! the clock, and a surface that pans only for a *fast* finger is not a surface
//! that pans.
//!
//! And the hold it spends is spent **on that node**.
//! [`PointerSequence::has_deferred_grab_for`] is keyed on a node, so a
//! heavyweight widget inside a dual-role container keeps its own touch long
//! press and its own touch context menu — a deferred grab on the container is
//! not a declaration that its descendants have given theirs up. The
//! ancestor-wide door is the explicit
//! [`LongPressRole::DragHandle`](crate::LongPressRole::DragHandle).
//!
//! **The mouse cannot enter that arm at all.** `defer_own_drag` refuses anything
//! but a live [`MemberRole::Pan`] member, and a mouse enrols none — so on a
//! mouse a dual-role node is enrolled by step 4's ordinary `Gesture` path and
//! latches at the 5.0 it always did.
//!
//! # Why the mouse is unchanged
//!
//! [`GestureProfile::pan_slop`] is `None` for a mouse and
//! [`PanClaim::devices`] defaults to direct pointers, so **no pan member is
//! ever eligible for a mouse**. Every mouse sequence is therefore either
//! decided at press (an explicit capture) or arbitrated exactly as
//! `drag_observers` arbitrated it: ancestors innermost-first, each latching at
//! its own `drag_slop`, which for the mouse profile is the 5.0 it has always
//! been. On touch the same widget defers by `drag_slop` (18) and still beats a
//! scroller, because `pan_slop` (36) is larger.
//!
//! Reference: `docs/events-and-gestures.md`.

use teksilo_canvas::Point;
use teksilo_tokens::{DragActivation, GestureProfile};

use crate::pointer::touch_action::{Axis, PanClaim, TouchAction};
use crate::pointer::{EventTime, PointerInfo};
use crate::widget_id::WidgetId;

/// What a member is competing *as*.
///
/// The role decides which threshold the member wins on and, for `Pan`, which
/// axes the frozen [`TouchAction`] has to permit.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MemberRole {
    /// A node whose own gesture recognizers (`on_drag` / `on_swipe`) are
    /// competing. This is what `drag_observers` used to hold, and it is what an
    /// ancestor of the pressed control is enrolled as.
    Gesture,
    /// A scroll container that declared a [`PanClaim`]. Only ever enrolled for
    /// a pointer kind the claim's `devices` mask admits and only when the
    /// pointer's profile has a `pan_slop` — so never for a mouse.
    Pan(PanClaim),
    /// A node that took the pointer by an explicit
    /// [`capture_pointer`](crate::widget::EventContext::capture_pointer) while
    /// the sequence was undecided, and drives its interaction from
    /// `PointerMove` rather than from a recognizer.
    RawDrag,
    /// A node that answered `Handled` from the root-first preview pass. It has
    /// already won by the time it is enrolled; the role exists so
    /// [`WidgetTree::sequence_members`](crate::WidgetTree::sequence_members)
    /// can report *why*.
    RawPreview,
}

/// Where one member stands in the arbitration.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemberState {
    /// Still in the running.
    Possible,
    /// Deferring its own decision — see
    /// [`hold_gesture`](crate::widget::EventContext::hold_gesture). Released
    /// automatically at `profile.max_hold`; the framework itself never holds.
    Held,
    /// Out of the running, either by its own choice
    /// ([`reject_gesture`](crate::widget::EventContext::reject_gesture)), by a
    /// threshold it can no longer meet, or because a peer won.
    Rejected,
    /// The winner.
    Won,
}

/// One competitor for a pointer sequence.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SequenceMember {
    /// The competing node.
    pub id: WidgetId,
    /// What it is competing as.
    pub role: MemberRole,
    /// The earliest time this member may win, when its activation defers it.
    /// `None` means "as soon as its threshold is met".
    pub eligible_at: Option<EventTime>,
    /// Where it stands.
    pub state: MemberState,
    /// When `true`, this member self-rejects the moment the pointer leaves the
    /// tap boundary — the [`DragActivation::AfterLongPress`] rule.
    pub(crate) rejects_on_tap_slop: bool,
    /// When [`state`](Self::state) became [`MemberState::Held`].
    pub(crate) held_since: Option<EventTime>,
    /// Whether this member's node **also** owns drag/swipe recognizers of its
    /// own — the dual-role shape. See
    /// [`PointerSequence::defer_own_drag`](PointerSequence::defer_own_drag).
    ///
    /// `false` for every member a mouse ever enrols, because the arm that sets
    /// it is reachable only through a [`MemberRole::Pan`] membership.
    pub(crate) has_own_drag: bool,
    /// When those self-drag recognizers may start running. `None` means "now".
    pub(crate) own_drag_eligible_at: Option<EventTime>,
    /// Whether that self-drag is out of the running for the rest of the press —
    /// the pan half won, or the press travelled past the tap boundary.
    pub(crate) own_drag_withdrawn: bool,
}

impl SequenceMember {
    /// A fresh member in the running.
    pub(crate) fn new(id: WidgetId, role: MemberRole) -> Self {
        Self {
            id,
            role,
            eligible_at: None,
            state: MemberState::Possible,
            rejects_on_tap_slop: false,
            held_since: None,
            has_own_drag: false,
            own_drag_eligible_at: None,
            own_drag_withdrawn: false,
        }
    }

    /// Whether this member could still win.
    pub fn is_live(&self) -> bool {
        matches!(self.state, MemberState::Possible | MemberState::Held)
    }

    /// Whether this member may win at `now`. A member deferred by
    /// [`DragActivation::AfterLongPress`] cannot win before its timer, and a
    /// holding member cannot win at all until it releases.
    pub fn is_eligible_at(&self, now: EventTime) -> bool {
        self.state == MemberState::Possible
            && self.eligible_at.is_none_or(|deadline| now >= deadline)
    }

    /// Whether this member's node may run its **own** drag/swipe recognizers at
    /// `now`.
    ///
    /// Always `true` for a member carrying no self-drag deferral — which is
    /// every member a mouse ever enrols, and every member of every sequence on
    /// a node that is not dual-role — so this predicate is inert everywhere the
    /// dual-role shape does not occur.
    ///
    /// Three answers, and the third is the load-bearing one:
    ///
    /// * no self-drag → `true`, unconditionally;
    /// * a self-drag still inside its deferral → `false` until `now` reaches
    ///   `own_drag_eligible_at`;
    /// * a **withdrawn** self-drag → `false` for the rest of the press, and
    ///   deliberately so. A withdrawal means the press is not the hold the
    ///   deferral was waiting for — the pan half took it, or the travel
    ///   disproved the hold — and the node's recognizers must stay silenced
    ///   afterwards, or a deferral ripening later would start the node's drag
    ///   under a finger that had already committed to something else. Because
    ///   the gate this feeds (`WidgetTree::sequence_blocks_arena`'s rule) is per
    ///   *node*, that silence covers the node's tap family too, which is the
    ///   same thing `WidgetTree::cancel_member_taps` does to the pan winner
    ///   explicitly. For a dual-role node mid-pan that is the wanted answer: a
    ///   finger that has committed to a pan is not also tapping, double-tapping
    ///   or long-pressing the surface it is panning. A **completed** tap is not
    ///   lost to it either way: `end_sequence` nulls the sequence before the
    ///   release is dispatched, and `TapRecognizer` decides the release against
    ///   its own [`TapBoundary`], so a press that wandered and lifted inside the
    ///   node still taps.
    pub fn own_drag_armed_at(&self, now: EventTime) -> bool {
        if !self.has_own_drag {
            return true;
        }
        !self.own_drag_withdrawn && self.own_drag_eligible_at.is_none_or(|at| now >= at)
    }
}

/// Where a press stops being a tap.
///
/// One predicate, three consumers: it fails a tap, it triggers
/// [`GestureArenaSet::cancel_taps`](super::GestureArenaSet::cancel_taps), and
/// it clears the framework press visual. A coarse pointer uses `Bounds` A coarse pointer uses `Bounds`
/// because a finger's reported centre wanders several device pixels while
/// resting inside the control it is pressing; a precise pointer keeps the
/// radius it always had.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TapBoundary {
    /// The press fails once it travels further than this from its origin.
    Radius(f32),
    /// The press fails once it leaves the pressed node's bounds.
    Bounds,
}

impl TapBoundary {
    /// The boundary a pointer of this kind uses.
    ///
    /// `Radius(profile.tap_slop)` for a precise pointer — the pre-existing
    /// rule, unchanged — and `Bounds` for a coarse one.
    pub fn for_pointer(pointer: &PointerInfo, profile: &GestureProfile) -> Self {
        if pointer.kind.is_coarse() {
            Self::Bounds
        } else {
            Self::Radius(profile.tap_slop)
        }
    }

    /// Whether `position` has left the boundary, given the press origin and the
    /// pressed node's bounds in the same (window-logical) space.
    ///
    /// A `Bounds` boundary with no bounds to test against — the pressed node
    /// went away — falls back to the radius, so the answer is never "the press
    /// can travel anywhere".
    ///
    /// So does a `Bounds` boundary whose press **began outside the node**. A
    /// press can be accepted for a node it did not land in: a control that
    /// declares a [`Widget::hit_outset`] is offered the ring around it (a 12 dp
    /// twist arrow lifted to a 24 dp target, a 16 dp clear affordance inside a
    /// text field), and the miss-only slop pass re-attributes a near miss the
    /// same way. For such a press the node's rectangle never contained the
    /// origin, so testing `position` against it alone would report the press as
    /// already-left at the instant it arrived — and the tap could never
    /// complete, silently making the whole outset mechanism useless to every
    /// coarse-pointer tap. The rule for that case is the pointer's own radius
    /// around where it landed, unioned with the node's bounds so sliding *onto*
    /// the control keeps the press alive. Android's `ViewGroup` takes the same
    /// shape from the other direction (`pointInView(x, y, mTouchSlop)` — the
    /// view's rect inflated by touch slop).
    ///
    /// A press that began inside the node is untouched: the rectangle is the
    /// boundary, exactly as before.
    ///
    /// [`Widget::hit_outset`]: crate::widget::Widget::hit_outset
    pub fn left(
        &self,
        origin: Point,
        position: Point,
        bounds: Option<teksilo_canvas::Rect>,
        profile: &GestureProfile,
    ) -> bool {
        match self {
            Self::Radius(radius) => super::distance(origin, position) > *radius,
            Self::Bounds => match bounds {
                Some(rect) if rect.contains(origin) => !rect.contains(position),
                Some(rect) => {
                    !rect.contains(position) && super::distance(origin, position) > profile.tap_slop
                }
                None => super::distance(origin, position) > profile.tap_slop,
            },
        }
    }
}

/// Everything the tree knows about one press: who is competing for it, and who
/// won.
///
/// Lives in [`PointerEntry::sequence`](crate::pointer::table::PointerEntry::sequence)
/// for as long as the pointer is down. The ordered decision procedure this
/// type is the state of is written out in `docs/events-and-gestures.md` §4.2 and
/// in this module's own header.
#[derive(Debug, Clone, PartialEq)]
pub struct PointerSequence {
    pointer: PointerInfo,
    path: Vec<WidgetId>,
    touch_action: TouchAction,
    dead_zone_boundary: Option<WidgetId>,
    members: Vec<SequenceMember>,
    winner: Option<WidgetId>,
    capture: Option<WidgetId>,
    press_origin: Point,
    last_position: Point,
    started_at: EventTime,
    pressed_owner: Option<WidgetId>,
    terminating: bool,
    taps_cancelled: bool,
    /// Per-press [`DragActivation`] overrides, queued by
    /// [`EventContext::set_drag_activation`](crate::widget::EventContext::set_drag_activation)
    /// from a press handler and read by the enrolment walk that runs
    /// immediately afterwards.
    ///
    /// On the **sequence**, not written back onto the node, because
    /// `on_pointer_event` previews root-first over every strict ancestor of the
    /// press target: a node whose press handler answers here fires for presses
    /// it does not own, and a node write would leave its build-time activation
    /// changed for the *next* press. A `Vec` rather than a map — a press has at
    /// most a handful of answering nodes, and the order it is written in is the
    /// order it is read back in.
    drag_activation_overrides: Vec<(WidgetId, DragActivation)>,
}

impl PointerSequence {
    /// Open a sequence for `pointer`'s press at `origin`.
    ///
    /// `path` runs target → root and is **frozen**: a rebuild mid-gesture
    /// cannot change who was competing for a press that has already started.
    pub fn new(
        pointer: PointerInfo,
        path: Vec<WidgetId>,
        touch_action: TouchAction,
        dead_zone_boundary: Option<WidgetId>,
        origin: Point,
        started_at: EventTime,
    ) -> Self {
        Self {
            pointer,
            path,
            touch_action,
            dead_zone_boundary,
            members: Vec::new(),
            winner: None,
            capture: None,
            press_origin: origin,
            last_position: origin,
            started_at,
            pressed_owner: None,
            terminating: false,
            taps_cancelled: false,
            drag_activation_overrides: Vec::new(),
        }
    }

    /// Which pointer this sequence follows.
    pub fn pointer(&self) -> PointerInfo {
        self.pointer
    }

    /// The frozen hit path, target → root.
    pub fn path(&self) -> &[WidgetId] {
        &self.path
    }

    /// The [`TouchAction`] frozen at press — the intersection of every
    /// declaration from the root down to the pressed target.
    pub fn touch_action(&self) -> TouchAction {
        self.touch_action
    }

    /// The innermost `gesture_dead_zone` node on the frozen path, if any.
    /// Nothing at or above it may be enrolled.
    pub fn dead_zone_boundary(&self) -> Option<WidgetId> {
        self.dead_zone_boundary
    }

    /// Every enrolled member, innermost first.
    pub fn members(&self) -> &[SequenceMember] {
        &self.members
    }

    /// The node that owns this press, once one has been decided.
    pub fn winner(&self) -> Option<WidgetId> {
        self.winner
    }

    /// Whether arbitration is over.
    pub fn is_decided(&self) -> bool {
        self.winner.is_some()
    }

    /// The node holding this pointer's capture, as the sequence recorded it.
    pub fn capture(&self) -> Option<WidgetId> {
        self.capture
    }

    /// Record who holds the capture.
    pub fn set_capture(&mut self, captor: Option<WidgetId>) {
        self.capture = captor;
    }

    /// The node whose gesture arena took the press — the tap owner, when the
    /// press was not claimed by anything else.
    pub fn pressed_owner(&self) -> Option<WidgetId> {
        self.pressed_owner
    }

    /// Record the node whose gesture arena took the press.
    pub fn set_pressed_owner(&mut self, owner: Option<WidgetId>) {
        self.pressed_owner = owner;
    }

    /// Where the press landed.
    pub fn press_origin(&self) -> Point {
        self.press_origin
    }

    /// Where the pointer was at its most recent sample.
    pub fn last_position(&self) -> Point {
        self.last_position
    }

    /// Record the pointer's current position.
    pub fn set_last_position(&mut self, position: Point) {
        self.last_position = position;
    }

    /// When the press landed, on the tree's input timeline.
    pub fn started_at(&self) -> EventTime {
        self.started_at
    }

    /// Whether the press has already been told it is no longer a tap.
    ///
    /// The `cancel_taps` revocation fires **once** per press: it resets the
    /// node's [`TapStreak`](super::TapStreak), and repeating it on every
    /// subsequent move would keep clearing state a live drag may still want.
    pub fn taps_cancelled(&self) -> bool {
        self.taps_cancelled
    }

    /// Record that the tap family has been revoked for this press.
    pub fn set_taps_cancelled(&mut self) {
        self.taps_cancelled = true;
    }

    /// Whether the sequence is inside its own terminal dispatch — set while the
    /// `Up` that ends it is being delivered, so a teardown triggered from a
    /// handler cannot cancel a press that has already completed.
    pub fn is_terminating(&self) -> bool {
        self.terminating
    }

    /// Mark the sequence as inside its terminal dispatch.
    pub fn set_terminating(&mut self, terminating: bool) {
        self.terminating = terminating;
    }

    /// How far the pointer has travelled from the press point.
    pub fn travel(&self) -> f32 {
        super::distance(self.press_origin, self.last_position)
    }

    /// How far the pointer has travelled along one axis.
    pub fn travel_on(&self, axis: Axis) -> f32 {
        match axis {
            Axis::X => (self.last_position.x - self.press_origin.x).abs(),
            Axis::Y => (self.last_position.y - self.press_origin.y).abs(),
        }
    }

    /// The slop a positional member of this sequence latches at.
    ///
    /// `profile.drag_slop` in every configuration **except** a direct pointer
    /// under a frozen [`TouchAction::NONE`], where the subtree has declared
    /// that a contact does nothing but manipulate it and the jitter floor is
    /// the right threshold. A precise pointer always uses `drag_slop`: reading
    /// `slop_precise` for it would silently retune every mouse drag latch from
    /// 5 dp to 2.
    pub fn latch_slop(&self, profile: &GestureProfile) -> f32 {
        if self.pointer.kind.is_direct() && self.touch_action.is_none() {
            profile.slop_precise
        } else {
            profile.drag_slop
        }
    }

    /// Whether `id` may be enrolled at all: it must be on the frozen path and
    /// strictly below the dead-zone boundary.
    pub fn may_enrol(&self, id: WidgetId) -> bool {
        let Some(index) = self.path.iter().position(|p| *p == id) else {
            return false;
        };
        match self.dead_zone_boundary {
            Some(boundary) => match self.path.iter().position(|p| *p == boundary) {
                Some(boundary_index) => index < boundary_index,
                None => true,
            },
            None => true,
        }
    }

    /// Depth of `id` on the frozen path, innermost first. Used to keep
    /// [`members`](Self::members) sorted no matter what order enrolment
    /// happened in.
    fn depth_of(&self, id: WidgetId) -> usize {
        self.path
            .iter()
            .position(|p| *p == id)
            .unwrap_or(usize::MAX)
    }

    /// Whether `id` is already enrolled.
    pub fn has_member(&self, id: WidgetId) -> bool {
        self.members.iter().any(|m| m.id == id)
    }

    /// Enrol `id` as a competitor, keeping the member list innermost-first.
    ///
    /// Refused — and reported as `false` — when `id` is at or above the
    /// dead-zone boundary, when it is not on the frozen path, or when it is
    /// already enrolled.
    pub fn enrol(&mut self, id: WidgetId, role: MemberRole) -> bool {
        if self.has_member(id) || !self.may_enrol(id) {
            return false;
        }
        let member = SequenceMember::new(id, role);
        let depth = self.depth_of(id);
        let at = self
            .members
            .iter()
            .position(|m| self.depth_of(m.id) > depth)
            .unwrap_or(self.members.len());
        self.members.insert(at, member);
        true
    }

    /// Enrol a drag member whose [`DragActivation`] defers it.
    ///
    /// `AfterLongPress` (and `Auto` resolving to it) sets `eligible_at` to the
    /// long-press deadline and arms the self-rejection rule: the member is out
    /// the moment the press travels past the tap boundary, because that travel
    /// is a pan, not a considered grab.
    pub fn enrol_drag(
        &mut self,
        id: WidgetId,
        role: MemberRole,
        activation: DragActivation,
        profile: &GestureProfile,
    ) -> bool {
        if !self.enrol(id, role) {
            return false;
        }
        if self.resolve_activation(activation) == DragActivation::AfterLongPress
            && let Some(member) = self.members.iter_mut().find(|m| m.id == id)
        {
            member.eligible_at = Some(self.started_at + profile.long_press);
            member.rejects_on_tap_slop = true;
        }
        true
    }

    /// Give the press owner's **own** drag a say when the node is already
    /// enrolled in another role.
    ///
    /// One node holds exactly one [`SequenceMember`] — [`decide`](Self::decide),
    /// [`reject`](Self::reject) and [`hold`](Self::hold) are all keyed on that —
    /// and [`enrol`](Self::enrol) refuses a second. But a node can genuinely
    /// want two roles: a `SceneView` with selection or magnetism on declares a
    /// [`PanClaim`] *and* carries `on_drag` on the same `HandlerSet`.
    /// `begin_sequence` enrols it as the pan claimant before any handler runs,
    /// so its drag was refused and its [`DragActivation`] was never consulted —
    /// and its `DragRecognizer`, driven by the ordinary capture dispatch that
    /// *precedes* the arbitration walk, then latched at `drag_slop` and decided
    /// the sequence at half the travel the pan needed. A surface shaped like
    /// that could not pan under a finger at all.
    ///
    /// Rather than enrol the node twice, the deferral is attached to the member
    /// it already has. The member goes on competing as a pan on `pan_slop`; its
    /// node's own recognizers are held off until `activation` allows them, by
    /// the same [`resolve_activation`](Self::resolve_activation) every other
    /// drag member is resolved through — so `Auto` on a direct pointer with an
    /// eligible pan means `AfterLongPress`, and `Immediate` means "today's
    /// behaviour, on request".
    ///
    /// Refused, and reported as `false`, unless the member exists, is live and
    /// holds a [`MemberRole::Pan`] — so a mouse, which enrols no pan member at
    /// all ([`GestureProfile::pan_slop`] is `None` for it and
    /// [`PanClaim::devices`] admits only direct pointers), can never reach it.
    /// A decided sequence refuses too: arbitration is over.
    pub fn defer_own_drag(
        &mut self,
        id: WidgetId,
        activation: DragActivation,
        profile: &GestureProfile,
    ) -> bool {
        if self.is_decided() {
            return false;
        }
        let resolved = self.resolve_activation(activation);
        let started_at = self.started_at;
        let Some(member) = self
            .members
            .iter_mut()
            .find(|m| m.id == id && m.is_live() && matches!(m.role, MemberRole::Pan(_)))
        else {
            return false;
        };
        member.has_own_drag = true;
        if resolved == DragActivation::AfterLongPress {
            member.own_drag_eligible_at = Some(started_at + profile.long_press);
        }
        true
    }

    /// Take a member's deferred self-drag out of the running for good.
    ///
    /// Three callers, one rule each:
    ///
    /// * the **pan half won**, so the press *is* a pan and the node's
    ///   recognizers must stay silent for the rest of it;
    /// * the press **travelled past `long_press_slop` before the deadline**, so
    ///   it was never a hold. That is the rule
    ///   [`LongPressRecognizer`](super::LongPressRecognizer) applies to itself —
    ///   it fails on the first move past that slop rather than waiting for its
    ///   timer — and applying it here is what stops a deliberate, slow pan from
    ///   arming a grab merely by outlasting the clock;
    /// * the press **left the tap boundary**, the same reading
    ///   [`enrol_drag`](Self::enrol_drag)'s `rejects_on_tap_slop` gives that
    ///   travel.
    ///
    /// The last two are both positional and both apply only while the self-drag
    /// is still unripe — see `Self::unripe_own_drag_members`. They are not
    /// redundant: `long_press_slop` is a radius around the press and bites on a
    /// surface the finger never leaves, while [`TapBoundary`] is the node's own
    /// rect for a coarse pointer and bites on a small node the finger slides off
    /// without travelling far.
    pub fn withdraw_own_drag(&mut self, id: WidgetId) {
        if let Some(member) = self.members.iter_mut().find(|m| m.id == id) {
            member.own_drag_withdrawn = true;
        }
    }

    /// Whether `id`'s **own** drag/swipe recognizers must be kept out of this
    /// press at `now`. `false` for a node that is not a member, and for every
    /// member carrying no self-drag.
    pub fn own_drag_blocked(&self, id: WidgetId, now: EventTime) -> bool {
        self.members
            .iter()
            .find(|m| m.id == id)
            .is_some_and(|m| !m.own_drag_armed_at(now))
    }

    /// The self-drag half of a dual-role member ripened and took the press:
    /// flip the member's role to [`MemberRole::Gesture`] so
    /// [`member_report`](Self::member_report) names the half that actually won
    /// rather than the pan claim the node was also holding.
    ///
    /// A no-op — and reported as `false` — for a member with no self-drag, or
    /// one whose self-drag has been withdrawn.
    pub(crate) fn promote_own_drag(&mut self, id: WidgetId) -> bool {
        let Some(member) = self
            .members
            .iter_mut()
            .find(|m| m.id == id && m.has_own_drag && !m.own_drag_withdrawn)
        else {
            return false;
        };
        member.role = MemberRole::Gesture;
        true
    }

    /// Every live member whose self-drag is **still waiting out its hold** at
    /// `now` — deferred, not withdrawn, and not yet ripe — innermost first.
    ///
    /// The self-drag counterpart of `rejects_on_tap_slop`, and scoped three
    /// ways:
    ///
    /// * only a **deferred** self-drag is swept. An `Immediate` one is armed
    ///   from the press and is governed by its recognizer, exactly as an
    ///   `Immediate` drag member is.
    /// * only an **unripe** one. Once the hold has been served the grab is live,
    ///   and a live grab travelling is the grab doing its job — withdrawing it
    ///   then would make hold-then-drag impossible on any node small enough for
    ///   a drag to leave its bounds.
    /// * only a **live** member, because a rejected one competes for nothing.
    ///
    /// The sweep this feeds is what makes the deferral a *hold* rather than a
    /// timer: see `WidgetTree::tick_sequence_timers`.
    pub(crate) fn unripe_own_drag_members(&self, now: EventTime) -> Vec<WidgetId> {
        self.members
            .iter()
            .filter(|m| {
                m.is_live()
                    && m.has_own_drag
                    && !m.own_drag_withdrawn
                    && m.own_drag_eligible_at.is_some_and(|at| now < at)
            })
            .map(|m| m.id)
            .collect()
    }

    /// Record a per-press [`DragActivation`] for `id`, overriding the node's
    /// build-time declaration for this press alone.
    ///
    /// Last writer wins: a handler that answers twice on one press means the
    /// second answer.
    pub fn set_drag_activation_override(&mut self, id: WidgetId, activation: DragActivation) {
        if let Some(slot) = self
            .drag_activation_overrides
            .iter_mut()
            .find(|(other, _)| *other == id)
        {
            slot.1 = activation;
        } else {
            self.drag_activation_overrides.push((id, activation));
        }
    }

    /// The per-press [`DragActivation`] a handler chose for `id`, if one did.
    pub fn drag_activation_override(&self, id: WidgetId) -> Option<DragActivation> {
        self.drag_activation_overrides
            .iter()
            .find(|(other, _)| *other == id)
            .map(|(_, activation)| *activation)
    }

    /// What [`DragActivation::Auto`] means for this sequence.
    ///
    /// `Immediate` for a precise pointer or a subtree that has declared
    /// [`TouchAction::NONE`] (nothing else can want the press); `AfterLongPress`
    /// for a coarse pointer with an eligible pan competitor, because the axis
    /// is already spoken for.
    pub fn resolve_activation(&self, activation: DragActivation) -> DragActivation {
        match activation {
            DragActivation::Auto => {
                if !self.pointer.kind.is_direct() || self.touch_action.is_none() {
                    DragActivation::Immediate
                } else if self.has_eligible_pan() {
                    DragActivation::AfterLongPress
                } else {
                    DragActivation::Immediate
                }
            }
            other => other,
        }
    }

    /// Whether **`id`'s own** grab on this press is waiting out the long-press
    /// deadline — i.e. the hold is what arms *that node's* grab.
    ///
    /// Two deferrals answer to this, and both are set only when
    /// [`resolve_activation`](Self::resolve_activation) answered
    /// [`DragActivation::AfterLongPress`]:
    ///
    /// * a member deferred whole, by [`enrol_drag`](Self::enrol_drag) —
    ///   `eligible_at`;
    /// * the **self-drag** half of a dual-role member, by
    ///   [`defer_own_drag`](Self::defer_own_drag) — `own_drag_eligible_at`. It
    ///   has to count: the node's grab is armed by the same hold, so without
    ///   this a `SceneView` with selection on would spend one hold on both its
    ///   marquee and its own long press.
    ///
    /// # Why it is keyed on a node and not on the sequence
    ///
    /// "One hold cannot mean two things" is a statement about **one node**, not
    /// about a press. A press reaches an ancestor chain, and a deferred grab
    /// somewhere on it says nothing about what a hold means further in: a
    /// `SceneView` that marquees after a hold is not thereby declaring that
    /// every heavyweight widget inside it has given up its touch long press and
    /// its touch context menu. A finger has no secondary button — the hold *is*
    /// the context-menu route — so answering this sequence-wide silently
    /// removed the only touch route to a context menu from every descendant of
    /// any dual-role container, which is an accessibility loss and not a rule.
    ///
    /// The ancestor-wide door exists and is **explicit**:
    /// `LongPressRole::DragHandle`, which `WidgetTree::long_press_is_a_grab`
    /// walks from the queried node to the root. A container that really does
    /// own every hold in its subtree says so there.
    ///
    /// A mouse reaches only the first, and only by an **explicit** declaration:
    /// `Auto` resolves to `AfterLongPress` for a direct pointer with an eligible
    /// pan competitor and a mouse enrols none, but an explicitly declared
    /// `AfterLongPress` is passed through untouched for every pointer kind — see
    /// `an_explicitly_deferred_grab_takes_the_hold_from_every_pointer_kind`. The
    /// `defer_own_drag` half stays out of a mouse's reach either way: it needs a
    /// live [`MemberRole::Pan`] member.
    ///
    /// Read by the framework through `WidgetTree::long_press_is_a_grab`.
    pub fn has_deferred_grab_for(&self, id: WidgetId) -> bool {
        self.members.iter().any(|m| {
            m.id == id
                && m.is_live()
                && (m.eligible_at.is_some()
                    || (m.has_own_drag
                        && !m.own_drag_withdrawn
                        && m.own_drag_eligible_at.is_some()))
        })
    }

    /// Whether any live member is a pan claimant. A mouse never has one:
    /// [`GestureProfile::pan_slop`] is `None` for it and [`PanClaim::devices`]
    /// admits only direct pointers.
    pub fn has_eligible_pan(&self) -> bool {
        self.members
            .iter()
            .any(|m| m.is_live() && matches!(m.role, MemberRole::Pan(_)))
    }

    /// Whether `claim` is eligible for this sequence's pointer at all: the
    /// claim must admit the device, the pointer's profile must have a pan slop,
    /// and the frozen [`TouchAction`] must permit at least one claimed axis.
    pub fn pan_is_eligible(&self, claim: &PanClaim, profile: &GestureProfile) -> bool {
        if profile.pan_slop.is_none() {
            return false;
        }
        if !claim.devices.contains(self.pointer.kind) {
            return false;
        }
        [Axis::X, Axis::Y]
            .into_iter()
            .any(|axis| claim.axes.contains(axis) && self.touch_action.allows_pan(axis))
    }

    /// The axis a pan member of this sequence would win on, if its travel has
    /// passed `pan_slop` on one the claim and the frozen action both permit.
    ///
    /// A diagonal tie resolves by **dominant axis** — the one that has moved
    /// further — so a pan that is mostly vertical scrolls vertically even when
    /// both axes are claimed.
    pub fn pan_axis_past_slop(&self, claim: &PanClaim, profile: &GestureProfile) -> Option<Axis> {
        let slop = profile.pan_slop?;
        let mut candidates: Vec<(Axis, f32)> = [Axis::X, Axis::Y]
            .into_iter()
            .filter(|axis| claim.axes.contains(*axis) && self.touch_action.allows_pan(*axis))
            .map(|axis| (axis, self.travel_on(axis)))
            .filter(|(_, travel)| *travel >= slop)
            .collect();
        // Dominant axis first; ties keep X, which is the declaration order.
        candidates.sort_by(|a, b| b.1.total_cmp(&a.1));
        candidates.first().map(|(axis, _)| *axis)
    }

    /// Declare `id` the winner and reject every other live member.
    ///
    /// Returns the members that were knocked out, so the caller can cancel each
    /// exactly once.
    pub fn decide(&mut self, id: WidgetId) -> Vec<WidgetId> {
        self.winner = Some(id);
        let mut losers = Vec::new();
        for member in &mut self.members {
            if member.id == id {
                member.state = MemberState::Won;
            } else if member.is_live() {
                member.state = MemberState::Rejected;
                losers.push(member.id);
            }
        }
        losers
    }

    /// Withdraw `id` from the running.
    pub fn reject(&mut self, id: WidgetId) {
        if let Some(member) = self.members.iter_mut().find(|m| m.id == id)
            && member.is_live()
        {
            member.state = MemberState::Rejected;
        }
    }

    /// Defer `id`'s decision until it releases or `profile.max_hold` elapses.
    pub fn hold(&mut self, id: WidgetId, now: EventTime) {
        if let Some(member) = self.members.iter_mut().find(|m| m.id == id)
            && member.state == MemberState::Possible
        {
            member.state = MemberState::Held;
            member.held_since = Some(now);
        }
    }

    /// End `id`'s hold, putting it back in the running.
    pub fn release_hold(&mut self, id: WidgetId) {
        if let Some(member) = self.members.iter_mut().find(|m| m.id == id)
            && member.state == MemberState::Held
        {
            member.state = MemberState::Possible;
            member.held_since = None;
        }
    }

    /// Release every hold older than `profile.max_hold`.
    ///
    /// A hold exists so an **application** recognizer can await an
    /// asynchronous decision; leaving one standing would strand the press, so
    /// the framework times it out rather than trusting the holder.
    pub fn expire_holds(&mut self, now: EventTime, profile: &GestureProfile) {
        for member in &mut self.members {
            if member.state == MemberState::Held
                && let Some(since) = member.held_since
                && now.saturating_since(since) >= profile.max_hold
            {
                member.state = MemberState::Possible;
                member.held_since = None;
            }
        }
    }

    /// Whether any member is holding.
    pub fn is_held(&self) -> bool {
        self.members.iter().any(|m| m.state == MemberState::Held)
    }

    /// When [`expire_holds`](Self::expire_holds) next has work: the earliest
    /// instant at which a standing hold reaches `profile.max_hold`.
    ///
    /// **A deferred member's `eligible_at` is deliberately not a term here.**
    /// It looks like a sibling deadline and is not one. Nothing happens at that
    /// instant: eligibility is never *stored*, it is re-derived by
    /// [`SequenceMember::is_eligible_at`] against whatever instant its caller
    /// names, and no reader *transitions* anything on reaching it. Two call
    /// sites read it — the arbitration walk, and the arena gate the ordinary
    /// bubble and the timer tick share, the one naming the sample being
    /// dispatched and the other the tick's own instant — and each of them only
    /// answers a question its caller already had. A press that has sat
    /// still past its `long_press` is already eligible the moment it moves,
    /// with no intervening tick, so waking the event loop at `eligible_at`
    /// would buy an idle frame with nothing to do in it. The expiry of a hold
    /// is the opposite: it is a stored state transition, and if nobody performs
    /// it the hold stands past the duration the framework promises to trust it
    /// for.
    pub fn next_hold_deadline(&self, profile: &GestureProfile) -> Option<EventTime> {
        self.members
            .iter()
            .filter(|m| m.state == MemberState::Held)
            .filter_map(|m| m.held_since.map(|since| since + profile.max_hold))
            .min()
    }

    /// Drop every member whose node is no longer active, reporting them so the
    /// caller can cancel each individually.
    ///
    /// Run every sample: a rebuild mints fresh ids, and a member left pointing
    /// at a destroyed node would either be fed events forever or silently win.
    /// The *sequence* dies only when the winner or the captor dies — see
    /// [`lost_owner`](Self::lost_owner).
    pub fn revalidate(&mut self, arena: &crate::arena::WidgetArena) -> Vec<WidgetId> {
        let mut dead = Vec::new();
        self.members.retain(|member| {
            if arena.is_active(member.id) {
                true
            } else {
                dead.push(member.id);
                false
            }
        });
        dead
    }

    /// Whether the node that owns this sequence — its winner, or failing that
    /// its captor — has gone away. The sequence itself must then be cancelled.
    pub fn lost_owner(&self, arena: &crate::arena::WidgetArena) -> bool {
        let owner = self.winner.or(self.capture);
        owner.is_some_and(|id| !arena.is_active(id))
    }

    /// The role and state of every member, for
    /// [`WidgetTree::sequence_members`](crate::WidgetTree::sequence_members).
    pub fn member_report(&self) -> Vec<(WidgetId, MemberRole, MemberState)> {
        self.members
            .iter()
            .map(|m| (m.id, m.role, m.state))
            .collect()
    }

    /// Every live member of one role, innermost first.
    pub(crate) fn live_ids_with<F: Fn(&MemberRole) -> bool>(&self, filter: F) -> Vec<WidgetId> {
        self.members
            .iter()
            .filter(|m| m.is_live() && filter(&m.role))
            .map(|m| m.id)
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pointer::{BackendDeviceKey, PointerIdAllocator};
    use crate::widget_id::WidgetId;
    use slotmap::KeyData;
    use teksilo_tokens::{PointerKind, TargetDensity};

    fn tokens() -> teksilo_tokens::InputTokens {
        teksilo_tokens::InputTokens::for_density(TargetDensity::Compact)
    }

    fn mouse() -> PointerInfo {
        PointerInfo::mouse(EventTime::ZERO)
    }

    fn finger() -> PointerInfo {
        let id = PointerIdAllocator::global().begin(BackendDeviceKey::DEFAULT, 7);
        PointerInfo::touch(id, EventTime::ZERO)
    }

    fn seq(pointer: PointerInfo, action: TouchAction, path: Vec<WidgetId>) -> PointerSequence {
        PointerSequence::new(pointer, path, action, None, Point::ZERO, EventTime::ZERO)
    }

    /// Synthetic ids for the pure-logic tests: the sequence only ever compares
    /// and orders them, so no arena is needed to make them meaningful.
    fn ids(n: u64) -> Vec<WidgetId> {
        (0..n)
            .map(|i| KeyData::from_ffi((1u64 << 32) | (i + 1)).into())
            .collect()
    }

    #[test]
    fn a_mouse_latches_at_five_in_every_configuration() {
        // The single most important invariant in the package: no frozen
        // TouchAction, and no density, may retune the mouse drag latch.
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Mouse);
        for action in [
            TouchAction::AUTO,
            TouchAction::NONE,
            TouchAction::PAN,
            TouchAction::PAN_X,
            TouchAction::PAN_Y,
            TouchAction::PINCH_ZOOM,
            TouchAction::MANIPULATION,
        ] {
            let s = seq(mouse(), action, ids(1));
            assert_eq!(
                s.latch_slop(profile),
                5.0,
                "a mouse under {action:?} must latch at 5.0"
            );
        }
    }

    #[test]
    fn slop_precise_reaches_only_a_direct_pointer_under_a_frozen_none() {
        let tokens = tokens();
        let touch_profile = tokens.profile(PointerKind::Touch);
        let none = seq(finger(), TouchAction::NONE, ids(1));
        assert_eq!(none.latch_slop(touch_profile), touch_profile.slop_precise);
        let auto = seq(finger(), TouchAction::AUTO, ids(1));
        assert_eq!(auto.latch_slop(touch_profile), touch_profile.drag_slop);
    }

    #[test]
    fn a_mouse_never_has_an_eligible_pan_member() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Mouse);
        let s = seq(mouse(), TouchAction::AUTO, ids(1));
        assert!(!s.pan_is_eligible(&PanClaim::both(), profile));
    }

    #[test]
    fn members_stay_innermost_first_whatever_order_they_enrol_in() {
        let path = ids(4);
        let mut s = seq(mouse(), TouchAction::AUTO, path.clone());
        assert!(s.enrol(path[3], MemberRole::Gesture));
        assert!(s.enrol(path[1], MemberRole::RawDrag));
        assert!(s.enrol(path[2], MemberRole::Gesture));
        let order: Vec<_> = s.members().iter().map(|m| m.id).collect();
        assert_eq!(order, vec![path[1], path[2], path[3]]);
    }

    #[test]
    fn the_dead_zone_boundary_refuses_everything_at_or_above_it() {
        let path = ids(4);
        let mut s = PointerSequence::new(
            mouse(),
            path.clone(),
            TouchAction::AUTO,
            Some(path[2]),
            Point::ZERO,
            EventTime::ZERO,
        );
        assert!(s.enrol(path[1], MemberRole::Gesture), "below the boundary");
        assert!(
            !s.enrol(path[2], MemberRole::Gesture),
            "the boundary itself"
        );
        assert!(!s.enrol(path[3], MemberRole::Gesture), "above the boundary");
    }

    #[test]
    fn deciding_rejects_every_other_live_member_exactly_once() {
        let path = ids(3);
        let mut s = seq(mouse(), TouchAction::AUTO, path.clone());
        s.enrol(path[0], MemberRole::Gesture);
        s.enrol(path[1], MemberRole::Gesture);
        s.enrol(path[2], MemberRole::Gesture);
        let losers = s.decide(path[1]);
        assert_eq!(losers, vec![path[0], path[2]]);
        assert_eq!(s.winner(), Some(path[1]));
        // A second decide reports nothing new: the losers are no longer live.
        assert!(s.decide(path[1]).is_empty());
    }

    #[test]
    fn after_long_press_defers_eligibility_and_arms_self_rejection() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let path = ids(2);
        let mut s = seq(finger(), TouchAction::PAN_Y, path.clone());
        s.enrol_drag(
            path[0],
            MemberRole::Gesture,
            DragActivation::AfterLongPress,
            profile,
        );
        let member = s.members()[0];
        assert_eq!(
            member.eligible_at,
            Some(EventTime::ZERO + profile.long_press)
        );
        assert!(member.rejects_on_tap_slop);
        assert!(!member.is_eligible_at(EventTime::ZERO));
        assert!(member.is_eligible_at(EventTime::ZERO + profile.long_press));
    }

    #[test]
    fn auto_activation_defers_only_a_coarse_pointer_facing_a_pan() {
        let path = ids(2);

        // A mouse is always immediate.
        let mut m = seq(mouse(), TouchAction::AUTO, path.clone());
        m.enrol(path[1], MemberRole::Pan(PanClaim::vertical()));
        assert_eq!(
            m.resolve_activation(DragActivation::Auto),
            DragActivation::Immediate
        );

        // A finger with no pan competitor is immediate too.
        let bare = seq(finger(), TouchAction::AUTO, path.clone());
        assert_eq!(
            bare.resolve_activation(DragActivation::Auto),
            DragActivation::Immediate
        );

        // A finger facing a pan claimant defers.
        let mut contested = seq(finger(), TouchAction::AUTO, path.clone());
        contested.enrol(path[1], MemberRole::Pan(PanClaim::vertical()));
        assert_eq!(
            contested.resolve_activation(DragActivation::Auto),
            DragActivation::AfterLongPress
        );
    }

    #[test]
    fn a_pan_wins_on_the_dominant_axis_and_only_where_permitted() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let slop = profile.pan_slop.expect("touch pans");
        let path = ids(1);

        let mut s = seq(finger(), TouchAction::PAN, path);
        s.set_last_position(Point::new(slop + 10.0, slop + 1.0));
        assert_eq!(
            s.pan_axis_past_slop(&PanClaim::both(), profile),
            Some(Axis::X),
            "the axis that travelled further wins the diagonal"
        );

        // The frozen action forbids X, so the same travel resolves to Y.
        let mut only_y = seq(finger(), TouchAction::PAN_Y, ids(1));
        only_y.set_last_position(Point::new(slop + 10.0, slop + 1.0));
        assert_eq!(
            only_y.pan_axis_past_slop(&PanClaim::both(), profile),
            Some(Axis::Y)
        );
    }

    #[test]
    fn a_hold_expires_at_max_hold_and_not_before() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Mouse);
        let path = ids(1);
        let mut s = seq(mouse(), TouchAction::AUTO, path.clone());
        s.enrol(path[0], MemberRole::Gesture);
        s.hold(path[0], EventTime::ZERO);
        assert!(s.is_held());

        s.expire_holds(EventTime::from_duration(profile.max_hold / 2), profile);
        assert!(s.is_held(), "a hold survives until max_hold");

        s.expire_holds(EventTime::from_duration(profile.max_hold), profile);
        assert!(!s.is_held(), "and is released at it");
        assert_eq!(s.members()[0].state, MemberState::Possible);
    }

    #[test]
    fn revalidate_drops_dead_members_one_at_a_time() {
        // The tree-level half — losing the captor cancels the whole sequence —
        // is pinned in `gesture_dispatch_impl`; in a real tree a member is
        // always an ancestor of the captor and so cannot die on its own, which
        // is why the per-member rule is asserted here.
        let mut arena = crate::arena::WidgetArena::new();
        let live = arena.insert(Box::new(crate::test_widgets::FillWidget::new()));
        let doomed = arena.insert(Box::new(crate::test_widgets::FillWidget::new()));
        let mut s = seq(mouse(), TouchAction::AUTO, vec![doomed, live]);
        s.enrol(doomed, MemberRole::Gesture);
        s.enrol(live, MemberRole::Gesture);
        s.set_capture(Some(live));

        assert!(s.revalidate(&arena).is_empty(), "nothing has died yet");
        arena.destroy(doomed);

        assert_eq!(s.revalidate(&arena), vec![doomed]);
        assert_eq!(
            s.members().iter().map(|m| m.id).collect::<Vec<_>>(),
            vec![live],
            "only the dead member is dropped"
        );
        assert!(!s.lost_owner(&arena), "the captor is still alive");

        arena.destroy(live);
        assert!(
            s.lost_owner(&arena),
            "losing the captor is what cancels the sequence"
        );
    }

    #[test]
    fn the_tap_boundary_is_a_radius_for_a_mouse_and_bounds_for_a_finger() {
        let tokens = tokens();
        let mouse_profile = tokens.profile(PointerKind::Mouse);
        let touch_profile = tokens.profile(PointerKind::Touch);
        assert_eq!(
            TapBoundary::for_pointer(&mouse(), mouse_profile),
            TapBoundary::Radius(mouse_profile.tap_slop)
        );
        assert_eq!(
            TapBoundary::for_pointer(&finger(), touch_profile),
            TapBoundary::Bounds
        );

        // A coarse press well past tap_slop but still inside the control has
        // NOT left the boundary — that is the whole point of `Bounds`.
        let bounds = teksilo_canvas::Rect::new(0.0, 0.0, 100.0, 100.0);
        assert!(!TapBoundary::Bounds.left(
            Point::new(50.0, 50.0),
            Point::new(50.0, 80.0),
            Some(bounds),
            touch_profile,
        ));
        assert!(TapBoundary::Bounds.left(
            Point::new(50.0, 50.0),
            Point::new(50.0, 120.0),
            Some(bounds),
            touch_profile,
        ));
        // With no bounds to test, it falls back to the radius rather than
        // letting the press travel anywhere.
        assert!(TapBoundary::Bounds.left(
            Point::new(50.0, 50.0),
            Point::new(50.0, 80.0),
            None,
            touch_profile,
        ));
    }

    /// A press accepted through a `Widget::hit_outset` begins outside the node
    /// it was accepted for, so the node's rectangle cannot be its boundary:
    /// with `Bounds` taken literally the press is "already gone" on arrival and
    /// the tap can never complete. It falls back to the pointer's own radius
    /// around where it landed, and sliding onto the control keeps it alive.
    #[test]
    fn a_press_that_began_outside_the_node_is_bounded_by_its_own_radius() {
        let tokens = tokens();
        let touch_profile = tokens.profile(PointerKind::Touch);
        let rect = teksilo_canvas::Rect::new(0.0, 0.0, 12.0, 12.0);
        // Landed 4 dp past the trailing edge — inside the outset ring the
        // arena offered it, outside the rectangle.
        let origin = Point::new(16.0, 6.0);
        assert!(
            !TapBoundary::Bounds.left(origin, origin, Some(rect), touch_profile),
            "a press cannot have left the boundary on the sample that opened it",
        );
        assert!(
            !TapBoundary::Bounds.left(origin, Point::new(6.0, 6.0), Some(rect), touch_profile),
            "sliding onto the control keeps the press",
        );
        assert!(
            TapBoundary::Bounds.left(
                origin,
                Point::new(16.0 + touch_profile.tap_slop + 1.0, 6.0),
                Some(rect),
                touch_profile,
            ),
            "and past the radius it is gone, so the abort gesture still works",
        );
    }

    /// The union term, on its own.
    ///
    /// The radius half of the outside-origin rule is a *travel* allowance, and
    /// on a small control it runs out before the finger has finished arriving:
    /// a contact that lands in the outset ring of a wide control and then
    /// slides well past `tap_slop` **onto** the control is further from its
    /// origin than the radius permits and squarely inside the rectangle. Only
    /// the union with the node's bounds keeps that press alive; with the
    /// `!rect.contains(position)` term gone, the radius alone kills a press
    /// that is sitting on the middle of the thing it is pressing.
    #[test]
    fn sliding_onto_the_control_keeps_a_press_the_radius_alone_would_lose() {
        let tokens = tokens();
        let touch_profile = tokens.profile(PointerKind::Touch);
        let rect = teksilo_canvas::Rect::new(0.0, 0.0, 100.0, 20.0);
        // 4 dp past the trailing edge — inside the outset ring, outside the rect.
        let origin = Point::new(104.0, 10.0);
        // 24 dp of travel, against a Touch `tap_slop` of 18: past the radius,
        // and 20 dp inside the control.
        let onto = Point::new(80.0, 10.0);
        assert!(
            super::super::distance(origin, onto) > touch_profile.tap_slop,
            "the probe is only discriminating while the travel exceeds tap_slop",
        );
        assert!(rect.contains(onto), "…and lands inside the control");
        assert!(
            !TapBoundary::Bounds.left(origin, onto, Some(rect), touch_profile),
            "a finger resting on the control it pressed has not left it",
        );
    }

    /// Which rule applies is decided by the **origin**, not by where the
    /// pointer is now.
    ///
    /// The two questions agree on most samples, which is why the distinction
    /// has to be pinned on the one geometry where they cannot: a press that
    /// began *inside* the node and has moved a short way outside it. The rule
    /// for that press is the rectangle — it left the moment it crossed the
    /// edge, however little it travelled — while a press that began outside is
    /// allowed the pointer's radius around where it landed, so with the same
    /// `position` it has not left at all. Reading `position` instead of
    /// `origin` collapses both onto the second answer and silently hands every
    /// coarse press that starts inside a control a `tap_slop` grace band
    /// outside it, which is exactly the slop `Bounds` exists to replace.
    #[test]
    fn the_boundary_rule_is_chosen_by_where_the_press_began() {
        let tokens = tokens();
        let touch_profile = tokens.profile(PointerKind::Touch);
        let rect = teksilo_canvas::Rect::new(0.0, 0.0, 100.0, 20.0);
        // One sample, 4 dp past the trailing edge, reached from two origins —
        // both within `tap_slop` of it, so the radius rule cannot fail either.
        let position = Point::new(104.0, 10.0);
        let from_inside = Point::new(96.0, 10.0);
        let from_outside = Point::new(108.0, 10.0);
        assert!(rect.contains(from_inside), "the first press began inside");
        assert!(
            !rect.contains(from_outside) && !rect.contains(position),
            "the second began outside, and neither sample is in the rect",
        );
        for origin in [from_inside, from_outside] {
            assert!(
                super::super::distance(origin, position) < touch_profile.tap_slop,
                "the probe only discriminates while the travel is inside tap_slop",
            );
        }

        assert!(
            TapBoundary::Bounds.left(from_inside, position, Some(rect), touch_profile),
            "a press that began inside the node is bounded by the node: crossing \
             the edge ends it, with no radius grace outside",
        );
        assert!(
            !TapBoundary::Bounds.left(from_outside, position, Some(rect), touch_profile),
            "a press that began outside is bounded by its own radius, and this \
             one has barely moved",
        );
    }

    // -----------------------------------------------------------------
    // The self-drag half of a dual-role member
    // -----------------------------------------------------------------

    /// `defer_own_drag` refuses anything that is not a live `Pan` member — the
    /// structural reason a mouse can never reach it, since a mouse enrols no
    /// pan member at all.
    #[test]
    fn defer_own_drag_refuses_anything_but_a_live_pan_member() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let ids = ids(3);

        // A `Gesture` member: the node's drag already has the slot, so there is
        // no second half to defer.
        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Gesture));
        assert!(
            !s.defer_own_drag(ids[0], DragActivation::Auto, profile),
            "a Gesture member is not dual-role"
        );

        // A node that is not a member at all.
        assert!(
            !s.defer_own_drag(ids[1], DragActivation::Auto, profile),
            "a non-member has nothing to attach a deferral to"
        );

        // A rejected pan member.
        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        s.reject(ids[0]);
        assert!(
            !s.defer_own_drag(ids[0], DragActivation::Auto, profile),
            "a member that is out of the running gets no second half"
        );

        // A decided sequence.
        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        s.decide(ids[0]);
        assert!(
            !s.defer_own_drag(ids[0], DragActivation::Auto, profile),
            "arbitration is over"
        );

        // …and the one shape that is accepted.
        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(s.defer_own_drag(ids[0], DragActivation::Auto, profile));
    }

    /// A mouse sequence never has a pan member, so the shape `defer_own_drag`
    /// exists for cannot arise. Stated on the object rather than through a
    /// tree, so it is a property of the type and not of one fixture.
    #[test]
    fn a_mouse_can_never_defer_its_own_drag() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Mouse);
        let ids = ids(1);
        let mut s = seq(mouse(), TouchAction::AUTO, ids.clone());

        // `pan_is_eligible` is what `begin_sequence` gates the enrolment on, and
        // for a mouse it is false whatever the claim asks for — so no `Pan`
        // member is ever created and the arm has nothing to attach to.
        assert!(
            !s.pan_is_eligible(&PanClaim::both(), profile),
            "the mouse profile has no pan_slop, so no claim is eligible"
        );
        assert!(!s.defer_own_drag(ids[0], DragActivation::Auto, profile));
        assert!(!s.has_deferred_grab_for(ids[0]));
    }

    /// `Auto` on a direct pointer with an eligible pan defers the self-drag to
    /// the long-press deadline; `Immediate` arms it at the press.
    #[test]
    fn defer_own_drag_resolves_auto_the_way_every_other_drag_resolves_it() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let ids = ids(1);

        let mut deferred = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(deferred.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(deferred.defer_own_drag(ids[0], DragActivation::Auto, profile));
        assert!(
            deferred.own_drag_blocked(ids[0], EventTime::ZERO),
            "Auto + an eligible pan means a hold"
        );
        assert!(
            !deferred.own_drag_blocked(ids[0], EventTime::ZERO + profile.long_press),
            "…and the hold ends at long_press"
        );
        assert!(
            deferred.has_deferred_grab_for(ids[0]),
            "so the hold is spent on the grab and cannot also be a long press"
        );

        let mut immediate = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(immediate.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(immediate.defer_own_drag(ids[0], DragActivation::Immediate, profile));
        assert!(
            !immediate.own_drag_blocked(ids[0], EventTime::ZERO),
            "Immediate arms at the press"
        );
        assert!(
            !immediate.has_deferred_grab_for(ids[0]),
            "and spends no hold, so a long press on the same node still fires"
        );
    }

    /// A withdrawal is permanent for the press. That is what keeps a deferral
    /// ripening mid-pan from starting a grab under a scrolling finger.
    #[test]
    fn a_withdrawn_self_drag_stays_blocked_past_its_own_deadline() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let ids = ids(1);
        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(s.defer_own_drag(ids[0], DragActivation::Auto, profile));

        s.withdraw_own_drag(ids[0]);
        assert!(
            s.own_drag_blocked(ids[0], EventTime::ZERO + profile.long_press * 10),
            "a withdrawn self-drag does not come back when its timer ripens"
        );
        assert!(
            !s.has_deferred_grab_for(ids[0]),
            "and stops spending the hold, so the node's long press is free again"
        );
    }

    /// `promote_own_drag` is what makes the member report name the half that
    /// actually won, and it is a no-op on anything else.
    #[test]
    fn promote_own_drag_renames_the_half_that_won() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let ids = ids(1);

        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(s.defer_own_drag(ids[0], DragActivation::Immediate, profile));
        assert!(matches!(s.members()[0].role, MemberRole::Pan(_)));
        assert!(s.promote_own_drag(ids[0]));
        assert_eq!(s.members()[0].role, MemberRole::Gesture);

        // A plain claimant is untouched.
        let mut plain = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(plain.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(!plain.promote_own_drag(ids[0]));
        assert!(matches!(plain.members()[0].role, MemberRole::Pan(_)));

        // …and so is one whose self-drag has been withdrawn: the pan won, and
        // renaming the member would make the report say otherwise.
        let mut withdrawn = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(withdrawn.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(withdrawn.defer_own_drag(ids[0], DragActivation::Auto, profile));
        withdrawn.withdraw_own_drag(ids[0]);
        assert!(!withdrawn.promote_own_drag(ids[0]));
        assert!(matches!(withdrawn.members()[0].role, MemberRole::Pan(_)));
    }

    /// Only a **deferred** self-drag answers the positional sweep, mirroring
    /// `rejects_on_tap_slop`: an `Immediate` one is governed by its recognizer.
    #[test]
    fn only_a_deferred_self_drag_is_swept_positionally() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let ids = ids(1);

        let mut deferred = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(deferred.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(deferred.defer_own_drag(ids[0], DragActivation::Auto, profile));
        assert_eq!(
            deferred.unripe_own_drag_members(EventTime::ZERO),
            vec![ids[0]]
        );

        let mut immediate = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(immediate.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(immediate.defer_own_drag(ids[0], DragActivation::Immediate, profile));
        assert!(
            immediate
                .unripe_own_drag_members(EventTime::ZERO)
                .is_empty()
        );

        // A plain claimant never appears.
        let mut plain = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(plain.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(plain.unripe_own_drag_members(EventTime::ZERO).is_empty());
    }

    /// …and only while it is still **unripe**. Once the hold has been served the
    /// grab is live, and a live grab travelling is the grab doing its job: a
    /// sweep that still fired then would make hold-then-drag impossible on any
    /// node small enough for the drag to leave its bounds.
    #[test]
    fn a_ripe_self_drag_is_no_longer_swept() {
        let tokens = tokens();
        let profile = tokens.profile(PointerKind::Touch);
        let ids = ids(1);

        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Pan(PanClaim::both())));
        assert!(s.defer_own_drag(ids[0], DragActivation::Auto, profile));

        let deadline = EventTime::ZERO + profile.long_press;
        assert_eq!(
            s.unripe_own_drag_members(
                EventTime::ZERO + (profile.long_press - std::time::Duration::from_millis(1)),
            ),
            vec![ids[0]],
            "still inside the hold"
        );
        assert!(
            s.unripe_own_drag_members(deadline).is_empty(),
            "the hold has been served; the grab is live and answers to its own \
             recognizer from here"
        );
    }

    /// `own_drag_armed_at` is inert for every member carrying no self-drag,
    /// which is what makes the gate it feeds free for every other sequence.
    #[test]
    fn own_drag_armed_is_true_for_a_member_with_no_self_drag() {
        let ids = ids(1);
        let mut s = seq(mouse(), TouchAction::AUTO, ids.clone());
        assert!(s.enrol(ids[0], MemberRole::Gesture));
        for at in [
            EventTime::ZERO,
            EventTime::ZERO + std::time::Duration::from_secs(10),
        ] {
            assert!(s.members()[0].own_drag_armed_at(at));
            assert!(!s.own_drag_blocked(ids[0], at));
        }
    }

    /// The per-press activation override is recorded per node,
    /// last-writer-wins, and answers `None` for a node that never spoke.
    #[test]
    fn a_drag_activation_override_is_recorded_per_node() {
        let ids = ids(2);
        let mut s = seq(finger(), TouchAction::AUTO, ids.clone());
        assert_eq!(s.drag_activation_override(ids[0]), None);

        s.set_drag_activation_override(ids[0], DragActivation::Immediate);
        s.set_drag_activation_override(ids[1], DragActivation::AfterLongPress);
        assert_eq!(
            s.drag_activation_override(ids[0]),
            Some(DragActivation::Immediate)
        );
        assert_eq!(
            s.drag_activation_override(ids[1]),
            Some(DragActivation::AfterLongPress)
        );

        s.set_drag_activation_override(ids[0], DragActivation::Auto);
        assert_eq!(
            s.drag_activation_override(ids[0]),
            Some(DragActivation::Auto),
            "answering twice on one press means the second answer"
        );
    }
}