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

//! The boundary rule, the fling, the single pinch ingress, and the palm
//! fallback, against real trees driven through the real ingress doors.

use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;

use teksilo_canvas::{Point, Rect, Size, SizeProposal};

use super::*;
use crate::WidgetId;
use crate::event::{EventResponse, Modifiers, PointerButton, ScrollDelta, WidgetEvent};
use crate::gesture::{GestureEvent, PinchPhase};
use crate::pointer::clock::ManualClock;
use crate::pointer::touch_action::{PanAxes, TouchAction};
use crate::pointer::{
    BackendDeviceKey, EventTime, PointerAxes, PointerId, PointerIdAllocator, PointerInfo,
    PointerPhase, PointerSample,
};
use crate::test_widgets::{FillWidget, StackWidget};
use crate::widget_builder::WidgetBuilder;

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// A fresh contact identity, minted through the real allocator.
fn contact_id(raw: u64) -> PointerId {
    let alloc = PointerIdAllocator::global();
    let device = BackendDeviceKey::new(0x9A11);
    let id = alloc.begin(device, raw);
    alloc.end(device, raw);
    id
}

fn contact(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(),
    }
}

/// What one test scrollable recorded.
#[derive(Default, Debug)]
struct Log {
    /// Scroll deltas the node **absorbed**, newest last.
    absorbed: Vec<f32>,
    /// Scroll deltas it was offered and declined.
    declined: Vec<f32>,
    /// Phases it was offered, in order.
    phases: Vec<ScrollPhase>,
    /// `PointerCancel`s it received.
    cancels: Vec<CancelReason>,
    /// Its scroll offset.
    offset: f32,
}

type Shared = Rc<RefCell<Log>>;

/// A test scrollable: a vertical [`PanClaim`], plus the exact `on_scroll`
/// contract `teksilo-widgets`' `common/scroll.rs` implements — clamp to
/// `[0, max]`, answer `Handled` when the axis absorbed anything and `Ignored`
/// at a hard boundary.
fn scrollable(
    log: Shared,
    max: f32,
    children: Vec<WidgetId>,
) -> impl crate::widget::Widget + 'static {
    scrollable_with(log, max, children, OverscrollBehavior::Chain)
}

/// [`scrollable`], declaring an explicit boundary policy.
///
/// Taken as a parameter rather than chained on afterwards: a second
/// `WidgetBuilder` call on an already-wrapped `impl Widget` re-wraps rather
/// than merging in place. `Widget::take_handler_set` merges the inner
/// wrapper's set through on insertion, so it costs a wasted node rather than
/// the handlers above it.
fn scrollable_with(
    log: Shared,
    max: f32,
    children: Vec<WidgetId>,
    overscroll: OverscrollBehavior,
) -> impl crate::widget::Widget + 'static {
    scrollable_options(log, max, children, overscroll, PanAxes::Y, false)
}

/// [`scrollable`], declaring its claimed axes and whether it also carries a
/// **tap handler**.
///
/// The tap handler is what makes the node an editing surface rather than a
/// plain list: a node with a gesture arena takes an implicit pointer capture on
/// `PointerDown`, which makes it the sequence's `pressed_owner`. Every text
/// surface in `teksilo-widgets` is shaped this way — it places a caret on a tap
/// *and* scrolls itself under a finger.
fn scrollable_options(
    log: Shared,
    max: f32,
    children: Vec<WidgetId>,
    overscroll: OverscrollBehavior,
    axes: PanAxes,
    takes_press: bool,
) -> impl crate::widget::Widget + 'static {
    scrollable_full(log, max, children, overscroll, axes, takes_press, None)
}

/// [`scrollable_options`], optionally also raising a **drag** from its own
/// `PointerMove` handler the first time the contact moves.
///
/// The `RichTextEditor` shape: a press inside an existing selection that has
/// travelled far enough hands the selected passage to the drag pipeline
/// (`rich_text/mouse.rs`), from the very handler the capture dispatch delivers
/// the move to. `drags` carries the source id, which the caller can only know
/// after `tree.add`, hence the cell.
#[allow(clippy::too_many_arguments)]
fn scrollable_full(
    log: Shared,
    max: f32,
    children: Vec<WidgetId>,
    overscroll: OverscrollBehavior,
    axes: PanAxes,
    takes_press: bool,
    drags: Option<Rc<std::cell::Cell<Option<WidgetId>>>>,
) -> impl crate::widget::Widget + 'static {
    let scroll_log = log.clone();
    let cancel_log = log;
    let mut stack = StackWidget::new();
    for child in children {
        stack = stack.child(child);
    }
    let widget = stack
        .scroll_container(axes)
        .overscroll_behavior(overscroll)
        .on_scroll(move |event, _ctx| {
            let WidgetEvent::Scroll { delta, phase, .. } = event else {
                return EventResponse::Ignored;
            };
            let dy = match delta {
                ScrollDelta::Pixels { y, .. } => *y,
                ScrollDelta::Lines { y, .. } => *y * 16.0,
            };
            let mut log = scroll_log.borrow_mut();
            log.phases.push(*phase);
            let before = log.offset;
            log.offset = (before + dy).clamp(0.0, max);
            let moved = (log.offset - before).abs() > crate::overscroll::SCROLL_MOVE_EPSILON;
            if moved {
                log.absorbed.push(dy);
                EventResponse::Handled
            } else {
                log.declined.push(dy);
                EventResponse::Ignored
            }
        })
        .on_pointer_cancel(move |_info, reason, _ctx| {
            cancel_log.borrow_mut().cancels.push(reason);
        });
    // Chained on the wrapper itself, never on the `impl Widget` it is returned
    // as: a `WidgetBuilder` call on an already-wrapped widget re-wraps rather
    // than merging in place, costing a wasted node — `take_handler_set` merges
    // the handlers above through it on insertion.
    let widget = if takes_press {
        widget.on_tap(|_event, _ctx| {})
    } else {
        widget
    };
    match drags {
        None => widget,
        Some(source) => {
            let raised = std::cell::Cell::new(false);
            widget.on_pointer_event(move |event, ctx| {
                if matches!(event, WidgetEvent::PointerMove { .. })
                    && !raised.get()
                    && let Some(id) = source.get()
                {
                    raised.set(true);
                    ctx.start_drag(id, crate::drag_payload::DragPayload::typed(RaisedDrag));
                }
                EventResponse::Ignored
            })
        }
    }
}

/// The payload [`scrollable_full`]'s drag carries. A distinct type so nothing
/// else in the suite can be mistaken for it.
#[derive(Debug)]
struct RaisedDrag;

/// A tree of `outer { inner }`, both scrollables, filling 200 × 200.
struct Nested {
    tree: WidgetTree,
    inner: WidgetId,
    outer: WidgetId,
    inner_log: Shared,
    outer_log: Shared,
}

fn nested(inner_max: f32, outer_max: f32) -> Nested {
    nested_inner_takes_press(inner_max, outer_max, false)
}

/// [`nested`], with the inner scrollable optionally carrying the tap handler
/// that makes it the press owner — the editing-surface shape.
fn nested_inner_takes_press(inner_max: f32, outer_max: f32, takes_press: bool) -> Nested {
    let inner_log = Shared::default();
    let outer_log = Shared::default();
    let mut tree = WidgetTree::new();
    let inner = tree.add(scrollable_options(
        inner_log.clone(),
        inner_max,
        vec![],
        OverscrollBehavior::Chain,
        PanAxes::Y,
        takes_press,
    ));
    let outer = tree.add(scrollable(outer_log.clone(), outer_max, vec![inner]));
    tree.layout(SizeProposal::exact(200.0, 200.0));
    Nested {
        tree,
        inner,
        outer,
        inner_log,
        outer_log,
    }
}

/// [`nested_inner_takes_press`], with the inner surface also **raising a drag**
/// from its own `PointerMove` handler on the first move of the contact.
fn nested_inner_drags(inner_max: f32, outer_max: f32) -> Nested {
    let inner_log = Shared::default();
    let outer_log = Shared::default();
    let mut tree = WidgetTree::new();
    let source = Rc::new(std::cell::Cell::new(None));
    let inner = tree.add(scrollable_full(
        inner_log.clone(),
        inner_max,
        vec![],
        OverscrollBehavior::Chain,
        PanAxes::Y,
        true,
        Some(source.clone()),
    ));
    source.set(Some(inner));
    let outer = tree.add(scrollable(outer_log.clone(), outer_max, vec![inner]));
    tree.layout(SizeProposal::exact(200.0, 200.0));
    Nested {
        tree,
        inner,
        outer,
        inner_log,
        outer_log,
    }
}

/// The pan slop for a contact, from the shipped touch profile.
fn pan_slop() -> f32 {
    crate::gesture::default_profile(teksilo_tokens::PointerKind::Touch)
        .pan_slop
        .expect("touch pans")
}

/// Press, then drag by `dy` in steps large enough to cross the pan slop.
///
/// Returns the finger's final position.
fn drag(tree: &mut WidgetTree, id: PointerId, from: Point, dy: f32) -> Point {
    tree.dispatch_pointer(contact(id, PointerPhase::Down, from));
    // One step past the slop to take the claim, then the movement itself.
    let arm = Point::new(from.x, from.y + pan_slop().copysign(dy) + dy.signum());
    tree.dispatch_pointer(contact(id, PointerPhase::Move, arm));
    let mut at = arm;
    let remaining = dy - (arm.y - from.y);
    if remaining.abs() > 0.0 {
        at = Point::new(from.x, arm.y + remaining);
        tree.dispatch_pointer(contact(id, PointerPhase::Move, at));
    }
    at
}

// ---------------------------------------------------------------------------
// The boundary rule
// ---------------------------------------------------------------------------

/// A finger on the inner list scrolls the **inner** list, and the outer one is
/// never offered the event while the inner can still absorb it.
#[test]
fn the_inner_container_keeps_the_claim_while_it_can_absorb() {
    let mut n = nested(1000.0, 1000.0);
    let finger = contact_id(1);
    drag(&mut n.tree, finger, Point::new(100.0, 100.0), -60.0);

    assert!(
        n.inner_log.borrow().offset > 0.0,
        "the inner list scrolled: {:?}",
        n.inner_log.borrow()
    );
    assert_eq!(
        n.outer_log.borrow().phases.len(),
        0,
        "the outer container was never offered an event the inner absorbed"
    );
}

/// At the inner list's boundary the **same whole event** goes to the outer one.
///
/// No residual and no back-channel: the delta the outer container receives is
/// bit-for-bit the delta the inner one declined, not a leftover.
#[test]
fn a_boundary_pan_hands_the_whole_event_outward_with_no_residual() {
    // The inner list has nothing to scroll, so it declines every sample.
    let mut n = nested(0.0, 1000.0);
    let finger = contact_id(2);
    drag(&mut n.tree, finger, Point::new(100.0, 100.0), -60.0);

    let inner = n.inner_log.borrow();
    let outer = n.outer_log.borrow();
    assert!(
        !inner.declined.is_empty(),
        "the inner list should have declined at its boundary"
    );
    assert!(
        !outer.absorbed.is_empty(),
        "the outer container should have taken what the inner declined"
    );
    assert_eq!(
        inner.declined, outer.absorbed,
        "the outer container receives the SAME whole deltas, never a residual"
    );
}

/// The claimant the chain moves past is told nothing at all — no
/// `PointerCancel`, and no terminal scroll phase. It did not lose the gesture.
#[test]
fn a_chained_past_claimant_gets_no_cancel_and_no_pan_ended() {
    let mut n = nested(0.0, 1000.0);
    let finger = contact_id(3);
    let at = drag(&mut n.tree, finger, Point::new(100.0, 100.0), -60.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Up, at));

    let inner = n.inner_log.borrow();
    assert!(
        inner.cancels.is_empty(),
        "the inner container must not be cancelled for declining an event: {:?}",
        inner.cancels
    );
    assert!(
        !inner.phases.contains(&ScrollPhase::Cancelled),
        "…and it must not be told the gesture was cancelled either"
    );
    // It DOES see the `Ended`, because the chain always offers it the event
    // first: the claim never left it.
    assert!(
        inner.phases.contains(&ScrollPhase::Ended),
        "the claimant is still first in line on the release"
    );
}

/// The inner container is offered the event first on **every** sample, even
/// after it declined one — the claim stays with it for the whole gesture.
#[test]
fn the_claim_does_not_move_outward_after_one_declined_event() {
    // A tiny inner range: it absorbs the first sample and then hits its end.
    let mut n = nested(4.0, 1000.0);
    let finger = contact_id(4);
    let from = Point::new(100.0, 100.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Down, from));
    let mut y = from.y;
    for _ in 0..4 {
        y -= pan_slop() + 10.0;
        n.tree
            .dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(from.x, y)));
    }

    let inner = n.inner_log.borrow();
    let outer = n.outer_log.borrow();
    assert!(
        inner.phases.len() > outer.phases.len(),
        "the inner container saw every sample ({}) and the outer only the ones \
         the inner could not use ({})",
        inner.phases.len(),
        outer.phases.len()
    );
    assert!(
        !inner.absorbed.is_empty() && !inner.declined.is_empty(),
        "the fixture must actually reach the inner boundary mid-gesture"
    );
}

/// `OverscrollBehavior::Contain` stops the chain, even having absorbed nothing.
#[test]
fn contain_stops_the_chain() {
    let inner_log = Shared::default();
    let outer_log = Shared::default();
    let mut tree = WidgetTree::new();
    let inner = tree.add(scrollable_with(
        inner_log.clone(),
        0.0,
        vec![],
        OverscrollBehavior::Contain,
    ));
    let _outer = tree.add(scrollable(outer_log.clone(), 1000.0, vec![inner]));
    tree.layout(SizeProposal::exact(200.0, 200.0));

    let finger = contact_id(5);
    drag(&mut tree, finger, Point::new(100.0, 100.0), -60.0);

    assert!(
        !inner_log.borrow().declined.is_empty(),
        "the contained container still declined the event"
    );
    assert_eq!(
        outer_log.borrow().phases.len(),
        0,
        "…and `Contain` stopped the chain before the outer container saw it"
    );
}

/// The chain visits **only** pan claimants.
///
/// This node stands for `SpinBox`, which increments its value on `on_scroll`
/// and declares no `PanClaim` at all. It sits on the bubble path between the
/// inner list and the outer container; a boundary pan that reached it would
/// silently change a number because the user ran out of list.
#[test]
fn a_boundary_pan_never_reaches_a_spin_box_shaped_on_scroll_handler() {
    let inner_log = Shared::default();
    let outer_log = Shared::default();
    let spin_box_value = Rc::new(RefCell::new(0i32));
    let value = spin_box_value.clone();

    let mut tree = WidgetTree::new();
    let inner = tree.add(scrollable(inner_log.clone(), 0.0, vec![]));
    // No `.scroll_container(..)`: a SpinBox is not a pan surface.
    let spin_box = tree.add(
        StackWidget::new()
            .child(inner)
            .on_scroll(move |_event, _ctx| {
                *value.borrow_mut() += 1;
                EventResponse::Handled
            }),
    );
    let _outer = tree.add(scrollable(outer_log.clone(), 1000.0, vec![spin_box]));
    tree.layout(SizeProposal::exact(200.0, 200.0));

    let finger = contact_id(6);
    drag(&mut tree, finger, Point::new(100.0, 100.0), -60.0);

    assert_eq!(
        *spin_box_value.borrow(),
        0,
        "a boundary pan must never reach a non-claimant `on_scroll` handler"
    );
    assert!(
        !outer_log.borrow().absorbed.is_empty(),
        "…and it must reach the next real claimant outward"
    );
}

/// The same shape again with the node that stands for `TabBar`, which remaps a
/// wheel to horizontal tab scrolling and would switch tabs under a finger.
#[test]
fn a_boundary_pan_never_reaches_a_tab_bar_shaped_wheel_remap() {
    let inner_log = Shared::default();
    let outer_log = Shared::default();
    let selected_tab = Rc::new(RefCell::new(0i32));
    let tab = selected_tab.clone();

    let mut tree = WidgetTree::new();
    let inner = tree.add(scrollable(inner_log.clone(), 0.0, vec![]));
    let tab_bar = tree.add(
        StackWidget::new()
            .child(inner)
            .on_scroll(move |event, _ctx| {
                // A TabBar's remap: any vertical wheel becomes a tab step.
                if let WidgetEvent::Scroll { delta, .. } = event {
                    let dy = match delta {
                        ScrollDelta::Pixels { y, .. } => *y,
                        ScrollDelta::Lines { y, .. } => *y,
                    };
                    *tab.borrow_mut() += dy.signum() as i32;
                }
                EventResponse::Handled
            }),
    );
    let _outer = tree.add(scrollable(outer_log.clone(), 1000.0, vec![tab_bar]));
    tree.layout(SizeProposal::exact(200.0, 200.0));

    let finger = contact_id(7);
    drag(&mut tree, finger, Point::new(100.0, 100.0), -60.0);

    assert_eq!(
        *selected_tab.borrow(),
        0,
        "a boundary pan must never reach a TabBar's wheel remap"
    );
}

/// A **mouse wheel** still bubbles: it reaches the non-claimant handler exactly
/// as it always has. The claimant chain is for fingers, and nothing else.
#[test]
fn a_mouse_wheel_still_reaches_a_non_claimant_on_scroll_handler() {
    let value = Rc::new(RefCell::new(0i32));
    let counter = value.clone();
    let mut tree = WidgetTree::new();
    let spin_box = tree.add(FillWidget::new().on_scroll(move |_event, _ctx| {
        *counter.borrow_mut() += 1;
        EventResponse::Handled
    }));
    let _root = tree.add(StackWidget::new().child(spin_box));
    tree.layout(SizeProposal::exact(200.0, 200.0));

    tree.dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 100.0)));
    tree.dispatch_event(WidgetEvent::scroll(
        ScrollDelta::Lines { x: 0.0, y: -1.0 },
        Modifiers::NONE,
    ));
    assert_eq!(*value.borrow(), 1, "the wheel bubbles, unchanged");
}

/// A pan claimant that **owns the press arena** pans itself.
///
/// The three text surfaces are shaped this way: each places a caret on a tap,
/// so its gesture arena takes the implicit capture on `PointerDown` and it
/// becomes the sequence's `pressed_owner`, and each declares a `PanClaim` so a
/// finger scrolls it. The arbitration walk stops at a `Gesture` member that is
/// the owner — the capture dispatch is already driving that recognizer — but a
/// `Pan` member is evaluated in that walk and nowhere else, so stopping there
/// too would leave the surface unable ever to win. Worse, the walk stops: the
/// container behind it would not be offered the gesture either, and a finger
/// inside the surface would scroll **nothing at all**.
#[test]
fn a_pan_claimant_that_owns_the_press_arena_pans_itself() {
    let mut n = nested_inner_takes_press(1000.0, 1000.0, true);
    let finger = contact_id(20);
    drag(&mut n.tree, finger, Point::new(100.0, 100.0), -60.0);

    assert_eq!(
        n.tree.sequence_winner(finger),
        Some(n.inner),
        "the press owner's own pan claim wins the arbitration"
    );
    assert!(
        n.inner_log.borrow().offset > 0.0,
        "…and the surface scrolls itself: {:?}",
        n.inner_log.borrow()
    );
    // The normative boundary rule, unchanged by the owner exemption: the claim
    // stays with the inner container for the whole gesture.
    assert_eq!(
        n.outer_log.borrow().phases.len(),
        0,
        "the container behind it is never offered an event the surface absorbed"
    );
}

/// The same surface **at its boundary** hands the whole pan outward, so the
/// page behind a scrolled-out editor scrolls under the finger.
///
/// This is the user-visible half of the rule above: an editing surface that
/// cannot move stops nothing.
#[test]
fn an_editing_surface_at_its_boundary_still_hands_the_pan_outward() {
    let mut n = nested_inner_takes_press(0.0, 1000.0, true);
    let finger = contact_id(21);
    drag(&mut n.tree, finger, Point::new(100.0, 100.0), -60.0);

    let inner = n.inner_log.borrow();
    let outer = n.outer_log.borrow();
    assert!(
        !inner.declined.is_empty(),
        "the surface declined at its boundary"
    );
    assert_eq!(
        inner.declined, outer.absorbed,
        "and the container behind it took the same whole deltas"
    );
}

/// The same surface **raising a drag** takes the press away from the pan
/// arbitration entirely — and the sequence is left undecided, not decided for
/// the owner.
///
/// This is the third shape the exempted press owner can be in, and the one the
/// exemption was suspected of changing. `RichTextEditor` reaches it: a press
/// inside an existing selection that travels far enough calls
/// `ctx.start_drag` from the very `PointerMove` handler the capture dispatch
/// delivers (`rich_text/mouse.rs`), and since the touch work that surface is
/// both a `Pan` claimant and the sequence's `pressed_owner`.
///
/// **What the exemption did NOT change.** `advance_sequence`'s
/// `won || self.active_drag.is_some()` arm looks as though a drag raised
/// during such a press would now name the owner the winner, since the old stop
/// rule short-circuited the walk before that line. It cannot: the router calls
/// `advance_sequence` only while `active_drag.is_none()`
/// (`pointer_router.rs`, both call sites), and `start_drag` is applied
/// synchronously when the handler returns — so a drag raised in the capture
/// dispatch closes the door on the walk for this sample and every later one.
/// Nobody wins, nobody is rejected, nobody is cancelled: the drag owns the
/// contact, which is what the hand asked for.
#[test]
fn a_drag_raised_by_the_press_owner_takes_the_press_out_of_the_arbitration() {
    use crate::gesture::MemberState;

    let mut n = nested_inner_drags(1000.0, 1000.0);
    let finger = contact_id(22);
    drag(&mut n.tree, finger, Point::new(100.0, 100.0), -60.0);

    assert!(
        n.tree
            .active_drag
            .as_ref()
            .is_some_and(|d| d.payload.has_typed::<RaisedDrag>()),
        "the surface's own drag is the one in flight"
    );
    assert_eq!(
        n.tree.sequence_winner(finger),
        None,
        "and it left the arbitration undecided rather than winning it"
    );
    assert!(
        n.tree
            .sequence_members(finger)
            .iter()
            .all(|(_, _, state)| *state == MemberState::Possible),
        "no member was decided against: {:?}",
        n.tree.sequence_members(finger)
    );
    assert_eq!(
        n.outer_log.borrow().cancels.len(),
        0,
        "so the container behind it was never cancelled"
    );
    assert_eq!(
        n.inner_log.borrow().phases.len(),
        0,
        "and nothing scrolled — the contact is dragging, not panning"
    );
    assert_eq!(n.outer_log.borrow().phases.len(), 0, "on either node");
}

/// A mouse wheel at a boundary still chains through the *bubble*, ancestor by
/// ancestor — the route it has always taken.
#[test]
fn mouse_wheel_boundary_chaining_is_unchanged() {
    let mut n = nested(0.0, 1000.0);
    n.tree
        .dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 100.0)));
    n.tree.dispatch_event(WidgetEvent::scroll(
        ScrollDelta::Pixels { x: 0.0, y: 30.0 },
        Modifiers::NONE,
    ));

    assert_eq!(
        n.inner_log.borrow().declined,
        vec![30.0],
        "the inner container declined at its boundary"
    );
    assert_eq!(
        n.outer_log.borrow().absorbed,
        vec![30.0],
        "…and the wheel bubbled to the outer container unchanged"
    );
}

// ---------------------------------------------------------------------------
// Fling
// ---------------------------------------------------------------------------

/// A fast release starts a coast, `advance_time` moves it, and it stops at the
/// boundary rather than spinning.
#[test]
fn a_release_flings_and_advance_time_moves_it() {
    let mut n = nested(10_000.0, 10_000.0);
    let clock = Rc::new(ManualClock::new(EventTime::ZERO));
    n.tree.set_input_clock(clock.clone());

    let finger = contact_id(8);
    let from = Point::new(100.0, 180.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Down, from));
    // A fast flick: 20 dp every 4 ms = 5000 dp/s, well past
    // `min_fling_velocity`.
    let mut y = from.y;
    for step in 1..=5 {
        clock.set(EventTime::from_millis(step * 4));
        y -= 20.0;
        n.tree
            .dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(from.x, y)));
    }
    clock.set(EventTime::from_millis(24));
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Up, Point::new(from.x, y)));

    assert!(
        n.tree.is_flinging(n.inner),
        "a fast release hands off to a coast"
    );
    let after_release = n.inner_log.borrow().offset;

    n.tree.advance_time(Duration::from_millis(100));
    let coasting = n.inner_log.borrow().offset;
    assert!(
        coasting > after_release,
        "one `advance_time` moves the fling: {after_release} -> {coasting}"
    );

    // Let it run out. How long that takes is the platform's: the clamping
    // curve settles well inside a second, the friction curve the Apple
    // platforms resolve `ScrollPhysics::Platform` to decays exponentially and
    // takes about three seconds from this velocity. The ceiling is generous
    // for both, and what is asserted is only that the coast ends.
    let mut advanced = Duration::ZERO;
    while n.tree.is_flinging(n.inner) && advanced < Duration::from_secs(10) {
        n.tree.advance_time(Duration::from_millis(50));
        advanced += Duration::from_millis(50);
    }
    assert!(
        !n.tree.is_flinging(n.inner),
        "the coast finishes rather than running for ever"
    );
}

/// **One** `advance_time` moves an animation and a live fling to the same
/// virtual now.
///
/// The two used to answer to different doors: `advance_time` pumped the coast
/// and left the scheduler frozen, `tick_animations` ticked the scheduler and
/// left the coast frozen, and each advanced the simulated clock on its own — so
/// calling both moved the clock twice and there was no sequence of calls that
/// put the animation and the fling at the same instant.
///
/// Timed entirely by the clock under test: no `ManualClock` anywhere, so the
/// flick's own velocity comes off the same axis the coast is later ticked on.
#[test]
fn one_advance_time_moves_an_animation_and_a_fling_to_the_same_virtual_time() {
    let mut n = nested(10_000.0, 10_000.0);
    let signal = crate::signal::Signal::<f32>::new_animated(0.0);
    n.tree.register_animated_signal(&signal, n.inner);

    // A fast flick — 20 dp every 4 ms — with the intervals supplied by
    // `advance_input_time`, which is `advance_time` under the name the input
    // side reads by.
    let finger = contact_id(21);
    let from = Point::new(100.0, 180.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Down, from));
    let mut y = from.y;
    for _ in 0..5 {
        n.tree.advance_input_time(Duration::from_millis(4));
        y -= 20.0;
        n.tree
            .dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(from.x, y)));
    }
    n.tree.advance_input_time(Duration::from_millis(4));
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Up, Point::new(from.x, y)));
    assert!(
        n.tree.is_flinging(n.inner),
        "the flick handed off to a coast"
    );

    signal.animate_to(
        100.0,
        Duration::from_millis(200),
        teksilo_tokens::Easing::Linear,
    );
    let before = n.inner_log.borrow().offset;

    // One call.
    n.tree.advance_time(Duration::from_millis(100));

    assert!(
        (signal.get() - 50.0).abs() < 2.0,
        "half of a 200 ms linear tween: {}",
        signal.get()
    );
    assert!(
        n.inner_log.borrow().offset > before,
        "…and the coast moved in the same call: {before} -> {}",
        n.inner_log.borrow().offset
    );
}

/// A fling that runs out of inner list scrolls the outer one — the same chain,
/// the same rule, and the inner container is still told nothing terminal.
#[test]
fn a_fling_chains_at_a_boundary_exactly_as_a_pan_does() {
    // The inner list can take 30 dp and no more; the outer is deep.
    let mut n = nested(30.0, 10_000.0);
    let clock = Rc::new(ManualClock::new(EventTime::ZERO));
    n.tree.set_input_clock(clock.clone());

    let finger = contact_id(9);
    let from = Point::new(100.0, 180.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Down, from));
    let mut y = from.y;
    for step in 1..=5 {
        clock.set(EventTime::from_millis(step * 4));
        y -= 20.0;
        n.tree
            .dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(from.x, y)));
    }
    clock.set(EventTime::from_millis(24));
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Up, Point::new(from.x, y)));
    assert!(n.tree.is_flinging(n.inner));

    let outer_before = n.outer_log.borrow().offset;
    for _ in 0..20 {
        n.tree.advance_time(Duration::from_millis(16));
    }

    assert_eq!(
        n.inner_log.borrow().offset,
        30.0,
        "the inner list is pinned at its end"
    );
    assert!(
        n.outer_log.borrow().offset > outer_before,
        "…and the coast chained outward"
    );
    assert!(
        n.inner_log.borrow().cancels.is_empty(),
        "chaining a fling cancels nobody either"
    );
}

/// A press on a coasting surface catches it.
#[test]
fn a_pointer_down_on_a_flinging_target_stops_the_fling() {
    let mut n = nested(10_000.0, 10_000.0);
    let clock = Rc::new(ManualClock::new(EventTime::ZERO));
    n.tree.set_input_clock(clock.clone());

    let finger = contact_id(10);
    let from = Point::new(100.0, 180.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Down, from));
    let mut y = from.y;
    for step in 1..=5 {
        clock.set(EventTime::from_millis(step * 4));
        y -= 20.0;
        n.tree
            .dispatch_pointer(contact(finger, PointerPhase::Move, Point::new(from.x, y)));
    }
    clock.set(EventTime::from_millis(24));
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Up, Point::new(from.x, y)));
    assert!(n.tree.is_flinging(n.inner));

    let catcher = contact_id(11);
    n.tree.dispatch_pointer(contact(
        catcher,
        PointerPhase::Down,
        Point::new(100.0, 100.0),
    ));
    assert!(
        !n.tree.is_flinging(n.inner),
        "pressing a coasting list catches it"
    );
}

/// macOS reports its own momentum. Starting a Teksilo fling on top of that is
/// the double-momentum bug, so a momentum-phase release must add nothing —
/// which is the rule [`KineticScroller::should_fling_for_phase`] states and
/// which the pan path inherits by never treating a momentum sample as a
/// release at all.
#[test]
fn macos_momentum_does_not_stack_a_second_fling() {
    let mut n = nested(10_000.0, 10_000.0);
    n.tree
        .dispatch_event(WidgetEvent::pointer_move(Point::new(100.0, 100.0)));
    // The OS momentum stream: pixel deltas with `phase: Momentum`, routed as
    // an ordinary (bubbling) trackpad scroll.
    for _ in 0..5 {
        n.tree.dispatch_scroll(crate::pointer::ScrollSample {
            delta: ScrollDelta::Pixels { x: 0.0, y: 20.0 },
            position: Some(Point::new(100.0, 100.0)),
            phase: ScrollPhase::Momentum,
            source: crate::pointer::ScrollSource::Trackpad,
            pointer: PointerInfo::mouse(EventTime::ZERO),
            modifiers: Modifiers::NONE,
        });
    }
    assert!(
        n.inner_log.borrow().offset > 0.0,
        "the OS momentum still scrolls the list"
    );
    assert!(
        !n.tree.is_flinging(n.inner) && !n.tree.is_flinging(n.outer),
        "…and no Teksilo coast is started on top of it"
    );
}

/// The fling is an input deadline like any other, and it is folded into the one
/// `WaitUntil`.
#[test]
fn next_input_deadline_folds_a_live_simulation() {
    let mut n = nested(10_000.0, 10_000.0);
    assert_eq!(
        n.tree.next_input_deadline(),
        None,
        "nothing pending, nothing to wake for"
    );
    // What the tree wanted the loop back for *before* the fling — so that the
    // equality below is a statement about the fold having gained a term, not
    // one that some unrelated deadline happened to satisfy.
    let before = n.tree.next_timer_deadline();

    n.tree.start_fling(
        n.inner,
        Vec2::new(0.0, 2000.0),
        vec![(n.inner, PanClaim::vertical())],
    );
    assert!(n.tree.is_flinging(n.inner));
    let deadline = n
        .tree
        .next_input_deadline()
        .expect("a live simulation wants the loop back");
    // `<= Some(deadline)` would not say this: `None < Some(_)`, so a fold that
    // dropped the input term entirely would satisfy it.
    assert_eq!(
        n.tree.next_timer_deadline(),
        Some(deadline),
        "…and the tree's one `WaitUntil` IS the input deadline — it was \
         {before:?} before the fling started"
    );

    n.tree.stop_fling(n.inner);
    assert_eq!(n.tree.next_input_deadline(), None);
}

/// `prefers-reduced-motion` collapses the coast: the content stays where the
/// finger left it.
#[test]
fn reduced_motion_starts_no_coast() {
    let mut n = nested(10_000.0, 10_000.0);
    n.tree.set_accessibility_preferences(false, true, 1.0);
    n.tree.start_fling(
        n.inner,
        Vec2::new(0.0, 4000.0),
        vec![(n.inner, PanClaim::vertical())],
    );
    assert!(!n.tree.is_flinging(n.inner));
}

// ---------------------------------------------------------------------------
// Pinch — the two ingresses
// ---------------------------------------------------------------------------

/// Everything one `on_pinch` handler was told, in order, in a form two runs can
/// be compared by.
#[derive(Clone, Debug, PartialEq)]
enum PinchNote {
    Started,
    Changed { scale: i32, rotation: i32 },
    Ended,
}

fn pinch_recorder(notes: Rc<RefCell<Vec<PinchNote>>>) -> impl crate::widget::Widget + 'static {
    FillWidget::new()
        .touch_action(TouchAction::MANIPULATION)
        .on_pinch(move |phase, _ctx| {
            let note = match phase {
                PinchPhase::Started { .. } => PinchNote::Started,
                PinchPhase::Changed {
                    scale, rotation, ..
                } => PinchNote::Changed {
                    // Quantised so the two runs are compared on what a consumer
                    // acts on rather than on float noise.
                    scale: (scale * 1000.0).round() as i32,
                    rotation: (rotation * 1000.0).round() as i32,
                },
                PinchPhase::Ended { .. } => PinchNote::Ended,
                _ => return,
            };
            notes.borrow_mut().push(note);
        })
}

/// **The point of the package.** Two contacts and the OS trackpad stream
/// produce the *same* pinch stream, because both go through the one ingress.
///
/// *Contract change.* Both arms of this test used to describe the span ratio
/// against the *start* of the gesture (`span / 100.0`), which is what the touch
/// recognizer emitted and what the OS arm was hand-fed to match. It could not be
/// what the OS arm really produces — winit reports a change per event — so the
/// parity was between the recognizer and a fixture, not between the two
/// producers. [`GestureEvent::PinchChanged`] now states a per-sample contract;
/// both arms describe the same geometry in those terms, so the second sample
/// reads 200/140 rather than 200/100 and the two streams are still identical.
#[test]
fn the_two_pinch_ingresses_produce_the_same_stream() {
    // The geometry both runs describe: two contacts 100 dp apart, spreading to
    // 200 dp in two steps, then one lifts.
    let start_span = 100.0f32;
    let spans = [140.0f32, 200.0f32];
    // The same geometry as the per-sample steps the contract asks for: each
    // span over the one before it.
    let steps: Vec<f32> = std::iter::once(start_span)
        .chain(spans)
        .collect::<Vec<_>>()
        .windows(2)
        .map(|w| w[1] / w[0])
        .collect();

    // --- ingress 1: two real contacts ---------------------------------
    let touch_notes = Rc::new(RefCell::new(Vec::new()));
    let mut tree = WidgetTree::new();
    tree.add(pinch_recorder(touch_notes.clone()));
    tree.layout(SizeProposal::exact(400.0, 400.0));

    let a = contact_id(20);
    let b = contact_id(21);
    let centre = 200.0f32;
    tree.dispatch_pointer(contact(
        a,
        PointerPhase::Down,
        Point::new(centre - 50.0, 200.0),
    ));
    tree.dispatch_pointer(contact(
        b,
        PointerPhase::Down,
        Point::new(centre + 50.0, 200.0),
    ));
    for span in spans {
        tree.dispatch_pointer(contact(
            b,
            PointerPhase::Move,
            Point::new(centre - 50.0 + span, 200.0),
        ));
    }
    tree.dispatch_pointer(contact(
        a,
        PointerPhase::Up,
        Point::new(centre - 50.0, 200.0),
    ));

    // --- ingress 2: the OS trackpad stream ----------------------------
    let os_notes = Rc::new(RefCell::new(Vec::new()));
    let mut os_tree = WidgetTree::new();
    os_tree.add(pinch_recorder(os_notes.clone()));
    os_tree.layout(SizeProposal::exact(400.0, 400.0));

    let mut ops = crate::window::NoopWindowOps;
    // The OS reports the same geometry: a start, then the same two scales, then
    // an end. Centres match because the first contact never moved.
    os_tree.dispatch_os_gesture(
        GestureEvent::PinchStarted {
            center: Point::new(centre, 200.0),
        },
        Some(Point::new(centre, 200.0)),
        &mut ops,
    );
    for (span, step) in spans.iter().zip(&steps) {
        let center = Point::new(centre - 50.0 + span / 2.0, 200.0);
        os_tree.dispatch_os_gesture(
            GestureEvent::PinchChanged {
                center,
                scale: *step,
                rotation: 0.0,
            },
            Some(center),
            &mut ops,
        );
    }
    os_tree.dispatch_os_gesture(GestureEvent::PinchEnded, None, &mut ops);

    assert_eq!(
        *touch_notes.borrow(),
        vec![
            PinchNote::Started,
            // 140/100 — the step since the start.
            PinchNote::Changed {
                scale: 1400,
                rotation: 0
            },
            // 200/140 — the step since the previous sample, not 200/100.
            PinchNote::Changed {
                scale: 1429,
                rotation: 0
            },
            PinchNote::Ended,
        ],
        "the touchscreen stream is Started / Changed × 2 / Ended, carrying \
         per-sample steps"
    );
    let folded: f32 = touch_notes
        .borrow()
        .iter()
        .filter_map(|n| match n {
            PinchNote::Changed { scale, .. } => Some(*scale as f32 / 1000.0),
            _ => None,
        })
        .product();
    assert!(
        (folded - 2.0).abs() < 1e-2,
        "and folding them in reaches the ×2 spread the fingers described, got {folded}"
    );
    assert_eq!(
        *touch_notes.borrow(),
        *os_notes.borrow(),
        "the two ingresses must produce the same stream — that is the whole point"
    );
}

/// A third contact never disturbs a running pinch.
#[test]
fn a_third_contact_is_ignored_by_the_tree() {
    let notes = Rc::new(RefCell::new(Vec::new()));
    let mut tree = WidgetTree::new();
    tree.add(pinch_recorder(notes.clone()));
    tree.layout(SizeProposal::exact(400.0, 400.0));

    let a = contact_id(22);
    let b = contact_id(23);
    let c = contact_id(24);
    tree.dispatch_pointer(contact(a, PointerPhase::Down, Point::new(150.0, 200.0)));
    tree.dispatch_pointer(contact(b, PointerPhase::Down, Point::new(250.0, 200.0)));
    let after_start = notes.borrow().len();

    tree.dispatch_pointer(contact(c, PointerPhase::Down, Point::new(200.0, 350.0)));
    tree.dispatch_pointer(contact(c, PointerPhase::Move, Point::new(200.0, 380.0)));
    assert_eq!(
        notes.borrow().len(),
        after_start,
        "the third contact produced no pinch phase at all"
    );
    assert!(tree.touch_pinch_active(), "…and the pinch is still running");
}

/// A contact leaving mid-pinch ends the gesture.
#[test]
fn a_contact_leaving_mid_pinch_ends_it() {
    let notes = Rc::new(RefCell::new(Vec::new()));
    let mut tree = WidgetTree::new();
    tree.add(pinch_recorder(notes.clone()));
    tree.layout(SizeProposal::exact(400.0, 400.0));

    let a = contact_id(25);
    let b = contact_id(26);
    tree.dispatch_pointer(contact(a, PointerPhase::Down, Point::new(150.0, 200.0)));
    tree.dispatch_pointer(contact(b, PointerPhase::Down, Point::new(250.0, 200.0)));
    tree.dispatch_pointer(contact(a, PointerPhase::Up, Point::new(150.0, 200.0)));

    assert_eq!(notes.borrow().last(), Some(&PinchNote::Ended));
    assert!(!tree.touch_pinch_active());
}

/// A subtree that forbids pinch-zoom gets none.
#[test]
fn touch_action_none_permits_no_pinch() {
    let notes = Rc::new(RefCell::new(Vec::new()));
    let mut tree = WidgetTree::new();
    let inner = tree.add(pinch_recorder(notes.clone()));
    // The ancestor narrows to NONE, which intersection makes absorbing.
    let _root = tree.add(
        StackWidget::new()
            .child(inner)
            .touch_action(TouchAction::NONE),
    );
    tree.layout(SizeProposal::exact(400.0, 400.0));

    let a = contact_id(27);
    let b = contact_id(28);
    tree.dispatch_pointer(contact(a, PointerPhase::Down, Point::new(150.0, 200.0)));
    tree.dispatch_pointer(contact(b, PointerPhase::Down, Point::new(250.0, 200.0)));
    assert!(notes.borrow().is_empty());
    assert!(!tree.touch_pinch_active());
}

// ---------------------------------------------------------------------------
// Palm
// ---------------------------------------------------------------------------

/// A large contact patch that never moves fires no tap and is cancelled
/// `PalmRejected`.
#[test]
fn a_large_stationary_contact_is_rejected_as_a_palm() {
    let taps = Rc::new(RefCell::new(0i32));
    let cancels = Rc::new(RefCell::new(Vec::new()));
    let tap_count = taps.clone();
    let cancel_log = cancels.clone();

    let mut tree = WidgetTree::new();
    tree.add(
        FillWidget::new()
            .on_tap(move |_e, _c| *tap_count.borrow_mut() += 1)
            .on_pointer_cancel(move |_info, reason, _c| cancel_log.borrow_mut().push(reason)),
    );
    tree.layout(SizeProposal::exact(200.0, 200.0));
    assert!(
        tree.palm_fallback_active(),
        "the fallback is on for a backend that reports no palms"
    );

    let palm = contact_id(30);
    let at = Point::new(100.0, 100.0);
    let mut down = contact(palm, PointerPhase::Down, at);
    down.pointer.axes = PointerAxes {
        contact: Some(Size::new(70.0, 70.0)),
        ..down.pointer.axes
    };
    let mut up = contact(palm, PointerPhase::Up, at);
    up.pointer.axes = down.pointer.axes;

    tree.dispatch_pointer(down);
    tree.dispatch_pointer(up);

    assert_eq!(*taps.borrow(), 0, "a palm fires no tap");
    assert_eq!(
        *cancels.borrow(),
        vec![CancelReason::PalmRejected],
        "…and is revoked with the reason that says why"
    );
}

/// A fingertip taps normally, and so does a large contact that actually
/// travelled — false-rejecting a real gesture is the worse failure, so the
/// heuristic needs *both* halves to be true.
#[test]
fn a_fingertip_and_a_travelling_large_contact_both_tap() {
    for (extent, travel) in [(12.0f32, 0.0f32), (70.0, 40.0)] {
        let taps = Rc::new(RefCell::new(0i32));
        let cancels = Rc::new(RefCell::new(Vec::new()));
        let counter = taps.clone();
        let cancel_log = cancels.clone();
        let mut tree = WidgetTree::new();
        tree.add(
            FillWidget::new()
                .on_tap(move |_e, _c| *counter.borrow_mut() += 1)
                .on_pointer_cancel(move |_i, reason, _c| cancel_log.borrow_mut().push(reason)),
        );
        tree.layout(SizeProposal::exact(200.0, 200.0));

        let finger = contact_id(31);
        let from = Point::new(100.0, 100.0);
        let axes = PointerAxes {
            contact: Some(Size::new(extent, extent)),
            ..PointerAxes::default()
        };
        let mut down = contact(finger, PointerPhase::Down, from);
        down.pointer.axes = axes;
        tree.dispatch_pointer(down);
        let to = Point::new(from.x + travel, from.y);
        if travel > 0.0 {
            let mut moved = contact(finger, PointerPhase::Move, to);
            moved.pointer.axes = axes;
            tree.dispatch_pointer(moved);
        }
        let mut up = contact(finger, PointerPhase::Up, to);
        up.pointer.axes = axes;
        tree.dispatch_pointer(up);

        assert_eq!(
            *taps.borrow(),
            1,
            "extent {extent}, travel {travel}: the tap must stand"
        );
        assert!(
            cancels.borrow().is_empty(),
            "extent {extent}, travel {travel}: and nothing may be revoked — \
             got {:?}",
            cancels.borrow()
        );
    }
}

/// A backend that classifies palms itself turns the heuristic off.
#[test]
fn a_palm_reporting_backend_disables_the_fallback() {
    let taps = Rc::new(RefCell::new(0i32));
    let counter = taps.clone();
    let mut tree = WidgetTree::new();
    tree.add(FillWidget::new().on_tap(move |_e, _c| *counter.borrow_mut() += 1));
    tree.layout(SizeProposal::exact(200.0, 200.0));
    tree.set_backend_reports_palm(true);
    assert!(!tree.palm_fallback_active());

    let big = contact_id(32);
    let at = Point::new(100.0, 100.0);
    let axes = PointerAxes {
        contact: Some(Size::new(70.0, 70.0)),
        ..PointerAxes::default()
    };
    let mut down = contact(big, PointerPhase::Down, at);
    down.pointer.axes = axes;
    let mut up = contact(big, PointerPhase::Up, at);
    up.pointer.axes = axes;
    tree.dispatch_pointer(down);
    tree.dispatch_pointer(up);

    assert_eq!(
        *taps.borrow(),
        1,
        "with the digitiser answering, the guess is off and the tap stands"
    );
}

// ---------------------------------------------------------------------------
// Routing
// ---------------------------------------------------------------------------

/// The route is decided by the source, and only a synthesised pan chains.
#[test]
fn only_a_touch_pan_takes_the_claimant_chain() {
    use crate::pointer::ScrollSource;
    assert_eq!(
        ScrollDelivery::for_source(ScrollSource::TouchPan),
        ScrollDelivery::ClaimantChain
    );
    for source in [
        ScrollSource::Wheel,
        ScrollSource::Trackpad,
        ScrollSource::Programmatic,
    ] {
        assert_eq!(
            ScrollDelivery::for_source(source),
            ScrollDelivery::Bubble,
            "{source:?} keeps the route it has always had"
        );
    }
}

/// A `TouchPan` sample from a backend that recognises pans itself derives its
/// own chain from the sample's position — the door P18 uses.
#[test]
fn an_external_touch_pan_sample_derives_its_own_chain() {
    let mut n = nested(0.0, 1000.0);
    n.tree.dispatch_scroll(crate::pointer::ScrollSample {
        delta: ScrollDelta::Pixels { x: 0.0, y: 40.0 },
        position: Some(Point::new(100.0, 100.0)),
        phase: ScrollPhase::Changed,
        source: crate::pointer::ScrollSource::TouchPan,
        pointer: PointerInfo::touch(contact_id(40), EventTime::ZERO),
        modifiers: Modifiers::NONE,
    });
    assert_eq!(
        n.inner_log.borrow().declined,
        vec![40.0],
        "the innermost claimant was offered it first"
    );
    assert_eq!(
        n.outer_log.borrow().absorbed,
        vec![40.0],
        "…and it chained outward whole"
    );
}

/// A claimant destroyed mid-gesture is skipped, not treated as the end of the
/// chain: the containers outward of it are still entitled to the event.
#[test]
fn a_destroyed_claimant_is_skipped_rather_than_ending_the_chain() {
    let mut n = nested(0.0, 1000.0);
    let finger = contact_id(41);
    n.tree.dispatch_pointer(contact(
        finger,
        PointerPhase::Down,
        Point::new(100.0, 100.0),
    ));
    n.tree.destroy_subtree(n.inner);
    n.tree.dispatch_pointer(contact(
        finger,
        PointerPhase::Move,
        Point::new(100.0, 100.0 - pan_slop() - 20.0),
    ));

    assert!(
        !n.outer_log.borrow().absorbed.is_empty(),
        "the outer container still received the pan"
    );
}

/// A cancel takes the pan and the coast with it, and tells nobody a lie.
#[test]
fn a_cancel_abandons_the_pan_and_stops_the_coast() {
    let mut n = nested(10_000.0, 10_000.0);
    let finger = contact_id(42);
    let from = Point::new(100.0, 180.0);
    drag(&mut n.tree, finger, from, -60.0);
    n.tree.start_fling(
        n.inner,
        Vec2::new(0.0, 3000.0),
        vec![(n.inner, PanClaim::vertical())],
    );
    assert!(n.tree.is_flinging(n.inner));

    let mut ops = crate::window::NoopWindowOps;
    n.tree
        .cancel_pointer(finger, CancelReason::Platform, &mut ops);

    assert!(
        !n.tree.is_flinging(n.inner),
        "the coast the revoked gesture owned is stopped"
    );
    let before = n.inner_log.borrow().phases.len();
    n.tree.dispatch_pointer(contact(
        finger,
        PointerPhase::Move,
        Point::new(100.0, 100.0),
    ));
    assert_eq!(
        n.inner_log.borrow().phases.len(),
        before,
        "and the abandoned pan delivers nothing more"
    );
}

/// The synthesised scroll carries the wheel's sign convention: a finger
/// dragging **up** scrolls the content down, i.e. the offset increases.
#[test]
fn a_pan_carries_the_wheel_sign_convention() {
    let mut n = nested(1000.0, 1000.0);
    let finger = contact_id(43);
    drag(&mut n.tree, finger, Point::new(100.0, 150.0), -60.0);
    assert!(
        n.inner_log.borrow().offset > 0.0,
        "dragging up increases the offset, exactly as a wheel-down does"
    );

    let mut m = nested(1000.0, 1000.0);
    m.inner_log.borrow_mut().offset = 500.0;
    let other = contact_id(44);
    drag(&mut m.tree, other, Point::new(100.0, 50.0), 60.0);
    assert!(
        m.inner_log.borrow().offset < 500.0,
        "and dragging down decreases it"
    );
}

/// A pan reports phases in the order a continuous gesture has: one `Began`,
/// then `Changed`, then exactly one `Ended`.
#[test]
fn the_synthesised_phases_read_as_one_continuous_gesture() {
    let mut n = nested(10_000.0, 10_000.0);
    let finger = contact_id(45);
    let at = drag(&mut n.tree, finger, Point::new(100.0, 180.0), -60.0);
    n.tree
        .dispatch_pointer(contact(finger, PointerPhase::Up, at));

    let phases = n.inner_log.borrow().phases.clone();
    assert_eq!(phases.first(), Some(&ScrollPhase::Began));
    assert_eq!(phases.last(), Some(&ScrollPhase::Ended));
    assert_eq!(
        phases.iter().filter(|p| **p == ScrollPhase::Began).count(),
        1,
        "exactly one Began"
    );
    assert_eq!(
        phases.iter().filter(|p| **p == ScrollPhase::Ended).count(),
        1,
        "exactly one Ended"
    );
}

/// `Rect` is used only to keep the fixture honest about geometry; this asserts
/// the nested fixture really does put the inner container inside the outer one,
/// so every chaining test above is testing what it says it is.
#[test]
fn the_nested_fixture_really_nests() {
    let n = nested(100.0, 100.0);
    let inner = n.tree.bounds(n.inner);
    let outer = n.tree.bounds(n.outer);
    assert_eq!(outer, Rect::new(0.0, 0.0, 200.0, 200.0));
    assert_eq!(inner, outer, "the inner container fills the outer one");
    assert!(
        n.tree
            .pan_candidates(n.inner, TouchAction::AUTO)
            .iter()
            .map(|(id, _)| *id)
            .eq([n.inner, n.outer]),
        "…and the claimant chain is inner-then-outer"
    );
}

/// A press with the primary button is what a contact reports; the fixture would
/// be testing nothing if the tap owner never saw one.
#[test]
fn a_contact_presses_as_the_primary_button() {
    let seen = Rc::new(RefCell::new(None));
    let button = seen.clone();
    let mut tree = WidgetTree::new();
    tree.add(FillWidget::new().on_tap(move |event, _c| {
        *button.borrow_mut() = Some(event.button);
    }));
    tree.layout(SizeProposal::exact(100.0, 100.0));

    let finger = contact_id(46);
    let at = Point::new(50.0, 50.0);
    tree.dispatch_pointer(contact(finger, PointerPhase::Down, at));
    tree.dispatch_pointer(contact(finger, PointerPhase::Up, at));
    assert_eq!(*seen.borrow(), Some(PointerButton::Primary));
}