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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
//! The cancel funnel: one queued path by which a pointer interaction is taken
//! away, and the enumerated set of things allowed to take it.
//!
//! # Why a funnel
//!
//! Before this module the framework revoked interactions by *forgetting* them.
//! A window that lost focus dropped every capture in the table, and a parked
//! subtree simply stopped being hit-testable: the widget mid-drag was
//! never told, so it kept its own half of the interaction — a latched
//! selection, a grabbed divider, a highlighted drop target — with no event
//! coming that could ever clear it. `PointerUp` cannot stand in, because "the
//! user finished" and "the system took it away" call for opposite responses:
//! an `Up` on a drag *drops*, and dropping a file because the window lost
//! focus is a data-loss bug.
//!
//! So every revocation now goes through [`WidgetTree::cancel_pointer`], which
//! tears the interaction down in one order and delivers exactly one
//! [`WidgetEvent::PointerCancel`] carrying the [`CancelReason`] that names who
//! took it.
//!
//! # Two granularities, and they are not the same act
//!
//! * [`cancel_pointer`](WidgetTree::cancel_pointer) revokes the **whole
//! pointer**. The sequence dies, the capture is given back, the table entry
//! goes (for a contact), and nothing more will be delivered for that
//! pointer.
//! * [`revoke_sequence_member`](WidgetTree::revoke_sequence_member) revokes
//! **one competitor** of a sequence that is still alive. Its recognizers are
//! cancelled and it is told so, and the pointer carries on — its winner
//! keeps receiving moves and will still get its `Up`. This is what a peer
//! claim does: exactly one member wins, and every other member is told it
//! lost. Revoking a member is emphatically not cancelling the pointer, and
//! confusing the two would make an ancestor's losing drag kill the tap that
//! beat it.
//!
//! # Queued, always
//!
//! A cancel raised from inside a handler must not unwind the sample that
//! handler is standing on. It therefore rides the same
//! [`pending_dispatch`](WidgetTree::pending_dispatch) queue P07 built for
//! nested dispatch, as a [`QueuedDispatch::Cancel`](super::pointer_router::QueuedDispatch::Cancel) entry rather than a second
//! queue of its own: one queue means one order, and the cancel a handler
//! raised lands after the event that provoked it rather than in the middle of
//! it. At depth zero the queue is drained immediately, so a caller outside a
//! dispatch — `set_window_active`, an overlay teardown — sees the cancel take
//! effect before its own call returns.
//!
//! Reference: `docs/touch-and-pen.md` §3.3.
use super::*;
use crate::pointer::{CancelReason, PointerId};
impl WidgetTree {
// -----------------------------------------------------------------
// The funnel
// -----------------------------------------------------------------
/// Revoke `pointer`'s interaction, for `reason`.
///
/// **Always queued** behind the sample currently being dispatched, and a
/// **no-op if that interaction has already finished** by the time the
/// queue drains — a cancel raised from a handler must not fire against a
/// press the very same sample completed. "Finished" means the pointer is
/// no longer live, or holds no capture and has no sequence, or its
/// sequence is already inside its own terminal dispatch; all three say
/// there is nothing left to revoke.
///
/// The teardown runs in one order, and the order is load-bearing: every
/// competitor's recognizer state goes first (so nothing can recognize on
/// the way out), then the arbitration, then the capture, then the drag
/// session, then the table entry, and the event is delivered last — to a
/// tree that has already forgotten the interaction, so a handler that
/// reacts by capturing or dragging starts from a clean slate rather than
/// racing the teardown.
///
/// Between the drag session and the table entry sits the touch-motion
/// layer: the pan session is abandoned without a release, every coast its
/// claimant chain was running is stopped, the palm watch is dropped, the
/// framework press signal is cleared and the pinch is told.
pub fn cancel_pointer(
&mut self,
pointer: PointerId,
reason: CancelReason,
ops: &mut dyn crate::window::WindowOps,
) {
self.cancel_pointer_to(pointer, reason, None, ops);
}
/// [`cancel_pointer`](Self::cancel_pointer), addressed to a widget the
/// caller names rather than to whoever the table says holds the pointer.
///
/// For a producer whose own teardown has already given the capture back
/// before it raises the cancel — the OS-drag escalation hands the pointer
/// to the platform first — so the funnel would otherwise have nobody left
/// to tell. The named widget is used only while it is still there; a
/// recipient destroyed in the meantime falls back to the ordinary chain.
pub fn cancel_pointer_to(
&mut self,
pointer: PointerId,
reason: CancelReason,
recipient: Option<WidgetId>,
ops: &mut dyn crate::window::WindowOps,
) {
self.enqueue_cancel(pointer, reason, recipient);
if self.dispatch_depth == 0 {
self.drain_pending_dispatch(ops);
}
}
/// Revoke every live pointer, for `reason`. The window went away under
/// them, a modal opened over them, the platform took the seat.
pub fn cancel_all_pointers(
&mut self,
reason: CancelReason,
ops: &mut dyn crate::window::WindowOps,
) {
let live: Vec<PointerId> = self.pointers.iter().map(|e| e.info.id).collect();
for id in live {
self.enqueue_cancel(id, reason, None);
}
if self.dispatch_depth == 0 {
self.drain_pending_dispatch(ops);
}
}
/// Revoke every pointer whose interaction is **anchored inside** `root`.
///
/// "Anchored inside" means the pointer's captor is `root` or a descendant
/// of it: that widget is the one about to stop existing, and the pointer
/// it holds would otherwise be stranded on it. A pointer merely passing
/// over the subtree is not anchored in it and is left alone.
///
/// A pointer whose press is no longer revocable is skipped, which is what
/// makes the named exemption work: tapping a menu item whose own handler
/// closes its menu must complete the tap, not have it cancelled out from
/// under itself by the teardown it asked for.
pub fn cancel_pointers_in_subtree(
&mut self,
root: WidgetId,
reason: CancelReason,
ops: &mut dyn crate::window::WindowOps,
) {
let anchored: Vec<PointerId> = self
.pointers
.iter()
.filter(|entry| {
entry
.captured_by
.is_some_and(|captor| captor == root || self.is_descendant_of(captor, root))
})
.map(|entry| entry.info.id)
.collect();
let mut queued = false;
for id in anchored {
if !self.press_is_revocable(id) {
crate::trace_input!(
Gestures,
"{id:?} is inside the parked subtree but its press has already ended: not cancelled"
);
continue;
}
self.enqueue_cancel(id, reason, None);
queued = true;
}
if queued && self.dispatch_depth == 0 {
self.drain_pending_dispatch(ops);
}
}
/// Park `root`'s subtree and cancel every pointer it was holding.
///
/// The tree-level door onto [`WidgetArena::set_dormant`](crate::arena::WidgetArena::set_dormant):
/// parking is invisible to hit-testing and to dispatch, so a widget parked
/// mid-interaction would keep whatever the press latched and never receive
/// another event. Every caller that parks a subtree which could plausibly
/// contain a live pointer goes through here; the audit of the ones that do
/// not is in `docs/touch-and-pen.md` §3.3.
pub(crate) fn park_subtree(&mut self, root: WidgetId) {
let mut noop = crate::window::NoopWindowOps;
self.park_subtree_with_ops(root, &mut noop);
}
/// [`park_subtree`](Self::park_subtree) with the caller's
/// [`WindowOps`](crate::window::WindowOps).
///
/// The cancel is raised **before** the subtree is parked, so the widget is
/// still active when it is told to let go — a `PointerCancel` delivered to
/// a node the dispatcher has just made dormant would be dropped, which is
/// precisely the silent teardown this replaces.
pub(crate) fn park_subtree_with_ops(
&mut self,
root: WidgetId,
ops: &mut dyn crate::window::WindowOps,
) {
self.cancel_pointers_in_subtree(root, CancelReason::SubtreeParked, ops);
let _parked = self.arena.set_dormant(root);
}
/// Revoke one **member** of a live sequence, leaving the sequence, the
/// capture and the pointer itself alone.
///
/// The member's recognizers are cancelled for this contact and the member
/// widget is told with a [`WidgetEvent::PointerCancel`]. Unlike
/// [`cancel_pointer`](Self::cancel_pointer) this is delivered **now**
/// rather than queued: it is raised from the arbitration itself, which
/// already runs at a point where the sequence is consistent, and a member
/// that lost must stop recognizing before the same sample reaches it
/// through the ordinary bubble.
///
/// A member whose node has already been destroyed gets the recognizer
/// teardown and no event — there is nothing left to deliver to. A merely
/// *dormant* one still exists and is told directly, without a bubble,
/// exactly as a dormant node is told about a lost focus.
pub(super) fn revoke_sequence_member(
&mut self,
pointer: PointerId,
member: WidgetId,
reason: CancelReason,
ops: &mut dyn crate::window::WindowOps,
) {
crate::trace_input!(
Gestures,
"member {member:?} of {pointer:?} revoked: {reason:?}"
);
self.cancel_member_arena(member, pointer);
if self.arena.get(member).is_none() {
return;
}
// The entry is still there on this path — a losing member's revoke does
// not end the pointer, only its own recognizers — so the event names the
// real device. A pointer that has gone anyway has no press left to
// announce, and the recognizer teardown above is the whole of what it
// needed.
let Some((info, at)) = self.pointers.get(pointer).map(|e| (e.info, e.position)) else {
return;
};
let event = Self::pointer_cancel_event(info, at, reason);
self.dispatch_to_widget_direct(member, &event, ops);
}
// -----------------------------------------------------------------
// Queue plumbing
// -----------------------------------------------------------------
/// Put a cancel on the shared dispatch queue, unless one for the same
/// pointer is already waiting there.
///
/// The de-duplication is what keeps "exactly one cancel" true when two
/// producers fire on the same sample — an overlay dismissal that also
/// parks the subtree it lived in, say. The first reason wins, because it
/// is the one that describes what actually happened.
fn enqueue_cancel(
&mut self,
pointer: PointerId,
reason: CancelReason,
recipient: Option<WidgetId>,
) {
if self.pending_dispatch.iter().any(|queued| {
matches!(queued, pointer_router::QueuedDispatch::Cancel { pointer: p, .. } if *p == pointer)
}) {
return;
}
crate::trace_input!(Samples, "cancel queued for {pointer:?}: {reason:?}");
// A revoked contact holds nothing, so its tree-owned hold is over. Done
// at *enqueue* rather than at dispatch: the queue can be drained a
// frame later, and a route that fires in between would be answering a
// press the system has already taken away.
self.cancel_touch_route(pointer);
self.pending_dispatch
.push_back(pointer_router::QueuedDispatch::Cancel {
pointer,
reason,
recipient,
});
}
/// Run one queued cancel, at dispatch depth zero.
pub(super) fn run_one_cancel(
&mut self,
pointer: PointerId,
reason: CancelReason,
recipient: Option<WidgetId>,
ops: &mut dyn crate::window::WindowOps,
) {
if !self.press_is_revocable(pointer) {
crate::trace_input!(
Samples,
"cancel for {pointer:?} ({reason:?}) dropped: nothing left to revoke"
);
return;
}
crate::trace_input!(Samples, "cancelling {pointer:?}: {reason:?}");
// Read the pointer's identity ONCE, here, while its table entry is
// certainly present — `press_is_revocable` above answered false for an
// absent entry, so this cannot fail. Both the snapshot below and the
// `PointerCancel` delivered at the end of the teardown are built from
// this one read, which is what stops them disagreeing: step 6 of the
// teardown *removes* a contact's entry, so anything reading the table
// after it gets a fabricated answer.
let Some((info, at)) = self.pointers.get(pointer).map(|e| (e.info, e.position)) else {
return;
};
// Serve the teardown as *this* pointer's sample: every helper below
// that reads "the pointer being dispatched" — the recognizer context,
// the drag's capture release, `EventContext::pointer()` inside the
// handler — must answer with the pointer being cancelled and not with
// whatever the outer dispatch was serving. Restored on the way out, so
// a cancel drained after an outer sample leaves that sample's snapshot
// as it found it.
let snapshot = crate::pointer::InputSnapshot {
pointer: info,
position: Some(at),
..Default::default()
};
let previous_input = std::mem::replace(&mut self.current_input, snapshot);
// Anything the cancel's own handler dispatches is queued behind it,
// exactly as it would be from inside an ordinary sample.
self.dispatch_depth += 1;
self.tear_down_cancelled_pointer(pointer, info, at, reason, recipient, ops);
self.dispatch_depth -= 1;
self.current_input = previous_input;
}
/// The ordered teardown itself, with `current_input` already serving
/// `pointer`. See [`cancel_pointer`](Self::cancel_pointer) for why the
/// order is what it is.
///
/// `info` and `at` are the pointer's identity and last position, read by the
/// caller **before** any of this ran: step 6 removes a contact's table
/// entry, and the event delivered in step 7 has to name the pointer that
/// went away.
fn tear_down_cancelled_pointer(
&mut self,
pointer: PointerId,
info: crate::pointer::PointerInfo,
at: Point,
reason: CancelReason,
recipient: Option<WidgetId>,
ops: &mut dyn crate::window::WindowOps,
) {
// 1. Every competitor's recognizer state, before anything else can
// recognize on the way out.
let members: Vec<WidgetId> = self
.pointers
.get(pointer)
.and_then(|e| e.sequence.as_ref())
.map(|s| s.members().iter().map(|m| m.id).collect())
.unwrap_or_default();
for member in members {
self.cancel_member_arena(member, pointer);
}
// The captor's own arena is not necessarily a member (a plain tap owner
// never enrols), and it is the node most likely to be holding
// recognizer state for this contact.
let captor = self.pointers.get(pointer).and_then(|e| e.captured_by);
if let Some(captor) = captor {
self.cancel_member_arena(captor, pointer);
}
// …and anything else that saw the press but is neither: an ancestor
// that took the capture off the node whose arena is still following the
// contact. See `release_arenas_following`.
self.release_arenas_following(pointer);
// 2. The arbitration. Whoever it decided for is about to be told the
// press it won has been taken away.
let recipient = recipient
.filter(|id| self.arena.get(*id).is_some())
.or_else(|| self.cancel_recipient(pointer));
if let Some(entry) = self.pointers.get_mut(pointer) {
entry.sequence = None;
}
// 3. The capture.
self.set_pointer_capture(pointer, None);
// 4. The drag session this pointer was driving, if it was driving one.
// `cancel_active_drag` is the same teardown Escape runs: the current
// drop target is told to clear its feedback and the source is told
// the drag ended as `Cancelled`, so nothing is left highlighted and
// no payload is silently dropped where the pointer happened to be.
if captor.is_some() && self.pointer_owns_active_drag_via(captor) {
self.cancel_active_drag(ops);
}
// 5. The touch-motion layer. The pan session goes without delivering a
// release — there is no velocity to hand on from an interaction that
// was taken away — and any coast the claimant chain is running stops
// with it. The palm watch is dropped rather than judged: a cancel is
// not a release, so there is nothing to be a palm *of*. The pinch is
// told, because a handler that has been zooming since `PinchStarted`
// must be given its `Cancelled` to unwind on. The framework press
// visual goes with them: a press that was taken away must not stay
// painted, and the node is never sent an `Up` to clear it from.
let pan_chain: Vec<WidgetId> = self.pan_chain_ids(pointer);
self.abandon_pan(pointer);
for id in pan_chain {
self.stop_fling(id);
}
self.forget_palm_watch(pointer);
self.end_press(pointer);
self.cancel_pinch(pointer, reason, ops);
// 6. The table entry, for a pointer that ceases to exist when it is
// taken away. A hovering-capable pointer does not: a mouse whose
// press was cancelled is still there, still hovering, and its entry
// is what every singular accessor reads — the same rule
// `dispatch_pointer_with_ops` applies to an `Up`.
let hovers = self
.pointers
.get(pointer)
.is_some_and(|e| e.info.kind.hovers());
if !hovers {
self.pointers.end(pointer);
} else if let Some(entry) = self.pointers.get_mut(pointer) {
// …and *hovering* is the whole of what it is now doing. The entry's
// button mask is what `PointerEntry::is_contacting` reads for a
// hovering-capable pointer, so leaving the press's mask on it
// leaves the pointer reading as held by an interaction the
// framework has just finished forgetting — for ever, since a Cancel
// sample never reaches `PointerTable::admit` and the next real
// sample is the earliest correction. The platform layer already
// builds its pen proximity-leave with an empty mask, intending
// exactly this; the intent was being discarded.
entry.info.buttons = crate::event::ButtonMask::NONE;
}
// A cancel is terminal: an `Up` that arrives for this pointer
// afterwards — a platform that sends both, a test that sends one by
// hand — must not complete the interaction that was taken away.
if !self.cancelled_pointers.contains(&pointer) {
self.cancelled_pointers.push(pointer);
}
// 7. The event, last, to a tree that has already let go — built from the
// identity the caller captured, since step 6 may have taken the
// entry away.
if let Some(recipient) = recipient {
let event = Self::pointer_cancel_event(info, at, reason);
self.dispatch_to_widget_direct(recipient, &event, ops);
}
}
// -----------------------------------------------------------------
// Predicates the producers and the funnel share
// -----------------------------------------------------------------
/// Whether `pointer` still has an interaction that can be taken away.
///
/// Three ways the answer is no, and all three mean the same thing — there
/// is nothing left for a `PointerCancel` to revoke:
///
/// * the pointer is not live at all (a contact that lifted);
/// * it holds no capture and has no sequence, so it is merely hovering;
/// * its sequence is inside its own terminal dispatch
/// ([`PointerSequence::is_terminating`](crate::gesture::PointerSequence::is_terminating)),
/// so the press has completed and only its epilogue is still running.
///
/// The second case is what carries the design's named exemption. By the
/// time a menu item's `on_tap` runs, the release sweep has already closed
/// that pointer's sequence (`end_sequence` clears it before the `Up` is
/// delivered), so a cancel the handler's own overlay teardown queues finds
/// no press to revoke and the tap completes. The third case covers the
/// same window for any future producer that fires while a sequence is
/// installed but already terminating.
pub(super) fn press_is_revocable(&self, pointer: PointerId) -> bool {
let Some(entry) = self.pointers.get(pointer) else {
return false;
};
match entry.sequence.as_ref() {
Some(sequence) => !sequence.is_terminating(),
None => entry.captured_by.is_some(),
}
}
/// Who receives the `PointerCancel`: the widget holding the capture, and
/// failing that the last widget that accepted an event from this pointer.
///
/// The first of the two that still *exists* wins. A captor destroyed by
/// the very rebuild that provoked the cancel cannot be told anything, and
/// falling through to the last acceptor is how the widget that was
/// actually interacting still hears about it.
fn cancel_recipient(&self, pointer: PointerId) -> Option<WidgetId> {
let entry = self.pointers.get(pointer)?;
[entry.captured_by, entry.last_accepted]
.into_iter()
.flatten()
.find(|id| self.arena.get(*id).is_some())
}
/// The `PointerCancel` announcing `pointer`, at the position it last
/// reported.
///
/// Takes the identity rather than looking it up, and that is the point: the
/// teardown **removes a contact's table entry** before the event is
/// delivered (step 6, deliberately — a lifted or revoked contact stops
/// existing), so a builder that read the table here read the entry it had
/// just deleted and fell back to a fabricated mouse with no position. The
/// handler whose entire job is to know which pointer went away was told the
/// mouse cancelled a press only a finger had made. Every caller now reads
/// the entry while it is still there and hands the answer down, so the event
/// payload and `EventContext::pointer()` inside the handler cannot disagree
/// — which is how that defect stayed invisible, since the snapshot half was
/// always right.
fn pointer_cancel_event(
pointer: crate::pointer::PointerInfo,
window_position: Point,
reason: CancelReason,
) -> WidgetEvent {
WidgetEvent::PointerCancel {
window_position: Some(window_position),
reason,
pointer,
}
}
/// Whether the in-flight drag belongs to the pointer whose capture is
/// `captor`.
///
/// An internal drag captures the pointer it started from onto its own
/// source widget (`collect_from_ctx`'s drag-start arm), so holding that
/// capture *is* what it means to be driving the drag. An external (OS)
/// drag takes no capture and has no in-app source: it belongs to the
/// platform backend that began it, and no in-app pointer cancel may end
/// it.
fn pointer_owns_active_drag_via(&self, captor: Option<WidgetId>) -> bool {
self.active_drag
.as_ref()
.and_then(|drag| drag.source_widget)
.is_some_and(|source| captor == Some(source))
}
}
// -------------------------------------------------------------------------
// P09: the cancel taxonomy — one funnel, an enumerated producer set
// -------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::event::{EventResponse, Modifiers, PointerButton, WidgetEvent};
use crate::pointer::{
BackendDeviceKey, EventTime, PointerIdAllocator, PointerInfo, PointerPhase, PointerSample,
};
use crate::test_widgets::{FillWidget, StackWidget};
use crate::widget_builder::WidgetBuilder;
use std::cell::RefCell;
use std::rc::Rc;
use teksilo_canvas::{Point, SizeProposal};
/// Every cancel a test observed, in delivery order.
type Log = Rc<RefCell<Vec<(WidgetId, CancelReason)>>>;
fn log() -> Log {
Rc::new(RefCell::new(Vec::new()))
}
/// A widget that records the cancels it is told about.
fn recorder(log: &Log, id_slot: Rc<std::cell::Cell<Option<WidgetId>>>) -> impl Widget {
let log = log.clone();
FillWidget::new().on_pointer_cancel(move |_pointer, reason, _ctx| {
let id = id_slot.get().expect("the recorder's id was never recorded");
log.borrow_mut().push((id, reason));
})
}
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,
));
}
/// 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(31_000);
PointerIdAllocator::global().begin(
BackendDeviceKey::DEFAULT,
NEXT.fetch_add(1, Ordering::Relaxed),
)
}
fn touch(id: PointerId, phase: PointerPhase, at: Point) -> PointerSample {
PointerSample {
pointer: PointerInfo::touch(id, EventTime::ZERO),
phase,
position: at,
button: None,
modifiers: Modifiers::NONE,
coalesced: Vec::new(),
}
}
/// A leaf that takes the pointer on press and drives itself from moves —
/// the splitter-handle / column-grip shape, and the simplest thing that
/// has an interaction a cancel can take away.
fn grip(log: &Log, id_slot: Rc<std::cell::Cell<Option<WidgetId>>>) -> impl Widget {
let log = log.clone();
let slot = id_slot.clone();
FillWidget::new()
.on_pointer_event(|event, ctx| {
if matches!(event, WidgetEvent::PointerDown { .. }) {
ctx.capture_pointer();
}
EventResponse::Ignored
})
.on_pointer_cancel(move |_pointer, reason, _ctx| {
let id = slot.get().expect("the grip's id was never recorded");
log.borrow_mut().push((id, reason));
})
}
/// Build a one-leaf tree whose leaf grips the pointer, and return it.
fn tree_with_grip(log: &Log) -> (WidgetTree, WidgetId) {
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let id = tree.add(grip(log, slot.clone()));
slot.set(Some(id));
tree.layout(SizeProposal::exact(200.0, 100.0));
(tree, id)
}
// ---------------------------------------------------------------
// Producer: window deactivation
// ---------------------------------------------------------------
/// The producer that replaces the framework's oldest silent teardown.
/// Deactivating a window used to drop every capture without a word; now
/// the widget holding one is told, so it can let go of what the press
/// latched.
#[test]
fn deactivating_the_window_cancels_the_pointer_it_stranded() {
let log = log();
let (mut tree, id) = tree_with_grip(&log);
press(&mut tree, Point::new(20.0, 50.0));
assert_eq!(tree.captured_by(PointerId::MOUSE), Some(id));
tree.set_window_active(false);
assert_eq!(
*log.borrow(),
vec![(id, CancelReason::WindowDeactivated)],
"the widget that captured the pointer is told the window took it away"
);
assert_eq!(
tree.captured_by(PointerId::MOUSE),
None,
"and the capture is released, as it always was"
);
tree.assert_no_leaked_pointer_state();
}
/// A window deactivated with nothing going on cancels nothing: there is no
/// interaction to revoke, and firing a `PointerCancel` at a widget the
/// mouse merely rests over would be noise.
#[test]
fn deactivating_the_window_with_no_live_press_cancels_nothing() {
let log = log();
let (mut tree, _id) = tree_with_grip(&log);
moved(&mut tree, Point::new(20.0, 50.0));
tree.set_window_active(false);
assert!(log.borrow().is_empty());
tree.assert_no_leaked_pointer_state();
}
/// The platform itself revoked the contact — a `wl_touch.cancel`, a
/// `WM_POINTERCAPTURECHANGED`, a compositor grab. It reaches the funnel
/// directly from the sample door rather than being lowered onto an event,
/// because lowering would first *admit* the pointer the sample revokes.
#[test]
fn a_platform_cancel_sample_tears_the_contact_down() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let leaf = tree.add(grip(&log, slot.clone()));
slot.set(Some(leaf));
tree.layout(SizeProposal::exact(200.0, 100.0));
let contact = new_contact();
tree.dispatch_pointer(touch(contact, PointerPhase::Down, Point::new(20.0, 50.0)));
assert_eq!(tree.captured_by(contact), Some(leaf));
tree.dispatch_pointer(touch(contact, PointerPhase::Cancel, Point::new(20.0, 50.0)));
assert_eq!(*log.borrow(), vec![(leaf, CancelReason::Platform)]);
assert!(
tree.pointers.get(contact).is_none(),
"a revoked contact leaves the table, as a lifted one does"
);
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// The delivered payload names the pointer that went away
// ---------------------------------------------------------------
/// What a `PointerCancel` handler was told, per delivery.
type PayloadLog = Rc<RefCell<Vec<(CancelReason, PointerInfo, Option<Point>)>>>;
/// A leaf that grips the pointer and records the whole `PointerCancel`
/// payload it is handed — not just the reason.
fn payload_grip(log: &PayloadLog) -> impl Widget {
let log = log.clone();
FillWidget::new()
.on_pointer_event(|event, ctx| {
if matches!(event, WidgetEvent::PointerDown { .. }) {
ctx.capture_pointer();
}
EventResponse::Ignored
})
.on_pointer_cancel(move |pointer, reason, ctx| {
log.borrow_mut()
.push((reason, *pointer, ctx.pointer_position()));
})
}
/// A cancelled **contact** is announced as that contact.
///
/// The handler whose whole job is to know which pointer went away was being
/// handed a fabricated mouse: the teardown removes a non-hovering pointer's
/// table entry before the event is built, and the builder read the entry it
/// had just deleted, so an app branching on `pointer.kind` — releasing a
/// per-contact grip, dropping a stroke, un-highlighting one finger's row —
/// was told the mouse cancelled a press only a finger had made, and given no
/// position to do it at.
#[test]
fn a_cancelled_contact_is_announced_as_that_contact() {
let log: PayloadLog = Rc::new(RefCell::new(Vec::new()));
let mut tree = WidgetTree::new();
let leaf = tree.add(payload_grip(&log));
tree.layout(SizeProposal::exact(200.0, 100.0));
let contact = new_contact();
let at = Point::new(20.0, 50.0);
tree.dispatch_pointer(touch(contact, PointerPhase::Down, at));
assert_eq!(tree.captured_by(contact), Some(leaf));
tree.dispatch_pointer(touch(contact, PointerPhase::Cancel, at));
let seen = log.borrow();
assert_eq!(seen.len(), 1, "one cancel, delivered once");
let (reason, pointer, position) = seen[0];
assert_eq!(reason, CancelReason::Platform);
assert_eq!(
pointer.kind,
teksilo_tokens::PointerKind::Touch,
"the event must name the device that was cancelled",
);
assert_eq!(
pointer.id, contact,
"and its own id, not the mouse's reserved one",
);
assert_eq!(
position,
Some(at),
"with the position the contact was last at",
);
}
/// The same for a mouse, so the fix above is a *translation* of whatever the
/// entry held and not a hardcoded touch.
#[test]
fn a_cancelled_mouse_press_is_still_announced_as_the_mouse() {
let log: PayloadLog = Rc::new(RefCell::new(Vec::new()));
let mut tree = WidgetTree::new();
tree.add(payload_grip(&log));
tree.layout(SizeProposal::exact(200.0, 100.0));
let at = Point::new(30.0, 40.0);
press(&mut tree, at);
tree.cancel_all_pointers(CancelReason::ModalOpened, &mut crate::window::NoopWindowOps);
let seen = log.borrow();
assert_eq!(seen.len(), 1);
let (reason, pointer, position) = seen[0];
assert_eq!(reason, CancelReason::ModalOpened);
assert_eq!(pointer.kind, teksilo_tokens::PointerKind::Mouse);
assert_eq!(pointer.id, PointerId::MOUSE);
assert_eq!(position, Some(at));
}
/// A second producer, with a different shape: the subtree holding the press
/// is parked, so the cancel is queued by `set_dormant` rather than raised
/// from the sample door, and the position it announces is the one carried by
/// a *later* move than the press. The payload must read the same — the
/// fallback the defect lived in sits below all fifteen producers, so one
/// producer being right is not evidence about the others.
#[test]
fn a_parked_subtree_announces_the_contact_it_stranded() {
let log: PayloadLog = Rc::new(RefCell::new(Vec::new()));
let mut tree = WidgetTree::new();
let leaf = tree.add(payload_grip(&log));
let branch = tree.add(StackWidget::new().child(leaf));
tree.layout(SizeProposal::exact(200.0, 100.0));
let contact = new_contact();
tree.dispatch_pointer(touch(contact, PointerPhase::Down, Point::new(20.0, 50.0)));
assert_eq!(tree.captured_by(contact), Some(leaf));
let moved_to = Point::new(24.0, 52.0);
tree.dispatch_pointer(touch(contact, PointerPhase::Move, moved_to));
tree.set_dormant(branch);
let seen = log.borrow();
assert_eq!(seen.len(), 1, "the parked leaf was told once");
let (reason, pointer, position) = seen[0];
assert_eq!(reason, CancelReason::SubtreeParked);
assert_eq!(pointer.kind, teksilo_tokens::PointerKind::Touch);
assert_eq!(pointer.id, contact);
assert_eq!(
position,
Some(moved_to),
"the position is where the contact last was, not where it pressed",
);
}
/// A cancel sample for a pointer the tree never saw must not *create* one.
/// Admitting it would leave an entry behind that nothing can ever remove.
#[test]
fn a_cancel_for_an_unknown_pointer_admits_nothing() {
let mut tree = WidgetTree::new();
tree.add(FillWidget::new());
tree.layout(SizeProposal::exact(200.0, 100.0));
let ghost = new_contact();
tree.dispatch_pointer(touch(ghost, PointerPhase::Cancel, Point::new(20.0, 50.0)));
assert!(tree.pointers.get(ghost).is_none());
tree.assert_no_leaked_pointer_state();
}
/// The recipient of last resort. A press that took no capture still has a
/// widget that was interacting with it — the last one that answered
/// `Handled` — and that is who must be told the press was taken away.
#[test]
fn a_cancel_without_a_capture_reaches_the_last_widget_that_accepted() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let leaf = {
let l = log.clone();
let s = slot.clone();
tree.add(
FillWidget::new()
// Handles the press without taking the pointer — the shape
// of a widget that paints a press state and nothing else.
.on_pointer_event(|event, _ctx| {
if matches!(event, WidgetEvent::PointerDown { .. }) {
return EventResponse::Handled;
}
EventResponse::Ignored
})
.on_pointer_cancel(move |_p, reason, _ctx| {
let id = s.get().expect("the leaf's id was never recorded");
l.borrow_mut().push((id, reason));
}),
)
};
slot.set(Some(leaf));
tree.layout(SizeProposal::exact(200.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
assert_eq!(
tree.captured_by(PointerId::MOUSE),
None,
"the widget took the press without taking the pointer"
);
tree.set_window_active(false);
assert_eq!(*log.borrow(), vec![(leaf, CancelReason::WindowDeactivated)]);
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// Producer: a modal opening
// ---------------------------------------------------------------
/// A modal opens over the press: the surface being worked on is now behind
/// a scrim, and the `Up` that would have completed the press will land on
/// the modal instead.
#[test]
fn opening_a_modal_cancels_every_live_pointer() {
let log = log();
let (mut tree, id) = tree_with_grip(&log);
press(&mut tree, Point::new(20.0, 50.0));
let modal_content = tree.add(FillWidget::new());
tree.show_overlay(crate::overlay::OverlayRequest {
content_id: modal_content,
anchor: id,
placement: crate::overlay::OverlayPlacement::Centered,
dismiss: crate::overlay::DismissBehavior::Manual,
layer: crate::overlay::OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
assert_eq!(*log.borrow(), vec![(id, CancelReason::ModalOpened)]);
assert_eq!(tree.captured_by(PointerId::MOUSE), None);
tree.assert_no_leaked_pointer_state();
}
/// Only a modal. A menu, a popover, a tooltip or a drag preview opens over
/// an interaction that legitimately continues.
#[test]
fn opening_a_non_modal_overlay_cancels_nothing() {
let log = log();
let (mut tree, id) = tree_with_grip(&log);
press(&mut tree, Point::new(20.0, 50.0));
let popover = tree.add(FillWidget::new());
tree.show_overlay(crate::overlay::OverlayRequest {
content_id: popover,
anchor: id,
placement: crate::overlay::OverlayPlacement::Below,
dismiss: crate::overlay::DismissBehavior::Manual,
layer: crate::overlay::OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
assert!(log.borrow().is_empty(), "a popover is not a modal");
assert_eq!(tree.captured_by(PointerId::MOUSE), Some(id));
release(&mut tree, Point::new(20.0, 50.0));
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// Producer: a subtree going dormant
// ---------------------------------------------------------------
/// Parking a subtree is invisible to hit-testing and to dispatch, so a
/// widget parked mid-press would keep what the press latched with no event
/// left that could clear it.
#[test]
fn parking_a_subtree_cancels_the_pointer_inside_it() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let leaf = tree.add(grip(&log, slot.clone()));
slot.set(Some(leaf));
let branch = tree.add(StackWidget::new().child(leaf));
tree.layout(SizeProposal::exact(200.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
assert_eq!(tree.captured_by(PointerId::MOUSE), Some(leaf));
tree.set_dormant(branch);
assert_eq!(*log.borrow(), vec![(leaf, CancelReason::SubtreeParked)]);
assert_eq!(tree.captured_by(PointerId::MOUSE), None);
tree.assert_no_leaked_pointer_state();
}
/// The parked-ids plumbing is what makes the producer above possible: a
/// caller that cannot see which nodes went to sleep cannot cancel the
/// pointers holding them. `set_dormant` reports the whole subtree, its
/// root first, and reports it once per node however deep the nesting.
#[test]
fn set_dormant_reports_the_whole_parked_subtree() {
let mut tree = WidgetTree::new();
let leaf_a = tree.add(FillWidget::new());
let leaf_b = tree.add(FillWidget::new());
let inner = tree.add(StackWidget::new().child(leaf_a).child(leaf_b));
let outer = tree.add(StackWidget::new().child(inner));
tree.layout(SizeProposal::exact(200.0, 100.0));
let parked = tree.arena.set_dormant(outer);
assert_eq!(parked.first(), Some(&outer), "the root is reported first");
let mut sorted = parked.clone();
sorted.sort();
sorted.dedup();
assert_eq!(
sorted.len(),
parked.len(),
"each node is reported exactly once"
);
for id in [outer, inner, leaf_a, leaf_b] {
assert!(
parked.contains(&id),
"{id:?} is missing from the parked set"
);
}
}
/// The other way a subtree parks: a `visible_when` gate flipping false,
/// resolved by the layout pass rather than by an explicit call. It is the
/// busiest `set_dormant` caller in the framework, and it goes through the
/// same door.
#[test]
fn a_visible_when_gate_closing_cancels_the_pointer_inside_it() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let shown = crate::signal::Signal::new(true);
let mut tree = WidgetTree::new();
let leaf = tree.add(grip(&log, slot.clone()));
slot.set(Some(leaf));
let branch = tree.add(StackWidget::new().child(leaf).visible_when(shown.clone()));
let _root = tree.add(StackWidget::new().child(branch));
tree.layout(SizeProposal::exact(200.0, 100.0));
let at = tree.bounds(leaf).center();
press(&mut tree, at);
assert_eq!(tree.captured_by(PointerId::MOUSE), Some(leaf));
shown.set(false);
tree.layout(SizeProposal::exact(200.0, 100.0));
assert_eq!(*log.borrow(), vec![(leaf, CancelReason::SubtreeParked)]);
assert_eq!(tree.captured_by(PointerId::MOUSE), None);
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// Producer: an overlay being dismissed, and its named exemption
// ---------------------------------------------------------------
/// A pointer anchored inside an overlay that is torn down under it is
/// stranded on a widget that no longer takes events.
#[test]
fn dismissing_an_overlay_cancels_a_pointer_anchored_inside_it() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let anchor = tree.add(FillWidget::new());
let content = tree.add(grip(&log, slot.clone()));
slot.set(Some(content));
tree.layout(SizeProposal::exact(200.0, 100.0));
let overlay = tree.show_overlay(crate::overlay::OverlayRequest {
content_id: content,
anchor,
placement: crate::overlay::OverlayPlacement::Below,
dismiss: crate::overlay::DismissBehavior::Manual,
layer: crate::overlay::OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
tree.layout(SizeProposal::exact(200.0, 100.0));
// The press lands on the overlay's own content, which grips the
// pointer — a scrollbar thumb inside a dropdown, say.
tree.dispatch_event(WidgetEvent::pointer_down(
tree.bounds(content).center(),
PointerButton::Primary,
Modifiers::NONE,
));
assert_eq!(tree.captured_by(PointerId::MOUSE), Some(content));
tree.dismiss_overlay(overlay);
assert_eq!(
*log.borrow(),
vec![(content, CancelReason::OverlayDismissed)]
);
tree.assert_no_leaked_pointer_state();
}
/// **The named exemption.** Tapping a menu item whose own handler closes
/// its menu must complete the tap. The overlay teardown the handler asks
/// for happens while that pointer's press is already over — the release
/// sweep ran before the `Up` was delivered — so there is nothing left for a
/// cancel to revoke, and the item is never told its own activation was
/// taken away.
#[test]
fn tapping_a_menu_item_that_closes_its_own_menu_completes_the_tap() {
for kind in ["mouse", "touch"] {
let log = log();
let tapped = Rc::new(std::cell::Cell::new(0_u32));
let overlay_slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let anchor = tree.add(FillWidget::new());
let item_slot = Rc::new(std::cell::Cell::new(None));
let item = {
let t = tapped.clone();
let o = overlay_slot.clone();
let l = log.clone();
let s = item_slot.clone();
tree.add(
FillWidget::new()
.on_tap(move |_e, ctx| {
t.set(t.get() + 1);
// The menu item closes its own menu, exactly as a
// real one does.
if let Some(id) = o.get() {
ctx.dismiss_overlay(id);
}
})
.on_pointer_cancel(move |_p, reason, _ctx| {
let id = s.get().expect("the item's id was never recorded");
l.borrow_mut().push((id, reason));
}),
)
};
item_slot.set(Some(item));
tree.layout(SizeProposal::exact(200.0, 100.0));
let overlay = tree.show_overlay(crate::overlay::OverlayRequest {
content_id: item,
anchor,
placement: crate::overlay::OverlayPlacement::Below,
dismiss: crate::overlay::DismissBehavior::Manual,
layer: crate::overlay::OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
overlay_slot.set(Some(overlay));
tree.layout(SizeProposal::exact(200.0, 100.0));
let at = tree.bounds(item).center();
if kind == "mouse" {
press(&mut tree, at);
release(&mut tree, at);
} else {
let contact = new_contact();
tree.dispatch_pointer(touch(contact, PointerPhase::Down, at));
tree.dispatch_pointer(touch(contact, PointerPhase::Up, at));
}
assert_eq!(tapped.get(), 1, "the {kind} tap completed");
assert!(
log.borrow().is_empty(),
"the {kind} tap must not be cancelled by the teardown it asked \
for: {:?}",
log.borrow()
);
tree.assert_no_leaked_pointer_state();
}
}
// ---------------------------------------------------------------
// Producer: a peer claiming the sequence
// ---------------------------------------------------------------
/// The member granularity, and the one that is emphatically *not* a
/// pointer cancel: two nested drag-capable ancestors compete for a press a
/// tapping descendant is holding, the inner one wins at the mouse latch,
/// and the outer one is told it lost — **once**, on that sample, and never
/// again however many more moves arrive.
#[test]
fn a_peer_claim_revokes_each_loser_exactly_once() {
let log = log();
let outer_slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
// The tap owner: it takes the capture, which is what enrols the
// drag-capable ancestors above it as competitors.
let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
let inner = tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
let outer = tree.add(
StackWidget::new()
.child(inner)
.on_drag(|_phase, _c| {})
.on_pointer_cancel({
let log = log.clone();
let slot = outer_slot.clone();
move |_p, reason, _ctx| {
let id = slot.get().expect("the outer id was never recorded");
log.borrow_mut().push((id, reason));
}
}),
);
outer_slot.set(Some(outer));
tree.layout(SizeProposal::exact(400.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
// Ten samples well past the mouse drag latch: the inner drag wins on
// the first one that clears 5 dp, and the outer must be revoked then
// and only then.
for step in 1..=10 {
moved(&mut tree, Point::new(20.0 + step as f32 * 10.0, 50.0));
}
assert_eq!(
tree.sequence_winner(PointerId::MOUSE),
Some(inner),
"the innermost drag won the press"
);
assert_eq!(
*log.borrow(),
vec![(outer, CancelReason::PeerClaimed)],
"the loser is revoked once, on the sample the peer won, and never again"
);
assert!(
tree.pointers.get(PointerId::MOUSE).is_some(),
"revoking a member is not cancelling the pointer: it is still live"
);
release(&mut tree, Point::new(120.0, 50.0));
assert_eq!(
log.borrow().len(),
1,
"and the release adds nothing: the loser was already told"
);
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// Producer: rebuild / member death
// ---------------------------------------------------------------
/// A competitor destroyed mid-press is revoked **individually**: the
/// pointer and its winner are untouched.
#[test]
fn a_destroyed_member_is_revoked_alone() {
let mut tree = WidgetTree::new();
let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
let ancestor = tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
tree.layout(SizeProposal::exact(400.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
assert!(
tree.sequence_members(PointerId::MOUSE)
.iter()
.any(|(id, _, _)| *id == ancestor),
"the ancestor drag is enrolled through the child's capture"
);
tree.destroy_subtree_for_testing(ancestor);
moved(&mut tree, Point::new(21.0, 50.0));
assert!(
tree.sequence_members(PointerId::MOUSE)
.iter()
.all(|(id, _, _)| *id != ancestor),
"the dead member is dropped from the arbitration"
);
}
/// The captor dying is a different act: the press belonged to it, so the
/// whole pointer is cancelled and the capture it left behind is given back.
#[test]
fn a_destroyed_captor_cancels_the_whole_pointer() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let leaf = tree.add(grip(&log, slot.clone()));
slot.set(Some(leaf));
let host = tree.add(StackWidget::new().child(leaf));
tree.layout(SizeProposal::exact(200.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
assert_eq!(tree.captured_by(PointerId::MOUSE), Some(leaf));
// Destroy the captor without a layout in between, so the sequence's own
// revalidation is what notices — the mandated hook.
tree.destroy_subtree_for_testing(host);
moved(&mut tree, Point::new(21.0, 50.0));
assert_eq!(
tree.captured_by(PointerId::MOUSE),
None,
"the orphaned capture is given back"
);
assert!(
tree.sequence_members(PointerId::MOUSE).is_empty(),
"and the arbitration is over"
);
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// Producer: an OS drag taking the pointer
// ---------------------------------------------------------------
/// Escalating an in-app drag to the OS hands the pointer to the platform:
/// this window sees no further move and no `Up`, so whatever the press
/// still had going has to be revoked here.
#[test]
fn escalating_to_an_os_drag_cancels_the_source_pointer() {
/// Stands in for the platform backend: accepts the hand-off and
/// records that it did.
struct AcceptingOps {
began: std::cell::Cell<bool>,
}
impl crate::window::WindowOps for AcceptingOps {
fn open_window(
&mut self,
_config: crate::window::WindowConfig,
) -> crate::window::TeksiloWindowId {
panic!("not used in this test")
}
fn find_window(&self, _id: &str) -> Option<crate::window::TeksiloWindowId> {
None
}
fn window_state(
&self,
_id: crate::window::TeksiloWindowId,
) -> Option<crate::window::WindowState> {
None
}
fn windows(&self) -> Vec<crate::window::WindowState> {
Vec::new()
}
fn focus_window(&mut self, _id: crate::window::TeksiloWindowId) {}
fn close_window_by_id(&mut self, _id: crate::window::TeksiloWindowId) {}
fn begin_os_drag(
&mut self,
_data: crate::drag_payload::OutboundDragData,
_image: Option<crate::drag_payload::DragImageData>,
_pointer: teksilo_tokens::PointerKind,
) -> bool {
self.began.set(true);
true
}
}
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let source = tree.add(recorder(&log, slot.clone()));
slot.set(Some(source));
tree.layout(SizeProposal::exact(200.0, 100.0));
let mut ops = AcceptingOps {
began: std::cell::Cell::new(false),
};
press(&mut tree, Point::new(20.0, 50.0));
let mut ctx = crate::widget::EventContext::new();
ctx.start_drag(
source,
crate::drag_payload::DragPayload::typed(7_u32).with_mime("text/plain", b"7".to_vec()),
);
tree.collect_from_ctx(ctx, source);
assert!(tree.active_drag.is_some());
// Out of the window: the drag escalates.
tree.dispatch_event_with_ops(WidgetEvent::pointer_move(Point::new(-40.0, 50.0)), &mut ops);
assert!(ops.began.get(), "the platform took the drag");
assert_eq!(
*log.borrow(),
vec![(source, CancelReason::OsDragStarted)],
"and the source is told the in-app half of the interaction is over"
);
tree.assert_no_leaked_pointer_state();
}
// ---------------------------------------------------------------
// The queue, and terminality
// ---------------------------------------------------------------
/// A cancel raised from inside a handler is **queued**: the handler that
/// raised it finishes on the state it started with, and the teardown runs
/// afterwards — before the top-level dispatch returns.
#[test]
fn a_cancel_raised_from_a_handler_is_queued_not_reentrant() {
let observed_capture = Rc::new(std::cell::Cell::new(None));
let cancelled = Rc::new(std::cell::Cell::new(false));
let mut tree = WidgetTree::new();
let leaf = {
let seen = observed_capture.clone();
let done = cancelled.clone();
tree.add(
FillWidget::new()
.on_pointer_event(move |event, ctx| {
if matches!(event, WidgetEvent::PointerDown { .. }) {
ctx.capture_pointer();
}
if matches!(event, WidgetEvent::PointerMove { .. }) {
ctx.cancel_pointer_sequence(CancelReason::Deactivated);
// Still owned, right here: the cancel has not run.
seen.set(Some(ctx.owns_pointer()));
}
EventResponse::Ignored
})
.on_pointer_cancel(move |_p, _reason, _ctx| done.set(true)),
)
};
tree.layout(SizeProposal::exact(200.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
moved(&mut tree, Point::new(30.0, 50.0));
assert_eq!(
observed_capture.get(),
Some(true),
"the handler that raised the cancel still owned the pointer when it returned"
);
assert!(
cancelled.get(),
"and the teardown ran once the sample finished"
);
assert!(
!tree.has_pending_dispatch(),
"the queue is empty again before the dispatch returns"
);
assert_eq!(tree.captured_by(PointerId::MOUSE), None);
assert_eq!(tree.arena.get(leaf).map(|_| ()), Some(()));
tree.assert_no_leaked_pointer_state();
}
/// A cancel that a handler raises against a pointer which lifts in the very
/// same sample must not fire: by the time the queue drains there is no
/// interaction left to revoke.
#[test]
fn a_cancel_does_not_fire_if_the_pointer_lifted_in_the_same_sample() {
let log = log();
let slot = Rc::new(std::cell::Cell::new(None));
let mut tree = WidgetTree::new();
let leaf = {
let l = log.clone();
let s = slot.clone();
tree.add(
FillWidget::new()
.on_pointer_event(|event, ctx| {
if matches!(event, WidgetEvent::PointerDown { .. }) {
ctx.capture_pointer();
}
if matches!(event, WidgetEvent::PointerUp { .. }) {
// The release itself asks for a cancel — the shape
// a menu item's "close my menu" handler has.
ctx.cancel_pointer_sequence(CancelReason::OverlayDismissed);
}
EventResponse::Ignored
})
.on_pointer_cancel(move |_p, reason, _ctx| {
let id = s.get().expect("the leaf's id was never recorded");
l.borrow_mut().push((id, reason));
}),
)
};
slot.set(Some(leaf));
tree.layout(SizeProposal::exact(200.0, 100.0));
let contact = new_contact();
tree.dispatch_pointer(touch(contact, PointerPhase::Down, Point::new(20.0, 50.0)));
tree.dispatch_pointer(touch(contact, PointerPhase::Up, Point::new(20.0, 50.0)));
assert!(
log.borrow().is_empty(),
"the press was already over when the queued cancel drained: {:?}",
log.borrow()
);
tree.assert_no_leaked_pointer_state();
}
/// `PointerCancel` is terminal. An `Up` that arrives for a press the system
/// already took away completes nothing — the widget has been told to let
/// go, and handing it back the release would resurrect an interaction that
/// no longer exists.
#[test]
fn no_pointer_up_follows_a_cancel() {
let ups = Rc::new(std::cell::Cell::new(0_u32));
let cancels = Rc::new(std::cell::Cell::new(0_u32));
let mut tree = WidgetTree::new();
{
let u = ups.clone();
let c = cancels.clone();
tree.add(
FillWidget::new()
.on_tap(move |_e, _ctx| u.set(u.get() + 1))
.on_pointer_cancel(move |_p, _reason, _ctx| c.set(c.get() + 1)),
);
}
tree.layout(SizeProposal::exact(200.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
tree.set_window_active(false);
assert_eq!(cancels.get(), 1);
// The platform (or a confused caller) sends the release anyway.
release(&mut tree, Point::new(20.0, 50.0));
assert_eq!(ups.get(), 0, "the tap must not complete after its cancel");
// …and the next press is a fresh interaction, unaffected.
tree.set_window_active(true);
press(&mut tree, Point::new(20.0, 50.0));
release(&mut tree, Point::new(20.0, 50.0));
assert_eq!(ups.get(), 1, "the next press works normally");
tree.assert_no_leaked_pointer_state();
}
/// The whole-pointer and member-level granularities are different acts,
/// and the difference has to be visible from outside: a member revocation
/// leaves the pointer, its capture and its winner exactly where they were.
#[test]
fn revoking_a_member_leaves_the_pointer_alive() {
let mut tree = WidgetTree::new();
let child = tree.add(FillWidget::new().on_tap(|_e, _c| {}));
let ancestor = tree.add(StackWidget::new().child(child).on_drag(|_phase, _c| {}));
tree.layout(SizeProposal::exact(400.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
let mut noop = crate::window::NoopWindowOps;
tree.revoke_sequence_member(
PointerId::MOUSE,
ancestor,
CancelReason::PeerClaimed,
&mut noop,
);
assert_eq!(
tree.captured_by(PointerId::MOUSE),
Some(child),
"the capture survives a member revocation"
);
assert!(
tree.pointers.get(PointerId::MOUSE).is_some(),
"and so does the pointer"
);
release(&mut tree, Point::new(20.0, 50.0));
tree.assert_no_leaked_pointer_state();
}
/// A drag the cancelled pointer was driving ends as `Cancelled`, not as a
/// drop: releasing the payload wherever the pointer happened to be is how
/// a lost window focus turns into a data-loss bug.
#[test]
fn cancelling_the_pointer_driving_a_drag_cancels_the_drag() {
let outcome = Rc::new(RefCell::new(None));
let mut tree = WidgetTree::new();
let source = {
let o = outcome.clone();
tree.add(FillWidget::new().on_drag_ended(move |result, _ctx| {
*o.borrow_mut() = Some(result);
}))
};
tree.layout(SizeProposal::exact(200.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
let mut ctx = crate::widget::EventContext::new();
ctx.start_drag(source, crate::drag_payload::DragPayload::typed(1_u8));
tree.collect_from_ctx(ctx, source);
assert!(tree.active_drag.is_some());
tree.set_window_active(false);
assert!(tree.active_drag.is_none(), "the drag session is torn down");
assert_eq!(
*outcome.borrow(),
Some(crate::drag_payload::DropOutcome::Cancelled),
"and its source is told it was cancelled, not dropped"
);
tree.assert_no_leaked_pointer_state();
}
/// A drag mid-flight is exactly the case the funnel exists for. Its phases
/// must not report an `Ended` — that is the `Up` story — and the widget
/// must hear about the revocation instead.
#[test]
fn a_cancelled_drag_reports_no_ended_phase() {
let phases = Rc::new(RefCell::new(Vec::new()));
let cancels = Rc::new(std::cell::Cell::new(0_u32));
let mut tree = WidgetTree::new();
{
let p = phases.clone();
let c = cancels.clone();
tree.add(
FillWidget::new()
.on_drag(move |phase, _ctx| {
p.borrow_mut().push(std::mem::discriminant(&phase));
})
.on_pointer_cancel(move |_p, _reason, _ctx| c.set(c.get() + 1)),
);
}
tree.layout(SizeProposal::exact(400.0, 100.0));
press(&mut tree, Point::new(20.0, 50.0));
for step in 1..=3 {
moved(&mut tree, Point::new(20.0 + step as f32 * 10.0, 50.0));
}
let before = phases.borrow().len();
assert!(before >= 2, "the drag started and moved");
tree.set_window_active(false);
assert_eq!(cancels.get(), 1, "the dragging widget is told");
assert_eq!(
phases.borrow().len(),
before,
"and no further drag phase — least of all an Ended — is reported"
);
tree.assert_no_leaked_pointer_state();
}
/// A cancelled hovering pointer stops reading as held.
///
/// A contact that is taken away leaves the table; a mouse or a pen does
/// not, and the entry that stays behind is what every singular accessor
/// reads. Its button mask is what `PointerEntry::is_contacting` answers
/// from, and a `Cancel` sample never reaches `PointerTable::admit` — so
/// before this was cleared, a stylus whose press was revoked by a modal, a
/// window deactivation or an OS drag went on reporting a held tip until the
/// next real sample, and `assert_no_leaked_pointer_state` said so.
///
/// A **pen**, not a mouse, because the legacy `WidgetEvent::PointerDown`
/// path admits `PointerInfo::mouse`, whose mask is empty — so a mouse press
/// has never read as contacting in the first place and could not show this.
/// The pen helpers build the sample the platform translator builds, mask
/// included.
#[test]
fn a_cancelled_hovering_pointer_stops_reading_as_held() {
let mut tree = WidgetTree::new();
let id_slot = Rc::new(std::cell::Cell::new(None::<WidgetId>));
let cancels = log();
// Built in one chain rather than through `recorder`: a second
// `WidgetBuilder` call on an already-wrapped `impl Widget` re-wraps
// rather than adding to the set it already has, and one wrapper is
// cheaper than two. The inner set is no longer lost either way —
// `Widget::take_handler_set` recurses and merges.
let recorded = cancels.clone();
let slot = id_slot.clone();
let node = tree.add(
FillWidget::new()
.on_pointer_cancel(move |_pointer, reason, _ctx| {
let id = slot.get().expect("the recorder's id was never recorded");
recorded.borrow_mut().push((id, reason));
})
.on_tap(|_e, _c| {}),
);
id_slot.set(Some(node));
tree.layout(SizeProposal::exact(100.0, 100.0));
tree.pen_down(Point::new(50.0, 50.0), 0.5, (0.0, 0.0));
let pen = tree
.live_pointers()
.find(|p| matches!(p.kind, teksilo_tokens::PointerKind::Pen(_)))
.map(|p| p.id)
.expect("the pen was admitted");
assert!(
tree.pointers.get(pen).is_some_and(|e| e.is_contacting()),
"the tip is on the surface"
);
let mut noop = crate::window::NoopWindowOps;
tree.cancel_pointer(pen, CancelReason::ModalOpened, &mut noop);
assert_eq!(
cancels.borrow().as_slice(),
&[(node, CancelReason::ModalOpened)],
"the node was told"
);
assert!(
tree.pointers.get(pen).is_some(),
"a pen keeps its entry: it is still in proximity, still hovering"
);
assert!(
!tree.pointers.get(pen).is_some_and(|e| e.is_contacting()),
"…but it is no longer contacting anything"
);
tree.assert_no_leaked_pointer_state();
}
}