crcbl-input 0.5.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
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
//! Device-agnostic action system: gameplay and UI code consume **actions**,
//! never raw devices. Keyboard, mouse, gamepad and on-screen controls are
//! interchangeable binding sources behind one config layer.
//!
//! # Contexts
//!
//! Every action belongs to one named context: [`ActionMap::declare`] puts it in
//! [`GAMEPLAY_CONTEXT`], which is always active, and [`ActionMap::declare_in`]
//! names another. [`ActionMap::push_context`] and [`ActionMap::pop_context`]
//! stack contexts over it — [`ActionMap::push_context_modal`] one that passes
//! nothing it does not bind — [`GLOBAL_CONTEXT`] stays above them all, and
//! **the topmost active context that binds an input consumes it** — `context.rs` has the rules, including what happens to a key
//! held while the stack changes, and what [`ActionMap::suppress_held`] and
//! [`ActionMap::suppress_held_action`] withhold on request. [`ui`] declares the
//! engine's reserved `ui`
//! context, [`text`] the `text` context a text field pushes over it, and
//! [`list`] the `list` context an open pop-up list pushes over it.
//!
//! # Patterns and devices
//!
//! [`ActionMap::set_repeat`] attaches a [`Repeat`] to an action, and
//! [`ActionMap::set_tap`], [`ActionMap::set_hold`] and
//! [`ActionMap::set_double_tap`] attach a [`Tap`], a [`Hold`] and a
//! [`DoubleTap`], all evaluated on the clock [`ActionMap::begin_tick`] advances
//! (`repeat.rs`, and `patterns.rs` for how the last three share a press and
//! what [`ActionMap::cancel_patterns`] cancels). [`ActionMap::set_emits`] makes
//! one of the last three press a named button action when it fires
//! (`emit.rs`).
//! [`ActionMap::last_device`] names the kind of [`Device`] that last spoke,
//! [`ActionMap::last_device_changed`] says it just changed, and
//! [`ActionMap::hint`] how an action's binding is shown to the player on it
//! ([`hint`]).
//!
//! # Why an input did what it did
//!
//! [`ActionMap::set_tracing`] records, for each press, the context that
//! consumed it and every binding that read it — or that a modal context
//! stopped it, or that nothing binds it — in a bounded ring an input
//! inspector reads ([`trace`]).
//!
//! # Gamepads
//!
//! Every pad backend emits [`GamepadEvent`]s, by the conventions `gamepad.rs`
//! states — positional buttons, sticks with +Y up, triggers 0…1, raw axes. A
//! game reads them directly, or feeds [`ActionMap::gamepad_event`], where
//! [`Binding::PadButton`], [`Binding::PadDpad`], [`Binding::PadStick`] and
//! [`Binding::PadTrigger`] read them. The Windows backend is `xinput`,
//! compiled on Windows only, the Linux one is `evdev`, compiled on Linux only,
//! the macOS one is `game_controller`, compiled on macOS only, and the browser
//! one is `web_gamepad`, compiled on `wasm32` only: no other target has a
//! backend yet, and none has a stand-in that would report "no pads" as though
//! it had looked.

mod active_pad;
pub mod binding_asset;
pub mod binding_text;
mod context;
mod device;
mod eight_way;
mod emit;
// Linux-only: the `evdev` backend. Compiled into every target's tests too, so
// its mapping, normalisation, layouts and poller run on the Windows and macOS
// runners; only the device access is Linux-only.
#[cfg(any(target_os = "linux", test))]
pub mod evdev;
#[cfg(test)]
mod ffi_layout;
// The clamp for pad values that arrive as floats, which the browser and
// GameController backends share.
#[cfg(any(target_arch = "wasm32", target_os = "macos", test))]
mod float_axis;
// macOS-only: the GameController.framework backend. Compiled into every
// target's tests too, so its mapping, classification and poller run on the
// Windows and Linux runners; only the framework access is macOS-only.
#[cfg(any(target_os = "macos", test))]
pub mod game_controller;
mod gamepad;
pub mod hint;
pub mod list;
mod overrides;
mod patterns;
// The name match the browser and GameController backends name a pad's family
// from when they have no USB ids.
#[cfg(any(target_arch = "wasm32", target_os = "macos", test))]
mod product_name;
mod repeat;
pub mod text;
pub mod trace;
pub mod ui;
// The vendor and product ids the evdev and browser backends name a pad's
// family from; only those two read them.
#[cfg(any(target_os = "linux", target_arch = "wasm32", test))]
mod usb;
// wasm32-only: the Web Gamepad API backend. Compiled into every target's tests
// too, so its mapping, poller and shim entry points run on the native runners;
// only the symbols a page calls are exported, and only from a wasm32 build.
#[cfg(any(target_arch = "wasm32", test))]
pub mod web_gamepad;
// Compiled into every target's tests too, so the mapping and the layouts are
// checked on the Linux and macOS runners; only the loader is Windows-only.
#[cfg(any(windows, test))]
pub mod xinput;

pub use active_pad::{ActivePad, StickUpdate};
pub use binding_asset::{AssetRefusal, AssetWriteError, BindingAssetError};
pub use binding_text::BindingParseError;
pub use context::{GAMEPLAY_CONTEXT, GLOBAL_CONTEXT};
pub use device::Device;
pub use eight_way::{EIGHT_WAY_SECTOR, eight_way};
pub use emit::Pattern;
pub use gamepad::{
    GamepadEvent, GamepadId, GamepadSnapshot, PAD_ACTIVITY_THRESHOLD, PadAxis, PadButton,
    PadButtons, PadKind, Stick, Trigger, radial_deadzone,
};
pub use hint::{DefaultLabels, Hint, HintLabels};
pub use overrides::{ActionOverride, OverrideRefusal};
pub use patterns::{DOUBLE_TAP_WINDOW, DoubleTap, HOLD_TIME, Hold, TAP_TIME, Tap};
pub use repeat::{Cardinal, REPEAT_DELAY, REPEAT_INTERVAL, Repeat};
pub use trace::{Outcome, RESOLUTION_TRACE_CAP, TraceEntry, TracedInput, TracedRead};

use context::{Routes, Suppressed, View};
use crcbl_core::input::{KeyCode, PointerButton};
use patterns::PatternState;
use repeat::RepeatState;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};

/// Every connected pad and what it last reported, ordered by id so a sum over
/// them runs in the same order every run.
type Pads = BTreeMap<GamepadId, GamepadSnapshot>;

/// Every key held down, with the serial of the press that put it there — a
/// later press has a larger one, which is how a [`Binding::ScrollChord`] finds
/// the most recently pressed key.
type HeldKeys = HashMap<KeyCode, u64>;

// ---------------------------------------------------------------------------
// Action primitives
// ---------------------------------------------------------------------------

/// A digital action: pressed / released / held with duration.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ButtonState {
    /// The button just went down this tick (or is being pressed for the first time).
    Pressed,
    /// The button came up this tick.
    Released,
    /// The button has been held for `duration` seconds.
    Held {
        /// Seconds since the button first went down.
        duration: f32,
    },
}

/// Button action with edge-detection flags.
///
/// `just_pressed` and `just_released` are true only on the tick the transition
/// occurred. They are cleared by [`ActionMap::begin_tick`] (and may also be
/// cleared earlier by the consumer via [`ActionMap::action_mut`]).
#[derive(Debug, Clone)]
pub struct ButtonAction {
    /// Current button state.
    pub state: ButtonState,
    /// True on the tick the button went down.
    pub just_pressed: bool,
    /// True on the tick the button came up.
    pub just_released: bool,
}

impl ButtonAction {
    fn reset_edges(&mut self) {
        self.just_pressed = false;
        self.just_released = false;
    }
}

impl Default for ButtonAction {
    fn default() -> Self {
        Self {
            state: ButtonState::Released,
            just_pressed: false,
            just_released: false,
        }
    }
}

/// 1-D analog axis: −1.0 … 1.0 (triggers, scroll wheels, an absolute pointer
/// coordinate).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Axis1Action {
    /// Current axis value.
    pub value: f32,
    /// True on the tick a [`Binding::PointerPosition`] on this action reported a
    /// coordinate different from the one it was holding.
    ///
    /// The edge an *absolute* source has and a relative one does not. A scroll
    /// axis returns to zero every [`ActionMap::begin_tick`], so a non-zero value
    /// already means "this moved"; a pointer axis holds its position across
    /// ticks — that is the whole point of it — so its value says where the
    /// pointer is and nothing about whether the player just asked for anything.
    ///
    /// Cleared by [`ActionMap::begin_tick`], like [`ButtonAction::just_pressed`].
    /// A consumer that drives one thing from both a pointer and the keyboard
    /// reads this to decide which spoke most recently — see the
    /// [`Binding::PointerPosition`] docs.
    pub pointer_moved: bool,
}

/// 2-D analog axis (WASD composite, stick, mouse motion).
///
/// Key-driven composites are normalized to at most unit length; mouse motion is
/// a raw pixel delta and is not.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Axis2Action {
    /// Horizontal component.
    pub x: f32,
    /// Vertical component.
    pub y: f32,
}

/// A unified action value — one variant per action kind.
#[derive(Debug, Clone)]
pub enum ActionValue {
    /// A button action.
    Button(ButtonAction),
    /// A 1-D axis action.
    Axis1(Axis1Action),
    /// A 2-D axis action.
    Axis2(Axis2Action),
}

// ---------------------------------------------------------------------------
// Bindings
// ---------------------------------------------------------------------------

/// Which coordinate of the pointer a [`Binding::PointerPosition`] reads.
///
/// One binding with an axis rather than a `PointerX`/`PointerY` pair: the two
/// would be the same variant twice, and a rebind menu listing both as unrelated
/// sources is a menu that has to explain why.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerAxis {
    /// Horizontal: −1.0 at the left edge of the surface, +1.0 at the right.
    X,
    /// Vertical: −1.0 at the **bottom** edge, +1.0 at the top.
    Y,
}

/// The modifier a [`Binding::Chord`] or a [`Binding::ButtonChord`] waits for:
/// either of its two keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Modifier {
    /// [`KeyCode::ShiftLeft`] or [`KeyCode::ShiftRight`].
    Shift,
    /// [`KeyCode::ControlLeft`] or [`KeyCode::ControlRight`].
    Control,
    /// [`KeyCode::AltLeft`] or [`KeyCode::AltRight`].
    Alt,
    /// [`KeyCode::SuperLeft`] or [`KeyCode::SuperRight`].
    Super,
}

impl Modifier {
    /// The left and the right key of this modifier.
    #[must_use]
    pub const fn keys(self) -> [KeyCode; 2] {
        match self {
            Self::Shift => [KeyCode::ShiftLeft, KeyCode::ShiftRight],
            Self::Control => [KeyCode::ControlLeft, KeyCode::ControlRight],
            Self::Alt => [KeyCode::AltLeft, KeyCode::AltRight],
            Self::Super => [KeyCode::SuperLeft, KeyCode::SuperRight],
        }
    }

    /// The modifier `key` is one side of, if it is one.
    #[must_use]
    pub const fn of(key: KeyCode) -> Option<Self> {
        match key {
            KeyCode::ShiftLeft | KeyCode::ShiftRight => Some(Self::Shift),
            KeyCode::ControlLeft | KeyCode::ControlRight => Some(Self::Control),
            KeyCode::AltLeft | KeyCode::AltRight => Some(Self::Alt),
            KeyCode::SuperLeft | KeyCode::SuperRight => Some(Self::Super),
            _ => None,
        }
    }

    /// Whether either side is in `held`.
    fn held(self, held: &HeldKeys) -> bool {
        self.keys().iter().any(|key| held.contains_key(key))
    }
}

/// A binding source: what raw input triggers this action.
///
/// Keyboard, mouse, gamepad and on-screen controls. A game
/// played with **one** finger needs nothing touch-specific — the platforms
/// deliver the primary contact as an ordinary pointer, so
/// [`Binding::MouseButton`] and [`Binding::PointerPosition`] are what a phone
/// plays it through. [`Binding::Virtual`] is what a game needs when one finger
/// is not enough.
///
/// `PartialEq` and not `Eq`: a pad binding's dead zone is an `f32`.
///
/// Its `Display` and `FromStr` are a stable text form, `KeyR` or `Pad:South`,
/// for a player's saved rebinds; [`binding_text`] has the spelling of each.
#[derive(Debug, Clone, PartialEq)]
pub enum Binding {
    /// A single key.
    Key(KeyCode),
    /// A mouse button.
    MouseButton(PointerButton),
    /// Mouse motion (delta in pixels).
    MouseMotion,
    /// Mouse scroll wheel.
    MouseScroll,
    /// Where the pointer **is**, normalised to the surface it is over: −1.0 at
    /// one edge, +1.0 at the other, with +X right and +Y up.
    ///
    /// Drives an [`ActionKind::Axis1`], whose −1…1 range is already exactly a
    /// normalised coordinate. Feeding an `Axis2` instead would put a *place* in
    /// the same value as [`Binding::Wasd`]'s *direction*, and a consumer handed
    /// `(0.5, 0.0)` could not tell "half way to the right edge" from "moving
    /// right at half speed"; a fourth [`ActionKind`] for one binding would be a
    /// whole value shape for a case `Axis1` already covers. Any other kind
    /// ignores this binding, as [`Binding::MouseMotion`] does on a button.
    ///
    /// **Normalised, not pixels**, because pixels are the surface's business:
    /// a device-pixel coordinate makes every consumer redo the DPI arithmetic
    /// the windowing layer already did, and get it wrong on exactly the displays
    /// nobody develops on. What the consumer still owns is the step from the
    /// surface to its own world — a camera's half width is not the map's to
    /// know.
    ///
    /// **A pointer that leaves keeps its last position.** Leaving is not a
    /// command: the platform reports it with no coordinate at all, so there is
    /// nothing to resolve, and an axis that recentred itself would walk a
    /// paddle to the middle of the field every time a finger lifted.
    ///
    /// **On an axis that also has a relative source** — a [`Binding::KeyAxis`],
    /// a [`Binding::MouseScroll`] — this one wins whenever the pointer has a
    /// position, because summing them would add a place to a rate and produce
    /// neither. That is a resolution, not an arbitration: a consumer whose
    /// keyboard means something genuinely different from its pointer (a paddle
    /// driven left at a speed, versus a paddle put at a coordinate) declares two
    /// actions and picks between them with
    /// [`Axis1Action::pointer_moved`].
    PointerPosition {
        /// Which coordinate this action reads.
        axis: PointerAxis,
    },
    /// Two keys driving one 1-D axis: `negative` contributes −1.0, `positive`
    /// +1.0, and both at once cancel.
    ///
    /// A single [`Binding::Key`] on an `Axis1` can only ever push the axis
    /// positive, so a keyboard-driven throttle or zoom needs this.
    KeyAxis {
        /// Key for the −1.0 direction.
        negative: KeyCode,
        /// Key for the +1.0 direction.
        positive: KeyCode,
    },
    /// A key that counts only while a [`Modifier`] is held — Shift+Tab.
    ///
    /// **The more specific binding takes the key.** While the modifier is
    /// held, every plain [`Binding::Key`], [`Binding::KeyAxis`] and
    /// [`Binding::Wasd`] on the same key, in the context that owns the key,
    /// reads it as up — so `ui_next` on Tab and `ui_prev` on Shift+Tab never
    /// both fire. Holding Tab and then pressing Shift therefore releases the
    /// one and presses the other.
    ///
    /// **The modifier is read, not consumed**: a chord owns its `key` and
    /// nothing else, so a Shift+Tab in a pushed context leaves a sprint bound
    /// to Shift in the context beneath it alone.
    Chord {
        /// The modifier that must be held.
        modifier: Modifier,
        /// The key the chord owns.
        key: KeyCode,
    },
    /// A mouse button that counts only while a [`Modifier`] is held —
    /// Alt+right click beside a plain right click. The mouse's
    /// [`Binding::Chord`], on the same two rules, and read as
    /// [`Binding::MouseButton`] is: down on an [`ActionKind::Button`], inert
    /// on the other kinds.
    ///
    /// **The more specific binding takes the button.** While the modifier is
    /// held, every plain [`Binding::MouseButton`] on the same button, in the
    /// context that owns the button, reads it as up — so an aim on the right
    /// button and a zoom on Alt+right never both fire. Holding the button and
    /// then pressing the modifier releases the one and presses the other;
    /// letting the modifier go first hands the button back.
    ///
    /// **The modifier is read, not consumed**: a button chord owns its
    /// `button` and nothing else, so a lean bound to Alt still sees every
    /// press of Alt, chorded or not.
    ButtonChord {
        /// The modifier that must be held.
        modifier: Modifier,
        /// The mouse button the chord owns.
        button: PointerButton,
    },
    /// The mouse wheel, read only while `held` is down — Z+wheel, Ctrl+wheel.
    ///
    /// Read as [`Binding::MouseScroll`] is: the vertical delta on an
    /// [`ActionKind::Axis1`], inert on the other kinds. It reads the wheel as
    /// one, too, so it takes the wheel for its context as a `MouseScroll`
    /// would.
    ///
    /// **The more specific binding takes the wheel**, as it takes the key for a
    /// [`Binding::Chord`]: while the `held` key of any scroll chord in the
    /// context that owns the wheel is down, every plain `MouseScroll` in that
    /// context reads zero. **With several of those keys down, the most recently
    /// pressed one takes the wheel** and the chords on the others read zero,
    /// so letting go of it hands the wheel back to the one pressed before. An
    /// OS auto-repeat of a key already down is not a press and takes nothing.
    ///
    /// **The held key is read, not consumed**, as a chord's modifier is: a
    /// scroll chord owns the wheel and nothing else, so a [`Binding::Key`] on
    /// Z still sees Z — a game that also taps Z cancels that tap with
    /// [`ActionMap::cancel_patterns`] when the wheel turns. A held key
    /// withheld from its owner (see `context.rs`) is up for this read too.
    ///
    /// **Only an enabled action's scroll chord competes.** A key whose action
    /// is disabled ([`ActionMap::set_enabled`]) takes the wheel from nothing
    /// and silences no plain `MouseScroll`, however recently it was pressed:
    /// Ctrl held for one chord keeps the wheel when Alt goes down for a chord
    /// that cannot act right now. Enabling it again restores its place by
    /// when its key went down, not by when it was enabled.
    ScrollChord {
        /// The key that must be down; any key, modifiers included.
        held: KeyCode,
    },
    /// An **on-screen control**, by the id the widget drawing it was given.
    ///
    /// The touch row of a binding table, and the one binding whose device is a
    /// piece of the game's own UI: a `crcbl-ui` control hit-tests the raw
    /// contacts, decides what its geometry makes of them, and reports the
    /// result here through [`ActionMap::virtual_button`] or
    /// [`ActionMap::virtual_stick`]. From this side it is a device like any
    /// other — the same action can carry a key, a mouse button and one of
    /// these, and nothing downstream can tell which of them spoke.
    ///
    /// That split is deliberate and it is why there is no binding on a raw
    /// contact. A finger reports a *place on the glass*; what it means is a
    /// question only the thing drawn under it can answer, and an [`ActionMap`]
    /// that hit-tested widgets would have to be told where every control was
    /// drawn this frame.
    ///
    /// **A control is a button or a stick, and an action reads whichever
    /// matches its own kind**: an [`ActionKind::Button`] is down while the
    /// named control is held, an [`ActionKind::Axis2`] takes the named
    /// control's deflection, and an [`ActionKind::Axis1`] takes **nothing** —
    /// reducing a stick to one axis is a choice the control would have to make
    /// and none of them makes it. A binding whose kind does not match is inert,
    /// the way [`Binding::MouseMotion`] is on a button.
    ///
    /// The vector arrives already inside the unit disc, and is clamped to it
    /// again here: a control with a longer throw than its own radius is a
    /// broken control, not a player asking to run faster.
    Virtual(String),
    /// WASD composite: four keys mapped to a 2-D axis.
    ///
    /// The composite is normalized, so a diagonal is a unit vector rather than
    /// `(1, 1)` — otherwise diagonal movement is 41% faster than cardinal.
    Wasd {
        /// Key for the +Y direction (forward / up).
        up: KeyCode,
        /// Key for the −Y direction (back / down).
        down: KeyCode,
        /// Key for the −X direction (left).
        left: KeyCode,
        /// Key for the +X direction (right).
        right: KeyCode,
    },
    /// A pad button, by position — see [`PadButton`].
    ///
    /// Read like a [`Binding::Key`]: down on an [`ActionKind::Button`], +1.0 on
    /// an [`ActionKind::Axis1`], nothing on an [`ActionKind::Axis2`] — the
    /// d-pad's `Axis2` is [`Binding::PadDpad`]. Down while any connected pad
    /// holds it.
    PadButton(PadButton),
    /// The d-pad as one 2-D axis: [`Binding::Wasd`] over
    /// [`PadButton::DpadUp`], [`PadButton::DpadDown`], [`PadButton::DpadLeft`]
    /// and [`PadButton::DpadRight`], +Y up.
    ///
    /// Resolved exactly as `Wasd` is: into the same unit disc as the keys and
    /// the sticks on the action, so a diagonal is a unit vector and opposite
    /// directions cancel; down on an [`ActionKind::Button`] while any of the
    /// four is held; inert on an [`ActionKind::Axis1`]. It owns the four
    /// buttons for routing, as `Wasd` owns its four keys.
    PadDpad,
    /// A pad stick's deflection, +Y up, through a **scaled radial** dead zone:
    /// zero within `deadzone` of centre, rescaled so the zone's edge reads 0
    /// and full throw reads 1.
    ///
    /// Drives an [`ActionKind::Axis2`], into the same unit disc as a
    /// [`Binding::Wasd`] or a [`Binding::Virtual`] stick on the action, so a
    /// stick and a key pushed together ask for one direction. Inert on the
    /// other kinds, as a [`Binding::Virtual`] stick is on an `Axis1`.
    PadStick {
        /// Which stick.
        stick: Stick,
        /// The dead zone's radius, in `0.0..1.0`; anything else is refused
        /// with [`ActionMapError::InvalidDeadzone`].
        deadzone: f32,
    },
    /// A pad button that counts only while another pad button is held — a
    /// held shoulder giving the face buttons a second layer. The pad's
    /// [`Binding::Chord`], on the same two rules:
    ///
    /// **The more specific binding takes the button.** While `modifier` is
    /// held, every plain [`Binding::PadButton`] on `button` (and a
    /// [`Binding::PadDpad`] reading it), in the context that owns the button,
    /// reads it as up — so a jump on South and a vault on LB+South never both
    /// fire. Holding South and then pressing LB releases the one and presses
    /// the other. A chord in a context beneath the owner reads nothing,
    /// unless its action is marked with [`ActionMap::set_pad_chords_outrank`]:
    /// then it takes the button from the contexts above while `modifier` is
    /// held (`context.rs`).
    ///
    /// **The modifier is read, not consumed**: a pad chord owns its `button`
    /// and nothing else, so `modifier` can still carry a plain binding of its
    /// own, which sees every press of it, chorded or not.
    PadChord {
        /// The pad button that must be held.
        modifier: PadButton,
        /// The pad button the chord owns.
        button: PadButton,
    },
    /// A pad trigger past a threshold.
    ///
    /// On an [`ActionKind::Button`], down while the pull is past `threshold`;
    /// on an [`ActionKind::Axis1`], the pull rescaled so the threshold reads 0
    /// and full pull reads 1. Inert on an [`ActionKind::Axis2`].
    PadTrigger {
        /// Which trigger.
        trigger: Trigger,
        /// The threshold, in `0.0..1.0`; anything else is refused with
        /// [`ActionMapError::InvalidDeadzone`].
        threshold: f32,
    },
}

impl Binding {
    /// Calls `visit` with every key this binding owns — the keys a context
    /// consumes by binding it. A [`Binding::Chord`]'s modifier is not one, and
    /// neither is a [`Binding::ScrollChord`]'s held key.
    pub fn visit_keys(&self, mut visit: impl FnMut(KeyCode)) {
        match self {
            Self::Key(key) | Self::Chord { key, .. } => visit(*key),
            Self::KeyAxis { negative, positive } => {
                visit(*negative);
                visit(*positive);
            }
            Self::Wasd {
                up,
                down,
                left,
                right,
            } => {
                visit(*up);
                visit(*down);
                visit(*left);
                visit(*right);
            }
            Self::MouseButton(_)
            | Self::ButtonChord { .. }
            | Self::MouseMotion
            | Self::MouseScroll
            | Self::ScrollChord { .. }
            | Self::PointerPosition { .. }
            | Self::Virtual(_)
            | Self::PadButton(_)
            | Self::PadChord { .. }
            | Self::PadDpad
            | Self::PadStick { .. }
            | Self::PadTrigger { .. } => {}
        }
    }

    /// Whether this binding reads the mouse wheel.
    const fn reads_wheel(&self) -> bool {
        matches!(self, Self::MouseScroll | Self::ScrollChord { .. })
    }

    /// The mouse button this binding owns, if it reads one: a
    /// [`Binding::ButtonChord`]'s button as much as a
    /// [`Binding::MouseButton`]'s.
    const fn mouse_button(&self) -> Option<PointerButton> {
        match *self {
            Self::MouseButton(button) | Self::ButtonChord { button, .. } => Some(button),
            _ => None,
        }
    }

    /// Whether this binding reads a gamepad.
    #[must_use]
    pub const fn reads_gamepad(&self) -> bool {
        matches!(
            self,
            Self::PadButton(_)
                | Self::PadChord { .. }
                | Self::PadDpad
                | Self::PadStick { .. }
                | Self::PadTrigger { .. }
        )
    }

    /// Whether this binding's dead zone or threshold is usable, if it has one.
    fn deadzone_is_valid(&self) -> bool {
        match *self {
            Self::PadStick { deadzone, .. } => gamepad::valid_deadzone(deadzone),
            Self::PadTrigger { threshold, .. } => gamepad::valid_deadzone(threshold),
            _ => true,
        }
    }

    /// Whether this binding reads the keyboard at all.
    fn reads_keyboard(&self) -> bool {
        let mut any = false;
        self.visit_keys(|_| any = true);
        any
    }

    /// Whether this binding owns `key`.
    #[must_use]
    pub fn owns_key(&self, key: KeyCode) -> bool {
        let mut owns = false;
        self.visit_keys(|owned| owns |= owned == key);
        owns
    }
}

// ---------------------------------------------------------------------------
// Action declaration
// ---------------------------------------------------------------------------

/// What kind of value an action produces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActionKind {
    /// A digital on/off action with edge detection.
    Button,
    /// A 1-D analog axis.
    Axis1,
    /// A 2-D analog axis.
    Axis2,
}

/// A declared action: name + kind + bindings.
#[derive(Debug, Clone)]
pub struct ActionDecl {
    /// Human-readable name, used as the lookup key in [`ActionMap`].
    pub name: String,
    /// What kind of value this action produces.
    pub kind: ActionKind,
    /// The raw inputs that drive this action.
    pub bindings: Vec<Binding>,
}

// ---------------------------------------------------------------------------
// Internal per-action state
// ---------------------------------------------------------------------------

/// Tracks the resolved value and edge-transition bookkeeping for one action.
#[derive(Debug, Clone)]
struct ActionSlot {
    decl: ActionDecl,
    /// The bindings it was declared with, which [`ActionMap::rebind`] leaves
    /// alone: the defaults a player's overrides are a diff over.
    defaults: Vec<Binding>,
    /// Index into [`ActionMap::contexts`] of the context this action is in.
    context: usize,
    /// The repeat pattern, if one is attached — see [`ActionMap::set_repeat`].
    repeat: Option<RepeatState>,
    /// The tap, hold and double-tap patterns — see [`ActionMap::set_tap`].
    patterns: PatternState,
    /// Whether a pattern emitting this action fired since the last
    /// [`ActionMap::begin_tick`], which holds it down until then — see
    /// `emit.rs`.
    emitted: bool,
    /// The current resolved value.
    value: ActionValue,
    /// True when at least one binding for this action is "down" (key held,
    /// button held, etc.). Used to detect press / release edges.
    active: bool,
    /// Accumulated time at which the action became active (None when inactive).
    /// Used to compute `Held { duration }`.
    hold_start: Option<f64>,
    /// Whether this action reacts to input at all.
    ///
    /// A flag on the slot rather than a `HashSet<String>` on the map: the set
    /// was hashed once per slot per raw event, and `set_enabled` on a name that
    /// was never declared grew it forever.
    enabled: bool,
    /// Whether its pad chords take their button from a context above — see
    /// [`ActionMap::set_pad_chords_outrank`].
    pad_chords_outrank: bool,
}

impl ActionSlot {
    fn new(decl: ActionDecl, context: usize) -> Self {
        let value = match decl.kind {
            ActionKind::Button => ActionValue::Button(ButtonAction::default()),
            ActionKind::Axis1 => ActionValue::Axis1(Axis1Action::default()),
            ActionKind::Axis2 => ActionValue::Axis2(Axis2Action::default()),
        };
        Self {
            defaults: decl.bindings.clone(),
            decl,
            context,
            repeat: None,
            patterns: PatternState::default(),
            emitted: false,
            value,
            active: false,
            hold_start: None,
            enabled: true,
            pad_chords_outrank: false,
        }
    }

    /// Returns the declared kind.
    fn kind(&self) -> ActionKind {
        self.decl.kind
    }

    /// Force the action back to its idle value and drop any hold state.
    fn reset(&mut self) {
        self.active = false;
        self.hold_start = None;
        if let Some(repeat) = &mut self.repeat {
            repeat.reset();
        }
        self.patterns.reset();
        self.emitted = false;
        match &mut self.value {
            ActionValue::Button(a) => {
                a.state = ButtonState::Released;
                a.just_pressed = false;
                a.just_released = false;
            }
            ActionValue::Axis1(a) => {
                a.value = 0.0;
                a.pointer_moved = false;
            }
            ActionValue::Axis2(a) => {
                a.x = 0.0;
                a.y = 0.0;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// What can go wrong when mutating an [`ActionMap`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ActionMapError {
    /// An action with this name is already declared.
    DuplicateName(String),
    /// No action with this name has been declared.
    UnknownAction(String),
    /// No context with this name has been declared.
    UnknownContext(String),
    /// [`ActionMap::push_context`] was asked for a context already active —
    /// [`GAMEPLAY_CONTEXT`] and [`GLOBAL_CONTEXT`] always are.
    ContextAlreadyActive(String),
    /// [`ActionMap::pop_context`] was asked for a context that is not the
    /// topmost pushed one — [`GAMEPLAY_CONTEXT`] and [`GLOBAL_CONTEXT`] are
    /// never pushed.
    ContextNotOnTop(String),
    /// A [`Binding::PadStick`]'s dead zone or a [`Binding::PadTrigger`]'s
    /// threshold on the named action is not finite and in `0.0..1.0`.
    InvalidDeadzone(String),
    /// [`ActionMap::set_emits`] was asked to make a pattern emit an action
    /// that is not an [`ActionKind::Button`].
    NotAButton(String),
    /// [`ActionMap::set_emits`] was asked to make a pattern emit the action it
    /// is attached to.
    EmitsItself(String),
}

impl std::fmt::Display for ActionMapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DuplicateName(name) => write!(f, "duplicate action name: {name}"),
            Self::UnknownAction(name) => write!(f, "no such action: {name}"),
            Self::UnknownContext(name) => write!(f, "no such context: {name}"),
            Self::ContextAlreadyActive(name) => write!(f, "context already active: {name}"),
            Self::ContextNotOnTop(name) => {
                write!(f, "context is not the topmost pushed one: {name}")
            }
            Self::InvalidDeadzone(name) => {
                write!(f, "dead zone or threshold not in 0..1: {name}")
            }
            Self::NotAButton(name) => {
                write!(f, "a pattern can emit only a button action: {name}")
            }
            Self::EmitsItself(name) => {
                write!(f, "a pattern cannot emit the action it is on: {name}")
            }
        }
    }
}

impl std::error::Error for ActionMapError {}

// ---------------------------------------------------------------------------
// ActionMap
// ---------------------------------------------------------------------------

/// Resolves raw input events to action values.
///
/// Bindings are declared once via [`ActionMap::declare`] and then driven by
/// feeding raw events (`key_event`, `mouse_button`, `mouse_motion`,
/// `mouse_scroll`).  Per-tick bookkeeping is done with [`ActionMap::begin_tick`].
pub struct ActionMap {
    /// All declared actions, in registration order.
    slots: Vec<ActionSlot>,
    /// name → index into `slots`.
    name_to_idx: HashMap<String, usize>,

    // Contexts ---------------------------------------------------------------
    /// Every declared context's name, in declaration order;
    /// [`GAMEPLAY_CONTEXT`] is index 0 and [`GLOBAL_CONTEXT`] index 1.
    contexts: Vec<String>,
    /// The pushable stack as indices into `contexts`, bottom first. Never
    /// empty: index 0 is the base and is never popped. [`GLOBAL_CONTEXT`] is
    /// always active and is not on it.
    stack: Vec<usize>,
    /// The contexts on `stack` that were pushed modal.
    modal: Vec<usize>,
    /// Which active context owns each bound input, rebuilt whenever the stack
    /// or a binding changes.
    routes: Routes,
    /// Held inputs withheld from their owner until released, because the
    /// stack changed under them.
    suppressed: Suppressed,
    /// Every kind of device that has spoken, most recent first and each
    /// once — see [`ActionMap::last_device`], and `hint.rs` for why the ones
    /// behind it are kept.
    devices: Vec<Device>,
    /// The family of the pad that last spoke — see
    /// [`ActionMap::last_pad_kind`].
    last_pad_kind: Option<PadKind>,
    /// Whether the front of `devices` changed since the last
    /// [`ActionMap::begin_tick`] — see [`ActionMap::last_device_changed`].
    device_changed: bool,
    /// The resolution trace, while [`ActionMap::set_tracing`] has it on — see
    /// `trace.rs`.
    trace: Option<VecDeque<TraceEntry>>,

    // Raw input state -------------------------------------------------------
    held_keys: HeldKeys,
    /// The serial of the last key press — see [`HeldKeys`].
    key_presses: u64,
    held_buttons: HashSet<PointerButton>,
    /// On-screen controls currently held — see [`Binding::Virtual`].
    held_controls: HashSet<String>,
    /// Where each on-screen stick is deflected to, inside the unit disc.
    ///
    /// A *level*, like [`ActionMap::pointer`] and unlike the two deltas below:
    /// a finger resting on a stick reports nothing on the frames it does not
    /// move, so a value cleared by [`ActionMap::begin_tick`] would centre the
    /// stick under a finger that never let go.
    control_sticks: HashMap<String, (f32, f32)>,
    /// Every connected pad's last snapshot — a level, like `control_sticks`.
    /// See `gamepad.rs`.
    pads: Pads,
    /// Every button some pad holds, as one set for routing to read.
    held_pad_buttons: PadButtons,
    mouse_delta: (f32, f32),
    scroll_delta: (f32, f32),
    /// Where the pointer is, normalised to the surface, or `None` until one has
    /// ever reported a position.
    ///
    /// Not cleared by [`ActionMap::begin_tick`] and not cleared when the pointer
    /// leaves — unlike the two deltas above, this is a *level* and it is the
    /// last thing the player actually asked for. See
    /// [`Binding::PointerPosition`].
    pointer: Option<(f32, f32)>,
    /// Slots a pattern fired an emission at, waiting to be pressed — see
    /// `emit.rs`. Empty between calls.
    pending_emits: Vec<usize>,

    /// Seconds elapsed since creation (advanced by `begin_tick`).
    ///
    /// `f64` rather than `f32`: an `f32` accumulator quantizes `Held`
    /// durations after a few hours of uptime and stops advancing entirely
    /// after about nineteen days, which is well inside a dedicated server's
    /// lifetime.
    elapsed: f64,
}

impl ActionMap {
    /// Create an empty action map.
    #[must_use]
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            name_to_idx: HashMap::new(),
            contexts: vec![GAMEPLAY_CONTEXT.to_owned(), GLOBAL_CONTEXT.to_owned()],
            stack: vec![0],
            modal: Vec::new(),
            routes: Routes::default(),
            suppressed: Suppressed::default(),
            devices: Vec::new(),
            last_pad_kind: None,
            device_changed: false,
            trace: None,
            held_keys: HeldKeys::new(),
            key_presses: 0,
            held_buttons: HashSet::new(),
            held_controls: HashSet::new(),
            control_sticks: HashMap::new(),
            pads: Pads::new(),
            held_pad_buttons: PadButtons::EMPTY,
            mouse_delta: (0.0, 0.0),
            scroll_delta: (0.0, 0.0),
            pointer: None,
            pending_emits: Vec::new(),
            elapsed: 0.0,
        }
    }

    /// Register an action in [`GAMEPLAY_CONTEXT`].  Actions are enabled by
    /// default.
    ///
    /// # Panics
    /// Panics if an action with the same name has already been declared. Use
    /// [`ActionMap::try_declare`] when the declaration comes from a user config
    /// file, where a duplicate is a message rather than a crash.
    pub fn declare(&mut self, decl: ActionDecl) {
        if let Err(error) = self.try_declare(decl) {
            panic!("{error}");
        }
    }

    /// Register an action, reporting a duplicate name rather than panicking.
    ///
    /// # Errors
    /// [`ActionMapError::DuplicateName`] if the name is already declared.
    pub fn try_declare(&mut self, decl: ActionDecl) -> Result<(), ActionMapError> {
        self.try_declare_in(GAMEPLAY_CONTEXT, decl)
    }

    /// Register an action in the named context, declaring the context on first
    /// use.
    ///
    /// # Panics
    /// Panics on a duplicate action name, as [`ActionMap::declare`] does.
    pub fn declare_in(&mut self, context: &str, decl: ActionDecl) {
        if let Err(error) = self.try_declare_in(context, decl) {
            panic!("{error}");
        }
    }

    /// Register an action in the named context, reporting a duplicate name
    /// rather than panicking. Action names are unique across every context.
    ///
    /// An action declared into an active context with its input already held
    /// reports it at once, as [`ActionMap::rebind`] does.
    ///
    /// # Errors
    /// [`ActionMapError::DuplicateName`] if the name is already declared,
    /// [`ActionMapError::InvalidDeadzone`] if a pad binding's dead zone or
    /// threshold is unusable.
    pub fn try_declare_in(
        &mut self,
        context: &str,
        decl: ActionDecl,
    ) -> Result<(), ActionMapError> {
        if self.name_to_idx.contains_key(&decl.name) {
            return Err(ActionMapError::DuplicateName(decl.name));
        }
        if !decl.bindings.iter().all(Binding::deadzone_is_valid) {
            return Err(ActionMapError::InvalidDeadzone(decl.name));
        }
        let context = match self.contexts.iter().position(|name| name == context) {
            Some(index) => index,
            None => {
                self.contexts.push(context.to_owned());
                self.contexts.len() - 1
            }
        };
        let idx = self.slots.len();
        self.name_to_idx.insert(decl.name.clone(), idx);
        self.slots.push(ActionSlot::new(decl, context));
        self.reroute();
        Ok(())
    }

    /// Replace an action's bindings in place — the rebind path.
    ///
    /// Keeps the action's registration order and enabled flag, and resets its
    /// value and hold state (the old bindings' "is it down" answer says nothing
    /// about the new ones). Rebuilding the whole map instead, which was the
    /// only option before, lost both.
    ///
    /// # Errors
    /// [`ActionMapError::UnknownAction`] if nothing with that name is declared,
    /// [`ActionMapError::InvalidDeadzone`] if a pad binding's dead zone or
    /// threshold is unusable — and then the old bindings stay.
    pub fn rebind(&mut self, name: &str, bindings: Vec<Binding>) -> Result<(), ActionMapError> {
        let Some(&idx) = self.name_to_idx.get(name) else {
            return Err(ActionMapError::UnknownAction(name.to_owned()));
        };
        if !bindings.iter().all(Binding::deadzone_is_valid) {
            return Err(ActionMapError::InvalidDeadzone(name.to_owned()));
        }
        let slot = &mut self.slots[idx];
        slot.decl.bindings = bindings;
        slot.reset();
        // Every live action, not only this one: the new bindings can take an
        // input from a context beneath, or give one back.
        self.reroute();
        Ok(())
    }

    /// The bindings currently driving an action, or `None` if it is not
    /// declared.
    #[must_use]
    pub fn bindings(&self, name: &str) -> Option<&[Binding]> {
        let &idx = self.name_to_idx.get(name)?;
        Some(&self.slots[idx].decl.bindings)
    }

    /// Whether an action is enabled. `None` if it is not declared.
    #[must_use]
    pub fn is_enabled(&self, name: &str) -> Option<bool> {
        let &idx = self.name_to_idx.get(name)?;
        Some(self.slots[idx].enabled)
    }

    /// Enable or disable an action by name.  Disabled actions always return
    /// their default (idle) value and do not react to input — including across
    /// [`ActionMap::begin_tick`], which used to re-read the held-key set and
    /// re-press a disabled action on the very next tick.
    ///
    /// An action with a [`Binding::ScrollChord`] also leaves or rejoins the
    /// wheel's competition, and the wheel is re-read at once.
    ///
    /// Has no effect if the named action does not exist.
    pub fn set_enabled(&mut self, name: &str, enabled: bool) {
        let Some(&idx) = self.name_to_idx.get(name) else {
            return;
        };
        let slot = &mut self.slots[idx];
        let changed = slot.enabled != enabled;
        slot.enabled = enabled;
        if !enabled {
            // Reset the action to idle so it doesn't stick.
            slot.reset();
        }
        // Only an enabled scroll chord competes for the wheel, so turning one
        // on or off can hand the wheel to another binding.
        let scroll_chord = slot
            .decl
            .bindings
            .iter()
            .any(|binding| matches!(binding, Binding::ScrollChord { .. }));
        if changed && scroll_chord {
            self.reroute();
        }
    }

    // -- feeding raw events --------------------------------------------------

    /// Feed a key event. `pressed` → key-down, `!pressed` → key-up.
    ///
    /// A press makes [`Device::Keyboard`] the last device; a release does not,
    /// since letting go of a key after reaching for the mouse is not the
    /// keyboard speaking.
    pub fn key_event(&mut self, key: KeyCode, pressed: bool) {
        // An OS auto-repeat of a key already down keeps its first serial: it
        // is not a new press, and the trace does not record it again.
        let fresh = pressed && !self.held_keys.contains_key(&key);
        if pressed {
            if fresh {
                self.key_presses += 1;
                self.held_keys.insert(key, self.key_presses);
            }
            self.spoke(Device::Keyboard);
        } else {
            self.held_keys.remove(&key);
            self.suppressed.keys.remove(&key);
        }
        // A scroll chord's key can hand the wheel from one binding to another.
        let wheel = self.routes.is_scroll_chord_key(key);
        if Modifier::of(key).is_some() {
            // A modifier can press or release any chord, and shadow or unshadow
            // any plain key or mouse button a chord shares.
            self.resolve_matching(|b| {
                b.reads_keyboard() || b.mouse_button().is_some() || (wheel && b.reads_wheel())
            });
        } else {
            self.resolve_matching(|b| b.owns_key(key) || (wheel && b.reads_wheel()));
        }
        if fresh {
            self.traced(|| TracedInput::Key(key));
        }
    }

    /// Feed a mouse-button event.
    pub fn mouse_button(&mut self, button: PointerButton, pressed: bool) {
        let mut fresh = false;
        if pressed {
            fresh = self.held_buttons.insert(button);
            self.spoke(Device::Pointer);
        } else {
            self.held_buttons.remove(&button);
            self.suppressed.buttons.remove(&button);
        }
        self.resolve_matching(|b| b.mouse_button() == Some(button));
        if fresh {
            self.traced(|| TracedInput::MouseButton(button));
        }
    }

    /// Feed mouse motion (delta in pixels since the last event).
    ///
    /// Non-finite deltas are dropped: a `NaN` from a driver or a divide-by-zero
    /// sensitivity would otherwise propagate straight into an action value and
    /// poison every comparison downstream.
    pub fn mouse_motion(&mut self, dx: f32, dy: f32) {
        if !dx.is_finite() || !dy.is_finite() {
            return;
        }
        if dx != 0.0 || dy != 0.0 {
            self.spoke(Device::Pointer);
        }
        self.mouse_delta.0 += dx;
        self.mouse_delta.1 += dy;
        self.resolve_matching(|b| matches!(b, Binding::MouseMotion));
    }

    /// Feed scroll input (delta in detents or pixels — caller normalises).
    ///
    /// Non-finite deltas are dropped, as for [`ActionMap::mouse_motion`];
    /// `f32::clamp` returns `NaN` for a `NaN` input, so the clamp downstream is
    /// no defence.
    pub fn mouse_scroll(&mut self, dx: f32, dy: f32) {
        if !dx.is_finite() || !dy.is_finite() {
            return;
        }
        let turned = dx != 0.0 || dy != 0.0;
        if turned {
            self.spoke(Device::Pointer);
        }
        self.scroll_delta.0 += dx;
        self.scroll_delta.1 += dy;
        self.resolve_matching(Binding::reads_wheel);
        if turned {
            self.traced(|| TracedInput::Wheel);
        }
    }

    /// Feed the pointer's position, normalised to the surface: −1.0 at one edge
    /// and +1.0 at the other, +X right and +Y up.
    ///
    /// The caller does the conversion because the caller is the only thing that
    /// knows the surface — see [`Binding::PointerPosition`], which also says why
    /// a pointer that *leaves* is not reported here at all.
    ///
    /// A coordinate equal to the one already held is dropped, so
    /// [`Axis1Action::pointer_moved`] means the pointer moved rather than that
    /// an event arrived. Non-finite coordinates are dropped like
    /// [`ActionMap::mouse_motion`]'s deltas: a `NaN` would poison every
    /// comparison downstream of the axis.
    pub fn pointer_position(&mut self, x: f32, y: f32) {
        if !x.is_finite() || !y.is_finite() {
            return;
        }
        let moved = Some((x, y));
        if self.pointer == moved {
            return;
        }
        self.pointer = moved;
        self.spoke(Device::Pointer);

        for i in 0..self.slots.len() {
            let slot = &self.slots[i];
            let drives = slot
                .decl
                .bindings
                .iter()
                .any(|b| matches!(b, Binding::PointerPosition { .. }));
            // The owner only: a consumed pointer has not moved for anyone else.
            if !self.is_live(i) || !drives || self.routes.pointer != Some(slot.context) {
                continue;
            }
            self.resolve_one(i);
            // Set here rather than in `resolve_one`, which also runs from
            // `begin_tick`: an edge raised by re-resolving an unchanged value
            // would be raised on every tick forever.
            if let ActionValue::Axis1(axis) = &mut self.slots[i].value {
                axis.pointer_moved = true;
            }
        }
    }

    /// Feed an on-screen **button**: the control named by `control` is held, or
    /// it is not.
    ///
    /// The widget decides what "held" means for its own geometry — which
    /// contact owns it, and whether a lift over it commits or cancels. What
    /// arrives here is the answer, and it drives every
    /// [`Binding::Virtual`] with this id on an [`ActionKind::Button`] exactly as
    /// a key event drives a [`Binding::Key`], edges included.
    pub fn virtual_button(&mut self, control: &str, pressed: bool) {
        // `contains` first so a control that is already held costs no
        // allocation: this runs once per frame per held control.
        let fresh = pressed && !self.held_controls.contains(control);
        if pressed {
            if fresh {
                self.held_controls.insert(control.to_owned());
            }
            self.spoke(Device::Touch);
        } else {
            self.held_controls.remove(control);
            self.suppressed.controls.remove(control);
        }
        self.resolve_matching(|b| matches!(b, Binding::Virtual(id) if id == control));
        if fresh {
            self.traced(|| TracedInput::Control(control.to_owned()));
        }
    }

    /// Feed an on-screen **stick**: where the control named by `control` is
    /// deflected to, with +X right and +Y up.
    ///
    /// A *level*, not a delta — a stick held still reports the same value every
    /// frame, and a stick nobody is touching reports `(0.0, 0.0)`. The magnitude
    /// belongs to the widget's own radius, so a control at its edge reports 1.0
    /// and the value is clamped to the unit disc when it is resolved.
    ///
    /// Non-finite coordinates are dropped like [`ActionMap::mouse_motion`]'s
    /// deltas: a `NaN` would poison every comparison downstream of the axis.
    pub fn virtual_stick(&mut self, control: &str, x: f32, y: f32) {
        if !x.is_finite() || !y.is_finite() {
            return;
        }
        let deflected = x != 0.0 || y != 0.0;
        if deflected {
            self.spoke(Device::Touch);
        }
        let before = if let Some(held) = self.control_sticks.get_mut(control) {
            std::mem::replace(held, (x, y))
        } else {
            self.control_sticks.insert(control.to_owned(), (x, y));
            (0.0, 0.0)
        };
        // Centred is a stick's release: what lifts a suppress.
        if !deflected {
            self.suppressed.control_sticks.remove(control);
        }
        self.resolve_matching(|b| matches!(b, Binding::Virtual(id) if id == control));
        if deflected && before == (0.0, 0.0) {
            self.traced(|| TracedInput::ControlStick(control.to_owned()));
        }
    }

    /// Called at the start of each server tick.
    ///
    /// - Resets per-frame edge flags (`just_pressed`, `just_released` on every
    ///   button action, `pointer_moved` on every 1-D axis, what
    ///   [`ActionMap::repeated`], [`ActionMap::tapped`],
    ///   [`ActionMap::hold_fired`] and [`ActionMap::double_tapped`] read, and
    ///   [`ActionMap::last_device_changed`]).
    /// - Zeroes accumulated mouse-motion and scroll deltas.
    /// - Releases every action a pattern emitted since the last tick, and
    ///   presses the ones a pattern emits as this tick begins — see `emit.rs`.
    /// - Advances the internal clock by `dt` seconds so that [`ButtonState::Held`]
    ///   durations are up-to-date next time a button action is resolved.
    pub fn begin_tick(&mut self, dt: f32) {
        // A negative dt would move the clock backwards and report negative
        // `Held` durations; only forward time is meaningful here.
        if dt.is_finite() && dt >= 0.0 {
            self.elapsed += f64::from(dt);
        }
        self.mouse_delta = (0.0, 0.0);
        self.scroll_delta = (0.0, 0.0);
        self.device_changed = false;
        // Every slot, live or not: one taken off the stack while pressed must
        // not come back pressed.
        for slot in &mut self.slots {
            slot.emitted = false;
        }

        // Reset edge flags and re-resolve every action so that Held durations
        // and axis values reflect the new elapsed time and cleared deltas.
        //
        // Disabled actions are skipped entirely. Resolving them here re-read
        // `held_keys` and re-pressed them — so disabling "jump" while Space was
        // held cleared it, and the next tick emitted `just_pressed` again.
        for i in 0..self.slots.len() {
            if !self.is_live(i) {
                continue;
            }
            if let Some(repeat) = &mut self.slots[i].repeat {
                repeat.fired = false;
            }
            self.slots[i].patterns.clear_fired();
            match &mut self.slots[i].value {
                ActionValue::Button(a) => a.reset_edges(),
                ActionValue::Axis1(a) => a.pointer_moved = false,
                ActionValue::Axis2(_) => {}
            }
            // Re-resolve to update Held duration and zero out axis deltas.
            // Not `resolve_one`: what a pattern emits now waits for the loop
            // to finish, so the edges do not depend on declaration order.
            self.resolve_slot(i);
        }
        self.drain_emits();
    }

    // -- reading resolved state ----------------------------------------------

    /// Get the current value of an action by name.
    ///
    /// Returns `None` if no action with that name was declared.
    #[must_use]
    pub fn action(&self, name: &str) -> Option<&ActionValue> {
        let &idx = self.name_to_idx.get(name)?;
        Some(&self.slots[idx].value)
    }

    /// Get a mutable reference to the current value of an action.
    ///
    /// The caller can use this to clear edge flags after consuming them
    /// (e.g. setting `just_pressed = false` after a jump was processed).
    #[must_use]
    pub fn action_mut(&mut self, name: &str) -> Option<&mut ActionValue> {
        let &idx = self.name_to_idx.get(name)?;
        Some(&mut self.slots[idx].value)
    }

    /// All declared action names, in registration order.
    pub fn action_names(&self) -> impl Iterator<Item = &str> {
        self.slots.iter().map(|s| s.decl.name.as_str())
    }

    /// Whether a button action is down — pressed this tick or still held.
    ///
    /// An action that was never declared, or that is not a button, is `false`
    /// rather than an error: a caller asking whether a button is down has no
    /// better answer to give, and every game was already collapsing both cases
    /// that way.
    ///
    /// The state is matched positively rather than as "not
    /// [`Released`](ButtonState::Released)". The two agree while
    /// [`ButtonState`] has three variants, and would stop agreeing the day it
    /// gains a fourth — silently, and only for whoever wrote the negation.
    #[must_use]
    pub fn button_held(&self, name: &str) -> bool {
        self.button(name).is_some_and(|button| {
            matches!(
                button.state,
                ButtonState::Pressed | ButtonState::Held { .. }
            )
        })
    }

    /// Whether a button action went down on this tick.
    ///
    /// The edge, not the level: true only for the tick of the transition, and
    /// cleared by [`ActionMap::begin_tick`]. This is what a jump or a flap
    /// reads, so that holding the key does not repeat it.
    #[must_use]
    pub fn just_pressed(&self, name: &str) -> bool {
        self.button(name).is_some_and(|button| button.just_pressed)
    }

    /// Whether a button action came up on this tick.
    #[must_use]
    pub fn just_released(&self, name: &str) -> bool {
        self.button(name).is_some_and(|button| button.just_released)
    }

    /// A 1-D axis action's value, or `0.0` if it is absent or another kind.
    #[must_use]
    pub fn axis1(&self, name: &str) -> f32 {
        match self.action(name) {
            Some(ActionValue::Axis1(axis)) => axis.value,
            _ => 0.0,
        }
    }

    /// A 2-D axis action's value, or `(0.0, 0.0)` if it is absent or another
    /// kind.
    ///
    /// Key-driven composites arrive normalised to at most unit length, so a
    /// diagonal is not faster than a cardinal; mouse motion is a raw pixel
    /// delta and is not normalised.
    #[must_use]
    pub fn axis2(&self, name: &str) -> (f32, f32) {
        match self.action(name) {
            Some(ActionValue::Axis2(axis)) => (axis.x, axis.y),
            _ => (0.0, 0.0),
        }
    }

    // -- reading raw input --------------------------------------------------

    /// Every key held down, in the order they were pressed — what an input
    /// inspector shows beside the actions they drive. Raw: a key no context
    /// binds, or one withheld, is listed as much as any other.
    #[must_use]
    pub fn held_keys(&self) -> Vec<KeyCode> {
        let mut held: Vec<(u64, KeyCode)> = self
            .held_keys
            .iter()
            .map(|(&key, &serial)| (serial, key))
            .collect();
        held.sort_unstable();
        held.into_iter().map(|(_, key)| key).collect()
    }

    /// Every pointer button held down, in [`PointerButton`]'s order. Raw, as
    /// [`ActionMap::held_keys`] is.
    #[must_use]
    pub fn held_mouse_buttons(&self) -> Vec<PointerButton> {
        let mut held: Vec<PointerButton> = self.held_buttons.iter().copied().collect();
        held.sort_unstable();
        held
    }

    /// Where the pointer last was, normalised to the surface as
    /// [`ActionMap::pointer_position`] takes it, or `None` before it reported
    /// a position.
    #[must_use]
    pub const fn pointer(&self) -> Option<(f32, f32)> {
        self.pointer
    }

    /// The button behind `name`, if it is declared and is one.
    fn button(&self, name: &str) -> Option<&ButtonAction> {
        match self.action(name)? {
            ActionValue::Button(button) => Some(button),
            _ => None,
        }
    }

    // -- internal resolution -------------------------------------------------

    /// Re-resolve every enabled action with a binding `matches` accepts.
    ///
    /// One helper rather than four near-identical bodies, and no `Vec<usize>`
    /// per event: the enabled flag lives on the slot, so nothing here allocates
    /// or hashes a `String`.
    fn resolve_matching(&mut self, matches: impl Fn(&Binding) -> bool) {
        for i in 0..self.slots.len() {
            let slot = &self.slots[i];
            if self.is_live(i) && slot.decl.bindings.iter().any(&matches) {
                self.resolve_one(i);
            }
        }
    }

    /// Compute the current value of a single action slot from raw state, and
    /// press whatever its patterns emitted on the way.
    fn resolve_one(&mut self, idx: usize) {
        self.resolve_slot(idx);
        self.drain_emits();
    }

    /// Compute the current value of a single action slot from raw state,
    /// queueing what its patterns emit for [`ActionMap::drain_emits`].
    ///
    /// Reads raw input only through the slot's context's [`View`], which is
    /// where consumption happens.
    fn resolve_slot(&mut self, idx: usize) {
        let control_sticks = &self.control_sticks;
        let pads = &self.pads;
        let mouse_delta = self.mouse_delta;
        let scroll_delta = self.scroll_delta;
        let pointer = self.pointer;
        let elapsed = self.elapsed;

        let slot = &mut self.slots[idx];
        let view = View {
            context: slot.context,
            routes: &self.routes,
            suppressed: &self.suppressed,
            held_keys: &self.held_keys,
            held_buttons: &self.held_buttons,
            held_controls: &self.held_controls,
            held_pad_buttons: self.held_pad_buttons,
        };
        let kind = slot.kind();
        let bindings = &slot.decl.bindings;

        match kind {
            ActionKind::Button => {
                let down = slot.emitted
                    || bindings.iter().any(|b| match b {
                        Binding::Key(k) => view.key(*k),
                        Binding::Chord { modifier, key } => view.chord(*modifier, *key),
                        Binding::MouseButton(b) => view.button(*b),
                        Binding::ButtonChord { modifier, button } => {
                            view.button_chord(*modifier, *button)
                        }
                        Binding::Virtual(id) => view.control(id),
                        Binding::PadButton(button) => view.pad_button(*button),
                        Binding::PadChord { modifier, button } => {
                            view.pad_chord(*modifier, *button)
                        }
                        Binding::PadDpad => PadButton::DPAD.iter().any(|&b| view.pad_button(b)),
                        Binding::PadTrigger { trigger, threshold } => {
                            view.trigger(*trigger)
                                && gamepad::pad_trigger(pads, *trigger) > *threshold
                        }
                        Binding::MouseMotion
                        | Binding::MouseScroll
                        | Binding::ScrollChord { .. }
                        | Binding::PointerPosition { .. }
                        | Binding::PadStick { .. } => false,
                        Binding::KeyAxis { negative, positive } => {
                            view.key(*negative) || view.key(*positive)
                        }
                        Binding::Wasd {
                            up,
                            down: w_down,
                            left,
                            right,
                        } => {
                            view.key(*up)
                                || view.key(*w_down)
                                || view.key(*left)
                                || view.key(*right)
                        }
                    });

                let was_active = slot.active;
                slot.active = down;

                let action = match &mut slot.value {
                    ActionValue::Button(a) => a,
                    _ => unreachable!(),
                };

                match (was_active, down) {
                    (false, true) => {
                        action.state = ButtonState::Pressed;
                        action.just_pressed = true;
                        slot.hold_start = Some(elapsed);
                    }
                    (true, true) => {
                        let duration = (elapsed - slot.hold_start.unwrap_or(elapsed)) as f32;
                        action.state = ButtonState::Held { duration };
                    }
                    (true, false) => {
                        action.state = ButtonState::Released;
                        action.just_released = true;
                        slot.hold_start = None;
                    }
                    (false, false) => {
                        action.state = ButtonState::Released;
                    }
                }
            }
            ActionKind::Axis1 => {
                // The absolute source, if this action has one and a pointer has
                // ever reported a position. It **replaces** the relative
                // contributions below rather than adding to them: a place and a
                // rate do not sum. See [`Binding::PointerPosition`].
                let absolute = pointer.filter(|_| view.pointer()).and_then(|(px, py)| {
                    bindings.iter().find_map(|binding| match binding {
                        Binding::PointerPosition { axis } => Some(match axis {
                            PointerAxis::X => px,
                            PointerAxis::Y => py,
                        }),
                        _ => None,
                    })
                });

                let mut value: f32 = absolute.unwrap_or(0.0);

                if absolute.is_none() {
                    for binding in bindings {
                        match binding {
                            Binding::MouseScroll if view.scroll() => {
                                value += scroll_delta.1;
                            }
                            Binding::ScrollChord { held } if view.scroll_chord(*held) => {
                                value += scroll_delta.1;
                            }
                            Binding::Key(k) if view.key(*k) => {
                                value += 1.0;
                            }
                            Binding::Chord { modifier, key } if view.chord(*modifier, *key) => {
                                value += 1.0;
                            }
                            Binding::PadButton(button) if view.pad_button(*button) => {
                                value += 1.0;
                            }
                            Binding::PadChord { modifier, button }
                                if view.pad_chord(*modifier, *button) =>
                            {
                                value += 1.0;
                            }
                            Binding::PadTrigger { trigger, threshold }
                                if view.trigger(*trigger) =>
                            {
                                value += gamepad::trigger_past(
                                    gamepad::pad_trigger(pads, *trigger),
                                    *threshold,
                                );
                            }
                            Binding::KeyAxis { negative, positive } => {
                                if view.key(*negative) {
                                    value -= 1.0;
                                }
                                if view.key(*positive) {
                                    value += 1.0;
                                }
                            }
                            _ => {}
                        }
                    }
                }

                // The surface's edge is the axis's end, whatever the caller
                // passed: a coordinate outside it is a pointer outside the
                // window, not a stronger command.
                value = value.clamp(-1.0, 1.0);

                let action = match &mut slot.value {
                    ActionValue::Axis1(a) => a,
                    _ => unreachable!(),
                };
                action.value = value;
            }
            ActionKind::Axis2 => {
                // The *direction* sources and the pointer delta are accumulated
                // separately: a direction is bounded by the unit disc, so a
                // diagonal is a unit vector rather than 1.414 long and a stick
                // pushed past its own radius is still all the way over. A
                // pointer delta is a pixel count, and normalizing it would
                // throw away the speed.
                let mut dir_x: f32 = 0.0;
                let mut dir_y: f32 = 0.0;
                let mut x: f32 = 0.0;
                let mut y: f32 = 0.0;

                for binding in bindings {
                    match binding {
                        Binding::Wasd {
                            up,
                            down: w_down,
                            left,
                            right,
                        } => {
                            if view.key(*up) {
                                dir_y += 1.0;
                            }
                            if view.key(*w_down) {
                                dir_y -= 1.0;
                            }
                            if view.key(*left) {
                                dir_x -= 1.0;
                            }
                            if view.key(*right) {
                                dir_x += 1.0;
                            }
                        }
                        Binding::PadDpad => {
                            if view.pad_button(PadButton::DpadUp) {
                                dir_y += 1.0;
                            }
                            if view.pad_button(PadButton::DpadDown) {
                                dir_y -= 1.0;
                            }
                            if view.pad_button(PadButton::DpadLeft) {
                                dir_x -= 1.0;
                            }
                            if view.pad_button(PadButton::DpadRight) {
                                dir_x += 1.0;
                            }
                        }
                        // Into the same accumulator as the keys, so a player
                        // pushing a stick *and* holding a key asks for one
                        // direction rather than for twice the speed.
                        Binding::Virtual(id) if view.stick(id) => {
                            if let Some((sx, sy)) = control_sticks.get(id.as_str()) {
                                dir_x += sx;
                                dir_y += sy;
                            }
                        }
                        // Each pad through its own dead zone, then into the
                        // same accumulator as the keys.
                        Binding::PadStick { stick, deadzone } if view.pad_stick(*stick) => {
                            for pad in pads.values() {
                                let (sx, sy) =
                                    gamepad::radial_deadzone(pad.stick(*stick), *deadzone);
                                dir_x += sx;
                                dir_y += sy;
                            }
                        }
                        Binding::MouseMotion if view.motion() => {
                            x += mouse_delta.0;
                            y += mouse_delta.1;
                        }
                        _ => {}
                    }
                }

                let len = (dir_x * dir_x + dir_y * dir_y).sqrt();
                if len > 1.0 {
                    dir_x /= len;
                    dir_y /= len;
                }
                x += dir_x;
                y += dir_y;

                let action = match &mut slot.value {
                    ActionValue::Axis2(a) => a,
                    _ => unreachable!(),
                };
                action.x = x;
                action.y = y;
            }
        }

        if let Some(repeat) = &mut slot.repeat {
            repeat.update(&slot.value, elapsed);
        }
        let before = slot.patterns.fired();
        slot.patterns.update(&slot.value, elapsed);
        slot.patterns.queue_emits(before, &mut self.pending_emits);
    }
}

impl Default for ActionMap {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for ActionMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ActionMap")
            .field(
                "actions",
                &self.slots.iter().map(|s| &s.decl.name).collect::<Vec<_>>(),
            )
            .field("held_keys", &self.held_keys.len())
            .field("held_buttons", &self.held_buttons.len())
            .field("held_controls", &self.held_controls)
            .field("control_sticks", &self.control_sticks)
            .field("pads", &self.pads)
            .field("contexts", &self.active_contexts().collect::<Vec<_>>())
            .field("devices", &self.devices)
            .field("last_pad_kind", &self.last_pad_kind)
            .field("pointer", &self.pointer)
            .field("elapsed", &self.elapsed)
            .finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// InputTickState
// ---------------------------------------------------------------------------

/// The input state for one server tick.
///
/// The client builds one per tick with [`InputTickState::capture`], sends it to
/// the server, which applies it before running the tick.
#[derive(Debug, Clone, Default)]
pub struct InputTickState {
    /// Active actions and their values at this tick.
    pub actions: Vec<(String, ActionValue)>,
}

impl InputTickState {
    /// Create an empty tick state.
    #[must_use]
    pub fn new() -> Self {
        Self {
            actions: Vec::new(),
        }
    }

    /// Capture the current state of every declared action from `map`.
    ///
    /// This snapshots enabled and disabled actions alike; disabled actions will
    /// be in their idle state, and so are the actions of a context that is not
    /// on the stack. An action whose input a context above it consumed is
    /// captured as that input left it — which is exactly what the active
    /// contexts let through, and all the simulation should see.
    pub fn capture(map: &ActionMap) -> Self {
        let actions = map
            .slots
            .iter()
            .map(|slot| (slot.decl.name.clone(), slot.value.clone()))
            .collect();
        Self { actions }
    }

    /// Look up an action value by name.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&ActionValue> {
        self.actions.iter().find(|(n, _)| n == name).map(|(_, v)| v)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- helpers ------------------------------------------------------------

    fn decl_button(name: &str, binding: Binding) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind: ActionKind::Button,
            bindings: vec![binding],
        }
    }

    fn decl_axis2_wasd(
        name: &str,
        up: KeyCode,
        down: KeyCode,
        left: KeyCode,
        right: KeyCode,
    ) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind: ActionKind::Axis2,
            bindings: vec![Binding::Wasd {
                up,
                down,
                left,
                right,
            }],
        }
    }

    fn decl_axis2_mouse(name: &str) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind: ActionKind::Axis2,
            bindings: vec![Binding::MouseMotion],
        }
    }

    fn decl_axis1_scroll(name: &str) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind: ActionKind::Axis1,
            bindings: vec![Binding::MouseScroll],
        }
    }

    // -- typed accessors ----------------------------------------------------

    /// One tick at sixty hertz, which is what `begin_tick` wants — a delta,
    /// not a timestamp.
    const TICK: f32 = 1.0 / 60.0;

    /// Held is down, and so is the tick the key went down on.
    ///
    /// Both, not just the second: a game reading "is the thrust on" during the
    /// very tick the key arrived would otherwise see it off for one tick and
    /// stutter.
    #[test]
    fn a_button_is_held_while_it_is_down_and_not_after() {
        let mut map = ActionMap::new();
        map.declare(decl_button("thrust", Binding::Key(KeyCode::KeyW)));

        assert!(!map.button_held("thrust"), "nothing is down yet");

        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyW, true);
        assert!(map.button_held("thrust"), "the tick the key arrives counts");

        map.begin_tick(TICK);
        assert!(
            matches!(
                map.action("thrust"),
                Some(ActionValue::Button(ButtonAction {
                    state: ButtonState::Held { .. },
                    ..
                }))
            ),
            "a second tick with the key still down is Held, which is the other \
             state that must read as down"
        );
        assert!(map.button_held("thrust"));

        map.key_event(KeyCode::KeyW, false);
        assert!(!map.button_held("thrust"), "released is not down");
    }

    /// The edges are one tick wide, and they are not the level.
    #[test]
    fn the_edges_fire_once_each() {
        let mut map = ActionMap::new();
        map.declare(decl_button("flap", Binding::Key(KeyCode::Space)));

        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(map.just_pressed("flap"));
        assert!(!map.just_released("flap"));

        map.begin_tick(TICK);
        assert!(
            !map.just_pressed("flap"),
            "holding the key does not press it again — this is the whole \
             reason a flap reads the edge and not the level"
        );
        assert!(map.button_held("flap"), "still down, though");

        map.key_event(KeyCode::Space, false);
        assert!(map.just_released("flap"));
        map.begin_tick(TICK);
        assert!(
            !map.just_released("flap"),
            "the release edge is one tick too"
        );
    }

    /// An axis answers with its value, and a composite is not longer than one.
    #[test]
    fn the_axis_accessors_read_the_value() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::KeyW,
            KeyCode::KeyS,
            KeyCode::KeyA,
            KeyCode::KeyD,
        ));
        map.declare(decl_axis1_scroll("zoom"));

        assert_eq!(map.axis2("move"), (0.0, 0.0));
        assert_eq!(map.axis1("zoom"), 0.0);

        map.begin_tick(TICK);
        map.key_event(KeyCode::KeyD, true);
        let (x, y) = map.axis2("move");
        assert!((x - 1.0).abs() < 1e-6, "right alone is +1 on x, got {x}");
        assert!(y.abs() < 1e-6, "and nothing on y, got {y}");

        map.key_event(KeyCode::KeyW, true);
        let (x, y) = map.axis2("move");
        let length = x.hypot(y);
        assert!(
            (length - 1.0).abs() < 1e-6,
            "a diagonal is normalised, or it is 41% faster than a cardinal: \
             got length {length}"
        );

        map.mouse_scroll(0.0, 3.0);
        assert_ne!(map.axis1("zoom"), 0.0, "the scroll reached the axis");
    }

    /// Asking the wrong kind, or a name nobody declared, is the idle value.
    ///
    /// Every game collapsed both cases this way already. Worth pinning because
    /// the alternative — a panic, or `true` — would turn a typo into a stuck
    /// input rather than a dead one.
    #[test]
    fn the_wrong_kind_and_the_wrong_name_are_idle() {
        let mut map = ActionMap::new();
        map.declare(decl_button("fire", Binding::Key(KeyCode::Space)));
        map.declare(decl_axis1_scroll("zoom"));

        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);

        assert!(!map.button_held("zoom"), "an axis is not a held button");
        assert!(!map.just_pressed("zoom"));
        assert!(!map.just_released("zoom"));
        assert_eq!(map.axis1("fire"), 0.0, "a button is not an axis");
        assert_eq!(map.axis2("fire"), (0.0, 0.0));

        assert!(!map.button_held("nonesuch"));
        assert!(!map.just_pressed("nonesuch"));
        assert_eq!(map.axis1("nonesuch"), 0.0);
        assert_eq!(map.axis2("nonesuch"), (0.0, 0.0));
    }

    // -- ButtonState / ButtonAction -----------------------------------------

    #[test]
    fn button_action_default_is_released() {
        let a = ButtonAction::default();
        assert!(matches!(a.state, ButtonState::Released));
        assert!(!a.just_pressed);
        assert!(!a.just_released);
    }

    #[test]
    fn reset_edges_clears_flags() {
        let mut a = ButtonAction {
            state: ButtonState::Pressed,
            just_pressed: true,
            just_released: true,
        };
        a.reset_edges();
        assert!(!a.just_pressed);
        assert!(!a.just_released);
        // state is untouched by reset_edges.
        assert!(matches!(a.state, ButtonState::Pressed));
    }

    // -- ActionMap: key binding ---------------------------------------------

    #[test]
    fn key_press_and_release() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));

        // Initially released.
        let v = map.action("jump").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                just_pressed: false,
                just_released: false,
            })
        ));

        // Press space.
        map.key_event(KeyCode::Space, true);
        let v = map.action("jump").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                just_released: false,
            })
        ));

        // Next tick: edges cleared, still held → Held { duration }.
        map.begin_tick(1.0 / 60.0);
        let v = map.action("jump").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Held { .. },
                just_pressed: false,
                just_released: false,
            })
        ));

        // Release space.
        map.key_event(KeyCode::Space, false);
        let v = map.action("jump").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                just_pressed: false,
                just_released: true,
            })
        ));
    }

    #[test]
    fn a_key_still_down_after_a_tick_reports_held_with_how_long_it_has_been() {
        let mut map = ActionMap::new();
        map.declare(decl_button("fire", Binding::Key(KeyCode::KeyF)));

        map.key_event(KeyCode::KeyF, true);
        // Advance 2 seconds.
        map.begin_tick(2.0);

        let v = map.action("fire").unwrap();
        if let ActionValue::Button(a) = v {
            if let ButtonState::Held { duration } = a.state {
                assert!(
                    (duration - 2.0).abs() < 0.001,
                    "expected ~2s, got {duration}"
                );
            } else {
                panic!("expected Held, got {:?}", a.state);
            }
        } else {
            panic!("expected Button, got {:?}", v);
        }
    }

    // -- ActionMap: mouse-button binding ------------------------------------

    #[test]
    fn mouse_button_press_and_release() {
        let mut map = ActionMap::new();
        map.declare(decl_button(
            "shoot",
            Binding::MouseButton(PointerButton::Left),
        ));

        map.mouse_button(PointerButton::Left, true);
        let v = map.action("shoot").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                just_released: false,
            })
        ));

        map.begin_tick(0.016);
        map.mouse_button(PointerButton::Left, false);
        let v = map.action("shoot").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                just_pressed: false,
                just_released: true,
            })
        ));
    }

    // -- ActionMap: WASD composite -------------------------------------------

    #[test]
    fn a_wasd_composite_stays_a_unit_vector_from_idle_through_every_diagonal() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::KeyW,
            KeyCode::KeyS,
            KeyCode::KeyA,
            KeyCode::KeyD,
        ));

        // Idle.
        let v = map.action("move").unwrap();
        assert_eq_axis2(v, 0.0, 0.0);

        // Press W → (0, 1).
        map.key_event(KeyCode::KeyW, true);
        let v = map.action("move").unwrap();
        assert_eq_axis2(v, 0.0, 1.0);

        // Press D as well → a *unit* diagonal, not (1, 1).
        map.key_event(KeyCode::KeyD, true);
        let v = map.action("move").unwrap();
        let diag = std::f32::consts::FRAC_1_SQRT_2;
        assert_eq_axis2(v, diag, diag);

        // Release W and D, then press S and A → the opposite unit diagonal.
        map.key_event(KeyCode::KeyW, false);
        map.key_event(KeyCode::KeyD, false);
        map.key_event(KeyCode::KeyA, true);
        map.key_event(KeyCode::KeyS, true);
        let v = map.action("move").unwrap();
        assert_eq_axis2(v, -diag, -diag);

        // Release all.
        map.key_event(KeyCode::KeyD, false);
        map.key_event(KeyCode::KeyA, false);
        map.key_event(KeyCode::KeyS, false);
        let v = map.action("move").unwrap();
        assert_eq_axis2(v, 0.0, 0.0);
    }

    #[test]
    fn wasd_opposing_keys_cancel() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::KeyW,
            KeyCode::KeyS,
            KeyCode::KeyA,
            KeyCode::KeyD,
        ));

        // W + S simultaneously → (0, 0).
        map.key_event(KeyCode::KeyW, true);
        map.key_event(KeyCode::KeyS, true);
        let v = map.action("move").unwrap();
        assert_eq_axis2(v, 0.0, 0.0);

        // A + D simultaneously → (0, 0).
        map.key_event(KeyCode::KeyA, true);
        map.key_event(KeyCode::KeyD, true);
        let v = map.action("move").unwrap();
        assert_eq_axis2(v, 0.0, 0.0);
    }

    // -- ActionMap: mouse motion --------------------------------------------

    #[test]
    fn mouse_motion_accumulates_within_a_tick_and_begin_tick_clears_it() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_mouse("look"));

        // Accumulate delta over several events in one tick.
        map.mouse_motion(5.0, -3.0);
        map.mouse_motion(2.0, 1.0);
        let v = map.action("look").unwrap();
        assert_eq_axis2(v, 7.0, -2.0);

        // begin_tick resets deltas.
        map.begin_tick(0.016);
        let v = map.action("look").unwrap();
        assert_eq_axis2(v, 0.0, 0.0);
    }

    // -- ActionMap: mouse scroll --------------------------------------------

    #[test]
    fn scroll_sums_positive_and_negative_notches_and_resets_on_the_next_tick() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_scroll("zoom"));

        map.mouse_scroll(0.0, 1.0);
        let v = map.action("zoom").unwrap();
        assert_eq_axis1(v, 1.0);

        map.mouse_scroll(0.0, -0.5);
        let v = map.action("zoom").unwrap();
        assert_eq_axis1(v, 0.5);

        // begin_tick resets.
        map.begin_tick(0.016);
        let v = map.action("zoom").unwrap();
        assert_eq_axis1(v, 0.0);
    }

    #[test]
    fn scroll_clamped_to_range() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_scroll("zoom"));

        map.mouse_scroll(0.0, 5.0);
        let v = map.action("zoom").unwrap();
        assert_eq_axis1(v, 1.0);

        map.begin_tick(0.016);
        map.mouse_scroll(0.0, -5.0);
        let v = map.action("zoom").unwrap();
        assert_eq_axis1(v, -1.0);
    }

    // -- ActionMap: absolute pointer position --------------------------------

    fn decl_axis1_pointer(name: &str, axis: PointerAxis) -> ActionDecl {
        ActionDecl {
            name: name.to_owned(),
            kind: ActionKind::Axis1,
            bindings: vec![Binding::PointerPosition { axis }],
        }
    }

    /// **Each axis reads its own coordinate, at the value it was given.**
    ///
    /// Two actions on one map and asymmetric coordinates, because that is what
    /// a swapped axis fails: a pointer at `(0.5, 0.5)` puts the right answer on
    /// both of them.
    #[test]
    fn a_pointer_position_lands_on_the_axis_it_is_bound_to() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_pointer("aim_x", PointerAxis::X));
        map.declare(decl_axis1_pointer("aim_y", PointerAxis::Y));

        assert_eq!(
            map.axis1("aim_x"),
            0.0,
            "an axis nothing has pointed at yet is idle, not at the left edge",
        );

        map.begin_tick(TICK);
        map.pointer_position(-0.75, 0.25);

        assert_eq_axis1(map.action("aim_x").unwrap(), -0.75);
        assert_eq_axis1(map.action("aim_y").unwrap(), 0.25);
    }

    /// **The position is a level: it survives ticks, unlike a scroll delta.**
    ///
    /// This is also what "a pointer that leaves keeps its last position" means
    /// mechanically — leaving reports no coordinate, so nothing here is fed and
    /// the axis is exactly where the last real position put it.
    #[test]
    fn an_absolute_axis_holds_its_position_across_ticks() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_pointer("aim", PointerAxis::X));
        map.declare(decl_axis1_scroll("zoom"));

        map.begin_tick(TICK);
        map.pointer_position(0.6, 0.0);
        map.mouse_scroll(0.0, 1.0);
        assert_eq_axis1(map.action("aim").unwrap(), 0.6);
        assert_eq_axis1(map.action("zoom").unwrap(), 1.0);

        map.begin_tick(TICK);
        assert_eq_axis1(map.action("zoom").unwrap(), 0.0);
        assert_eq_axis1(map.action("aim").unwrap(), 0.6);
    }

    /// **`pointer_moved` is an edge, and it is about the pointer moving.**
    ///
    /// A tick that re-sends the coordinate the axis already holds raises
    /// nothing: a consumer arbitrating between the pointer and the keyboard
    /// reads this as "the player just asked for this", and a browser that
    /// re-reports a resting cursor would otherwise hold the keyboard off
    /// forever.
    #[test]
    fn the_pointer_edge_is_one_tick_wide_and_only_for_a_new_position() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_pointer("aim", PointerAxis::X));

        let moved = |map: &ActionMap| match map.action("aim") {
            Some(ActionValue::Axis1(axis)) => axis.pointer_moved,
            other => panic!("expected Axis1, got {other:?}"),
        };

        map.begin_tick(TICK);
        assert!(!moved(&map), "nothing has pointed anywhere yet");
        map.pointer_position(0.2, 0.0);
        assert!(moved(&map), "the pointer moved on this tick");

        map.begin_tick(TICK);
        assert!(!moved(&map), "the edge is one tick wide");
        assert_eq_axis1(map.action("aim").unwrap(), 0.2);

        map.pointer_position(0.2, 0.0);
        assert!(
            !moved(&map),
            "the same coordinate again is not the player asking for anything",
        );
        map.pointer_position(0.2, 0.9);
        assert!(
            moved(&map),
            "the other coordinate changing is still the pointer moving",
        );
    }

    /// **An absolute source replaces the relative ones on the same axis.**
    ///
    /// Summing them would add a place to a rate. The keyboard drives the axis
    /// while no pointer has ever reported a position, and stops the moment one
    /// has — which is the documented reason a game whose keys mean something
    /// *different* from its pointer declares two actions instead of one.
    #[test]
    fn an_absolute_binding_replaces_the_relative_ones_on_the_same_axis() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "slide".to_owned(),
            kind: ActionKind::Axis1,
            bindings: vec![
                Binding::KeyAxis {
                    negative: KeyCode::ArrowLeft,
                    positive: KeyCode::ArrowRight,
                },
                Binding::PointerPosition {
                    axis: PointerAxis::X,
                },
            ],
        });

        map.begin_tick(TICK);
        map.key_event(KeyCode::ArrowRight, true);
        assert_eq_axis1(map.action("slide").unwrap(), 1.0);

        map.pointer_position(-0.5, 0.0);
        assert_eq_axis1(map.action("slide").unwrap(), -0.5);
    }

    /// **The surface's edge is the end of the axis.**
    #[test]
    fn a_pointer_outside_the_surface_is_clamped_to_its_edge() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_pointer("aim", PointerAxis::X));

        map.pointer_position(4.0, 0.0);
        assert_eq_axis1(map.action("aim").unwrap(), 1.0);

        map.pointer_position(-4.0, 0.0);
        assert_eq_axis1(map.action("aim").unwrap(), -1.0);
    }

    /// **A pointer binding joins the keys on a button, it does not replace
    /// them.**
    ///
    /// The flap that a phone taps and a keyboard presses is one action with
    /// both bindings on it, and each still fires on its own. A binding list
    /// that had been overwritten rather than appended to passes every test that
    /// only ever presses the pointer.
    #[test]
    fn a_pointer_button_joins_the_keys_bound_to_the_same_action() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "flap".to_owned(),
            kind: ActionKind::Button,
            bindings: vec![
                Binding::Key(KeyCode::Space),
                Binding::MouseButton(PointerButton::Left),
            ],
        });

        map.begin_tick(TICK);
        map.key_event(KeyCode::Space, true);
        assert!(map.just_pressed("flap"), "the key still flaps");
        map.key_event(KeyCode::Space, false);

        map.begin_tick(TICK);
        map.mouse_button(PointerButton::Left, true);
        assert!(map.just_pressed("flap"), "and so does the tap");
        map.mouse_button(PointerButton::Left, false);
        assert!(map.just_released("flap"));
    }

    // -- begin_tick resets edges and deltas ----------------------------------

    #[test]
    fn begin_tick_resets_just_pressed_and_just_released() {
        let mut map = ActionMap::new();
        map.declare(decl_button("a", Binding::Key(KeyCode::KeyA)));

        map.key_event(KeyCode::KeyA, true);
        assert!(matches!(
            map.action("a").unwrap(),
            ActionValue::Button(ButtonAction {
                just_pressed: true,
                ..
            })
        ));

        map.begin_tick(0.016);
        assert!(matches!(
            map.action("a").unwrap(),
            ActionValue::Button(ButtonAction {
                just_pressed: false,
                just_released: false,
                ..
            })
        ));

        map.key_event(KeyCode::KeyA, false);
        assert!(matches!(
            map.action("a").unwrap(),
            ActionValue::Button(ButtonAction {
                just_released: true,
                ..
            })
        ));

        map.begin_tick(0.016);
        assert!(matches!(
            map.action("a").unwrap(),
            ActionValue::Button(ButtonAction {
                just_released: false,
                ..
            })
        ));
    }

    // -- enable / disable ---------------------------------------------------

    #[test]
    fn disabled_action_returns_idle() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));

        map.key_event(KeyCode::Space, true);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                ..
            })
        ));

        map.set_enabled("jump", false);
        // Disabled → Released and edges cleared.
        let v = map.action("jump").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                just_pressed: false,
                just_released: false,
            })
        ));

        // Re-enable: key is still held, so it becomes pressed again.
        map.set_enabled("jump", true);
        map.key_event(KeyCode::Space, true); // need to re-trigger resolution
        let v = map.action("jump").unwrap();
        assert!(matches!(
            v,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                ..
            })
        ));
    }

    #[test]
    fn disabled_wasd_returns_zero() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::KeyW,
            KeyCode::KeyS,
            KeyCode::KeyA,
            KeyCode::KeyD,
        ));
        map.key_event(KeyCode::KeyW, true);
        assert_eq_axis2(map.action("move").unwrap(), 0.0, 1.0);

        map.set_enabled("move", false);
        assert_eq_axis2(map.action("move").unwrap(), 0.0, 0.0);

        // …and it must stay zero across ticks. `begin_tick` used to re-resolve
        // every slot with no enabled check, so the still-held W came straight
        // back on the next tick.
        for tick in 0..3 {
            map.begin_tick(1.0 / 60.0);
            assert_eq_axis2(map.action("move").unwrap(), 0.0, 0.0);
            assert!(tick < 3);
        }
    }

    /// The same bug for a Button action: disabling "jump" while Space is held
    /// cleared it, and the very next `begin_tick` re-emitted
    /// `state: Pressed, just_pressed: true` — a menu opened with gameplay
    /// disabled still jumped.
    #[test]
    fn a_disabled_button_does_not_re_press_itself_on_the_next_tick() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));

        map.key_event(KeyCode::Space, true);
        map.set_enabled("jump", false);

        for _ in 0..3 {
            map.begin_tick(1.0 / 60.0);
            let v = map.action("jump").unwrap();
            assert!(
                matches!(
                    v,
                    ActionValue::Button(ButtonAction {
                        state: ButtonState::Released,
                        just_pressed: false,
                        just_released: false,
                    })
                ),
                "a disabled action fired anyway: {v:?}"
            );
        }

        // Re-enabling with the key still held presses it again, which is the
        // intended behaviour.
        map.set_enabled("jump", true);
        map.begin_tick(1.0 / 60.0);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                ..
            })
        ));
    }

    /// `set_enabled` on a name that was never declared used to insert into a
    /// `HashSet<String>` that nothing ever pruned.
    #[test]
    fn set_enabled_on_an_unknown_action_is_a_no_op() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));
        map.set_enabled("typo-in-the-profile", true);
        map.set_enabled("typo-in-the-profile", false);
        assert_eq!(map.is_enabled("typo-in-the-profile"), None);
        assert_eq!(map.is_enabled("jump"), Some(true));
        assert_eq!(map.action_names().count(), 1);
    }

    // -- declare / rebind ---------------------------------------------------

    #[test]
    fn try_declare_reports_a_duplicate_rather_than_aborting() {
        let mut map = ActionMap::new();
        assert!(
            map.try_declare(decl_button("jump", Binding::Key(KeyCode::Space)))
                .is_ok()
        );
        assert_eq!(
            map.try_declare(decl_button("jump", Binding::Key(KeyCode::KeyJ))),
            Err(ActionMapError::DuplicateName("jump".to_owned()))
        );
        // The first declaration is untouched.
        assert_eq!(
            map.bindings("jump"),
            Some(&[Binding::Key(KeyCode::Space)][..])
        );
    }

    #[test]
    fn rebind_replaces_bindings_and_keeps_the_enabled_flag() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));
        map.set_enabled("jump", false);

        map.rebind("jump", vec![Binding::Key(KeyCode::KeyJ)])
            .expect("declared");
        assert_eq!(
            map.bindings("jump"),
            Some(&[Binding::Key(KeyCode::KeyJ)][..])
        );
        assert_eq!(
            map.is_enabled("jump"),
            Some(false),
            "the rebind must not silently re-enable the action"
        );

        map.set_enabled("jump", true);
        map.key_event(KeyCode::KeyJ, true);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                ..
            })
        ));
        // The old key no longer does anything.
        map.begin_tick(0.016);
        map.key_event(KeyCode::KeyJ, false);
        map.begin_tick(0.016);
        map.key_event(KeyCode::Space, true);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                ..
            })
        ));
    }

    #[test]
    fn rebind_an_unknown_action_errors() {
        let mut map = ActionMap::new();
        assert_eq!(
            map.rebind("nope", vec![]),
            Err(ActionMapError::UnknownAction("nope".to_owned()))
        );
    }

    /// A rebind while the new key is already held resolves immediately.
    #[test]
    fn rebind_resolves_against_the_current_held_keys() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));
        map.key_event(KeyCode::KeyJ, true);
        map.rebind("jump", vec![Binding::Key(KeyCode::KeyJ)])
            .expect("declared");
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                ..
            })
        ));
    }

    // -- Axis1 key pairs ----------------------------------------------------

    /// A single `Key` binding can only ever add +1.0, so a keyboard axis could
    /// not go negative at all.
    #[test]
    fn key_axis_reaches_both_ends_of_the_range() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "throttle".into(),
            kind: ActionKind::Axis1,
            bindings: vec![Binding::KeyAxis {
                negative: KeyCode::KeyS,
                positive: KeyCode::KeyW,
            }],
        });

        assert_eq_axis1(map.action("throttle").unwrap(), 0.0);

        map.key_event(KeyCode::KeyW, true);
        assert_eq_axis1(map.action("throttle").unwrap(), 1.0);

        // Both held → cancel.
        map.key_event(KeyCode::KeyS, true);
        assert_eq_axis1(map.action("throttle").unwrap(), 0.0);

        map.key_event(KeyCode::KeyW, false);
        assert_eq_axis1(map.action("throttle").unwrap(), -1.0);
    }

    /// A `KeyAxis` on a `Button` action is "either key is down".
    #[test]
    fn key_axis_drives_a_button_from_either_key() {
        let mut map = ActionMap::new();
        map.declare(decl_button(
            "any",
            Binding::KeyAxis {
                negative: KeyCode::KeyS,
                positive: KeyCode::KeyW,
            },
        ));
        map.key_event(KeyCode::KeyS, true);
        assert!(matches!(
            map.action("any").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                ..
            })
        ));
    }

    // -- non-finite input ---------------------------------------------------

    /// `mouse_motion(NAN, 1.0)` used to write `Axis2 { x: NaN, y: 1.0 }`
    /// straight through, and `f32::clamp` returns `NaN` for a `NaN` scroll, so
    /// the clamp downstream was no defence either.
    #[test]
    fn non_finite_deltas_are_dropped_at_the_ingest_boundary() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_mouse("look"));
        map.declare(decl_axis1_scroll("zoom"));

        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            map.mouse_motion(bad, 1.0);
            map.mouse_motion(1.0, bad);
            map.mouse_scroll(0.0, bad);
        }

        match map.action("look").unwrap() {
            ActionValue::Axis2(a) => assert!(
                a.x.is_finite() && a.y.is_finite(),
                "look went non-finite: {a:?}"
            ),
            other => panic!("expected Axis2, got {other:?}"),
        }
        match map.action("zoom").unwrap() {
            ActionValue::Axis1(a) => {
                assert!(a.value.is_finite(), "zoom went non-finite: {a:?}");
            }
            other => panic!("expected Axis1, got {other:?}"),
        }

        // Good deltas still land.
        map.begin_tick(0.016);
        map.mouse_motion(3.0, -4.0);
        assert_eq_axis2(map.action("look").unwrap(), 3.0, -4.0);
    }

    /// A non-finite pointer coordinate must not become the axis a paddle is
    /// positioned from — and must not evict the last good position either.
    #[test]
    fn a_non_finite_pointer_position_is_dropped_and_the_last_one_survives() {
        let mut map = ActionMap::new();
        map.declare(decl_axis1_pointer("aim", PointerAxis::X));

        map.pointer_position(0.4, 0.0);
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            map.pointer_position(bad, 0.0);
            map.pointer_position(0.0, bad);
        }

        assert_eq_axis1(map.action("aim").unwrap(), 0.4);
    }

    /// A non-finite `dt` must not poison the clock every `Held` duration is
    /// measured against.
    #[test]
    fn a_non_finite_dt_does_not_poison_hold_durations() {
        let mut map = ActionMap::new();
        map.declare(decl_button("fire", Binding::Key(KeyCode::KeyF)));
        map.key_event(KeyCode::KeyF, true);
        map.begin_tick(f32::NAN);
        map.begin_tick(2.0);

        let ActionValue::Button(a) = map.action("fire").unwrap() else {
            panic!("expected Button");
        };
        let ButtonState::Held { duration } = a.state else {
            panic!("expected Held, got {:?}", a.state);
        };
        assert!((duration - 2.0).abs() < 0.001, "got {duration}");
    }

    /// A negative `dt` used to move the clock backwards, so a key held across
    /// it reported a negative `Held` duration — and the lost time then made the
    /// next tick measure the hold as though it had never been held.
    #[test]
    fn a_negative_dt_does_not_report_a_negative_hold_duration() {
        let mut map = ActionMap::new();
        map.declare(decl_button("fire", Binding::Key(KeyCode::KeyF)));
        map.key_event(KeyCode::KeyF, true);

        map.begin_tick(-1.0);
        let ActionValue::Button(a) = map.action("fire").unwrap() else {
            panic!("expected Button");
        };
        let ButtonState::Held { duration } = a.state else {
            panic!("expected Held, got {:?}", a.state);
        };
        assert!(
            duration >= 0.0,
            "a negative dt must not report a negative hold duration, got {duration}"
        );

        // The negative tick was dropped rather than absorbed: a real 1s tick
        // measures a full second, not the second minus the backwards one.
        map.begin_tick(1.0);
        let ActionValue::Button(a) = map.action("fire").unwrap() else {
            panic!("expected Button");
        };
        let ButtonState::Held { duration } = a.state else {
            panic!("expected Held, got {:?}", a.state);
        };
        assert!(
            (duration - 1.0).abs() < 0.001,
            "with the negative tick dropped the hold measures normally, got {duration}"
        );
    }

    // -- action_mut ---------------------------------------------------------

    #[test]
    fn action_mut_lets_caller_clear_edges() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));

        map.key_event(KeyCode::Space, true);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                just_pressed: true,
                ..
            })
        ));

        // Consume the edge mid-tick.
        if let Some(ActionValue::Button(a)) = map.action_mut("jump") {
            a.just_pressed = false;
        }

        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                just_pressed: false,
                ..
            })
        ));
    }

    // -- multiple bindings per action ---------------------------------------

    #[test]
    fn multiple_bindings_any_triggers() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "jump".into(),
            kind: ActionKind::Button,
            bindings: vec![
                Binding::Key(KeyCode::Space),
                Binding::MouseButton(PointerButton::Left),
            ],
        });

        // Either binding triggers.
        map.key_event(KeyCode::Space, true);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                ..
            })
        ));

        map.begin_tick(0.016);
        map.key_event(KeyCode::Space, false);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                ..
            })
        ));

        map.begin_tick(0.016);
        map.mouse_button(PointerButton::Left, true);
        assert!(matches!(
            map.action("jump").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                ..
            })
        ));
    }

    #[test]
    fn multiple_bindings_stays_held_until_all_released() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "crouch".into(),
            kind: ActionKind::Button,
            bindings: vec![
                Binding::Key(KeyCode::ControlLeft),
                Binding::Key(KeyCode::KeyC),
            ],
        });

        map.key_event(KeyCode::ControlLeft, true);
        assert!(matches!(
            map.action("crouch").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                ..
            })
        ));

        map.begin_tick(0.016);
        map.key_event(KeyCode::KeyC, true);
        // Still held (via ControlLeft).
        assert!(matches!(
            map.action("crouch").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Held { .. },
                ..
            })
        ));

        // Release one, still held via the other.
        map.key_event(KeyCode::ControlLeft, false);
        assert!(matches!(
            map.action("crouch").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Held { .. },
                ..
            })
        ));

        // Release both → released.
        map.key_event(KeyCode::KeyC, false);
        assert!(matches!(
            map.action("crouch").unwrap(),
            ActionValue::Button(ButtonAction {
                state: ButtonState::Released,
                just_released: true,
                ..
            })
        ));
    }

    // -- action_names -------------------------------------------------------

    #[test]
    fn action_names_returns_in_order() {
        let mut map = ActionMap::new();
        map.declare(decl_button("a", Binding::Key(KeyCode::KeyA)));
        map.declare(decl_button("b", Binding::Key(KeyCode::KeyB)));
        map.declare(decl_button("c", Binding::Key(KeyCode::KeyC)));

        let names: Vec<&str> = map.action_names().collect();
        assert_eq!(names, vec!["a", "b", "c"]);
    }

    // -- InputTickState -----------------------------------------------------

    #[test]
    fn tick_state_capture_and_get() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::KeyW,
            KeyCode::KeyS,
            KeyCode::KeyA,
            KeyCode::KeyD,
        ));

        map.key_event(KeyCode::Space, true);
        map.key_event(KeyCode::KeyW, true);

        let tick = InputTickState::capture(&map);
        assert_eq!(tick.actions.len(), 2);

        // jump should be pressed.
        let jump = tick.get("jump").unwrap();
        assert!(matches!(
            jump,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                just_released: false,
            })
        ));

        // move should be (0, 1).
        let mv = tick.get("move").unwrap();
        assert_eq_axis2(mv, 0.0, 1.0);

        // Unknown name → None.
        assert!(tick.get("nope").is_none());
    }

    #[test]
    fn tick_state_new_is_empty() {
        let tick = InputTickState::new();
        assert!(tick.actions.is_empty());
        assert!(tick.get("anything").is_none());
    }

    // -- edge case: multiple actions with overlapping bindings ---------------

    #[test]
    fn two_actions_bound_to_one_key_both_report_pressed() {
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));
        map.declare(decl_button("fire", Binding::Key(KeyCode::Space)));

        map.key_event(KeyCode::Space, true);

        // Both should be pressed independently.
        let jump = map.action("jump").unwrap();
        let fire = map.action("fire").unwrap();
        assert!(matches!(
            jump,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                ..
            })
        ));
        assert!(matches!(
            fire,
            ActionValue::Button(ButtonAction {
                state: ButtonState::Pressed,
                just_pressed: true,
                ..
            })
        ));
    }

    // -- edge case: non-existent action -------------------------------------

    #[test]
    fn unknown_action_returns_none() {
        let mut map = ActionMap::new();
        assert!(map.action("nope").is_none());
        assert!(map.action_mut("nope").is_none());
    }

    // -- Debug implementations ----------------------------------------------

    #[test]
    fn every_input_type_debug_prints_without_panicking() {
        // Just make sure they don't panic.
        let mut map = ActionMap::new();
        map.declare(decl_button("jump", Binding::Key(KeyCode::Space)));
        let _ = format!("{map:?}");

        let tick = InputTickState::capture(&map);
        let _ = format!("{tick:?}");

        let _ = format!("{:?}", ButtonAction::default());
        let _ = format!("{:?}", ButtonState::Pressed);
        let _ = format!("{:?}", ActionKind::Button);
        let _ = format!(
            "{:?}",
            Binding::Wasd {
                up: KeyCode::KeyW,
                down: KeyCode::KeyS,
                left: KeyCode::KeyA,
                right: KeyCode::KeyD,
            }
        );
    }

    // -- Default impls ------------------------------------------------------

    #[test]
    fn axis_defaults_are_zero() {
        assert_eq!(
            Axis1Action::default(),
            Axis1Action {
                value: 0.0,
                pointer_moved: false,
            }
        );
        assert_eq!(Axis2Action::default(), Axis2Action { x: 0.0, y: 0.0 });
    }

    #[test]
    fn input_tick_state_default_is_empty() {
        let tick = InputTickState::default();
        assert!(tick.actions.is_empty());
    }

    // -- WASD with non-standard keys ----------------------------------------

    #[test]
    fn wasd_with_arrow_keys() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::ArrowUp,
            KeyCode::ArrowDown,
            KeyCode::ArrowLeft,
            KeyCode::ArrowRight,
        ));

        map.key_event(KeyCode::ArrowRight, true);
        map.key_event(KeyCode::ArrowUp, true);
        let diag = std::f32::consts::FRAC_1_SQRT_2;
        assert_eq_axis2(map.action("move").unwrap(), diag, diag);
    }

    /// The docs promised a unit vector and the code never normalized, so a
    /// diagonal was 1.414 long — 41% faster than a cardinal direction.
    #[test]
    fn wasd_diagonal_is_not_faster_than_a_cardinal_direction() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_wasd(
            "move",
            KeyCode::KeyW,
            KeyCode::KeyS,
            KeyCode::KeyA,
            KeyCode::KeyD,
        ));

        map.key_event(KeyCode::KeyW, true);
        let cardinal = axis2_len(map.action("move").unwrap());
        assert!((cardinal - 1.0).abs() < 0.001, "got {cardinal}");

        map.key_event(KeyCode::KeyD, true);
        let diagonal = axis2_len(map.action("move").unwrap());
        assert!(
            (diagonal - 1.0).abs() < 0.001,
            "diagonal magnitude {diagonal} should be 1.0"
        );
    }

    /// Mouse motion is a pixel delta, not a direction: normalizing it would
    /// throw away how far the pointer actually moved.
    #[test]
    fn mouse_motion_is_not_normalized() {
        let mut map = ActionMap::new();
        map.declare(decl_axis2_mouse("look"));
        map.mouse_motion(30.0, 40.0);
        assert_eq_axis2(map.action("look").unwrap(), 30.0, 40.0);
    }

    // -- on-screen controls --------------------------------------------------

    /// An on-screen stick and the keyboard drive the **same** action, and the
    /// action cannot tell which of them spoke.
    ///
    /// The whole claim of [`Binding::Virtual`]: one `move`, two devices, and a
    /// game that reads `axis2` and never asks where the value came from.
    #[test]
    fn a_stick_and_a_keyboard_drive_one_action() {
        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,
                },
                Binding::Virtual("stick_move".to_owned()),
            ],
        });

        assert_eq!(map.axis2("move"), (0.0, 0.0), "nothing is touching it yet");

        map.virtual_stick("stick_move", -0.5, 0.25);
        assert_eq_axis2(map.action("move").unwrap(), -0.5, 0.25);

        // A partial deflection is a partial value, which is the thing four
        // buttons could not say — and it survives the tick boundary, because a
        // finger resting on the glass reports nothing.
        map.begin_tick(TICK);
        assert_eq_axis2(map.action("move").unwrap(), -0.5, 0.25);

        // A key *and* a stick is one direction, not twice the speed: the two
        // sum to (-1.5, 0.25) and the sum is scaled back onto the disc, so the
        // heading survives and the magnitude does not exceed one.
        map.key_event(KeyCode::KeyA, true);
        let (x, y) = map.axis2("move");
        let len = x.hypot(y);
        assert!((len - 1.0).abs() < 0.001, "magnitude {len} left the disc");
        assert!(
            (y / x - 0.25 / -1.5).abs() < 0.001,
            "the summed heading was not kept, got ({x}, {y})",
        );

        map.virtual_stick("stick_move", 0.0, 0.0);
        map.key_event(KeyCode::KeyA, false);
        assert_eq!(map.axis2("move"), (0.0, 0.0), "both let go");
    }

    /// A stick reported past its own radius is still only all the way over,
    /// **and keeps its direction**.
    #[test]
    fn a_stick_past_its_radius_is_clamped_to_the_disc() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "move".to_owned(),
            kind: ActionKind::Axis2,
            bindings: vec![Binding::Virtual("stick_move".to_owned())],
        });

        // 3-4-5: a length of 5, so the clamped value is the exact (0.6, 0.8)
        // rather than a number that only looks about right.
        map.virtual_stick("stick_move", 3.0, 4.0);
        assert_eq_axis2(map.action("move").unwrap(), 0.6, 0.8);
        let len = axis2_len(map.action("move").unwrap());
        assert!((len - 1.0).abs() < 0.001, "got {len}");
    }

    /// A control drives a button action with the same edges a key does.
    #[test]
    fn a_virtual_button_has_the_edges_a_key_has() {
        let mut map = ActionMap::new();
        map.declare(decl_button(
            "pause",
            Binding::Virtual("btn_pause".to_owned()),
        ));

        map.begin_tick(TICK);
        map.virtual_button("btn_pause", true);
        assert!(map.just_pressed("pause"));
        assert!(map.button_held("pause"));

        map.begin_tick(TICK);
        assert!(
            !map.just_pressed("pause"),
            "holding the control does not press it again",
        );
        assert!(map.button_held("pause"));

        map.virtual_button("btn_pause", false);
        assert!(map.just_released("pause"));
        assert!(!map.button_held("pause"));
    }

    /// Ids name different controls: a second control does not drive the first
    /// one's action.
    #[test]
    fn a_control_drives_only_the_action_that_names_it() {
        let mut map = ActionMap::new();
        map.declare(decl_button("pause", Binding::Virtual("btn_pause".into())));
        map.declare(ActionDecl {
            name: "move".to_owned(),
            kind: ActionKind::Axis2,
            bindings: vec![Binding::Virtual("stick_move".to_owned())],
        });

        map.virtual_button("btn_other", true);
        map.virtual_stick("stick_other", 1.0, 0.0);
        assert!(!map.button_held("pause"), "another control's press");
        assert_eq!(map.axis2("move"), (0.0, 0.0), "another control's stick");

        map.virtual_button("btn_pause", true);
        map.virtual_stick("stick_move", 1.0, 0.0);
        assert!(map.button_held("pause"));
        assert_eq!(map.axis2("move"), (1.0, 0.0));
    }

    /// A stick fed to a 1-D axis reads nothing, and the docs say so: reducing a
    /// vector to one axis is a choice no control makes.
    ///
    /// The inert case pinned deliberately — a `Virtual` that silently drove
    /// `Axis1` off its `x` would be a value nobody chose.
    #[test]
    fn a_stick_on_a_one_dimensional_axis_reads_nothing() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "throttle".to_owned(),
            kind: ActionKind::Axis1,
            bindings: vec![Binding::Virtual("stick_move".to_owned())],
        });

        map.virtual_stick("stick_move", 1.0, 1.0);
        assert_eq!(map.axis1("throttle"), 0.0);
    }

    /// A non-finite deflection is dropped rather than stored, like a `NaN`
    /// mouse delta: one would poison every comparison downstream of the axis.
    #[test]
    fn a_non_finite_deflection_is_dropped() {
        let mut map = ActionMap::new();
        map.declare(ActionDecl {
            name: "move".to_owned(),
            kind: ActionKind::Axis2,
            bindings: vec![Binding::Virtual("stick_move".to_owned())],
        });

        map.virtual_stick("stick_move", 0.5, 0.5);
        map.virtual_stick("stick_move", f32::NAN, 0.0);
        assert_eq_axis2(map.action("move").unwrap(), 0.5, 0.5);
        map.virtual_stick("stick_move", 0.0, f32::INFINITY);
        assert_eq_axis2(map.action("move").unwrap(), 0.5, 0.5);
    }

    // -- assert helpers -----------------------------------------------------

    fn assert_eq_axis2(v: &ActionValue, x: f32, y: f32) {
        match v {
            ActionValue::Axis2(a) => {
                assert!(
                    (a.x - x).abs() < 0.001 && (a.y - y).abs() < 0.001,
                    "expected Axis2({x}, {y}), got Axis2({}, {})",
                    a.x,
                    a.y
                );
            }
            other => panic!("expected Axis2, got {other:?}"),
        }
    }

    fn axis2_len(v: &ActionValue) -> f32 {
        match v {
            ActionValue::Axis2(a) => (a.x * a.x + a.y * a.y).sqrt(),
            other => panic!("expected Axis2, got {other:?}"),
        }
    }

    fn assert_eq_axis1(v: &ActionValue, val: f32) {
        match v {
            ActionValue::Axis1(a) => {
                assert!(
                    (a.value - val).abs() < 0.001,
                    "expected Axis1({val}), got Axis1({})",
                    a.value
                );
            }
            other => panic!("expected Axis1, got {other:?}"),
        }
    }
}