nsh-core 0.7.1

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

use crate::{
    Bounds, EdgeInsets, EventKind, EventMask, GestureValues, NodeId, PanActivation, Point, Points,
    ROOT_ID, Size, ViewKind,
    geometry::Radians,
    tailwind::state::{FOCUSED, HOVERED, PRESSED},
};

/// Distance a pointer moves before a pan or scroll drag starts.
pub const PAN_SLOP: Points = Points(6.0);
/// Distance a pointer moves before its press is cancelled.
pub const PRESS_SLOP: Points = Points(10.0);
/// How far outside the pressed view (and its hit slop) a release still
/// counts as a press.
pub const PRESS_RETENTION: Points = Points(8.0);
/// Mouse wheel notches this close together (ms) are one scroll: they stay
/// on the scroll view the first one moved.
pub const WHEEL_LATCH: f64 = 200.0;
/// A precise (touchpad) scroll without phases ends once its deltas stop
/// for this long (ms).
pub const TOUCHPAD_IDLE: f64 = 150.0;
/// Scale one Ctrl + wheel notch pinches by.
pub const ZOOM_STEP: f32 = 1.1;
/// Points of one wheel notch at Windows' default (three lines of 16
/// points): Ctrl + wheel deltas in points are counted in these.
pub const ZOOM_NOTCH: Points = Points(48.0);
/// A Ctrl + wheel pinch ends once the notches stop for this long (ms).
pub const ZOOM_IDLE: u64 = 300;
/// Delay before `onPressDown` for touches inside scroll views (ms).
pub const SCROLL_PRESS_DELAY: u64 = 130;
/// Default `delayLongPress` (ms).
pub const LONG_PRESS: f32 = 500.0;
/// Velocities are measured over this many milliseconds.
pub const VELOCITY_WINDOW: f64 = 100.0;
/// Minimum duration a completed short press holds its `PRESSED` visual
/// state so a same-turn tap-to-click renders `:active` feedback.
pub const TAP_FEEDBACK: std::time::Duration = std::time::Duration::from_millis(64);

/// How long to hold a completed short press's `PRESSED` state after a
/// pointer release `elapsed` after the press began; `None` when the press
/// lasted at least [`TAP_FEEDBACK`], was `cancelled`, or visual feedback
/// must end `immediate`ly (reduced motion, automated tests).
pub fn tap_feedback_delay(
    elapsed: std::time::Duration,
    cancelled: bool,
    immediate: bool,
) -> Option<std::time::Duration> {
    if cancelled || immediate {
        return None;
    }
    TAP_FEEDBACK.checked_sub(elapsed).filter(|d| !d.is_zero())
}

/// Estimates a pointer's velocity from its recent positions (points).
#[derive(Debug, Clone, Copy, Default)]
pub struct VelocityTracker {
    samples: [(f64, f32, f32); VelocityTracker::LEN],
    count: usize,
    head: usize,
}

impl VelocityTracker {
    const LEN: usize = 16;

    /// The pointer is `at` a point at `time` (ms).
    pub fn add(&mut self, time: f64, at: Point<Points>) {
        self.samples[self.head] = (time, at.x.0, at.y.0);
        self.head = (self.head + 1) % Self::LEN;
        self.count = (self.count + 1).min(Self::LEN);
    }

    /// Points per second over the last [`VELOCITY_WINDOW`] ms (zero after
    /// a pause).
    pub fn velocity(&self) -> (f32, f32) {
        if self.count < 2 {
            return (0.0, 0.0);
        }
        let at = |i: usize| self.samples[(self.head + Self::LEN - 1 - i) % Self::LEN];
        let newest = at(0);
        let mut oldest = newest;
        for i in 1..self.count {
            let s = at(i);
            if newest.0 - s.0 > VELOCITY_WINDOW {
                break;
            }
            oldest = s;
        }
        let dt = newest.0 - oldest.0;
        if dt < 1.0 {
            return (0.0, 0.0);
        }
        let k = (1000.0 / dt) as f32;
        ((newest.1 - oldest.1) * k, (newest.2 - oldest.2) * k)
    }
}

// --- Drags --------------------------------------------------------------------------

/// What a drag on a view may start.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Candidate {
    /// A pan along these axes (both when it only has listeners).
    Pan {
        /// It pans horizontally.
        x: bool,
        /// It pans vertically.
        y: bool,
        /// The view's `panActivation`, which decides instead of the axes.
        #[doc(hidden)]
        activation: Option<PanActivation>,
    },
    /// A scroll view.
    Scroll {
        /// It scrolls horizontally.
        horizontal: bool,
    },
}

impl Candidate {
    /// Whether a drag by `(dx, dy)` starts it: single-axis pans and scroll
    /// views take mostly-along-their-axis movements, so a horizontal pan
    /// coexists with a vertical scroll view around it; a pan with a
    /// `panActivation` starts when that activates.
    pub fn accepts(self, dx: Points, dy: Points) -> bool {
        let horizontal = dx.0.abs() > dy.0.abs();
        match self {
            Candidate::Pan {
                activation: Some(activation),
                ..
            } => activation.decide(dx, dy) == Some(true),
            Candidate::Pan { x, y, .. } => (x && y) || (x && horizontal) || (y && !horizontal),
            Candidate::Scroll { horizontal: h } => h == horizontal,
        }
    }

    /// The pan a view with gesture `values`, `events` and `activation`
    /// starts: along the axes it drives values of, or both when it only
    /// listens, as its activation decides when it has one. For the
    /// backends.
    #[doc(hidden)]
    pub fn pan(
        values: &GestureValues,
        events: EventMask,
        activation: Option<PanActivation>,
    ) -> Option<Candidate> {
        let pans = values.pan_x.is_some()
            || values.pan_y.is_some()
            || events.contains(EventKind::PanStart)
            || events.contains(EventKind::PanEnd);
        pans.then(|| {
            let (x, y) = match (values.pan_x.is_some(), values.pan_y.is_some()) {
                (false, false) => (true, true),
                axes => axes,
            };
            Candidate::Pan { x, y, activation }
        })
    }
}

/// The `panActivation` the gate of a view with gesture `values`, `events`
/// and `activation` decides with: its activation while something follows
/// it, the view's own native pan (`pan` values, `onPanStart` /
/// `onPanEnd`) or its responder (`onTouch`: the responder system, Rust
/// claims); none otherwise. A view whose pan is off (`pan_enabled(false)`)
/// then leaves the drags to its content and to the views around it, as
/// with no activation (a stack's swipe back inside a drawer). For the
/// backends.
#[doc(hidden)]
pub fn gate_activation(
    values: &GestureValues,
    events: EventMask,
    activation: Option<PanActivation>,
) -> Option<PanActivation> {
    activation.filter(|_| {
        events.contains(EventKind::Touch) || Candidate::pan(values, events, None).is_some()
    })
}

/// A view's `panActivation` deciding on a pointer's drag.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Gate {
    id: NodeId,
    activation: PanActivation,
    outer: usize,
    /// The pointer's offset at the last step.
    last: Point<Points>,
}

impl Gate {
    /// The gate of view `id`, whose candidates from index `outer` on are
    /// around it: they wait for its pan to fail.
    pub fn new(id: NodeId, activation: PanActivation, outer: usize) -> Gate {
        Gate {
            id,
            activation,
            outer,
            last: Point::default(),
        }
    }

    /// The index of the first candidate around the gated view.
    pub fn outer(&self) -> usize {
        self.outer
    }

    /// Decides on a drag by `(dx, dy)` from where the pointer went down:
    /// the gated view when its pan activates (the candidates around it are
    /// dropped), and whether the gate is still undecided.
    pub fn decide<V, C>(
        &self,
        candidates: &mut Vec<(V, C)>,
        dx: Points,
        dy: Points,
    ) -> (Option<NodeId>, bool) {
        self.apply(candidates, self.activation.decide(dx, dy))
    }

    fn apply<V, C>(
        &self,
        candidates: &mut Vec<(V, C)>,
        decision: Option<bool>,
    ) -> (Option<NodeId>, bool) {
        match decision {
            Some(true) => {
                candidates.truncate(self.outer);
                (Some(self.id), false)
            }
            Some(false) => (None, false),
            None => (None, true),
        }
    }

    /// [`Gate::decide`] on a pointer's gate, which stays only while
    /// undecided: the view whose pan activated. The move since the last
    /// step is judged along its line ([`PanActivation::decide_move`]).
    pub fn step<V, C>(
        gate: &mut Option<Gate>,
        candidates: &mut Vec<(V, C)>,
        dx: Points,
        dy: Points,
    ) -> Option<NodeId> {
        let mut g = gate.take()?;
        let to = crate::geometry::point(dx, dy);
        let decision = g.activation.decide_move(g.last, to);
        g.last = to;
        let (id, undecided) = g.apply(candidates, decision);
        if let Some(id) = id {
            log::debug!(target: "nsh::input", "panActivation of {id} activated");
        }
        if undecided {
            *gate = Some(g);
        }
        id
    }
}

/// The candidate a drag by `(dx, dy)` past the pan slop starts, innermost
/// first: while `gate` decides, those around it wait, and so do those
/// around a pan whose `panActivation` has not decided yet.
pub fn startable<'a, V>(
    candidates: &'a [(V, Candidate)],
    gate: Option<&Gate>,
    dx: Points,
    dy: Points,
) -> Option<&'a (V, Candidate)> {
    pick(candidates, gate, dx, dy).ok().flatten()
}

/// Whether a drag by `(dx, dy)` past the pan slop that starts nothing
/// leaves the pointer waiting for a later move: while its gate decides, or
/// a pan whose `panActivation` has not decided yet comes before any
/// candidate that starts. Otherwise its drags are over. For the backends.
#[doc(hidden)]
pub fn waits<V>(
    candidates: &[(V, Candidate)],
    gate: Option<&Gate>,
    dx: Points,
    dy: Points,
) -> bool {
    gate.is_some() || pick(candidates, gate, dx, dy).is_err()
}

/// Whether view `activated`, whose gate just activated, takes the
/// pointer's drag as its JS responder alone, so that nothing native starts:
/// unless its own native pan (`pan` values, `onPanStart`) follows the
/// activation, the one pan with a `panActivation` among the `candidates`
/// the gate left (those inside the gated view, and its own). For the
/// backends.
#[doc(hidden)]
pub fn activation_frees<V>(activated: Option<NodeId>, candidates: &[(V, Candidate)]) -> bool {
    activated.is_some()
        && !candidates.iter().any(|(_, c)| {
            matches!(
                c,
                Candidate::Pan {
                    activation: Some(_),
                    ..
                }
            )
        })
}

/// [`startable`], or `Err` while a pan's `panActivation` has not decided.
fn pick<'a, V>(
    candidates: &'a [(V, Candidate)],
    gate: Option<&Gate>,
    dx: Points,
    dy: Points,
) -> Result<Option<&'a (V, Candidate)>, ()> {
    let open = gate.map_or(candidates.len(), Gate::outer);
    for candidate in &candidates[..open] {
        let decision = match candidate.1 {
            Candidate::Pan {
                activation: Some(activation),
                ..
            } => activation.decide(dx, dy),
            c => Some(c.accepts(dx, dy)),
        };
        match decision {
            Some(true) => return Ok(Some(candidate)),
            Some(false) => {}
            None => return Err(()),
        }
    }
    Ok(None)
}

/// One view around a pointer going down, as [`Grab::add`] reads it.
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct Link {
    /// The view's node.
    pub id: NodeId,
    /// The events it listens to.
    pub events: EventMask,
    /// The interaction states it tracks.
    pub tracked: u16,
    /// Its native gesture values.
    pub values: GestureValues,
    /// It scrolls: horizontally or not.
    pub scroll: Option<bool>,
    /// Its `panActivation`.
    pub pan_activation: Option<PanActivation>,
}

impl Link {
    /// A view with these props.
    pub fn new(
        id: NodeId,
        events: EventMask,
        tracked: u16,
        values: GestureValues,
        scroll: Option<bool>,
        pan_activation: Option<PanActivation>,
    ) -> Link {
        Link {
            id,
            events,
            tracked,
            values,
            scroll,
            pan_activation,
        }
    }
}

/// How a pointer went down, for [`Grab::add`].
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct GrabOptions {
    /// A finger or a pen: it drags scroll views.
    pub touch: bool,
    /// An item that handles its own pointer took it (a hosted widget, a
    /// text field): no pans, scroll drags or gates.
    pub native: bool,
    /// It selects text: no pans or scroll drags.
    pub selects: bool,
    /// No other pointer is down: the gate follows the first pointer only.
    pub first: bool,
    /// Where the pointer went down in the surface, and the surface's size:
    /// an edge pan ([`PanActivation::edge`]) starts only at its edge, and
    /// never without these.
    #[doc(hidden)]
    pub start: Option<(Point<Points>, Size<Points>)>,
}

impl GrabOptions {
    /// Options of a pointer.
    pub fn new(touch: bool, native: bool, selects: bool, first: bool) -> GrabOptions {
        GrabOptions {
            touch,
            native,
            selects,
            first,
            start: None,
        }
    }

    /// The pointer went down `at` in a surface of `size`
    /// ([`GrabOptions::start`]).
    #[doc(hidden)]
    pub fn start(mut self, at: Point<Points>, size: Size<Points>) -> GrabOptions {
        self.start = Some((at, size));
        self
    }

    /// Whether the pointer may start the pans of a view with `activation`:
    /// an edge pan's only from its edge.
    fn admits(&self, activation: Option<PanActivation>) -> bool {
        match (activation, self.start) {
            (Some(a), Some((at, size))) => a.starts_at(at, size),
            (Some(a), None) => a.edge.is_none(),
            (None, _) => true,
        }
    }
}

/// What a pointer going down finds along the views under it, innermost
/// first.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Grab<V> {
    /// The views that listen to touches.
    pub path: Vec<NodeId>,
    /// What a drag may start.
    pub candidates: Vec<(V, Candidate)>,
    /// The view a second finger would pinch / rotate.
    pub pinch: Option<V>,
    /// Views that track `PRESSED`.
    pub pressed: Vec<V>,
    /// A scroll view is around it.
    pub in_scroll: bool,
    /// The `panActivation` around it.
    pub gate: Option<Gate>,
}

impl<V> Default for Grab<V> {
    fn default() -> Self {
        Grab {
            path: Vec::new(),
            candidates: Vec::new(),
            pinch: None,
            pressed: Vec::new(),
            in_scroll: false,
            gate: None,
        }
    }
}

impl<V: Clone> Grab<V> {
    /// Takes in the next view outwards.
    pub fn add(&mut self, view: &V, link: &Link, options: GrabOptions) {
        if link.events.contains(EventKind::Touch) {
            self.path.push(link.id);
        }
        if link.tracked & PRESSED != 0 {
            self.pressed.push(view.clone());
        }
        // A pointer away from an edge pan's edge starts neither of its pans.
        let pans = options.admits(link.pan_activation);
        if pans
            && !options.native
            && !options.selects
            && let Some(pan) = Candidate::pan(&link.values, link.events, link.pan_activation)
        {
            self.candidates.push((view.clone(), pan));
        }
        if let Some(horizontal) = link.scroll {
            self.in_scroll = true;
            // Dragging the content is a touchscreen's way to scroll; on the
            // desktop the mouse's drags are the app's.
            if options.touch && !options.native && !options.selects {
                self.candidates
                    .push((view.clone(), Candidate::Scroll { horizontal }));
            }
        }
        if self.pinch.is_none() && transforms(&link.values, link.events) != (false, false) {
            self.pinch = Some(view.clone());
        }
        if self.gate.is_none()
            && pans
            && options.first
            && !options.native
            && let Some(activation) =
                gate_activation(&link.values, link.events, link.pan_activation)
        {
            self.gate = Some(Gate::new(link.id, activation, self.candidates.len()));
        }
    }
}

// --- Presses ------------------------------------------------------------------------

/// Whether `events` hold a press listener.
pub fn has_press(events: EventMask) -> bool {
    [
        EventKind::Press,
        EventKind::LongPress,
        EventKind::PressDown,
        EventKind::PressUp,
    ]
    .into_iter()
    .any(|k| events.contains(k))
}

/// Whether `events` hold a tap listener: a press listener other than
/// `onLongPress`.
pub fn has_tap(events: EventMask) -> bool {
    [EventKind::Press, EventKind::PressDown, EventKind::PressUp]
        .into_iter()
        .any(|k| events.contains(k))
}

/// The press of the views under the pointer, innermost first, each with
/// its node, events, `delayLongPress` and whether it is disabled.
///
/// The innermost enabled view with a press listener gets the press. When
/// it listens only to `onLongPress`, as on the Web, iOS and Android a long
/// press recognizer does not take the taps of the views around it: the
/// taps go to the nearest enabled view outside it with a tap listener,
/// and the long press stays with it.
pub fn pick_press<V>(
    views: impl IntoIterator<Item = (V, NodeId, EventMask, Option<f32>, bool)>,
    generation: u64,
) -> Option<Press<V>> {
    let mut long: Option<Press<V>> = None;
    for (view, node, events, delay, disabled) in views {
        if disabled || !has_press(events) {
            continue;
        }
        match &long {
            None if has_tap(events) => {
                return Some(Press::new(view, node, events, delay, generation));
            }
            None => long = Some(Press::new(view, node, events, delay, generation)),
            Some(inner) if has_tap(events) => {
                let mut events = events;
                events.set(EventKind::LongPress, true);
                let mut press = Press::new(view, node, events, Some(inner.long_delay), generation);
                press.long_node = Some(inner.node);
                return Some(press);
            }
            Some(_) => {}
        }
    }
    long
}

/// A press in progress on a view `V`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Press<V> {
    /// The view whose bounds the press must end in (the text view for a
    /// span).
    pub view: V,
    /// The node that gets the events.
    pub node: NodeId,
    /// The events it listens to.
    pub events: EventMask,
    /// Milliseconds before a long press.
    pub long_delay: f32,
    /// `onPressDown` was reported.
    pub pressed: bool,
    /// `onLongPress` was reported: the release is no press.
    pub long: bool,
    /// Tells the press's timers from those of earlier presses.
    pub generation: u64,
    /// The modifier keys held when it went down, sent with its events.
    pub modifiers: crate::keymap::Modifiers,
    /// Consecutive clicks it is (1 for a click, 2 for a double click).
    pub clicks: u32,
    /// The view inside `node` that listens only to `onLongPress` and gets
    /// it, while the taps go to `node` ([`pick_press`]).
    pub long_node: Option<NodeId>,
}

impl<V> Press<V> {
    /// A press of `node` listening to `events`, ended in `view`'s bounds,
    /// with the view's `delayLongPress`.
    pub fn new(
        view: V,
        node: NodeId,
        events: EventMask,
        long_delay: Option<f32>,
        generation: u64,
    ) -> Press<V> {
        Press {
            view,
            node,
            events,
            long_delay: long_delay.unwrap_or(LONG_PRESS),
            pressed: false,
            long: false,
            generation,
            modifiers: crate::keymap::Modifiers::default(),
            clicks: 1,
            long_node: None,
        }
    }

    /// The node that gets an event of `kind`: the long-press-only view
    /// inside for `onLongPress`, else [`Press::node`].
    pub fn target(&self, kind: EventKind) -> NodeId {
        match (kind, self.long_node) {
            (EventKind::LongPress, Some(node)) => node,
            _ => self.node,
        }
    }

    /// The press with the modifier keys held and the consecutive clicks
    /// (at least 1) of the pointer that went down.
    pub fn clicked(mut self, modifiers: crate::keymap::Modifiers, clicks: u32) -> Press<V> {
        self.modifiers = modifiers;
        self.clicks = clicks.max(1);
        self
    }

    /// The press goes in: `onPressDown`, the first time, if it listens.
    pub fn press_in(&mut self) -> Option<EventKind> {
        if self.pressed {
            return None;
        }
        self.pressed = true;
        self.events
            .contains(EventKind::PressDown)
            .then_some(EventKind::PressDown)
    }

    /// The press ends: `onPressUp`, then `onPress` if `fire` (released
    /// inside) and it was no long press, those it listens to.
    pub fn press_out(&mut self, fire: bool) -> impl Iterator<Item = EventKind> + use<V> {
        let was = std::mem::replace(&mut self.pressed, false);
        let up = was && self.events.contains(EventKind::PressUp);
        let press = was && fire && !self.long && self.events.contains(EventKind::Press);
        [
            up.then_some(EventKind::PressUp),
            press.then_some(EventKind::Press),
        ]
        .into_iter()
        .flatten()
    }
}

/// Whether a release at `local` (the pressed view's coordinates) is on a
/// view of `size`, its hit `slop` and [`PRESS_RETENTION`] around them.
pub fn released_inside(local: Point<Points>, size: Size<Points>, slop: EdgeInsets) -> bool {
    let (lx, ly) = (local.x.0, local.y.0);
    let r = PRESS_RETENTION.0;
    lx >= -slop.left.0 - r
        && ly >= -slop.top.0 - r
        && lx <= size.width.0 + slop.right.0 + r
        && ly <= size.height.0 + slop.bottom.0 + r
}

// --- States and hover ---------------------------------------------------------------

/// The interaction states a view that tracks `tracked`
/// ([`crate::MountItem::TrackStates`]) reports: those, and always
/// `FOCUSED`. The core keeps one keyboard focus per surface and works out
/// `focus-within` from it (the views around the focused one, the overlays
/// counting as inside the view the app put them in), so every view the
/// focus reaches tells it, whatever its classes read. A focus change is
/// one report.
pub fn reported_states(tracked: u16) -> u16 {
    tracked | FOCUSED
}

/// Interaction states `states` with `bit` set (or cleared), when the view
/// reports it ([`reported_states`]) and they change.
pub fn next_states(tracked: u16, states: u16, bit: u16, on: bool) -> Option<u16> {
    if reported_states(tracked) & bit == 0 {
        return None;
    }
    let next = if on { states | bit } else { states & !bit };
    (next != states).then_some(next)
}

/// Whether hovering a view that tracks `tracked` and listens to `events`
/// matters: for its `hover:` styles (the `HOVERED` state) or its
/// `onMouseEnter` / `onMouseLeave` / `onMouseMove`.
pub fn hoverable(tracked: u16, events: EventMask) -> bool {
    tracked & HOVERED != 0
        || events.contains(EventKind::MouseEnter)
        || events.contains(EventKind::MouseLeave)
        || events.contains(EventKind::MouseMove)
}

/// The views under the mouse went from `old` to `new` (innermost first):
/// those it left, from the inside out, and those it came over, from the
/// outside in, as with the DOM's `pointerleave` / `pointerenter`.
pub fn hover_changes<'a, V: PartialEq>(
    old: &'a [V],
    new: &'a [V],
) -> (
    impl Iterator<Item = &'a V> + 'a,
    impl Iterator<Item = &'a V> + 'a,
) {
    (
        old.iter().filter(move |v| !new.contains(v)),
        new.iter().rev().filter(move |v| !old.contains(v)),
    )
}

// --- Hit testing --------------------------------------------------------------------

/// Whether the core lays out the children of a view of `kind`, so that
/// they are outside its bounds only in its overflow area.
pub fn laid_out(kind: ViewKind, id: NodeId) -> bool {
    id != ROOT_ID && matches!(kind, ViewKind::View | ViewKind::Text)
}

/// Where a point is relative to a view, for hit testing.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct HitArea {
    /// Inside its bounds.
    pub inside: bool,
    /// Inside its bounds and hit slop: the view itself is hit.
    pub in_slop: bool,
    /// Its children are looked into.
    pub children: bool,
}

/// Where `p` (the view's coordinates) is on a view of `size` with hit
/// `slop`, whose descendants cover `overflow` outside it; `clip`: it clips
/// its children; `laid_out`: the core lays them out ([`laid_out`]), else
/// the platform places them (screens, header items) and the core knows no
/// area for them.
pub fn hit_area(
    p: Point<Points>,
    size: Size<Points>,
    slop: EdgeInsets,
    overflow: Option<Bounds<Points>>,
    clip: bool,
    laid_out: bool,
) -> HitArea {
    let (x, y) = (p.x.0, p.y.0);
    let (w, h) = (size.width.0, size.height.0);
    let inside = x >= 0.0 && y >= 0.0 && x < w && y < h;
    let in_slop =
        x >= -slop.left.0 && y >= -slop.top.0 && x < w + slop.right.0 && y < h + slop.bottom.0;
    let children = if clip {
        inside
    } else if laid_out {
        in_slop
            || overflow.is_some_and(|e| {
                x >= e.origin.x.0
                    && y >= e.origin.y.0
                    && x < e.origin.x.0 + e.size.width.0
                    && y < e.origin.y.0 + e.size.height.0
            })
    } else {
        true
    };
    HitArea {
        inside,
        in_slop,
        children,
    }
}

impl HitArea {
    /// The area left by a view's `clipPath` (`clip`) at `p` on a view of
    /// `size`: outside it, neither the view nor anything in it is hit, its
    /// hit slop and its children's overflow included (CSS's `clip-path`).
    pub fn clipped(
        self,
        clip: Option<&crate::ClipInset>,
        p: Point<Points>,
        size: Size<Points>,
    ) -> Self {
        match clip {
            Some(clip) if !clip.contains(size, p) => HitArea::default(),
            _ => self,
        }
    }
}

// --- Pans, pinches and rotations ----------------------------------------------------

/// Whether a view pinches / rotates natively or listens to it.
pub fn transforms(values: &GestureValues, events: EventMask) -> (bool, bool) {
    (
        values.pinch.is_some()
            || events.contains(EventKind::PinchStart)
            || events.contains(EventKind::PinchEnd),
        values.rotation.is_some()
            || events.contains(EventKind::RotationStart)
            || events.contains(EventKind::RotationEnd),
    )
}

/// Two fingers pinching / rotating, from where they began.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Pinch {
    distance: f32,
    angle: f32,
}

impl Pinch {
    /// Fingers at `a` and `b` begin.
    pub fn new(a: Point<Points>, b: Point<Points>) -> Pinch {
        let (dx, dy) = (b.x.0 - a.x.0, b.y.0 - a.y.0);
        Pinch {
            distance: dx.hypot(dy).max(1.0),
            angle: dy.atan2(dx),
        }
    }

    /// The fingers are at `a` and `b`: the scale and the rotation from
    /// where they began.
    pub fn at(&self, a: Point<Points>, b: Point<Points>) -> (f32, Radians) {
        let (dx, dy) = (b.x.0 - a.x.0, b.y.0 - a.y.0);
        (
            dx.hypot(dy) / self.distance,
            Radians(dy.atan2(dx) - self.angle),
        )
    }
}

/// The scale `notches` Ctrl + wheel notches pinch by: one notch is one
/// [`ZOOM_STEP`], scrolling up (negative) zooms in.
pub fn zoom_factor(notches: f32) -> f32 {
    ZOOM_STEP.powf(-notches)
}

// --- Wheels -------------------------------------------------------------------------

/// Whether wheel notches latched to a view at `last` (ms) along
/// `latched_horizontal` still go there at `time`.
pub fn latch_holds(latched_horizontal: bool, last: f64, horizontal: bool, time: f64) -> bool {
    latched_horizontal == horizontal && time - last < WHEEL_LATCH
}

/// How much longer (ms) to wait for the precise scroll whose last delta
/// came at `last` before it ends, or `None` when it ended (or there is
/// none).
pub fn touchpad_wait(last: Option<f64>, now: f64) -> Option<f64> {
    let idle = now - last?;
    (idle < TOUCHPAD_IDLE).then(|| (TOUCHPAD_IDLE - idle).max(1.0))
}

/// The innermost of `views` (innermost first) a wheel by `(dx, dy)`
/// scrolls: `axis` is a view's scroll axis (horizontal or not; `None` for
/// views that do not scroll), `takes` whether a scroll view can move by it
/// (nested views fall through to outer ones at their edges). Scroll views
/// along the wheel's axis take it: a vertical wheel over a carousel
/// scrolls the page around it, as in browsers; horizontal views take
/// vertical wheels only where nothing around scrolls vertically.
pub fn scroll_target<V>(
    views: Vec<V>,
    dx: Points,
    dy: Points,
    axis: impl Fn(&V) -> Option<bool>,
    takes: impl Fn(&V) -> bool,
) -> Option<V> {
    let horizontal = dx.0.abs() > dy.0.abs();
    let along = |v: &V| axis(v) == Some(horizontal);
    let any_along = views.iter().any(along);
    views
        .into_iter()
        .find(|v| (!any_along || along(v)) && takes(v))
}

/// The view of `views` (innermost first: the one under the pointer, then
/// the views around it) that hears a wheel (`onWheel`): the nearest that
/// `listens`, and whether it takes the wheel (`true`: nothing scrolls or
/// zooms natively). It takes it when no view nearer, nor itself, is one
/// that `scrolls` (a scroll view, a hosted widget scrolling itself):
/// a canvas inside a page hears the wheel instead of the page scrolling,
/// while a listening scroll view, or a view around one, only observes it.
pub fn wheel_listener<V>(
    views: impl IntoIterator<Item = V>,
    listens: impl Fn(&V) -> bool,
    scrolls: impl Fn(&V) -> bool,
) -> Option<(V, bool)> {
    let mut scroll_seen = false;
    for v in views {
        let scrolls = scrolls(&v);
        if listens(&v) {
            return Some((v, !scroll_seen && !scrolls));
        }
        scroll_seen |= scrolls;
    }
    None
}

/// Whether a listener that [`wheel_listener`] found taking the wheel takes
/// one mostly along the `horizontal` axis, `control` held: a view whose
/// `panActivation` names one axis ([`PanActivation::axis`]) takes only the
/// wheels along it and Ctrl + wheel (zoom), and lets the others reach the
/// scroll views around it, as a horizontal scroll view does: a timeline in
/// a page takes horizontal wheels while vertical ones scroll the page.
/// Views without one take every wheel.
pub fn wheel_along(activation: Option<PanActivation>, horizontal: bool, control: bool) -> bool {
    control
        || activation
            .and_then(|a| a.axis())
            .is_none_or(|axis| axis == horizontal)
}

/// Where a wheel or touchpad event is in a scroll, for [`WheelLatch`].
/// Plumbing of the backends, not an API for apps.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WheelStep {
    /// A touchpad gesture began (macOS' `Began`, GPUI's `Started`): its
    /// first event that moves decides where all of it goes.
    Begin,
    /// A touchpad gesture went on, or the system's momentum after it.
    Continue,
    /// The last event of a gesture (its momentum came to rest, a touchpad
    /// scroll stopped).
    End,
    /// An event outside any gesture: a mouse wheel notch, or a touchpad
    /// scroll where the platform reports no phases (Windows, the web), at
    /// `time` (ms). Steps that keep coming stay where they went: a mouse
    /// wheel's along one axis ([`latch_holds`]), a touchpad's (`precise`)
    /// whichever way they turn, as a touchpad scroll stays on its scroll
    /// view.
    Discrete {
        /// Mostly along the horizontal axis, as the scroll views take it
        /// (Shift turning a mouse's vertical notches horizontal).
        horizontal: bool,
        /// From a touchpad or a high-resolution wheel.
        precise: bool,
        /// When, in ms.
        time: f64,
    },
}

/// One scroll of the wheel or the touchpad stays where it went, as a
/// scroll view's does: a view that took it as `onWheel`
/// ([`wheel_listener`]) keeps the rest of it wherever the pointer goes,
/// and a scroll a scroll view has started is not taken over by a listener
/// that comes under the pointer meanwhile (which then only observes). The
/// backends keep one per surface and decide each event with it before
/// their scroll views do. Plumbing of the backends, not an API for apps.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct WheelLatch<V> {
    state: Option<Latched<V>>,
}

#[derive(Debug, Clone)]
enum Latched<V> {
    /// A gesture began and has not moved yet.
    Undecided,
    /// A gesture the scroll views have.
    Declined,
    /// A gesture a listener took.
    Gesture(V),
    /// Discrete steps a listener took, along `horizontal`, the last at
    /// `last` (ms).
    Steps {
        view: V,
        horizontal: bool,
        last: f64,
    },
}

impl<V> Default for WheelLatch<V> {
    fn default() -> Self {
        Self { state: None }
    }
}

impl<V: Clone> WheelLatch<V> {
    /// The view `step` goes to as `onWheel`, and whether it takes it
    /// (nothing scrolls), as [`wheel_listener`] answers but for the scroll
    /// it is part of: `find` is that answer where the pointer is now,
    /// asked only when the scroll is not decided yet or a listener may
    /// only observe it. A gesture goes where its first event that `moved`
    /// found a taker; discrete steps stay on their taker while they keep
    /// coming; while `scrolling` (a scroll view's scroll is going on:
    /// notches latched to it, a touchpad gesture or its glide) a listener
    /// only observes. `alive`: the view still shows and still listens (a
    /// taker that stopped listening lets the rest of the scroll go).
    pub fn route(
        &mut self,
        step: WheelStep,
        moved: bool,
        scrolling: bool,
        alive: impl Fn(&V) -> bool,
        find: impl FnOnce() -> Option<(V, bool)>,
    ) -> Option<(V, bool)> {
        let observe = |found: Option<(V, bool)>| found.map(|(view, _)| (view, false));
        match (step, self.state.take()) {
            (WheelStep::Begin, _) | (WheelStep::Continue, Some(Latched::Undecided)) => {
                if !moved {
                    self.state = Some(Latched::Undecided);
                    return None;
                }
                let found = find();
                self.state = Some(match &found {
                    Some((view, true)) => Latched::Gesture(view.clone()),
                    _ => Latched::Declined,
                });
                found
            }
            (WheelStep::Continue, Some(Latched::Gesture(view))) if alive(&view) => {
                self.state = Some(Latched::Gesture(view.clone()));
                Some((view, true))
            }
            (WheelStep::Continue, Some(Latched::Declined)) => {
                self.state = Some(Latched::Declined);
                observe(find())
            }
            // A gesture's events without its begin, or a listener gone.
            (WheelStep::Continue, _) => observe(find()),
            (WheelStep::End, Some(Latched::Gesture(view) | Latched::Steps { view, .. }))
                if alive(&view) =>
            {
                Some((view, true))
            }
            (WheelStep::End, _) => observe(find()),
            (
                WheelStep::Discrete {
                    horizontal,
                    precise,
                    time,
                },
                state,
            ) => {
                if !moved {
                    // Nothing to scroll: as no event.
                    self.state = state;
                    return None;
                }
                if let Some(Latched::Steps {
                    view,
                    horizontal: h,
                    last,
                }) = state
                    && latch_holds(if precise { horizontal } else { h }, last, horizontal, time)
                    && alive(&view)
                {
                    self.state = Some(Latched::Steps {
                        view: view.clone(),
                        horizontal,
                        last: time,
                    });
                    return Some((view, true));
                }
                let found = find();
                if scrolling {
                    return observe(found);
                }
                if let Some((view, true)) = &found {
                    self.state = Some(Latched::Steps {
                        view: view.clone(),
                        horizontal,
                        last: time,
                    });
                }
                found
            }
        }
    }

    /// A gesture began ([`WheelStep::Begin`]) and has not ended, whoever
    /// has it: its later events are [`WheelStep::Continue`]s (GPUI sends a
    /// touchpad's events without phases as moves of no gesture).
    pub fn in_gesture(&self) -> bool {
        matches!(
            self.state,
            Some(Latched::Undecided | Latched::Declined | Latched::Gesture(_))
        )
    }

    /// The view that took the scroll going on, if a listener did.
    pub fn taker(&self) -> Option<&V> {
        match &self.state {
            Some(Latched::Gesture(view) | Latched::Steps { view, .. }) => Some(view),
            _ => None,
        }
    }

    /// Forgets the scroll (a new touch on the touchpad, the surface reset).
    pub fn clear(&mut self) {
        self.state = None;
    }
}

// --- The keyboard -------------------------------------------------------------------

/// The views under `root` (itself first) in Tab order: depth first, each
/// before its children in the order `children` gives them, except that a
/// shown overlay's view (`tab_after`: its [`crate::ViewProps::tab_after`])
/// goes right after the view it names and before that view's children,
/// not among the children of the root view it is in. So a popover's
/// content follows its trigger, as WAI-ARIA's non-modal popups have it.
/// An overlay whose view is not met stays where it is.
///
/// For the backends that order Tab themselves: they filter the views it
/// returns for their stops, and leave out of `children` what Tab passes
/// over (hidden subtrees, the screens under the top one).
pub fn tab_order<V>(
    root: V,
    children: impl FnMut(&V) -> Vec<V>,
    id: impl FnMut(&V) -> NodeId,
    tab_after: impl FnMut(&V) -> Option<NodeId>,
) -> Vec<V> {
    let mut walk = TabWalk {
        children,
        id,
        tab_after,
        waiting: rustc_hash::FxHashMap::default(),
        out: Vec::new(),
    };
    walk.visit(root);
    walk.out
}

/// [`tab_order`]'s walk.
struct TabWalk<V, C, I, A> {
    children: C,
    id: I,
    tab_after: A,
    /// The overlays met, by the view they go after, until it is.
    waiting: rustc_hash::FxHashMap<NodeId, Vec<V>>,
    out: Vec<V>,
}

impl<V, C, I, A> TabWalk<V, C, I, A>
where
    C: FnMut(&V) -> Vec<V>,
    I: FnMut(&V) -> NodeId,
    A: FnMut(&V) -> Option<NodeId>,
{
    fn visit(&mut self, view: V) {
        let own = (self.id)(&view);
        let children = (self.children)(&view);
        self.out.push(view);
        let mut placed = Vec::new();
        let mut rest = Vec::with_capacity(children.len());
        for child in children {
            match (self.tab_after)(&child) {
                Some(after) => {
                    placed.push((after, (self.id)(&child)));
                    self.waiting.entry(after).or_default().push(child);
                }
                None => rest.push(child),
            }
        }
        for overlay in self.waiting.remove(&own).unwrap_or_default() {
            self.visit(overlay);
        }
        for child in rest {
            self.visit(child);
        }
        // Not met under this view: where they are.
        for (after, placed) in placed {
            let Some(waiting) = self.waiting.get_mut(&after) else {
                continue;
            };
            let Some(at) = waiting.iter().position(|v| (self.id)(v) == placed) else {
                continue;
            };
            let overlay = waiting.remove(at);
            if waiting.is_empty() {
                self.waiting.remove(&after);
            }
            self.visit(overlay);
        }
    }
}

/// The Tab stop Tab (Shift + Tab with `back`) moves to among `n` from
/// `current`: past the ends it wraps around with `wrap`, else leaves them
/// (`None`).
pub fn tab_stop(current: Option<usize>, n: usize, back: bool, wrap: bool) -> Option<usize> {
    if n == 0 {
        return None;
    }
    Some(match (current, back) {
        (Some(i), false) if i + 1 == n => {
            if !wrap {
                return None;
            }
            0
        }
        (Some(0), true) => {
            if !wrap {
                return None;
            }
            n - 1
        }
        (Some(i), false) => i + 1,
        (Some(i), true) => i - 1,
        (None, false) => 0,
        (None, true) => n - 1,
    })
}

/// Whether a key down asks for the context menu of the view with the
/// keyboard focus: the Menu key (`menu_key`) or Shift+F10, as Windows, GTK
/// and WAI-ARIA have it, with neither Control, Alt nor Command / Super
/// held (Shift+Menu too).
pub fn opens_context_menu(
    menu_key: bool,
    key: Option<crate::keymap::Key>,
    modifiers: crate::keymap::Modifiers,
) -> bool {
    if modifiers.ctrl || modifiers.alt || modifiers.cmd {
        return false;
    }
    menu_key || (modifiers.shift && key == Some(crate::keymap::Key::F(10)))
}

/// Whether a key down presses the control with the keyboard focus (a view
/// that takes presses, not a text input): Return / Enter or Space with
/// neither Control, Alt nor Command / Super held (Shift may be). Such a
/// key goes to that control before the app's shortcuts and the menus'
/// key equivalents see it, so a binding of the same key elsewhere (a
/// dialog's Enter for its main action) cannot act instead of the control
/// the user moved the focus to.
pub fn presses_focused_control(
    key: crate::keymap::Key,
    modifiers: crate::keymap::Modifiers,
) -> bool {
    !(modifiers.ctrl || modifiers.alt || modifiers.cmd)
        && matches!(
            key,
            crate::keymap::Key::Enter | crate::keymap::Key::Char(' ')
        )
}

/// Where a context menu asked for without a pointer (the keyboard, an
/// assistive technology) opens in a view of `size`: its bottom-start
/// corner, the bottom right one right to left (`rtl`: the surface's
/// direction, `MountItem::LayoutDirection`), so a menu placed below it
/// starts where the view does.
pub fn context_menu_anchor(size: Size<Points>, rtl: bool) -> Point<Points> {
    let x = if rtl { size.width } else { Points(0.0) };
    Point { x, y: size.height }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::{point, size};

    fn p(x: f32, y: f32) -> Point<Points> {
        point(Points(x), Points(y))
    }

    #[test]
    fn velocity_over_recent_samples() {
        let mut v = VelocityTracker::default();
        for i in 0..10 {
            v.add(i as f64 * 10.0, p(i as f32 * 5.0, 0.0));
        }
        let (vx, vy) = v.velocity();
        assert!((vx - 500.0).abs() < 1.0, "{vx}");
        assert_eq!(vy, 0.0);
    }

    #[test]
    fn velocity_is_zero_after_a_pause() {
        let mut v = VelocityTracker::default();
        v.add(0.0, p(0.0, 0.0));
        v.add(10.0, p(10.0, 10.0));
        v.add(300.0, p(10.0, 10.0));
        assert_eq!(v.velocity(), (0.0, 0.0));
    }

    #[test]
    fn velocity_needs_two_samples() {
        let mut v = VelocityTracker::default();
        assert_eq!(v.velocity(), (0.0, 0.0));
        v.add(5.0, p(3.0, 3.0));
        assert_eq!(v.velocity(), (0.0, 0.0));
    }

    #[test]
    fn velocity_wraps_around() {
        let mut v = VelocityTracker::default();
        for i in 0..100 {
            v.add(i as f64 * 8.0, p(0.0, -(i as f32) * 4.0));
        }
        let (_, vy) = v.velocity();
        assert!((vy + 500.0).abs() < 1.0, "{vy}");
    }

    #[test]
    fn candidates_take_their_axis() {
        let accepts = |c: Candidate, dx: f32, dy: f32| c.accepts(Points(dx), Points(dy));
        let horizontal = Candidate::Pan {
            x: true,
            y: false,
            activation: None,
        };
        assert!(accepts(horizontal, 8.0, 2.0));
        assert!(!accepts(horizontal, 2.0, 8.0));
        let both = Candidate::Pan {
            x: true,
            y: true,
            activation: None,
        };
        assert!(accepts(both, 2.0, 8.0) && accepts(both, 8.0, 2.0));
        let vertical = Candidate::Scroll { horizontal: false };
        assert!(accepts(vertical, 1.0, -7.0));
        assert!(!accepts(vertical, -7.0, 1.0));
    }

    #[test]
    fn a_pan_with_an_activation_starts_as_it_activates() {
        let accepts = |c: Candidate, dx: f32, dy: f32| c.accepts(Points(dx), Points(dy));
        let values = GestureValues {
            pan_x: Some(1),
            ..GestureValues::default()
        };
        let right = PanActivation::default().direction(crate::PanDirection::Right);
        let pan = Candidate::pan(&values, EventMask::default(), Some(right)).unwrap();
        assert!(accepts(pan, 12.0, 3.0));
        // The axis alone would take these: the activation does not.
        assert!(!accepts(pan, -12.0, 3.0));
        assert!(!accepts(pan, 8.0, 1.0));
        let plain = Candidate::pan(&values, EventMask::default(), None).unwrap();
        assert!(accepts(plain, -12.0, 3.0));
        // A pager around it waits for it, then takes what it leaves.
        let pager = Candidate::Scroll { horizontal: true };
        let candidates = [(1, pan), (2, pager)];
        let start = |dx: f32| startable(&candidates, None, Points(dx), Points(0.0)).map(|c| c.0);
        assert_eq!(start(7.0), None);
        assert_eq!(start(-7.0), None);
        assert_eq!(start(11.0), Some(1));
        assert_eq!(start(-11.0), Some(2));
    }

    #[test]
    fn an_edge_pan_starts_only_from_its_edge() {
        let mut events = EventMask::default();
        events.set(EventKind::PanEnd, true);
        let edge = PanActivation::default().edge(crate::PanEdge::Left);
        let link = Link::new(5, events, 0, GestureValues::default(), None, Some(edge));
        let surface = crate::geometry::size(Points(400.0), Points(800.0));
        let grab = |at: Option<Point<Points>>| {
            let mut grab: Grab<&str> = Grab::default();
            let mut options = GrabOptions::new(true, false, false, true);
            if let Some(at) = at {
                options = options.start(at, surface);
            }
            grab.add(&"edge", &link, options);
            grab
        };
        let at_edge = grab(Some(crate::geometry::point(Points(12.0), Points(300.0))));
        assert_eq!(at_edge.candidates.len(), 1);
        assert_eq!(at_edge.gate.map(|g| g.outer()), Some(1));
        // Away from it: neither its native pan nor its gate.
        let inside = grab(Some(crate::geometry::point(Points(60.0), Points(300.0))));
        assert!(inside.candidates.is_empty() && inside.gate.is_none());
        // A backend that does not say where the pointer went down.
        let unknown = grab(None);
        assert!(unknown.candidates.is_empty() && unknown.gate.is_none());
        // An edge pan moves away from its edge.
        let (_, pan) = at_edge.candidates[0];
        assert!(pan.accepts(Points(14.0), Points(2.0)));
        assert!(!pan.accepts(Points(-14.0), Points(2.0)));
    }

    #[test]
    fn gates_decide_on_their_offsets() {
        let gate = Gate::new(7, PanActivation::horizontal(Points(6.0), Points(8.0)), 0);
        let mut candidates: Vec<((), Candidate)> = Vec::new();
        let mut decide = |dx: f32, dy: f32| gate.decide(&mut candidates, Points(dx), Points(dy));
        assert_eq!(decide(3.0, 3.0), (None, true));
        assert_eq!(decide(7.0, 1.0), (Some(7), false));
        assert_eq!(decide(2.0, -9.0), (None, false));
        // A fail offset passed by the same move wins.
        assert_eq!(decide(9.0, 9.0), (None, false));
    }

    #[test]
    fn a_gate_steps_to_the_offset_its_pointer_passed_first() {
        // 1.5 across for 1 down, 10 points a move: the second move passes
        // both offsets, x first.
        let sideways = PanActivation::horizontal(Points(10.0), Points(10.0));
        let mut candidates: Vec<((), Candidate)> = Vec::new();
        let mut gate = Some(Gate::new(3, sideways, 0));
        assert_eq!(
            Gate::step(&mut gate, &mut candidates, Points(-8.3), Points(-5.5)),
            None
        );
        assert_eq!(
            Gate::step(&mut gate, &mut candidates, Points(-16.6), Points(-11.1)),
            Some(3)
        );
        // 1 across for 1.5 down: y first.
        let mut gate = Some(Gate::new(3, sideways, 0));
        assert_eq!(
            Gate::step(&mut gate, &mut candidates, Points(5.5), Points(8.3)),
            None
        );
        assert_eq!(
            Gate::step(&mut gate, &mut candidates, Points(11.1), Points(16.6)),
            None
        );
        assert!(gate.is_none());
    }

    #[test]
    fn an_activated_gate_drops_the_candidates_around_it() {
        let pan = Candidate::Pan {
            x: true,
            y: true,
            activation: None,
        };
        let mut candidates = vec![(1, pan), (2, pan)];
        let mut gate = Some(Gate::new(
            1,
            PanActivation::horizontal(Points(6.0), Points(8.0)),
            1,
        ));
        // Undecided: the outer candidate waits.
        let (dx, dy) = (Points(3.0), Points(0.0));
        assert_eq!(Gate::step(&mut gate, &mut candidates, dx, dy), None);
        assert!(gate.is_some());
        assert_eq!(
            startable(&candidates, gate.as_ref(), dx, dy),
            Some(&(1, pan))
        );
        let (dx, dy) = (Points(7.0), Points(0.0));
        assert_eq!(Gate::step(&mut gate, &mut candidates, dx, dy), Some(1));
        assert!(gate.is_none());
        assert_eq!(candidates, vec![(1, pan)]);
    }

    #[test]
    fn a_long_press_only_view_leaves_taps_to_the_view_around_it() {
        let mask = |kinds: &[EventKind]| {
            let mut m = EventMask::default();
            for k in kinds {
                m.set(*k, true);
            }
            m
        };
        let long = mask(&[EventKind::LongPress]);
        let tap = mask(&[EventKind::Press]);
        let press = pick_press(
            [(1, 1, long, Some(300.0), false), (2, 2, tap, None, false)],
            0,
        )
        .unwrap();
        assert_eq!((press.view, press.node, press.long_delay), (2, 2, 300.0));
        assert_eq!(press.target(EventKind::LongPress), 1);
        assert_eq!(press.target(EventKind::Press), 2);
        assert!(press.events.contains(EventKind::LongPress));
        // Alone, it keeps the press.
        let press = pick_press([(1, 1, long, None, false)], 0).unwrap();
        assert_eq!((press.node, press.long_node), (1, None));
        // A tap listener inside wins.
        let press = pick_press([(1, 1, tap, None, false), (2, 2, long, None, false)], 0).unwrap();
        assert_eq!((press.node, press.long_node), (1, None));
        // Disabled views are skipped.
        let press = pick_press([(1, 1, tap, None, true), (2, 2, tap, None, false)], 0).unwrap();
        assert_eq!(press.node, 2);
    }

    #[test]
    fn only_a_pan_or_a_responder_has_a_gate() {
        let activation = Some(PanActivation::default().direction(crate::PanDirection::Right));
        let mask = |kinds: &[EventKind]| {
            let mut m = EventMask::default();
            for k in kinds {
                m.set(*k, true);
            }
            m
        };
        let none = GestureValues::default();
        let values = GestureValues {
            pan_x: Some(3),
            ..GestureValues::default()
        };
        let gated = |values: &GestureValues, kinds: &[EventKind]| {
            gate_activation(values, mask(kinds), activation) == activation
        };
        // Its pan off (`pan_enabled(false)` mounts no values or pan
        // listeners) and no responder: no gate, the content keeps the drags.
        assert_eq!(
            gate_activation(&none, mask(&[EventKind::Press]), activation),
            None
        );
        assert!(gated(&none, &[EventKind::PanStart]));
        assert!(gated(&none, &[EventKind::PanEnd]));
        assert!(gated(&values, &[]));
        assert!(gated(&none, &[EventKind::Touch]));
        assert_eq!(
            gate_activation(&values, mask(&[EventKind::Touch]), None),
            None
        );
        // The backends that grab: the pan's view, off, around a stack.
        let grab = |events: EventMask, values: GestureValues| {
            let mut grab: Grab<&str> = Grab::default();
            let options = GrabOptions::new(true, false, false, true);
            grab.add(
                &"drawer",
                &Link::new(2, events, 0, values, None, activation),
                options,
            );
            grab.gate
        };
        assert!(grab(EventMask::default(), none).is_none());
        assert_eq!(
            grab(mask(&[EventKind::PanStart]), none).map(|g| g.outer()),
            Some(1)
        );
        assert_eq!(
            grab(mask(&[EventKind::Touch]), none).map(|g| g.outer()),
            Some(0)
        );
    }

    #[test]
    fn grabs_collect_along_the_chain() {
        let mut grab = Grab::default();
        let mut values = GestureValues::default();
        let mut events = EventMask::default();
        events.set(EventKind::Touch, true);
        let options = GrabOptions::new(true, false, false, true);
        grab.add(
            &"inner",
            &Link::new(4, events, PRESSED, values, None, None),
            options,
        );
        values.pinch = Some(1);
        let activation = PanActivation::horizontal(Points(6.0), Points(8.0));
        let link = Link::new(6, events, 0, values, Some(false), Some(activation));
        grab.add(&"scroll", &link, options);
        assert_eq!(grab.path, vec![4, 6]);
        assert_eq!(grab.pressed, vec!["inner"]);
        assert_eq!(
            grab.candidates,
            vec![("scroll", Candidate::Scroll { horizontal: false })]
        );
        assert_eq!(grab.pinch, Some("scroll"));
        assert!(grab.in_scroll);
        assert_eq!(grab.gate.map(|g| g.outer()), Some(1));
        // The mouse drags no scroll view.
        let mut mouse = Grab::default();
        mouse.add(
            &"scroll",
            &link,
            GrabOptions::new(false, false, false, true),
        );
        assert!(mouse.candidates.is_empty() && mouse.in_scroll);
    }

    #[test]
    fn presses_report_down_up_and_press() {
        let mut events = EventMask::default();
        assert!(!has_press(events));
        events.set(EventKind::LongPress, true);
        assert!(has_press(events));
        events.set(EventKind::PressDown, true);
        events.set(EventKind::PressUp, true);
        events.set(EventKind::Press, true);
        let mut press = Press::new((), 3, events, None, 0);
        assert_eq!(press.long_delay, LONG_PRESS);
        assert!(press.press_out(true).next().is_none());
        assert_eq!(press.press_in(), Some(EventKind::PressDown));
        assert_eq!(press.press_in(), None);
        let out: Vec<_> = press.press_out(true).collect();
        assert_eq!(out, vec![EventKind::PressUp, EventKind::Press]);
        press.press_in();
        press.long = true;
        let out: Vec<_> = press.press_out(true).collect();
        assert_eq!(out, vec![EventKind::PressUp]);
    }

    #[test]
    fn releases_count_near_the_view() {
        let slop = EdgeInsets::all(Points(2.0));
        let s = size(Points(10.0), Points(10.0));
        assert!(released_inside(p(19.0, 0.0), s, slop));
        assert!(!released_inside(p(21.0, 0.0), s, slop));
        assert!(released_inside(p(-9.0, -9.0), s, slop));
    }

    #[test]
    fn states_change_only_when_tracked() {
        let hovered = HOVERED;
        assert_eq!(next_states(0, 0, hovered, true), None);
        assert_eq!(next_states(hovered, 0, hovered, true), Some(hovered));
        assert_eq!(next_states(hovered, hovered, hovered, true), None);
        assert_eq!(next_states(hovered, hovered, hovered, false), Some(0));
    }

    #[test]
    fn focus_is_reported_whatever_is_tracked() {
        assert_eq!(reported_states(0), FOCUSED);
        assert_eq!(next_states(0, 0, FOCUSED, true), Some(FOCUSED));
        assert_eq!(next_states(0, FOCUSED, FOCUSED, false), Some(0));
        assert_eq!(next_states(0, FOCUSED, FOCUSED, true), None);
    }

    #[test]
    fn hovers_leave_inside_out_and_enter_outside_in() {
        let (left, entered) = hover_changes(&[3, 2, 1], &[5, 4, 1]);
        assert_eq!(left.collect::<Vec<_>>(), vec![&3, &2]);
        assert_eq!(entered.collect::<Vec<_>>(), vec![&4, &5]);
    }

    #[test]
    fn hit_areas() {
        let s = size(Points(10.0), Points(10.0));
        let slop = EdgeInsets::all(Points(5.0));
        let a = hit_area(p(12.0, 5.0), s, slop, None, false, true);
        assert!(!a.inside && a.in_slop && a.children);
        assert!(!hit_area(p(12.0, 5.0), s, slop, None, true, true).children);
        let overflow = Bounds::new(p(0.0, 10.0), size(Points(10.0), Points(50.0)));
        let a = hit_area(p(5.0, 40.0), s, slop, Some(overflow), false, true);
        assert!(!a.in_slop && a.children);
        assert!(hit_area(p(500.0, 500.0), s, slop, None, false, false).children);
    }

    #[test]
    fn a_clip_path_bounds_the_view_and_its_children() {
        let s = size(Points(100.0), Points(100.0));
        let slop = EdgeInsets::all(Points(5.0));
        let overflow = Bounds::new(p(0.0, 100.0), size(Points(100.0), Points(50.0)));
        let clip = crate::ClipInset::new()
            .left(crate::geometry::percentage(0.5))
            .rounded(Points(10.0));
        let at = |x, y| {
            hit_area(p(x, y), s, slop, Some(overflow), false, true).clipped(Some(&clip), p(x, y), s)
        };
        let a = at(75.0, 50.0);
        assert!(a.inside && a.in_slop && a.children);
        // Clipped out: inside the box, in its slop, in its children's
        // overflow, and in a rounded corner.
        for (x, y) in [(25.0, 50.0), (102.0, 50.0), (75.0, 120.0), (51.0, 1.0)] {
            assert_eq!(at(x, y), HitArea::default(), "{x}, {y}");
        }
        // Without one, nothing changes.
        let a = hit_area(p(25.0, 50.0), s, slop, None, false, true);
        assert_eq!(a.clipped(None, p(25.0, 50.0), s), a);
    }

    #[test]
    fn only_laid_out_views_bound_their_children() {
        assert!(laid_out(ViewKind::View, 8));
        assert!(laid_out(ViewKind::Text, 8));
        assert!(!laid_out(ViewKind::View, ROOT_ID));
        assert!(!laid_out(ViewKind::Screen, 8));
        assert!(!laid_out(ViewKind::Modal, 8));
    }

    #[test]
    fn two_fingers_scale_and_rotate() {
        let pinch = Pinch::new(p(0.0, 0.0), p(10.0, 0.0));
        let (scale, rotation) = pinch.at(p(0.0, 0.0), p(0.0, 20.0));
        assert!((scale - 2.0).abs() < 1e-5);
        assert!((rotation.0.to_degrees() - 90.0).abs() < 1e-3);
    }

    #[test]
    fn wheel_notches_latch_along_their_axis() {
        assert!(latch_holds(false, 1000.0, false, 1150.0));
        assert!(!latch_holds(false, 1000.0, false, 1250.0));
        assert!(!latch_holds(false, 1000.0, true, 1050.0));
    }

    #[test]
    fn touchpad_scrolls_end_after_a_pause() {
        assert_eq!(touchpad_wait(None, 500.0), None);
        assert_eq!(touchpad_wait(Some(400.0), 500.0), Some(50.0));
        assert_eq!(touchpad_wait(Some(300.0), 500.0), None);
    }

    #[test]
    fn ctrl_wheel_zooms_by_notches() {
        assert!((zoom_factor(-1.0) - 1.1).abs() < 1e-5);
        assert!((zoom_factor(2.0) - 1.0 / 1.21).abs() < 1e-5);
    }

    #[test]
    fn wheels_take_scroll_views_along_their_axis() {
        // (id, axis, can scroll)
        let views = vec![
            (1, Some(true), true),
            (2, None, false),
            (3, Some(false), true),
        ];
        let target = |dx, dy, views: &Vec<(i32, Option<bool>, bool)>| {
            scroll_target(
                views.clone(),
                Points(dx),
                Points(dy),
                |v| v.1,
                |v| v.1.is_some() && v.2,
            )
            .map(|v| v.0)
        };
        assert_eq!(target(0.0, 5.0, &views), Some(3));
        assert_eq!(target(5.0, 0.0, &views), Some(1));
        // Only a horizontal view: it takes vertical wheels too.
        assert_eq!(target(0.0, 5.0, &views[..2].to_vec()), Some(1));
    }

    #[test]
    fn tab_order_puts_overlays_after_the_view_they_follow() {
        // (id, tab_after, children): the root view holds a trigger with a
        // label, a button after it, then its overlays: one after the
        // label, one inside that one's content, one after a view that is
        // not there, one after the root view itself.
        let tree: &[(NodeId, Option<NodeId>, &[NodeId])] = &[
            (1, None, &[2, 4, 5, 10, 7, 9]),
            (2, None, &[3]),
            (3, None, &[]),
            (4, None, &[]),
            (5, Some(3), &[6]),
            (6, None, &[]),
            (10, Some(6), &[11]),
            (11, None, &[]),
            (7, Some(99), &[8]),
            (8, None, &[]),
            (9, Some(1), &[]),
        ];
        let node = |id: NodeId| tree.iter().find(|n| n.0 == id).unwrap();
        let order = tab_order(1, |&id| node(id).2.to_vec(), |&id| id, |&id| node(id).1);
        assert_eq!(order, vec![1, 9, 2, 3, 5, 6, 10, 11, 4, 7, 8]);
    }

    #[test]
    fn tab_stops_wrap_or_leave() {
        assert_eq!(tab_stop(None, 0, false, true), None);
        assert_eq!(tab_stop(None, 3, false, true), Some(0));
        assert_eq!(tab_stop(None, 3, true, true), Some(2));
        assert_eq!(tab_stop(Some(2), 3, false, true), Some(0));
        assert_eq!(tab_stop(Some(0), 3, true, true), Some(2));
        assert_eq!(tab_stop(Some(2), 3, false, false), None);
        assert_eq!(tab_stop(Some(0), 3, true, false), None);
        assert_eq!(tab_stop(Some(1), 3, true, false), Some(0));
    }

    #[test]
    fn a_gesture_stays_on_the_listener_its_first_move_found() {
        let mut latch = WheelLatch::default();
        let alive = |_: &u32| true;
        let decided = || -> Option<(u32, bool)> { panic!("a taken gesture does not look again") };
        // Fingers down, not moving yet: undecided, the scroll views see it.
        assert_eq!(
            latch.route(WheelStep::Begin, false, false, alive, decided),
            None
        );
        // The first move finds a taker: it keeps the gesture and its
        // momentum, wherever the pointer goes.
        let first = latch.route(WheelStep::Continue, true, false, alive, || Some((7, true)));
        assert_eq!(first, Some((7, true)));
        assert_eq!(latch.taker(), Some(&7));
        assert_eq!(
            latch.route(WheelStep::Continue, true, false, alive, decided),
            Some((7, true))
        );
        assert_eq!(
            latch.route(WheelStep::End, false, false, alive, decided),
            Some((7, true))
        );
        assert_eq!(latch.taker(), None);
        // A gesture a scroll view has: a taker the pointer comes over only
        // observes it.
        let observer = latch.route(WheelStep::Begin, true, false, alive, || Some((1, false)));
        assert_eq!(observer, Some((1, false)));
        let passing = latch.route(WheelStep::Continue, true, false, alive, || Some((7, true)));
        assert_eq!(passing, Some((7, false)));
        // A taker that went away hears no more of its gesture.
        latch.route(WheelStep::Begin, true, false, alive, || Some((7, true)));
        let gone = latch.route(WheelStep::Continue, true, false, |_| false, || None);
        assert_eq!(gone, None);
    }

    #[test]
    fn notches_stay_on_their_taker_and_never_take_over_a_scroll() {
        let mut latch = WheelLatch::default();
        let alive = |_: &u32| true;
        let notch = |time| WheelStep::Discrete {
            horizontal: false,
            precise: false,
            time,
        };
        assert_eq!(
            latch.route(notch(0.0), true, false, alive, || Some((7, true))),
            Some((7, true))
        );
        // A step that moves nothing is no event, and keeps the latch.
        assert_eq!(
            latch.route(notch(10.0), false, false, alive, || Some((7, true))),
            None
        );
        assert_eq!(latch.taker(), Some(&7));
        // The taker scrolled away from under the pointer: still its.
        assert_eq!(
            latch.route(notch(50.0), true, false, alive, || None),
            Some((7, true))
        );
        // After a pause the wheel goes where the pointer is.
        let later = 50.0 + WHEEL_LATCH + 1.0;
        assert_eq!(latch.route(notch(later), true, false, alive, || None), None);
        // Notches latched to a scroll view: a taker under the pointer only
        // observes them, and the scroll view keeps scrolling.
        let scrolling = latch.route(notch(later + 10.0), true, true, alive, || Some((7, true)));
        assert_eq!(scrolling, Some((7, false)));
        // A notch along the other axis is another scroll; a touchpad's
        // steps stay whichever way they turn.
        latch.route(notch(1000.0), true, false, alive, || Some((7, true)));
        let sideways = WheelStep::Discrete {
            horizontal: true,
            precise: false,
            time: 1010.0,
        };
        assert_eq!(
            latch.route(sideways, true, false, alive, || Some((8, true))),
            Some((8, true))
        );
        let pad = WheelStep::Discrete {
            horizontal: false,
            precise: true,
            time: 1020.0,
        };
        assert_eq!(
            latch.route(pad, true, false, alive, || None),
            Some((8, true))
        );
        // A touchpad scroll's stop ends its steps (Linux).
        assert_eq!(
            latch.route(WheelStep::End, false, false, alive, || None),
            Some((8, true))
        );
        assert_eq!(latch.taker(), None);
    }

    #[test]
    fn wheel_listener_takes_the_wheel_only_inside_scroll_views() {
        // (id, listens, scrolls), innermost first.
        let pick = |views: &[(u32, bool, bool)]| {
            wheel_listener(views.iter().copied(), |v| v.1, |v| v.2).map(|(v, t)| (v.0, t))
        };
        // A canvas in a page: it takes the wheel.
        assert_eq!(
            pick(&[(3, false, false), (2, true, false), (1, false, true)]),
            Some((2, true))
        );
        // A listening scroll view observes; it still scrolls.
        assert_eq!(
            pick(&[(3, false, false), (2, true, true)]),
            Some((2, false))
        );
        // A listener around a scroll view observes.
        assert_eq!(
            pick(&[(3, false, false), (2, false, true), (1, true, false)]),
            Some((1, false))
        );
        // No listener.
        assert_eq!(pick(&[(2, false, true), (1, false, false)]), None);
    }

    #[test]
    fn wheel_listener_with_a_pan_axis_takes_only_wheels_along_it() {
        let horizontal = Some(PanActivation::horizontal(Points(6.0), Points(8.0)));
        let vertical = Some(PanActivation::vertical(Points(6.0), Points(8.0)));
        // A timeline in a page: horizontal wheels are its own, vertical ones
        // scroll the page.
        assert!(wheel_along(horizontal, true, false));
        assert!(!wheel_along(horizontal, false, false));
        // A picker in a horizontal pager.
        assert!(wheel_along(vertical, false, false));
        assert!(!wheel_along(vertical, true, false));
        // Ctrl + wheel zooms whichever way.
        assert!(wheel_along(horizontal, false, true));
        // Without a pan axis, every wheel (#1567).
        assert!(wheel_along(None, false, false));
        assert!(wheel_along(Some(PanActivation::default()), true, false));
        assert_eq!(PanActivation::default().axis(), None);
    }

    #[test]
    fn context_menu_keys() {
        use crate::keymap::{Key, Modifiers};
        let none = Modifiers::default();
        let shift = Modifiers {
            shift: true,
            ..Modifiers::default()
        };
        let ctrl_shift = Modifiers {
            ctrl: true,
            ..shift
        };
        assert!(opens_context_menu(true, None, none));
        assert!(opens_context_menu(true, None, shift));
        assert!(opens_context_menu(false, Some(Key::F(10)), shift));
        assert!(!opens_context_menu(false, Some(Key::F(10)), none));
        assert!(!opens_context_menu(false, Some(Key::F(10)), ctrl_shift));
        assert!(!opens_context_menu(true, None, ctrl_shift));
        assert!(!opens_context_menu(false, Some(Key::F(9)), shift));
    }

    #[test]
    fn context_menu_anchor_is_the_bottom_start_corner() {
        let s = size(Points(120.0), Points(40.0));
        assert_eq!(context_menu_anchor(s, false), p(0.0, 40.0));
        assert_eq!(context_menu_anchor(s, true), p(120.0, 40.0));
    }

    #[test]
    fn tap_feedback_delay_holds_short_presses() {
        use std::time::Duration;
        assert_eq!(
            tap_feedback_delay(Duration::ZERO, false, false),
            Some(Duration::from_millis(64))
        );
        assert_eq!(
            tap_feedback_delay(Duration::from_millis(12), false, false),
            Some(Duration::from_millis(52))
        );
        assert_eq!(
            tap_feedback_delay(Duration::from_millis(64), false, false),
            None
        );
        assert_eq!(
            tap_feedback_delay(Duration::from_millis(120), false, false),
            None
        );
        assert_eq!(tap_feedback_delay(Duration::ZERO, true, false), None);
        assert_eq!(tap_feedback_delay(Duration::ZERO, false, true), None);
    }
}