crcbl-input 0.12.0

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

use std::collections::{HashMap, HashSet};

use crcbl_core::input::{KeyCode, PointerButton};

use super::{
    ActionMap, ActionMapError, Binding, HeldKeys, Modifier, PadButton, PadButtons, Stick, Trigger,
};
use crate::trace::TracedInput;

/// The base context: always active, and where [`ActionMap::declare`] puts an
/// action.
pub const GAMEPLAY_CONTEXT: &str = "gameplay";

/// The context above every other: always active, never pushed or popped, and
/// routed ahead of the whole stack, a modal context included — where a toggle
/// that must work over any screen goes (a debug camera, the map key, the key
/// that opens and closes an inventory). Declare into it with
/// [`ActionMap::declare_in`]. It is not on the stack, so
/// [`ActionMap::active_contexts`] does not list it.
pub const GLOBAL_CONTEXT: &str = "global";

/// [`GLOBAL_CONTEXT`]'s index in [`ActionMap::contexts`]: registered second, at
/// construction.
const GLOBAL_INDEX: usize = 1;

/// The owner of each input some active context binds, as an index into
/// [`ActionMap::contexts`].
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct Routes {
    keys: HashMap<KeyCode, usize>,
    /// For each key, the modifiers of the chords its **owner** binds on it:
    /// what shadows that owner's plain bindings on the key.
    chords: HashMap<KeyCode, Vec<Modifier>>,
    /// For each pad button, the modifiers of the pad chords its **owner**
    /// binds on it — [`Self::chords`] for the pad.
    pad_chords: HashMap<PadButton, Vec<PadButton>>,
    /// For each pad button, the outranking pad chords on it from contexts
    /// beneath its owner, as `(modifier, context)`, topmost context first —
    /// see [`ActionMap::set_pad_chords_outrank`].
    outranking_pad_chords: HashMap<PadButton, Vec<(PadButton, usize)>>,
    /// For each pointer button, the modifiers of the button chords its
    /// **owner** binds on it — [`Self::chords`] for the mouse.
    button_chords: HashMap<PointerButton, Vec<Modifier>>,
    buttons: HashMap<PointerButton, usize>,
    controls: HashMap<String, usize>,
    motion: Option<usize>,
    scroll: Option<usize>,
    /// The held keys of the scroll chords the wheel's **owner** binds: what
    /// shadows that owner's plain wheel bindings.
    scroll_chords: Vec<KeyCode>,
    pub(crate) pointer: Option<usize>,
    pad_buttons: HashMap<PadButton, usize>,
    pad_sticks: HashMap<Stick, usize>,
    pad_triggers: HashMap<Trigger, usize>,
}

/// Held inputs withheld from their owner until released — see the module docs.
#[derive(Debug, Default, Clone)]
pub(crate) struct Suppressed {
    pub(crate) keys: HashSet<KeyCode>,
    pub(crate) buttons: HashSet<PointerButton>,
    pub(crate) controls: HashSet<String>,
    /// Pad buttons withheld — by a stack change, or by
    /// [`ActionMap::release_gamepads`].
    pub(crate) pad_buttons: PadButtons,
    /// The levels only [`ActionMap::suppress_held`] and
    /// [`ActionMap::suppress_held_action`] withhold, each until it rests.
    pub(crate) control_sticks: HashSet<String>,
    pub(crate) pad_sticks: HashSet<Stick>,
    pub(crate) pad_triggers: HashSet<Trigger>,
}

impl Suppressed {
    /// Withhold everything `other` does as well.
    fn extend(&mut self, other: Self) {
        self.keys.extend(other.keys);
        self.buttons.extend(other.buttons);
        self.controls.extend(other.controls);
        self.pad_buttons = self.pad_buttons.union(other.pad_buttons);
        self.control_sticks.extend(other.control_sticks);
        self.pad_sticks.extend(other.pad_sticks);
        self.pad_triggers.extend(other.pad_triggers);
    }

    /// Whether `binding` reads any input this withholds.
    fn withholds(&self, binding: &Binding) -> bool {
        let mut key = false;
        binding.visit_keys(|owned| key |= self.keys.contains(&owned));
        key || match binding {
            Binding::ScrollChord { held } => self.keys.contains(held),
            Binding::MouseButton(button) | Binding::ButtonChord { button, .. } => {
                self.buttons.contains(button)
            }
            Binding::Virtual(id) => {
                self.controls.contains(id.as_str()) || self.control_sticks.contains(id.as_str())
            }
            Binding::PadButton(button) | Binding::PadChord { button, .. } => {
                self.pad_buttons.contains(*button)
            }
            Binding::PadDpad => PadButton::DPAD
                .iter()
                .any(|&button| self.pad_buttons.contains(button)),
            Binding::PadStick { stick, .. } => self.pad_sticks.contains(stick),
            Binding::PadTrigger { trigger, .. } => self.pad_triggers.contains(trigger),
            Binding::Key(_)
            | Binding::KeyAxis { .. }
            | Binding::Chord { .. }
            | Binding::Wasd { .. }
            | Binding::MouseMotion
            | Binding::MouseScroll
            | Binding::PointerPosition { .. } => false,
        }
    }

    /// Whether this withholds `input` itself — the trace's
    /// [`Outcome::Withheld`](crate::trace::Outcome::Withheld). The wheel is a
    /// delta, and nothing withholds it.
    pub(crate) fn holds(&self, input: &TracedInput) -> bool {
        match input {
            TracedInput::Key(key) => self.keys.contains(key),
            TracedInput::MouseButton(button) => self.buttons.contains(button),
            TracedInput::Wheel => false,
            TracedInput::Control(id) => self.controls.contains(id.as_str()),
            TracedInput::ControlStick(id) => self.control_sticks.contains(id.as_str()),
            TracedInput::PadButton(button) => self.pad_buttons.contains(*button),
            TracedInput::PadStick(stick) => self.pad_sticks.contains(stick),
            TracedInput::PadTrigger(trigger) => self.pad_triggers.contains(trigger),
        }
    }
}

/// What one context can see of the raw input.
pub(crate) struct View<'a> {
    pub(crate) context: usize,
    pub(crate) routes: &'a Routes,
    pub(crate) suppressed: &'a Suppressed,
    pub(crate) held_keys: &'a HeldKeys,
    pub(crate) held_buttons: &'a HashSet<PointerButton>,
    pub(crate) held_controls: &'a HashSet<String>,
    /// Every button some pad holds.
    pub(crate) held_pad_buttons: PadButtons,
}

impl View<'_> {
    /// The key is held, this context owns it, and it is not withheld.
    fn owns_held(&self, key: KeyCode) -> bool {
        self.held_keys.contains_key(&key)
            && !self.suppressed.keys.contains(&key)
            && self.routes.keys.get(&key) == Some(&self.context)
    }

    /// A plain binding's read of `key`: down unless a chord on it is satisfied.
    pub(crate) fn key(&self, key: KeyCode) -> bool {
        self.owns_held(key) && !self.any_held(self.routes.chords.get(&key))
    }

    /// Whether any of `modifiers` — the modifiers of the chords an input's
    /// owner binds on it — is held, which shadows that owner's plain bindings
    /// on the input. What [`Self::key`] and [`Self::button`] both ask, so a
    /// key chord and a button chord hand their input over on one rule.
    fn any_held(&self, modifiers: Option<&Vec<Modifier>>) -> bool {
        modifiers.is_some_and(|modifiers| modifiers.iter().any(|m| m.held(self.held_keys)))
    }

    /// A [`Binding::Chord`]'s read: its key, and its modifier read raw.
    pub(crate) fn chord(&self, modifier: Modifier, key: KeyCode) -> bool {
        self.owns_held(key) && modifier.held(self.held_keys)
    }

    /// The pointer button is held, this context owns it, and it is not
    /// withheld.
    fn owns_held_button(&self, button: PointerButton) -> bool {
        self.held_buttons.contains(&button)
            && !self.suppressed.buttons.contains(&button)
            && self.routes.buttons.get(&button) == Some(&self.context)
    }

    /// A plain [`Binding::MouseButton`]'s read: down unless a button chord on
    /// it is satisfied.
    pub(crate) fn button(&self, button: PointerButton) -> bool {
        self.owns_held_button(button) && !self.any_held(self.routes.button_chords.get(&button))
    }

    /// A [`Binding::ButtonChord`]'s read: its button, and its modifier read
    /// raw.
    pub(crate) fn button_chord(&self, modifier: Modifier, button: PointerButton) -> bool {
        self.owns_held_button(button) && modifier.held(self.held_keys)
    }

    pub(crate) fn control(&self, id: &str) -> bool {
        self.held_controls.contains(id)
            && !self.suppressed.controls.contains(id)
            && self.owns_control(id)
    }

    /// A stick's deflection is a level: a stack change never withholds it, and
    /// only a suppress does.
    pub(crate) fn stick(&self, id: &str) -> bool {
        self.owns_control(id) && !self.suppressed.control_sticks.contains(id)
    }

    fn owns_control(&self, id: &str) -> bool {
        self.routes.controls.get(id) == Some(&self.context)
    }

    pub(crate) fn motion(&self) -> bool {
        self.routes.motion == Some(self.context)
    }

    /// A plain [`Binding::MouseScroll`]'s read: this context owns the wheel,
    /// and none of its scroll chords' keys is down.
    pub(crate) fn scroll(&self) -> bool {
        self.routes.scroll == Some(self.context) && self.wheel_key().is_none()
    }

    /// A [`Binding::ScrollChord`]'s read: this context owns the wheel, and
    /// `held` is the most recently pressed of its scroll chords' keys down.
    pub(crate) fn scroll_chord(&self, held: KeyCode) -> bool {
        self.routes.scroll == Some(self.context) && self.wheel_key() == Some(held)
    }

    /// The most recently pressed scroll-chord key that is down and not
    /// withheld, in the context that owns the wheel.
    fn wheel_key(&self) -> Option<KeyCode> {
        self.routes
            .scroll_chords
            .iter()
            .filter(|key| !self.suppressed.keys.contains(key))
            .filter_map(|&key| self.held_keys.get(&key).map(|&serial| (serial, key)))
            .max()
            .map(|(_, key)| key)
    }

    pub(crate) fn pointer(&self) -> bool {
        self.routes.pointer == Some(self.context)
    }

    /// The pad button is held, this context reads it with the modifiers held
    /// now ([`Routes::pad_reader`]), and it is not withheld.
    fn owns_held_pad_button(&self, button: PadButton) -> bool {
        self.held_pad_buttons.contains(button)
            && !self.suppressed.pad_buttons.contains(button)
            && self.routes.pad_reader(button, self.held_pad_buttons) == Some(self.context)
    }

    /// A plain pad binding's read of `button`: down unless a pad chord on it
    /// is satisfied.
    pub(crate) fn pad_button(&self, button: PadButton) -> bool {
        self.owns_held_pad_button(button)
            && !self
                .routes
                .pad_chords
                .get(&button)
                .is_some_and(|modifiers| {
                    modifiers
                        .iter()
                        .any(|&modifier| self.held_pad_buttons.contains(modifier))
                })
    }

    /// A [`Binding::PadChord`]'s read: its button, and its modifier read raw.
    /// Beneath the button's owner, only an outranking chord reads it.
    pub(crate) fn pad_chord(&self, modifier: PadButton, button: PadButton) -> bool {
        self.owns_held_pad_button(button)
            && self.held_pad_buttons.contains(modifier)
            && (self.routes.pad_buttons.get(&button) == Some(&self.context)
                || self.routes.outranks(button, modifier, self.context))
    }

    /// A stick is a level: a stack change never withholds it, and only a
    /// suppress does.
    pub(crate) fn pad_stick(&self, stick: Stick) -> bool {
        self.routes.pad_sticks.get(&stick) == Some(&self.context)
            && !self.suppressed.pad_sticks.contains(&stick)
    }

    /// A trigger is a level: a stack change never withholds it, and only a
    /// suppress does.
    pub(crate) fn trigger(&self, trigger: Trigger) -> bool {
        self.routes.pad_triggers.get(&trigger) == Some(&self.context)
            && !self.suppressed.pad_triggers.contains(&trigger)
    }
}

impl Routes {
    /// Whether `key` is the held key of a scroll chord the wheel's owner binds.
    pub(crate) fn is_scroll_chord_key(&self, key: KeyCode) -> bool {
        self.scroll_chords.contains(&key)
    }

    /// The context that reads `input` while `held` is every pad button down,
    /// if an active one binds it: the owner, or for a pad button the context
    /// [`Self::pad_reader`] hands it to.
    pub(crate) fn owner(&self, input: &TracedInput, held: PadButtons) -> Option<usize> {
        match input {
            TracedInput::Key(key) => self.keys.get(key).copied(),
            TracedInput::MouseButton(button) => self.buttons.get(button).copied(),
            TracedInput::Wheel => self.scroll,
            TracedInput::Control(id) | TracedInput::ControlStick(id) => {
                self.controls.get(id.as_str()).copied()
            }
            TracedInput::PadButton(button) => self.pad_reader(*button, held),
            TracedInput::PadStick(stick) => self.pad_sticks.get(stick).copied(),
            TracedInput::PadTrigger(trigger) => self.pad_triggers.get(trigger).copied(),
        }
    }

    /// The context that reads `button` while `held` is down: the topmost one
    /// with an outranking chord on it whose modifier is held, or else its
    /// owner. What a change of owner compares for a pad button, so the
    /// modifier of an outranking chord hands a held button over the way a
    /// push does.
    pub(crate) fn pad_reader(&self, button: PadButton, held: PadButtons) -> Option<usize> {
        self.outranking_pad_chords
            .get(&button)
            .and_then(|chords| {
                chords
                    .iter()
                    .find(|&&(modifier, _)| held.contains(modifier))
            })
            .map(|&(_, context)| context)
            .or_else(|| self.pad_buttons.get(&button).copied())
    }

    /// Whether `context` has an outranking chord on `button` held by
    /// `modifier`.
    fn outranks(&self, button: PadButton, modifier: PadButton, context: usize) -> bool {
        self.outranking_pad_chords
            .get(&button)
            .is_some_and(|chords| chords.contains(&(modifier, context)))
    }

    /// Owners for the stack as it stands: each context from the top down
    /// claims what nothing above it already has.
    fn build(map: &ActionMap) -> Self {
        let mut routes = Self::default();
        // Below a modal context only the pointer's position and motion still
        // route: a screen reads the cursor, and nothing else passes it.
        let mut below_modal = false;
        // Every pad chord a context above binds, outranking or not: a context
        // that binds a chord itself keeps it from an outranking one beneath.
        let mut pad_chords_above = HashSet::new();
        for context in map.route_order() {
            let bindings = || {
                map.slots
                    .iter()
                    .filter(move |slot| slot.context == context)
                    .flat_map(|slot| slot.decl.bindings.iter())
            };
            if below_modal {
                for binding in bindings() {
                    match binding {
                        Binding::MouseMotion => {
                            routes.motion.get_or_insert(context);
                        }
                        Binding::PointerPosition { .. } => {
                            routes.pointer.get_or_insert(context);
                        }
                        _ => {}
                    }
                }
                continue;
            }
            for binding in bindings() {
                binding.visit_keys(|key| {
                    routes.keys.entry(key).or_insert(context);
                });
                match binding {
                    Binding::MouseButton(button) | Binding::ButtonChord { button, .. } => {
                        routes.buttons.entry(*button).or_insert(context);
                    }
                    Binding::Virtual(id) => {
                        if !routes.controls.contains_key(id.as_str()) {
                            routes.controls.insert(id.clone(), context);
                        }
                    }
                    Binding::MouseMotion => {
                        routes.motion.get_or_insert(context);
                    }
                    Binding::MouseScroll | Binding::ScrollChord { .. } => {
                        routes.scroll.get_or_insert(context);
                    }
                    Binding::PointerPosition { .. } => {
                        routes.pointer.get_or_insert(context);
                    }
                    Binding::PadButton(button) | Binding::PadChord { button, .. } => {
                        routes.pad_buttons.entry(*button).or_insert(context);
                    }
                    Binding::PadDpad => {
                        for button in PadButton::DPAD {
                            routes.pad_buttons.entry(button).or_insert(context);
                        }
                    }
                    Binding::PadStick { stick, .. } => {
                        routes.pad_sticks.entry(*stick).or_insert(context);
                    }
                    Binding::PadTrigger { trigger, .. } => {
                        routes.pad_triggers.entry(*trigger).or_insert(context);
                    }
                    Binding::Key(_)
                    | Binding::KeyAxis { .. }
                    | Binding::Chord { .. }
                    | Binding::Wasd { .. } => {}
                }
            }
            // After this context's keys and wheel are claimed, so a chord
            // registers only where its context is the one reading the key, and
            // a scroll chord only where its context is the one reading the
            // wheel. An outranking pad chord whose button a context above owns
            // registers beneath that owner instead, unless a context above
            // binds the same chord.
            //
            // A scroll chord competes for the wheel only while its action is
            // enabled: a newer key whose action cannot use the wheel right now
            // must not take it from an older one that can, nor silence the
            // plain wheel. The wheel itself stays this context's either way.
            let slots = map.slots.iter().filter(|slot| slot.context == context);
            for slot in slots {
                for binding in &slot.decl.bindings {
                    match binding {
                        Binding::Chord { modifier, key }
                            if routes.keys.get(key) == Some(&context) =>
                        {
                            add_chord(&mut routes.chords, *key, *modifier);
                        }
                        Binding::ButtonChord { modifier, button }
                            if routes.buttons.get(button) == Some(&context) =>
                        {
                            add_chord(&mut routes.button_chords, *button, *modifier);
                        }
                        Binding::PadChord { modifier, button }
                            if routes.pad_buttons.get(button) == Some(&context) =>
                        {
                            add_chord(&mut routes.pad_chords, *button, *modifier);
                        }
                        Binding::PadChord { modifier, button }
                            if slot.pad_chords_outrank
                                && !pad_chords_above.contains(&(*modifier, *button)) =>
                        {
                            add_chord(
                                &mut routes.outranking_pad_chords,
                                *button,
                                (*modifier, context),
                            );
                        }
                        Binding::ScrollChord { held }
                            if slot.enabled
                                && routes.scroll == Some(context)
                                && !routes.scroll_chords.contains(held) =>
                        {
                            routes.scroll_chords.push(*held);
                        }
                        _ => {}
                    }
                }
            }
            for binding in bindings() {
                if let Binding::PadChord { modifier, button } = binding {
                    pad_chords_above.insert((*modifier, *button));
                }
            }
            below_modal = map.modal.contains(&context);
        }
        routes
    }
}

/// Record that `input`'s owner binds a chord on it held by `modifier`, once
/// per modifier: the table [`View`] reads to shadow that owner's plain
/// bindings on the input, for a key, a mouse button and a pad button alike.
/// [`Routes::outranking_pad_chords`] keeps each chord's context beside its
/// modifier, so a chord is recorded once per modifier and context there.
fn add_chord<I: Eq + std::hash::Hash, M: PartialEq>(
    chords: &mut HashMap<I, Vec<M>>,
    input: I,
    modifier: M,
) {
    let modifiers = chords.entry(input).or_default();
    if !modifiers.contains(&modifier) {
        modifiers.push(modifier);
    }
}

impl ActionMap {
    /// Push a declared context on top of the stack.
    ///
    /// Every held input the context takes from a context beneath is withheld
    /// until released — see the module docs — and every action re-resolves, so
    /// what the context beneath lost reads as released on this tick.
    ///
    /// # Errors
    /// [`ActionMapError::UnknownContext`] if no action was ever declared in it,
    /// [`ActionMapError::ContextAlreadyActive`] if it is already on the stack.
    pub fn push_context(&mut self, context: &str) -> Result<(), ActionMapError> {
        self.push(context, false)
    }

    /// Push a declared context on top of the stack as **modal**: every key,
    /// pointer button, on-screen control, wheel and pad input it does not bind
    /// reaches nothing beneath it, where [`ActionMap::push_context`] lets it
    /// fall through. The pointer's position and motion still route beneath,
    /// and [`GLOBAL_CONTEXT`] stays above it.
    ///
    /// Everything else is [`ActionMap::push_context`]'s: an input held when it
    /// opens loses its owner and is withheld until released, so a walk held
    /// into an inventory stops, and does not resume when it closes until the
    /// key is pressed again.
    ///
    /// # Errors
    /// As [`ActionMap::push_context`].
    pub fn push_context_modal(&mut self, context: &str) -> Result<(), ActionMapError> {
        self.push(context, true)
    }

    fn push(&mut self, context: &str, modal: bool) -> Result<(), ActionMapError> {
        let index = self.context_index(context)?;
        if self.is_active(index) {
            return Err(ActionMapError::ContextAlreadyActive(context.to_owned()));
        }
        self.stack.push(index);
        if modal {
            self.modal.push(index);
        }
        self.restack();
        Ok(())
    }

    /// Pop the topmost pushed context, which must be `context`.
    ///
    /// Its actions go idle without a release edge, as a disabled action does,
    /// and inputs it held fall through to the contexts beneath only once they
    /// have been released.
    ///
    /// # Errors
    /// [`ActionMapError::UnknownContext`] if it was never declared,
    /// [`ActionMapError::ContextNotOnTop`] if it is not the topmost pushed
    /// context — including [`GAMEPLAY_CONTEXT`], which is never pushed.
    pub fn pop_context(&mut self, context: &str) -> Result<(), ActionMapError> {
        let index = self.context_index(context)?;
        if self.stack.len() == 1 || self.stack.last() != Some(&index) {
            return Err(ActionMapError::ContextNotOnTop(context.to_owned()));
        }
        self.stack.pop();
        self.modal.retain(|&modal| modal != index);
        self.restack();
        Ok(())
    }

    /// The stack's contexts' names, bottom first: [`GAMEPLAY_CONTEXT`], then
    /// each pushed context in the order it was pushed. [`GLOBAL_CONTEXT`] is
    /// active too, above them all, and is not listed.
    pub fn active_contexts(&self) -> impl Iterator<Item = &str> {
        self.stack
            .iter()
            .map(|&index| self.contexts[index].as_str())
    }

    /// Whether `context` is on the stack. `false` for one never declared.
    #[must_use]
    pub fn is_context_active(&self, context: &str) -> bool {
        self.contexts
            .iter()
            .position(|name| name == context)
            .is_some_and(|index| self.is_active(index))
    }

    /// Every active context in the order routing claims inputs for them:
    /// [`GLOBAL_CONTEXT`], then the stack from the top down.
    fn route_order(&self) -> impl Iterator<Item = usize> + '_ {
        std::iter::once(GLOBAL_INDEX).chain(self.stack.iter().rev().copied())
    }

    /// The modal context that stops an input from reaching a context beneath
    /// it with a binding `claims` accepts, if one does — what routing does to
    /// everything a modal context does not bind but the pointer's position and
    /// motion, which the trace never asks about.
    pub(crate) fn blocking_modal(&self, claims: impl Fn(&Binding) -> bool) -> Option<usize> {
        let mut modal = None;
        for context in self.route_order() {
            let binds = || {
                self.slots
                    .iter()
                    .filter(|slot| slot.context == context)
                    .any(|slot| slot.decl.bindings.iter().any(&claims))
            };
            if modal.is_some() && binds() {
                return modal;
            }
            if modal.is_none() && self.modal.contains(&context) {
                modal = Some(context);
            }
        }
        None
    }

    /// Whether `context` was pushed with [`ActionMap::push_context_modal`].
    /// `false` for one not on the stack, or never declared.
    #[must_use]
    pub fn is_context_modal(&self, context: &str) -> bool {
        self.contexts
            .iter()
            .position(|name| name == context)
            .is_some_and(|index| self.modal.contains(&index))
    }

    /// Whether the context at `index` routes input: [`GLOBAL_CONTEXT`] always,
    /// any other while it is on the stack.
    fn is_active(&self, index: usize) -> bool {
        index == GLOBAL_INDEX || self.stack.contains(&index)
    }

    /// The context an action was declared in, or `None` if it is not declared.
    #[must_use]
    pub fn context_of(&self, name: &str) -> Option<&str> {
        let &idx = self.name_to_idx.get(name)?;
        Some(self.contexts[self.slots[idx].context].as_str())
    }

    /// Let an action's [`Binding::PadChord`]s take their button from the
    /// contexts above it while their modifier is held, or put them back under
    /// the ordinary precedence — see the module docs.
    ///
    /// For a pad chord a player can give a gameplay action when the plain
    /// button is a global one: LB+Select rebound from a global free look to a
    /// gameplay reload reloads, and Select alone still opens the global map.
    /// The mark is the action's, not a binding's, so it holds whatever the
    /// action is rebound to — [`ActionMap::rebind`] and
    /// [`ActionMap::apply_overrides`] leave it alone, restoring the defaults
    /// included — and a binding asset declares it with
    /// `pad_chords_outrank: true` (`binding_asset.rs`). Off for every action
    /// until set.
    ///
    /// Every action re-resolves, as after a rebind, and nothing is withheld.
    ///
    /// # Errors
    /// [`ActionMapError::UnknownAction`] if nothing with that name is declared.
    pub fn set_pad_chords_outrank(
        &mut self,
        name: &str,
        outrank: bool,
    ) -> Result<(), ActionMapError> {
        let Some(&idx) = self.name_to_idx.get(name) else {
            return Err(ActionMapError::UnknownAction(name.to_owned()));
        };
        if self.slots[idx].pad_chords_outrank != outrank {
            self.slots[idx].pad_chords_outrank = outrank;
            self.reroute();
        }
        Ok(())
    }

    /// Whether an action's pad chords outrank the contexts above it — see
    /// [`ActionMap::set_pad_chords_outrank`]. `None` if it is not declared.
    #[must_use]
    pub fn pad_chords_outrank(&self, name: &str) -> Option<bool> {
        let &idx = self.name_to_idx.get(name)?;
        Some(self.slots[idx].pad_chords_outrank)
    }

    fn context_index(&self, context: &str) -> Result<usize, ActionMapError> {
        self.contexts
            .iter()
            .position(|name| name == context)
            .ok_or_else(|| ActionMapError::UnknownContext(context.to_owned()))
    }

    /// Whether the slot at `idx` reacts to input: enabled, in an active context.
    pub(crate) fn is_live(&self, idx: usize) -> bool {
        let slot = &self.slots[idx];
        slot.enabled && self.is_active(slot.context)
    }

    /// Rebuild the routes after a binding changed, and re-resolve every live
    /// action against them. Nothing is withheld.
    pub(crate) fn reroute(&mut self) {
        self.routes = Routes::build(self);
        self.resolve_live();
    }

    /// Re-resolve every live action.
    fn resolve_live(&mut self) {
        for idx in 0..self.slots.len() {
            if self.is_live(idx) {
                self.resolve_one(idx);
            }
        }
    }

    /// Withhold every input held right now, whoever owns it, until it is
    /// released — or for a level, until it rests — and cancel every pattern in
    /// flight. See the module docs for what lifts each input.
    ///
    /// For a state change that is not a context: movement keys held when a
    /// revival starts or a menu opens stop moving the player, and move it again
    /// only once pressed again. Every action re-resolves, so one that was down
    /// reads as released on this tick.
    pub fn suppress_held(&mut self) {
        let withheld = Suppressed {
            keys: self.held_keys.keys().copied().collect(),
            buttons: self.held_buttons.clone(),
            controls: self.held_controls.clone(),
            pad_buttons: self.held_pad_buttons,
            control_sticks: self
                .control_sticks
                .iter()
                .filter(|(_, deflection)| **deflection != (0.0, 0.0))
                .map(|(id, _)| id.clone())
                .collect(),
            pad_sticks: [Stick::Left, Stick::Right]
                .into_iter()
                .filter(|&stick| !self.stick_rests(stick))
                .collect(),
            pad_triggers: [Trigger::Left, Trigger::Right]
                .into_iter()
                .filter(|&trigger| !self.trigger_rests(trigger))
                .collect(),
        };
        for slot in &mut self.slots {
            slot.patterns.cancel();
        }
        self.withhold(withheld);
    }

    /// Withhold every input held right now that one action's bindings read,
    /// as [`ActionMap::suppress_held`] does for all of them, and cancel the
    /// patterns in flight on that action and on every action reading one of
    /// those inputs.
    ///
    /// The input is withheld, not the action: another action bound to the same
    /// key reads it as up too — see the module docs. A [`Binding::Chord`]
    /// withholds its key and not its modifier, and a [`Binding::ScrollChord`]
    /// its held key.
    ///
    /// # Errors
    /// [`ActionMapError::UnknownAction`] if nothing with that name is declared.
    pub fn suppress_held_action(&mut self, name: &str) -> Result<(), ActionMapError> {
        let Some(&idx) = self.name_to_idx.get(name) else {
            return Err(ActionMapError::UnknownAction(name.to_owned()));
        };
        let mut withheld = Suppressed::default();
        for binding in &self.slots[idx].decl.bindings {
            self.held_by(binding, &mut withheld);
        }
        self.slots[idx].patterns.cancel();
        for slot in &mut self.slots {
            if slot.decl.bindings.iter().any(|b| withheld.withholds(b)) {
                slot.patterns.cancel();
            }
        }
        self.withhold(withheld);
        Ok(())
    }

    /// Add to `withheld` every input `binding` reads that is held right now:
    /// a key down, a stick or trigger off rest, an on-screen stick off centre.
    fn held_by(&self, binding: &Binding, withheld: &mut Suppressed) {
        binding.visit_keys(|key| {
            if self.held_keys.contains_key(&key) {
                withheld.keys.insert(key);
            }
        });
        match binding {
            Binding::ScrollChord { held } if self.held_keys.contains_key(held) => {
                withheld.keys.insert(*held);
            }
            Binding::MouseButton(button) | Binding::ButtonChord { button, .. }
                if self.held_buttons.contains(button) =>
            {
                withheld.buttons.insert(*button);
            }
            Binding::Virtual(id) => {
                if self.held_controls.contains(id.as_str()) {
                    withheld.controls.insert(id.clone());
                }
                if self
                    .control_sticks
                    .get(id.as_str())
                    .is_some_and(|&deflection| deflection != (0.0, 0.0))
                {
                    withheld.control_sticks.insert(id.clone());
                }
            }
            Binding::PadButton(button) | Binding::PadChord { button, .. }
                if self.held_pad_buttons.contains(*button) =>
            {
                withheld.pad_buttons.insert(*button);
            }
            Binding::PadDpad => {
                for button in PadButton::DPAD {
                    if self.held_pad_buttons.contains(button) {
                        withheld.pad_buttons.insert(button);
                    }
                }
            }
            Binding::PadStick { stick, .. } if !self.stick_rests(*stick) => {
                withheld.pad_sticks.insert(*stick);
            }
            Binding::PadTrigger { trigger, .. } if !self.trigger_rests(*trigger) => {
                withheld.pad_triggers.insert(*trigger);
            }
            _ => {}
        }
    }

    /// Add `withheld` to what is withheld, and re-resolve every live action
    /// against it. The caller cancels the patterns first, so a press taken
    /// away is not read as a release that taps.
    fn withhold(&mut self, withheld: Suppressed) {
        self.suppressed.extend(withheld);
        self.resolve_live();
    }

    /// Rebuild the routes after the stack changed: withhold every held input
    /// whose owner moved, idle the actions of contexts that left, and
    /// re-resolve the rest.
    fn restack(&mut self) {
        let routes = Routes::build(self);
        let old = std::mem::replace(&mut self.routes, routes);
        let new = &self.routes;
        for key in self.held_keys.keys() {
            if old.keys.get(key) != new.keys.get(key) {
                self.suppressed.keys.insert(*key);
            }
        }
        for button in &self.held_buttons {
            if old.buttons.get(button) != new.buttons.get(button) {
                self.suppressed.buttons.insert(*button);
            }
        }
        for control in &self.held_controls {
            if old.controls.get(control) != new.controls.get(control) {
                self.suppressed.controls.insert(control.clone());
            }
        }
        let held = self.held_pad_buttons;
        for button in PadButton::ALL {
            if held.contains(button) && old.pad_reader(button, held) != new.pad_reader(button, held)
            {
                self.suppressed.pad_buttons.insert(button);
            }
        }
        for idx in 0..self.slots.len() {
            // Before resolving, so a press the new stack takes away is not
            // read as a release that taps: a stack change cancels every
            // pattern in flight — see `patterns.rs`.
            self.slots[idx].patterns.cancel();
            if self.is_active(self.slots[idx].context) {
                if self.slots[idx].enabled {
                    self.resolve_one(idx);
                }
            } else {
                self.slots[idx].reset();
            }
        }
    }
}

#[cfg(test)]
mod outrank_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ActionDecl, ActionKind, ActionValue, InputTickState, Repeat};

    const TICK: f32 = 1.0 / 60.0;

    fn button(name: &str, bindings: Vec<Binding>) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind: ActionKind::Button,
            bindings,
        }
    }

    /// `jump` on Space in gameplay, `accept` on Space and Enter in `menu`.
    fn menu_over_gameplay() -> ActionMap {
        let mut map = ActionMap::new();
        map.declare(button("jump", vec![Binding::Key(KeyCode::Space)]));
        map.declare(button("crouch", vec![Binding::Key(KeyCode::KeyC)]));
        map.declare_in(
            "menu",
            button(
                "accept",
                vec![Binding::Key(KeyCode::Space), Binding::Key(KeyCode::Enter)],
            ),
        );
        map
    }

    /// **A key bound in two contexts reaches only the topmost one while it is
    /// pushed, and the one beneath once it is popped.**
    #[test]
    fn a_key_bound_in_both_reaches_only_the_pushed_context_then_gameplay_after_pop() {
        let mut map = menu_over_gameplay();
        assert_eq!(map.context_of("accept"), Some("menu"));
        assert_eq!(map.context_of("jump"), Some(GAMEPLAY_CONTEXT));

        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(
            map.just_pressed("jump"),
            "nothing is pushed: gameplay has it"
        );
        assert!(
            !map.button_held("accept"),
            "and a context off the stack is idle"
        );
        map.key_event(KeyCode::Space, false);

        map.push_context("menu").expect("declared, not active");
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(map.just_pressed("accept"), "the pushed context owns Space");
        assert!(
            !map.button_held("jump"),
            "and gameplay beneath it does not see it"
        );
        map.key_event(KeyCode::Space, false);

        map.pop_context("menu").expect("menu is on top");
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(
            map.just_pressed("jump"),
            "popped: Space is gameplay's again"
        );
        assert!(!map.button_held("accept"));
    }

    /// Gameplay's walk on W, shoot on the left button, zoom on the wheel and
    /// an aim that reads the pointer's X; an inventory that binds only Escape;
    /// and the map toggle on M in [`GLOBAL_CONTEXT`].
    fn inventory_over_gameplay() -> ActionMap {
        let mut map = ActionMap::new();
        map.declare(button("walk", vec![Binding::Key(KeyCode::KeyW)]));
        map.declare(button(
            "shoot",
            vec![Binding::MouseButton(PointerButton::Left)],
        ));
        map.declare(axis("zoom", ActionKind::Axis1, vec![Binding::MouseScroll]));
        map.declare(axis(
            "aim_x",
            ActionKind::Axis1,
            vec![Binding::PointerPosition {
                axis: crate::PointerAxis::X,
            }],
        ));
        map.declare_in(
            "inventory",
            button("close", vec![Binding::Key(KeyCode::Escape)]),
        );
        map.declare_in(
            GLOBAL_CONTEXT,
            button("map", vec![Binding::Key(KeyCode::KeyM)]),
        );
        map
    }

    /// **A modal context stops every input it does not bind; a plain one lets
    /// it fall through.** Over a plain inventory, W still walks; over a modal
    /// one, W, the left button and the wheel reach nothing while Escape, which
    /// it binds, closes it — and the pointer's position still reaches the aim
    /// beneath, because a screen reads the cursor.
    #[test]
    fn a_modal_context_stops_what_it_does_not_bind() {
        let mut map = inventory_over_gameplay();
        map.push_context("inventory").expect("declared");
        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyW, true);
        assert!(map.button_held("walk"), "a plain context lets W through");
        map.key_event(KeyCode::KeyW, false);
        map.pop_context("inventory").expect("on top");

        map.push_context_modal("inventory").expect("declared");
        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyW, true);
        map.mouse_button(PointerButton::Left, true);
        map.mouse_scroll(0.0, 1.0);
        map.pointer_position(0.5, 0.25);
        map.key_event(KeyCode::Escape, true);
        assert!(!map.button_held("walk"), "W reached gameplay");
        assert!(
            !map.button_held("shoot"),
            "the left button reached gameplay"
        );
        assert_eq!(map.axis1("zoom"), 0.0, "the wheel reached gameplay");
        assert!(map.just_pressed("close"), "the modal context's own key");
        assert_eq!(map.axis1("aim_x"), 0.5, "the cursor is still read beneath");
    }

    /// **A key held into a modal context is dead until pressed again**, after
    /// it closes too: the walk held when the inventory opened does not resume
    /// when it closes.
    #[test]
    fn a_key_held_into_a_modal_context_waits_for_a_new_press() {
        let mut map = inventory_over_gameplay();
        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyW, true);
        assert!(map.button_held("walk"));

        map.push_context_modal("inventory").expect("declared");
        assert!(!map.button_held("walk"), "the walk stops as it opens");
        map.pop_context("inventory").expect("on top");
        map.begin_tick(TICK);
        assert!(!map.button_held("walk"), "and does not resume as it closes");

        map.key_event(KeyCode::KeyW, false);
        map.key_event(KeyCode::KeyW, true);
        assert!(map.button_held("walk"), "a new press walks");
    }

    /// **The global context works over anything, and is never pushed or
    /// popped.** M toggles the map over a modal inventory; pushing or popping
    /// it is refused; it is active and not listed among the stack's contexts.
    #[test]
    fn the_global_context_stays_above_a_modal_one() {
        let mut map = inventory_over_gameplay();
        map.push_context_modal("inventory").expect("declared");
        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyM, true);
        assert!(
            map.just_pressed("map"),
            "M is global's over the modal screen"
        );

        assert_eq!(
            map.push_context(GLOBAL_CONTEXT),
            Err(ActionMapError::ContextAlreadyActive(
                GLOBAL_CONTEXT.to_owned()
            ))
        );
        assert_eq!(
            map.pop_context(GLOBAL_CONTEXT),
            Err(ActionMapError::ContextNotOnTop(GLOBAL_CONTEXT.to_owned()))
        );
        assert!(map.is_context_active(GLOBAL_CONTEXT));
        assert_eq!(
            map.active_contexts().collect::<Vec<_>>(),
            [GAMEPLAY_CONTEXT, "inventory"]
        );
    }

    /// **An input the top context does not bind falls through**, and one no
    /// active context binds reaches nothing.
    #[test]
    fn an_input_the_top_context_does_not_bind_falls_through() {
        let mut map = menu_over_gameplay();
        map.push_context("menu").expect("declared");

        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyC, true);
        assert!(
            map.just_pressed("crouch"),
            "menu binds no C, so it falls through"
        );
        map.key_event(KeyCode::KeyQ, true);
        assert!(!map.button_held("accept") && !map.button_held("jump"));
    }

    /// **Nested pushes**: each input goes to the topmost context binding it,
    /// the stack is enforced, and popping the top hands its inputs back to the
    /// next one down.
    #[test]
    fn nested_pushes_route_each_input_to_the_topmost_binder() {
        let mut map = menu_over_gameplay();
        map.declare_in(
            "editor",
            button("select", vec![Binding::Key(KeyCode::Enter)]),
        );

        map.push_context("menu").expect("declared");
        map.push_context("editor").expect("declared");
        assert_eq!(
            map.active_contexts().collect::<Vec<_>>(),
            [GAMEPLAY_CONTEXT, "menu", "editor"],
        );
        assert_eq!(
            map.push_context("menu"),
            Err(ActionMapError::ContextAlreadyActive("menu".to_owned())),
        );
        assert_eq!(
            map.pop_context("menu"),
            Err(ActionMapError::ContextNotOnTop("menu".to_owned())),
            "menu is under editor, and popping it would pop editor's",
        );

        map.begin_tick(TICK);
        map.key_event(KeyCode::Enter, true);
        map.key_event(KeyCode::Space, true);
        map.key_event(KeyCode::KeyC, true);
        assert!(
            map.button_held("select"),
            "Enter: editor is topmost and binds it"
        );
        assert!(
            map.button_held("accept"),
            "Space falls through editor to menu"
        );
        assert!(
            !map.button_held("jump"),
            "and menu consumes it before gameplay"
        );
        assert!(map.button_held("crouch"), "C falls through both");
        for key in [KeyCode::Enter, KeyCode::Space, KeyCode::KeyC] {
            map.key_event(key, false);
        }

        map.pop_context("editor").expect("editor is on top");
        map.begin_tick(TICK);
        map.key_event(KeyCode::Enter, true);
        assert!(map.just_pressed("accept"), "editor popped: menu owns Enter");
        assert!(!map.button_held("select"), "and a popped context is idle");
    }

    /// **A key held while the stack changes is withheld from its new owner
    /// until it is released** — in both directions.
    #[test]
    fn a_key_held_across_a_push_or_pop_waits_for_its_release() {
        let mut map = menu_over_gameplay();

        // Held into a push: gameplay sees it come up, menu does not see it go
        // down.
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        map.begin_tick(TICK);
        map.push_context("menu").expect("declared");
        assert!(
            map.just_released("jump"),
            "the walk stops when a menu opens over it"
        );
        assert!(
            !map.button_held("accept"),
            "and the menu is not pressed by it"
        );
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true); // an OS auto-repeat is not a new press
        assert!(!map.button_held("accept"));
        map.key_event(KeyCode::Space, false);
        map.key_event(KeyCode::Space, true);
        assert!(
            map.just_pressed("accept"),
            "a fresh press after the lift is menu's"
        );

        // Held out through a pop: the accept that closed the menu does not jump.
        map.pop_context("menu").expect("menu is on top");
        assert!(
            !map.button_held("jump"),
            "the key that closed the menu does not jump"
        );
        map.begin_tick(TICK);
        assert!(!map.button_held("jump"));
        map.key_event(KeyCode::Space, false);
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(map.just_pressed("jump"));
    }

    /// A held key the pushed context does not bind keeps its owner, and so
    /// keeps working with no lift.
    #[test]
    fn a_held_key_whose_owner_does_not_change_is_not_withheld() {
        let mut map = menu_over_gameplay();
        map.key_event(KeyCode::KeyC, true);
        map.push_context("menu").expect("declared");
        map.begin_tick(TICK);
        assert!(map.button_held("crouch"));
        assert!(!map.just_released("crouch"));
    }

    /// Unknown contexts and the base are refused rather than ignored.
    #[test]
    fn the_stack_refuses_unknown_contexts_and_the_base() {
        let mut map = menu_over_gameplay();
        assert_eq!(
            map.push_context("nope"),
            Err(ActionMapError::UnknownContext("nope".to_owned())),
        );
        assert_eq!(
            map.push_context(GAMEPLAY_CONTEXT),
            Err(ActionMapError::ContextAlreadyActive(
                GAMEPLAY_CONTEXT.to_owned()
            )),
        );
        assert_eq!(
            map.pop_context(GAMEPLAY_CONTEXT),
            Err(ActionMapError::ContextNotOnTop(GAMEPLAY_CONTEXT.to_owned())),
        );
        assert!(map.is_context_active(GAMEPLAY_CONTEXT));
        assert!(!map.is_context_active("menu"));
        assert!(!map.is_context_active("nope"));
    }

    /// The pointer, a button and an on-screen control are consumed like keys.
    #[test]
    fn pointer_inputs_and_controls_are_consumed_too() {
        let mut map = ActionMap::new();
        map.declare(button(
            "fire",
            vec![
                Binding::MouseButton(PointerButton::Left),
                Binding::Virtual("btn".to_owned()),
            ],
        ));
        map.declare(ActionDecl {
            name: "aim".to_owned(),
            kind: ActionKind::Axis1,
            bindings: vec![Binding::PointerPosition {
                axis: crate::PointerAxis::X,
            }],
        });
        map.declare_in(
            "menu",
            ActionDecl {
                name: "cursor".to_owned(),
                kind: ActionKind::Axis1,
                bindings: vec![Binding::PointerPosition {
                    axis: crate::PointerAxis::X,
                }],
            },
        );
        map.declare_in(
            "menu",
            button(
                "click",
                vec![
                    Binding::MouseButton(PointerButton::Left),
                    Binding::Virtual("btn".to_owned()),
                ],
            ),
        );
        map.push_context("menu").expect("declared");

        map.begin_tick(TICK);
        map.pointer_position(0.5, 0.0);
        map.mouse_button(PointerButton::Left, true);
        map.virtual_button("btn", true);
        assert!(map.just_pressed("click"));
        assert!(!map.button_held("fire"));
        assert_eq!(map.axis1("cursor"), 0.5);
        assert_eq!(
            map.axis1("aim"),
            0.0,
            "the menu's pointer is not the game's"
        );
        let Some(ActionValue::Axis1(aim)) = map.action("aim") else {
            panic!("aim is an Axis1");
        };
        assert!(!aim.pointer_moved, "nor did it move for the game");

        // And not on the next tick either, which re-resolves every action.
        map.begin_tick(TICK);
        assert_eq!(map.axis1("aim"), 0.0, "a consumed pointer stays consumed");
        assert!(!map.button_held("fire"));
    }

    /// A rebind can take a key from a context beneath, and the context beneath
    /// releases it on the spot.
    #[test]
    fn a_rebind_moves_ownership_and_re_resolves_the_loser() {
        let mut map = menu_over_gameplay();
        map.push_context("menu").expect("declared");
        map.key_event(KeyCode::KeyC, true);
        assert!(map.button_held("crouch"));

        map.rebind("accept", vec![Binding::Key(KeyCode::KeyC)])
            .expect("declared");
        assert!(
            !map.button_held("crouch"),
            "menu took C, so gameplay lost it"
        );
        assert!(
            map.button_held("accept"),
            "and a rebind resolves against held keys"
        );
    }

    /// **Chords take the key from plain bindings on it**: Tab and Shift+Tab in
    /// one context never both fire, and the modifier is not consumed.
    #[test]
    fn a_chord_shadows_the_plain_key_and_leaves_its_modifier_alone() {
        let mut map = ActionMap::new();
        map.declare(button("sprint", vec![Binding::Key(KeyCode::ShiftLeft)]));
        map.declare_in("menu", button("next", vec![Binding::Key(KeyCode::Tab)]));
        map.declare_in(
            "menu",
            button(
                "prev",
                vec![Binding::Chord {
                    modifier: Modifier::Shift,
                    key: KeyCode::Tab,
                }],
            ),
        );
        map.push_context("menu").expect("declared");

        map.begin_tick(TICK);
        map.key_event(KeyCode::Tab, true);
        assert!(map.button_held("next") && !map.button_held("prev"));

        map.key_event(KeyCode::ShiftLeft, true);
        assert!(
            map.just_released("next"),
            "Shift turns the held Tab into Shift+Tab"
        );
        assert!(map.just_pressed("prev"));
        assert!(
            map.button_held("sprint"),
            "the modifier still reaches gameplay"
        );

        map.key_event(KeyCode::ShiftLeft, false);
        assert!(!map.button_held("prev") && map.button_held("next"));
    }

    fn alt_right() -> Binding {
        Binding::ButtonChord {
            modifier: Modifier::Alt,
            button: PointerButton::Right,
        }
    }

    /// `aim` on the right button, `zoom` on Alt+right and `lean` on Alt alone,
    /// all in gameplay.
    fn sights() -> ActionMap {
        let mut map = ActionMap::new();
        map.declare(button(
            "aim",
            vec![Binding::MouseButton(PointerButton::Right)],
        ));
        map.declare(button("zoom", vec![alt_right()]));
        map.declare(button("lean", vec![Binding::Key(KeyCode::AltLeft)]));
        map
    }

    /// **A button chord takes the button from the plain binding on it**, and
    /// leaves its modifier alone: a right click aims, Alt+right click zooms
    /// and does not aim, and Alt's own binding sees Alt either way.
    #[test]
    fn a_button_chord_shadows_the_plain_button_and_leaves_its_modifier_alone() {
        let mut map = sights();
        map.begin_tick(TICK);
        map.mouse_button(PointerButton::Right, true);
        assert!(map.button_held("aim") && !map.button_held("zoom"));

        map.mouse_button(PointerButton::Right, false);
        map.begin_tick(TICK);
        map.key_event(KeyCode::AltLeft, true);
        map.mouse_button(PointerButton::Right, true);
        assert!(map.just_pressed("zoom"));
        assert!(!map.button_held("aim"), "the plain binding fired too");
        assert!(map.button_held("lean"), "the modifier was consumed");
    }

    /// **The modifier hands the held button over both ways**, as a key
    /// chord's does: pressed over a held right button it releases the aim and
    /// presses the zoom, and let go first it hands the button back.
    #[test]
    fn a_modifier_hands_a_held_mouse_button_to_the_chord_and_back() {
        let mut map = sights();
        map.begin_tick(TICK);
        map.mouse_button(PointerButton::Right, true);
        assert!(map.just_pressed("aim"));

        map.begin_tick(TICK);
        map.key_event(KeyCode::AltRight, true);
        assert!(
            map.just_released("aim"),
            "Alt turns the held right button into Alt+right"
        );
        assert!(map.just_pressed("zoom"));

        map.begin_tick(TICK);
        map.key_event(KeyCode::AltRight, false);
        assert!(map.just_released("zoom"));
        assert!(map.just_pressed("aim"), "the button went back to the aim");
    }

    /// **A button chord shadows plain bindings only in the context that owns
    /// the button**: declared in a context off the stack, it leaves the right
    /// button with gameplay; pushed, it takes it.
    #[test]
    fn a_button_chord_shadows_only_in_the_context_that_owns_its_button() {
        let mut map = ActionMap::new();
        map.declare(button(
            "aim",
            vec![Binding::MouseButton(PointerButton::Right)],
        ));
        map.declare_in("optic", button("magnify", vec![alt_right()]));
        map.key_event(KeyCode::AltLeft, true);
        map.mouse_button(PointerButton::Right, true);
        assert!(
            map.button_held("aim"),
            "a chord off the stack shadowed the button"
        );
        assert!(!map.button_held("magnify"));

        map.mouse_button(PointerButton::Right, false);
        map.push_context("optic").expect("declared");
        map.mouse_button(PointerButton::Right, true);
        assert!(map.button_held("magnify"));
        assert!(!map.button_held("aim"));
    }

    fn axis(name: &str, kind: ActionKind, bindings: Vec<Binding>) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind,
            bindings,
        }
    }

    fn wasd() -> Binding {
        Binding::Wasd {
            up: KeyCode::KeyW,
            down: KeyCode::KeyS,
            left: KeyCode::KeyA,
            right: KeyCode::KeyD,
        }
    }

    /// **`suppress_held` withholds a held key until it is pressed again**: the
    /// action reads released at once, an OS auto-repeat does not bring it back,
    /// and a fresh press after the lift does.
    #[test]
    fn suppress_held_withholds_a_key_until_it_is_pressed_again() {
        let mut map = menu_over_gameplay();
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        map.begin_tick(TICK);
        map.suppress_held();
        assert!(map.just_released("jump"), "the walk stops on the spot");
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true); // an OS auto-repeat
        assert!(!map.button_held("jump"));
        map.key_event(KeyCode::Space, false);
        map.key_event(KeyCode::Space, true);
        assert!(map.just_pressed("jump"), "pressed again");
    }

    /// **Suppressing mid-press fires neither the hold nor the tap**, and the
    /// press after the release fires as usual.
    #[test]
    fn suppress_held_mid_press_fires_no_pattern_and_the_next_press_does() {
        let mut map = menu_over_gameplay();
        map.set_tap("jump", Some(crate::Tap::default()))
            .expect("declared");
        map.set_hold("jump", Some(crate::Hold::default()))
            .expect("declared");
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        map.begin_tick(TICK);
        map.suppress_held();
        let mut fired = map.tapped("jump");
        for _ in 0..60 {
            map.begin_tick(TICK);
            fired |= map.hold_fired("jump");
        }
        map.key_event(KeyCode::Space, false);
        fired |= map.tapped("jump");
        assert!(!fired, "neither a hold nor a tap");

        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, false);
        assert!(map.tapped("jump"), "suppress, release, press: it taps");
    }

    /// A first tap waiting for its second is dropped by `suppress_held`, with
    /// nothing held at the time.
    #[test]
    fn suppress_held_drops_a_waiting_first_tap() {
        let mut map = menu_over_gameplay();
        map.set_double_tap("jump", Some(crate::DoubleTap::default()))
            .expect("declared");
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        map.key_event(KeyCode::Space, false);
        map.suppress_held();
        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(!map.double_tapped("jump"));
    }

    /// **A `Wasd` axis is withheld per key**: a key held through the suppress
    /// reads zero until pressed again, and a key pressed afresh moves the axis
    /// meanwhile. A `KeyAxis` likewise.
    #[test]
    fn suppress_held_withholds_an_axis_per_key() {
        let mut map = ActionMap::new();
        map.declare(axis("move", ActionKind::Axis2, vec![wasd()]));
        map.declare(axis(
            "zoom",
            ActionKind::Axis1,
            vec![Binding::KeyAxis {
                negative: KeyCode::KeyQ,
                positive: KeyCode::KeyE,
            }],
        ));
        map.key_event(KeyCode::KeyW, true);
        map.key_event(KeyCode::KeyE, true);
        map.suppress_held();
        assert_eq!(map.axis2("move"), (0.0, 0.0));
        assert_eq!(map.axis1("zoom"), 0.0);

        map.begin_tick(TICK);
        assert_eq!(map.axis2("move"), (0.0, 0.0), "still held, still withheld");
        map.key_event(KeyCode::KeyD, true);
        assert_eq!(map.axis2("move"), (1.0, 0.0), "a fresh key moves");
        map.key_event(KeyCode::KeyQ, true);
        assert_eq!(map.axis1("zoom"), -1.0);

        map.key_event(KeyCode::KeyW, false);
        map.key_event(KeyCode::KeyW, true);
        let (x, y) = map.axis2("move");
        assert!(
            x > 0.0 && y > 0.0,
            "W pressed again: diagonal, got {x}, {y}"
        );
    }

    /// A chord is withheld through its key: pressed again with the modifier
    /// still down, it reads again.
    #[test]
    fn suppress_held_withholds_a_chord_until_its_key_is_pressed_again() {
        let mut map = ActionMap::new();
        map.declare(button(
            "save",
            vec![Binding::Chord {
                modifier: Modifier::Control,
                key: KeyCode::KeyS,
            }],
        ));
        map.key_event(KeyCode::ControlLeft, true);
        map.key_event(KeyCode::KeyS, true);
        assert!(map.button_held("save"));
        map.suppress_held();
        assert!(!map.button_held("save"));
        map.key_event(KeyCode::KeyS, false);
        map.key_event(KeyCode::KeyS, true);
        assert!(map.just_pressed("save"), "Ctrl never let go");
    }

    /// A button chord is withheld through its button, as a key chord is
    /// through its key: clicked again with the modifier still down, it reads
    /// again.
    #[test]
    fn suppress_held_withholds_a_button_chord_until_its_button_is_pressed_again() {
        let mut map = sights();
        map.key_event(KeyCode::AltLeft, true);
        map.mouse_button(PointerButton::Right, true);
        assert!(map.button_held("zoom"));
        map.suppress_held();
        assert!(!map.button_held("zoom"));
        map.mouse_button(PointerButton::Right, false);
        map.mouse_button(PointerButton::Right, true);
        assert!(map.just_pressed("zoom"), "Alt never let go");
    }

    /// Pointer buttons, on-screen buttons and on-screen sticks are withheld
    /// too, a stick until it reports centre.
    #[test]
    fn suppress_held_withholds_pointer_buttons_and_on_screen_controls() {
        let mut map = ActionMap::new();
        map.declare(button(
            "fire",
            vec![
                Binding::MouseButton(PointerButton::Left),
                Binding::Virtual("btn".to_owned()),
            ],
        ));
        map.declare(axis(
            "move",
            ActionKind::Axis2,
            vec![Binding::Virtual("stick".to_owned())],
        ));
        map.mouse_button(PointerButton::Left, true);
        map.virtual_button("btn", true);
        map.virtual_stick("stick", 0.0, 1.0);
        map.suppress_held();
        assert!(!map.button_held("fire"));
        assert_eq!(map.axis2("move"), (0.0, 0.0));

        map.virtual_stick("stick", 0.5, 0.5);
        assert_eq!(map.axis2("move"), (0.0, 0.0), "moved, never centred");
        map.virtual_stick("stick", 0.0, 0.0);
        map.virtual_stick("stick", 0.0, 1.0);
        assert_eq!(map.axis2("move"), (0.0, 1.0), "centred, then pushed");

        map.mouse_button(PointerButton::Left, false);
        assert!(
            !map.button_held("fire"),
            "the on-screen button is still held"
        );
        map.virtual_button("btn", false);
        map.mouse_button(PointerButton::Left, true);
        assert!(map.just_pressed("fire"));
    }

    fn pad(snapshot: impl FnOnce(&mut crate::GamepadSnapshot)) -> crate::GamepadEvent {
        let mut state = crate::GamepadSnapshot::neutral(crate::PadKind::Xbox);
        snapshot(&mut state);
        crate::GamepadEvent::State {
            id: crate::GamepadId(1),
            snapshot: state,
        }
    }

    fn stick_y(y: f32) -> crate::GamepadEvent {
        pad(|state| state.axes[crate::PadAxis::LeftY as usize] = y)
    }

    /// **A pad stick is withheld until it rests inside its dead zone**, and a
    /// trigger until it is back under its threshold; a pad button until it is
    /// released.
    #[test]
    fn suppress_held_withholds_pad_buttons_sticks_and_triggers() {
        let mut map = ActionMap::new();
        map.declare(axis(
            "move",
            ActionKind::Axis2,
            vec![Binding::PadStick {
                stick: Stick::Left,
                deadzone: 0.2,
            }],
        ));
        map.declare(button(
            "fire",
            vec![Binding::PadTrigger {
                trigger: Trigger::Right,
                threshold: 0.5,
            }],
        ));
        map.declare(button("jump", vec![Binding::PadButton(PadButton::South)]));
        map.gamepad_event(&pad(|state| {
            state.axes[crate::PadAxis::LeftY as usize] = 1.0;
            state.axes[crate::PadAxis::RightTrigger as usize] = 1.0;
            state.buttons.insert(PadButton::South);
        }));
        assert_eq!(map.axis2("move"), (0.0, 1.0));
        assert!(map.button_held("fire") && map.button_held("jump"));
        map.suppress_held();
        assert_eq!(map.axis2("move"), (0.0, 0.0));
        assert!(!map.button_held("fire") && !map.button_held("jump"));

        map.gamepad_event(&stick_y(0.8));
        assert_eq!(map.axis2("move"), (0.0, 0.0), "eased off, never rested");
        assert!(!map.button_held("jump"), "and South was let go of");
        map.gamepad_event(&stick_y(0.1));
        map.gamepad_event(&stick_y(1.0));
        assert_eq!(map.axis2("move"), (0.0, 1.0), "rested, then pushed");
        map.gamepad_event(&pad(|state| {
            state.axes[crate::PadAxis::RightTrigger as usize] = 1.0;
            state.buttons.insert(PadButton::South);
        }));
        assert!(map.button_held("fire") && map.button_held("jump"));
    }

    /// **`suppress_held_action` withholds only what that action reads**: an
    /// action on another held key keeps it, and an action sharing the key
    /// loses it too.
    #[test]
    fn suppress_held_action_withholds_only_that_actions_inputs() {
        let mut map = ActionMap::new();
        map.declare(axis("move", ActionKind::Axis2, vec![wasd()]));
        map.declare(button("forward", vec![Binding::Key(KeyCode::KeyW)]));
        map.declare(button("jump", vec![Binding::Key(KeyCode::Space)]));
        map.key_event(KeyCode::KeyW, true);
        map.key_event(KeyCode::Space, true);
        map.suppress_held_action("move").expect("declared");
        assert_eq!(map.axis2("move"), (0.0, 0.0));
        assert!(!map.button_held("forward"), "W itself is withheld");
        assert!(map.button_held("jump"), "Space is not move's");
        map.key_event(KeyCode::KeyW, false);
        map.key_event(KeyCode::KeyW, true);
        assert_eq!(map.axis2("move"), (0.0, 1.0));
        assert_eq!(
            map.suppress_held_action("nope"),
            Err(ActionMapError::UnknownAction("nope".to_owned())),
        );
    }

    /// `zoom` on the plain wheel, `zoom_z` on Z+wheel, `zoom_ctrl` on
    /// Ctrl+wheel, and `z` on Z itself, all in gameplay.
    fn scroll_chords() -> ActionMap {
        let mut map = ActionMap::new();
        map.declare(axis("zoom", ActionKind::Axis1, vec![Binding::MouseScroll]));
        for (name, held) in [
            ("zoom_z", KeyCode::KeyZ),
            ("zoom_ctrl", KeyCode::ControlLeft),
        ] {
            map.declare(axis(
                name,
                ActionKind::Axis1,
                vec![Binding::ScrollChord { held }],
            ));
        }
        map.declare(button("z", vec![Binding::Key(KeyCode::KeyZ)]));
        map
    }

    /// Scroll one detent on a fresh tick and read who got it.
    fn wheel(map: &mut ActionMap) -> [f32; 3] {
        map.begin_tick(TICK);
        map.mouse_scroll(0.0, 1.0);
        ["zoom", "zoom_z", "zoom_ctrl"].map(|name| map.axis1(name))
    }

    /// **A disabled action's scroll chord takes the wheel from nothing.** Ctrl
    /// goes down for `zoom_ctrl`, then Z for `zoom_z` while `zoom_z` is
    /// disabled: the wheel stays Ctrl's. With Ctrl up too, the plain wheel is
    /// not silenced by Z. Enabled again, Z takes the wheel back from Ctrl by
    /// when it went down, which was after Ctrl, not by when it was enabled.
    #[test]
    fn a_disabled_scroll_chord_takes_the_wheel_from_nothing() {
        let mut map = scroll_chords();
        map.key_event(KeyCode::ControlLeft, true);
        map.set_enabled("zoom_z", false);
        map.key_event(KeyCode::KeyZ, true);
        assert_eq!(wheel(&mut map), [0.0, 0.0, 1.0], "Ctrl keeps the wheel");

        map.key_event(KeyCode::ControlLeft, false);
        assert_eq!(wheel(&mut map), [1.0, 0.0, 0.0], "Z silences nothing");

        map.key_event(KeyCode::ControlLeft, true);
        map.set_enabled("zoom_z", true);
        assert_eq!(
            wheel(&mut map),
            [0.0, 0.0, 1.0],
            "Ctrl went down after Z, so it is the newer press"
        );
        map.key_event(KeyCode::ControlLeft, false);
        map.key_event(KeyCode::ControlLeft, true);
        map.key_event(KeyCode::KeyZ, false);
        map.key_event(KeyCode::KeyZ, true);
        map.set_enabled("zoom_z", false);
        map.set_enabled("zoom_z", true);
        assert_eq!(
            wheel(&mut map),
            [0.0, 1.0, 0.0],
            "Z pressed after Ctrl takes it back once enabled"
        );
    }

    /// **A scroll chord takes the wheel from the plain binding while its key is
    /// down**, gives it back on release, and reads the key without consuming
    /// it.
    #[test]
    fn a_scroll_chord_takes_the_wheel_while_its_key_is_down() {
        let mut map = scroll_chords();
        assert_eq!(wheel(&mut map), [1.0, 0.0, 0.0]);
        map.key_event(KeyCode::KeyZ, true);
        assert_eq!(wheel(&mut map), [0.0, 1.0, 0.0]);
        assert!(map.button_held("z"), "Z is read, not consumed");
        map.key_event(KeyCode::KeyZ, false);
        assert_eq!(wheel(&mut map), [1.0, 0.0, 0.0], "the wheel is back");
    }

    /// **With two scroll-chord keys down, the most recently pressed one takes
    /// the wheel**, in either order, and releasing it hands the wheel back to
    /// the other; an auto-repeat of the earlier key takes nothing.
    #[test]
    fn the_most_recently_pressed_scroll_chord_key_takes_the_wheel() {
        let mut map = scroll_chords();
        map.key_event(KeyCode::ControlLeft, true);
        map.key_event(KeyCode::KeyZ, true);
        assert_eq!(wheel(&mut map), [0.0, 1.0, 0.0], "Ctrl then Z: Z's");
        map.key_event(KeyCode::ControlLeft, true); // an OS auto-repeat
        assert_eq!(wheel(&mut map), [0.0, 1.0, 0.0], "a repeat is no press");
        map.key_event(KeyCode::KeyZ, false);
        assert_eq!(wheel(&mut map), [0.0, 0.0, 1.0], "back to Ctrl");
        map.key_event(KeyCode::ControlLeft, false);

        map.key_event(KeyCode::KeyZ, true);
        map.key_event(KeyCode::ControlLeft, true);
        assert_eq!(wheel(&mut map), [0.0, 0.0, 1.0], "Z then Ctrl: Ctrl's");
        map.key_event(KeyCode::ControlLeft, false);
        assert_eq!(wheel(&mut map), [0.0, 1.0, 0.0], "back to Z");
        map.key_event(KeyCode::KeyZ, false);
        assert_eq!(wheel(&mut map), [1.0, 0.0, 0.0]);
    }

    /// A key pressed after the wheel turned, in the same tick, moves that
    /// tick's scroll to the chord: the key re-resolves the wheel's bindings.
    #[test]
    fn a_scroll_chord_key_pressed_mid_tick_takes_that_ticks_scroll() {
        let mut map = scroll_chords();
        map.begin_tick(TICK);
        map.mouse_scroll(0.0, 1.0);
        map.key_event(KeyCode::KeyZ, true);
        assert_eq!(["zoom", "zoom_z"].map(|name| map.axis1(name)), [0.0, 1.0]);
    }

    /// **A scroll chord in a pushed context takes the wheel for it**, and its
    /// key shadows only that context's plain wheel: the context beneath gets
    /// no wheel at all, as with any consumed input.
    #[test]
    fn a_scroll_chord_claims_the_wheel_for_its_context() {
        let mut map = ActionMap::new();
        map.declare(axis("zoom", ActionKind::Axis1, vec![Binding::MouseScroll]));
        map.declare_in(
            "map",
            axis(
                "pan",
                ActionKind::Axis1,
                vec![Binding::ScrollChord {
                    held: KeyCode::AltLeft,
                }],
            ),
        );
        map.push_context("map").expect("declared");
        map.begin_tick(TICK);
        map.mouse_scroll(0.0, 1.0);
        assert_eq!(map.axis1("zoom"), 0.0, "the pushed context owns the wheel");
        assert_eq!(map.axis1("pan"), 0.0, "and Alt is not down");
        map.key_event(KeyCode::AltLeft, true);
        assert_eq!(map.axis1("pan"), 1.0);
    }

    /// A scroll chord's key withheld by `suppress_held` reads as up: the plain
    /// wheel has it until the key is pressed again.
    #[test]
    fn a_suppressed_scroll_chord_key_leaves_the_wheel_plain() {
        let mut map = scroll_chords();
        map.key_event(KeyCode::KeyZ, true);
        map.suppress_held();
        assert_eq!(wheel(&mut map), [1.0, 0.0, 0.0]);
        map.key_event(KeyCode::KeyZ, false);
        map.key_event(KeyCode::KeyZ, true);
        assert_eq!(wheel(&mut map), [0.0, 1.0, 0.0]);
    }

    /// **The same scripted input yields the same action stream twice**, from
    /// two maps built independently — each with its own hash seeds, so a rule
    /// that leaned on a `HashMap`'s iteration order would split them.
    #[test]
    fn a_scripted_sequence_yields_the_same_action_stream_twice() {
        fn run() -> Vec<String> {
            let mut map = ActionMap::new();
            map.declare(ActionDecl {
                name: "move".to_owned(),
                kind: ActionKind::Axis2,
                bindings: vec![Binding::Wasd {
                    up: KeyCode::KeyW,
                    down: KeyCode::KeyS,
                    left: KeyCode::KeyA,
                    right: KeyCode::KeyD,
                }],
            });
            map.declare(button("jump", vec![Binding::Key(KeyCode::Space)]));
            crate::ui::declare(&mut map).expect("no clash with move or jump");
            map.set_repeat("jump", Some(Repeat::UI)).expect("declared");

            let script: &[(u32, KeyCode, bool)] = &[
                (0, KeyCode::KeyD, true),
                (1, KeyCode::Space, true),
                (3, KeyCode::KeyW, true),
                (5, KeyCode::Tab, true),
                (6, KeyCode::ShiftRight, true),
                (9, KeyCode::Space, false),
                (12, KeyCode::KeyD, false),
                (14, KeyCode::Space, true),
                (20, KeyCode::KeyW, false),
                (40, KeyCode::Tab, false),
                (41, KeyCode::ShiftRight, false),
                (44, KeyCode::Space, false),
            ];
            let mut stream = Vec::new();
            for tick in 0..60 {
                map.begin_tick(TICK);
                match tick {
                    4 | 30 => map.push_context(crate::ui::CONTEXT).expect("off the stack"),
                    18 | 50 => map.pop_context(crate::ui::CONTEXT).expect("on top"),
                    _ => {}
                }
                for &(at, key, pressed) in script {
                    if at == tick {
                        map.key_event(key, pressed);
                    }
                }
                let repeats: Vec<bool> =
                    map.action_names().map(|name| map.repeated(name)).collect();
                stream.push(format!(
                    "{tick} {:?} {repeats:?} {:?}",
                    InputTickState::capture(&map),
                    map.last_device(),
                ));
            }
            stream
        }

        let first = run();
        assert_eq!(first, run());
        assert!(
            first.iter().any(|line| line.contains("just_pressed: true")),
            "the script pressed something, or equality says nothing",
        );
    }
}