File: input.c

package info (click to toggle)
foot 1.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,108 kB
  • sloc: ansic: 41,260; python: 474; sh: 181; xml: 57; makefile: 18
file content (3651 lines) | stat: -rw-r--r-- 125,822 bytes parent folder | download
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
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
#include "input.h"

#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <threads.h>
#include <locale.h>
#include <errno.h>
#include <wctype.h>
#include <sys/mman.h>
#include <sys/timerfd.h>
#include <sys/epoll.h>
#include <fcntl.h>

#include <linux/input-event-codes.h>

#include <xkbcommon/xkbcommon.h>
#include <xkbcommon/xkbcommon-keysyms.h>
#include <xkbcommon/xkbcommon-compose.h>

#include <xdg-shell.h>

#define LOG_MODULE "input"
#define LOG_ENABLE_DBG 0
#include "log.h"
#include "commands.h"
#include "config.h"
#include "grid.h"
#include "keymap.h"
#include "kitty-keymap.h"
#include "macros.h"
#include "quirks.h"
#include "render.h"
#include "search.h"
#include "selection.h"
#include "spawn.h"
#include "terminal.h"
#include "tokenize.h"
#include "unicode-mode.h"
#include "url-mode.h"
#include "util.h"
#include "vt.h"
#include "xkbcommon-vmod.h"
#include "xmalloc.h"
#include "xsnprintf.h"

struct pipe_context {
    char *text;
    size_t idx;
    size_t left;
};

static bool
fdm_write_pipe(struct fdm *fdm, int fd, int events, void *data)
{
    struct pipe_context *ctx = data;

    if (events & EPOLLHUP)
        goto pipe_closed;

    xassert(events & EPOLLOUT);
    ssize_t written = write(fd, &ctx->text[ctx->idx], ctx->left);

    if (written < 0) {
        LOG_WARN("failed to write to pipe: %s", strerror(errno));
        goto pipe_closed;
    }

    xassert(written <= ctx->left);
    ctx->idx += written;
    ctx->left -= written;

    if (ctx->left == 0)
        goto pipe_closed;

    return true;

pipe_closed:
    free(ctx->text);
    free(ctx);
    fdm_del(fdm, fd);
    return true;
}

static void alternate_scroll(struct seat *seat, int amount, int button);

static bool
execute_binding(struct seat *seat, struct terminal *term,
                const struct key_binding *binding, uint32_t serial, int amount)
{
    const enum bind_action_normal action = binding->action;

    switch (action) {
    case BIND_ACTION_NONE:
        return true;

    case BIND_ACTION_NOOP:
        return true;

    case BIND_ACTION_SCROLLBACK_UP_PAGE:
        if (term->grid == &term->normal) {
            cmd_scrollback_up(term, term->rows);
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_UP_HALF_PAGE:
        if (term->grid == &term->normal) {
            cmd_scrollback_up(term, max(term->rows / 2, 1));
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_UP_LINE:
        if (term->grid == &term->normal) {
            cmd_scrollback_up(term, 1);
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_UP_MOUSE:
        if (term->grid == &term->alt) {
            if (term->alt_scrolling)
                alternate_scroll(seat, amount, BTN_BACK);
        } else
                cmd_scrollback_up(term, amount);
        break;

    case BIND_ACTION_SCROLLBACK_DOWN_PAGE:
        if (term->grid == &term->normal) {
            cmd_scrollback_down(term, term->rows);
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_DOWN_HALF_PAGE:
        if (term->grid == &term->normal) {
            cmd_scrollback_down(term, max(term->rows / 2, 1));
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_DOWN_LINE:
        if (term->grid == &term->normal) {
            cmd_scrollback_down(term, 1);
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_DOWN_MOUSE:
        if (term->grid == &term->alt) {
            if (term->alt_scrolling)
                alternate_scroll(seat, amount, BTN_FORWARD);
        } else
            cmd_scrollback_down(term, amount);
        break;

    case BIND_ACTION_SCROLLBACK_HOME:
        if (term->grid == &term->normal) {
            cmd_scrollback_up(term, term->grid->num_rows);
            return true;
        }
        break;

    case BIND_ACTION_SCROLLBACK_END:
        if (term->grid == &term->normal) {
            cmd_scrollback_down(term, term->grid->num_rows);
            return true;
        }
        break;

    case BIND_ACTION_CLIPBOARD_COPY:
        selection_to_clipboard(seat, term, serial);
        return true;

    case BIND_ACTION_CLIPBOARD_PASTE:
        selection_from_clipboard(seat, term, serial);
        term_reset_view(term);
        return true;

    case BIND_ACTION_PRIMARY_PASTE:
        selection_from_primary(seat, term);
        term_reset_view(term);
        return true;

    case BIND_ACTION_SEARCH_START:
        search_begin(term);
        return true;

    case BIND_ACTION_FONT_SIZE_UP:
        term_font_size_increase(term);
        return true;

    case BIND_ACTION_FONT_SIZE_DOWN:
        term_font_size_decrease(term);
        return true;

    case BIND_ACTION_FONT_SIZE_RESET:
        term_font_size_reset(term);
        return true;

    case BIND_ACTION_SPAWN_TERMINAL:
        term_spawn_new(term);
        return true;

    case BIND_ACTION_MINIMIZE:
        xdg_toplevel_set_minimized(term->window->xdg_toplevel);
        return true;

    case BIND_ACTION_MAXIMIZE:
        if (term->window->is_fullscreen)
            xdg_toplevel_unset_fullscreen(term->window->xdg_toplevel);
        if (term->window->is_maximized)
            xdg_toplevel_unset_maximized(term->window->xdg_toplevel);
        else
            xdg_toplevel_set_maximized(term->window->xdg_toplevel);
        return true;

    case BIND_ACTION_FULLSCREEN:
        if (term->window->is_fullscreen)
            xdg_toplevel_unset_fullscreen(term->window->xdg_toplevel);
        else
            xdg_toplevel_set_fullscreen(term->window->xdg_toplevel, NULL);
        return true;

    case BIND_ACTION_PIPE_SCROLLBACK:
        if (term->grid == &term->alt)
            break;
        /* FALLTHROUGH */
    case BIND_ACTION_PIPE_VIEW:
    case BIND_ACTION_PIPE_SELECTED:
    case BIND_ACTION_PIPE_COMMAND_OUTPUT: {
        if (binding->aux->type != BINDING_AUX_PIPE)
            return true;

        struct pipe_context *ctx = NULL;

        int pipe_fd[2] = {-1, -1};
        int stdout_fd = -1;
        int stderr_fd = -1;

        char *text = NULL;
        size_t len = 0;

        if (pipe(pipe_fd) < 0) {
            LOG_ERRNO("failed to create pipe");
            goto pipe_err;
        }

        stdout_fd = open("/dev/null", O_WRONLY);
        stderr_fd = open("/dev/null", O_WRONLY);

        if (stdout_fd < 0 || stderr_fd < 0) {
            LOG_ERRNO("failed to open /dev/null");
            goto pipe_err;
        }

        bool success;
        switch (action) {
        case BIND_ACTION_PIPE_SCROLLBACK:
            success = term_scrollback_to_text(term, &text, &len);
            break;

        case BIND_ACTION_PIPE_VIEW:
            success = term_view_to_text(term, &text, &len);
            break;

        case BIND_ACTION_PIPE_SELECTED:
            text = selection_to_text(term);
            success = text != NULL;
            len = text != NULL ? strlen(text) : 0;
            break;

        case BIND_ACTION_PIPE_COMMAND_OUTPUT:
            success = term_command_output_to_text(term, &text, &len);
            break;

        default:
            BUG("Unhandled action type");
            success = false;
            break;
        }

        if (!success)
            goto pipe_err;

        /* Make write-end non-blocking; required by the FDM */
        {
            int flags = fcntl(pipe_fd[1], F_GETFL);
            if (flags < 0 ||
                fcntl(pipe_fd[1], F_SETFL, flags | O_NONBLOCK) < 0)
            {
                LOG_ERRNO("failed to make write-end of pipe non-blocking");
                goto pipe_err;
            }
        }

        /* Make sure write-end is closed on exec() - or the spawned
         * program may not terminate*/
        {
            int flags = fcntl(pipe_fd[1], F_GETFD);
            if (flags < 0 ||
                fcntl(pipe_fd[1], F_SETFD, flags | FD_CLOEXEC) < 0)
            {
                LOG_ERRNO("failed to set FD_CLOEXEC on writeend of pipe");
                goto pipe_err;
            }
        }

        if (spawn(term->reaper, term->cwd, binding->aux->pipe.args,
                  pipe_fd[0], stdout_fd, stderr_fd, NULL, NULL, NULL) < 0)
            goto pipe_err;

        /* Close read end */
        close(pipe_fd[0]);

        ctx = xmalloc(sizeof(*ctx));
        *ctx = (struct pipe_context){
            .text = text,
            .left = len,
        };

        /* Asynchronously write the output to the pipe */
        if (!fdm_add(term->fdm, pipe_fd[1], EPOLLOUT, &fdm_write_pipe, ctx))
            goto pipe_err;

        return true;

        pipe_err:
        if (stdout_fd >= 0)
            close(stdout_fd);
        if (stderr_fd >= 0)
            close(stderr_fd);
        if (pipe_fd[0] >= 0)
            close(pipe_fd[0]);
        if (pipe_fd[1] >= 0)
            close(pipe_fd[1]);
        free(text);
        free(ctx);
        return true;
    }

    case BIND_ACTION_SHOW_URLS_COPY:
    case BIND_ACTION_SHOW_URLS_LAUNCH:
    case BIND_ACTION_SHOW_URLS_PERSISTENT: {
        xassert(!urls_mode_is_active(term));

        enum url_action url_action =
            action == BIND_ACTION_SHOW_URLS_COPY ? URL_ACTION_COPY :
            action == BIND_ACTION_SHOW_URLS_LAUNCH ? URL_ACTION_LAUNCH :
            URL_ACTION_PERSISTENT;

        urls_collect(term, url_action, &term->conf->url.preg, true, &term->urls);
        urls_assign_key_combos(term->conf, &term->urls);
        urls_render(term, &term->conf->url.launch);
        return true;
    }

    case BIND_ACTION_TEXT_BINDING:
        xassert(binding->aux->type == BINDING_AUX_TEXT);
        term_to_slave(term, binding->aux->text.data, binding->aux->text.len);
        return true;

    case BIND_ACTION_PROMPT_PREV: {
        if (term->grid != &term->normal)
            return false;

        struct grid *grid = term->grid;
        const int sb_start =
            grid_sb_start_ignore_uninitialized(grid, term->rows);

        /* Check each row from current view-1 (that is, the first
         * currently not visible row), up to, and including, the
         * scrollback start */
        for (int r_sb_rel =
                 grid_row_abs_to_sb_precalc_sb_start(
                     grid, sb_start, grid->view) - 1;
             r_sb_rel >= 0; r_sb_rel--)
        {
            const int r_abs =
                grid_row_sb_to_abs_precalc_sb_start(grid, sb_start, r_sb_rel);

            const struct row *row = grid->rows[r_abs];
            xassert(row != NULL);

            if (!row->shell_integration.prompt_marker)
                continue;

            grid->view = r_abs;
            term_damage_view(term);
            render_refresh(term);
            break;
        }

        return true;
    }

    case BIND_ACTION_PROMPT_NEXT: {
        if (term->grid != &term->normal)
            return false;

        struct grid *grid = term->grid;
        const int num_rows = grid->num_rows;

        if (grid->view == grid->offset) {
            /* Already at the bottom */
            return true;
        }

        /* Check each row from view+1, to the bottom of the scrollback */
        for (int r_abs = (grid->view + 1) & (num_rows - 1);
             ;
             r_abs = (r_abs + 1) & (num_rows - 1))
        {
            const struct row *row = grid->rows[r_abs];
            xassert(row != NULL);

            if (!row->shell_integration.prompt_marker) {
                if (r_abs == grid->offset + term->rows - 1) {
                    /* We've reached the bottom of the scrollback */
                    break;
                }
                continue;
            }

            int sb_start = grid_sb_start_ignore_uninitialized(grid, term->rows);
            int ofs_sb_rel =
                grid_row_abs_to_sb_precalc_sb_start(grid, sb_start, grid->offset);
            int new_view_sb_rel =
                grid_row_abs_to_sb_precalc_sb_start(grid, sb_start, r_abs);

            new_view_sb_rel = min(ofs_sb_rel, new_view_sb_rel);
            grid->view = grid_row_sb_to_abs_precalc_sb_start(
                grid, sb_start, new_view_sb_rel);

            term_damage_view(term);
            render_refresh(term);
            break;
        }

        return true;
    }

    case BIND_ACTION_UNICODE_INPUT:
        unicode_mode_activate(term);
        return true;

    case BIND_ACTION_QUIT:
        term_shutdown(term);
        return true;

    case BIND_ACTION_REGEX_LAUNCH:
    case BIND_ACTION_REGEX_COPY:
        if (binding->aux->type != BINDING_AUX_REGEX)
            return true;

        tll_foreach(term->conf->custom_regexes, it) {
            const struct custom_regex *regex = &it->item;

            if (streq(regex->name, binding->aux->regex_name)) {
                xassert(!urls_mode_is_active(term));

                enum url_action url_action = action == BIND_ACTION_REGEX_LAUNCH
                    ? URL_ACTION_LAUNCH : URL_ACTION_COPY;

                if (regex->regex == NULL) {
                    LOG_ERR("regex:%s has no regex defined", regex->name);
                    return true;
                }
                if (url_action == URL_ACTION_LAUNCH && regex->launch.argv.args == NULL) {
                    LOG_ERR("regex:%s has no launch command defined", regex->name);
                    return true;
                }

                urls_collect(term, url_action, &regex->preg, false, &term->urls);
                urls_assign_key_combos(term->conf, &term->urls);
                urls_render(term, &regex->launch);
                return true;
            }
        }

        LOG_ERR(
            "no regex section named '%s' defined in the configuration",
            binding->aux->regex_name);

        return true;

    case BIND_ACTION_THEME_SWITCH_1:
        term_theme_switch_to_1(term);
        return true;

    case BIND_ACTION_THEME_SWITCH_2:
        term_theme_switch_to_2(term);
        return true;

    case BIND_ACTION_THEME_TOGGLE:
        term_theme_toggle(term);
        return true;

    case BIND_ACTION_SELECT_BEGIN:
        selection_start(
            term, seat->mouse.col, seat->mouse.row, SELECTION_CHAR_WISE, false);
        return true;

    case BIND_ACTION_SELECT_BEGIN_BLOCK:
        selection_start(
            term, seat->mouse.col, seat->mouse.row, SELECTION_BLOCK, false);
        return true;

    case BIND_ACTION_SELECT_EXTEND:
        selection_extend(
            seat, term, seat->mouse.col, seat->mouse.row, term->selection.kind);
        return true;

    case BIND_ACTION_SELECT_EXTEND_CHAR_WISE:
        if (term->selection.kind != SELECTION_BLOCK) {
            selection_extend(
                seat, term, seat->mouse.col, seat->mouse.row, SELECTION_CHAR_WISE);
            return true;
        }
        return false;

    case BIND_ACTION_SELECT_WORD:
        selection_start(
            term, seat->mouse.col, seat->mouse.row, SELECTION_WORD_WISE, false);
        return true;

    case BIND_ACTION_SELECT_WORD_WS:
        selection_start(
            term, seat->mouse.col, seat->mouse.row, SELECTION_WORD_WISE, true);
        return true;

    case BIND_ACTION_SELECT_QUOTE:
        selection_start(
            term, seat->mouse.col, seat->mouse.row, SELECTION_QUOTE_WISE, false);
        break;

    case BIND_ACTION_SELECT_ROW:
        selection_start(
            term, seat->mouse.col, seat->mouse.row, SELECTION_LINE_WISE, false);
        return true;

    case BIND_ACTION_COUNT:
        BUG("Invalid action type");
        return false;
    }

    return false;
}

static void
keyboard_keymap(void *data, struct wl_keyboard *wl_keyboard,
                uint32_t format, int32_t fd, uint32_t size)
{
    LOG_DBG("keyboard_keymap: keyboard=%p (format=%u, size=%u)",
            (void *)wl_keyboard, format, size);

    struct seat *seat = data;
    struct wayland *wayl = seat->wayl;

    /*
     * Free old keymap state
     */

    if (seat->kbd.xkb_keymap != NULL) {
        xkb_keymap_unref(seat->kbd.xkb_keymap);
        seat->kbd.xkb_keymap = NULL;
    }
    if (seat->kbd.xkb_state != NULL) {
        xkb_state_unref(seat->kbd.xkb_state);
        seat->kbd.xkb_state = NULL;
    }

    key_binding_unload_keymap(wayl->key_binding_manager, seat);

    /* Verify keymap is in a format we understand */
    switch ((enum wl_keyboard_keymap_format)format) {
    case WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP:
        close(fd);
        return;

    case WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1:
        break;

    default:
        LOG_WARN("unrecognized keymap format: %u", format);
        close(fd);
        return;
    }

    char *map_str = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (map_str == MAP_FAILED) {
        LOG_ERRNO("failed to mmap keyboard keymap");
        close(fd);
        return;
    }

    while (map_str[size - 1] == '\0')
        size--;

    if (seat->kbd.xkb != NULL) {
        seat->kbd.xkb_keymap = xkb_keymap_new_from_buffer(
            seat->kbd.xkb, map_str, size, XKB_KEYMAP_FORMAT_TEXT_V1,
            XKB_KEYMAP_COMPILE_NO_FLAGS);

    }

    if (seat->kbd.xkb_keymap != NULL) {
        seat->kbd.xkb_state = xkb_state_new(seat->kbd.xkb_keymap);

        seat->kbd.mod_shift = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_MOD_NAME_SHIFT);
        seat->kbd.mod_alt = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_MOD_NAME_ALT) ;
        seat->kbd.mod_ctrl = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_MOD_NAME_CTRL);
        seat->kbd.mod_super = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_MOD_NAME_LOGO);
        seat->kbd.mod_caps = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_MOD_NAME_CAPS);
        seat->kbd.mod_num = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_MOD_NAME_NUM);

        /* Significant modifiers in the legacy keyboard protocol */
        seat->kbd.legacy_significant = 0;
        if (seat->kbd.mod_shift != XKB_MOD_INVALID)
            seat->kbd.legacy_significant |= 1 << seat->kbd.mod_shift;
        if (seat->kbd.mod_alt != XKB_MOD_INVALID)
            seat->kbd.legacy_significant |= 1 << seat->kbd.mod_alt;
        if (seat->kbd.mod_ctrl != XKB_MOD_INVALID)
            seat->kbd.legacy_significant |= 1 << seat->kbd.mod_ctrl;
        if (seat->kbd.mod_super != XKB_MOD_INVALID)
            seat->kbd.legacy_significant |= 1 << seat->kbd.mod_super;

        /* Significant modifiers in the kitty keyboard protocol */
        seat->kbd.kitty_significant = seat->kbd.legacy_significant;
        if (seat->kbd.mod_caps != XKB_MOD_INVALID)
            seat->kbd.kitty_significant |= 1 << seat->kbd.mod_caps;
        if (seat->kbd.mod_num != XKB_MOD_INVALID)
            seat->kbd.kitty_significant |= 1 << seat->kbd.mod_num;


        /*
         * Create a mask of all "virtual" modifiers. Some compositors
         * add these *in addition* to the "real" modifiers (Mod1,
         * Mod2, etc).
         *
         * Since our modifier logic (both for internal shortcut
         * processing, and e.g. the kitty keyboard protocol) makes
         * very few assumptions on available modifiers, which keys map
         * to which modifier etc, the presence of virtual modifiers
         * causes various things to break.
         *
         * For example, if a foot shortcut is Mod1+b (i.e. Alt+b), it
         * won't match if the compositor _also_ sets the Alt modifier
         * (the corresponding shortcut in foot would be Alt+Mod1+b).
         *
         * See https://codeberg.org/dnkl/foot/issues/2009
         *
         * Mutter (GNOME) is known to set the virtual modifiers in
         * addtiion to the real modifiers.
         *
         * As far as I know, there's no compositor that _only_ sets
         * virtual modifiers (don't think that's even legal...?)
         */
        {
            xkb_mod_index_t alt = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_ALT);
            xkb_mod_index_t meta = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_META);
            xkb_mod_index_t super = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_SUPER);
            xkb_mod_index_t hyper = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_HYPER);
            xkb_mod_index_t num_lock = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_NUM);
            xkb_mod_index_t scroll_lock = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_SCROLL);
            xkb_mod_index_t level_three = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_LEVEL3);
            xkb_mod_index_t level_five = xkb_keymap_mod_get_index(seat->kbd.xkb_keymap, XKB_VMOD_NAME_LEVEL5);

            xkb_mod_index_t ignore = 0;

            if (alt != XKB_MOD_INVALID) ignore |= 1 << alt;
            if (meta != XKB_MOD_INVALID) ignore |= 1 << meta;
            if (super != XKB_MOD_INVALID) ignore |= 1 << super;
            if (hyper != XKB_MOD_INVALID) ignore |= 1 << hyper;
            if (num_lock != XKB_MOD_INVALID) ignore |= 1 << num_lock;
            if (scroll_lock != XKB_MOD_INVALID) ignore |= 1 << scroll_lock;
            if (level_three != XKB_MOD_INVALID) ignore |= 1 << level_three;
            if (level_five != XKB_MOD_INVALID) ignore |= 1 << level_five;

            seat->kbd.virtual_modifiers = ignore;
        }

        seat->kbd.key_arrow_up = xkb_keymap_key_by_name(seat->kbd.xkb_keymap, "UP");
        seat->kbd.key_arrow_down = xkb_keymap_key_by_name(seat->kbd.xkb_keymap, "DOWN");
    }

    munmap(map_str, size);
    close(fd);

    key_binding_load_keymap(wayl->key_binding_manager, seat);
}

static void
keyboard_enter(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,
               struct wl_surface *surface, struct wl_array *keys)
{
    xassert(surface != NULL);
    xassert(serial != 0);

    struct seat *seat = data;
    struct wl_window *win = wl_surface_get_user_data(surface);
    struct terminal *term = win->term;

    LOG_DBG("%s: keyboard_enter: keyboard=%p, serial=%u, surface=%p",
            seat->name, (void *)wl_keyboard, serial, (void *)surface);

    term_kbd_focus_in(term);
    seat->kbd_focus = term;
    seat->kbd.serial = serial;
}

static bool
start_repeater(struct seat *seat, uint32_t key)
{
    if (seat->kbd.repeat.dont_re_repeat)
        return true;

    if (seat->kbd.repeat.rate == 0)
        return true;

    struct itimerspec t = {
        .it_value = {.tv_sec = 0, .tv_nsec = seat->kbd.repeat.delay * 1000000},
        .it_interval = {.tv_sec = 0, .tv_nsec = 1000000000 / seat->kbd.repeat.rate},
    };

    if (t.it_value.tv_nsec >= 1000000000) {
        t.it_value.tv_sec += t.it_value.tv_nsec / 1000000000;
        t.it_value.tv_nsec %= 1000000000;
    }
    if (t.it_interval.tv_nsec >= 1000000000) {
        t.it_interval.tv_sec += t.it_interval.tv_nsec / 1000000000;
        t.it_interval.tv_nsec %= 1000000000;
    }
    if (timerfd_settime(seat->kbd.repeat.fd, 0, &t, NULL) < 0) {
        LOG_ERRNO("%s: failed to arm keyboard repeat timer", seat->name);
        return false;
    }

    seat->kbd.repeat.key = key;
    return true;
}

static bool
stop_repeater(struct seat *seat, uint32_t key)
{
    if (key != -1 && key != seat->kbd.repeat.key)
        return true;

    if (timerfd_settime(seat->kbd.repeat.fd, 0, &(struct itimerspec){{0}}, NULL) < 0) {
        LOG_ERRNO("%s: failed to disarm keyboard repeat timer", seat->name);
        return false;
    }

    return true;
}

static void
keyboard_leave(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,
               struct wl_surface *surface)
{
    struct seat *seat = data;

    LOG_DBG("keyboard_leave: keyboard=%p, serial=%u, surface=%p",
            (void *)wl_keyboard, serial, (void *)surface);

    xassert(
        seat->kbd_focus == NULL ||
        surface == NULL ||  /* Seen on Sway 1.2 */
        ((const struct wl_window *)wl_surface_get_user_data(surface))->term == seat->kbd_focus
        );

    struct terminal *old_focused = seat->kbd_focus;
    seat->kbd_focus = NULL;

    stop_repeater(seat, -1);
    seat->kbd.shift = false;
    seat->kbd.alt = false;
    seat->kbd.ctrl = false;
    seat->kbd.super = false;

    if (seat->kbd.xkb_compose_state != NULL)
        xkb_compose_state_reset(seat->kbd.xkb_compose_state);

    if (seat->kbd.xkb_state != NULL && seat->kbd.xkb_keymap != NULL) {
        const xkb_layout_index_t layout_count = xkb_keymap_num_layouts(seat->kbd.xkb_keymap);

        for (xkb_layout_index_t i = 0; i < layout_count; i++)
            xkb_state_update_mask(seat->kbd.xkb_state, 0, 0, 0, i, i, i);
    }

    if (old_focused != NULL) {
        seat->pointer.hidden = false;
        term_xcursor_update_for_seat(old_focused, seat);
        term_kbd_focus_out(old_focused);
    } else {
        /*
         * Sway bug - under certain conditions we get a
         * keyboard_leave() (and keyboard_key()) without first having
         * received a keyboard_enter()
         */
        LOG_WARN(
            "compositor sent keyboard_leave event without a keyboard_enter "
            "event: surface=%p", (void *)surface);
    }
}

static const struct key_data *
keymap_data_for_sym(xkb_keysym_t sym, size_t *count)
{
    switch (sym) {
    case XKB_KEY_Escape:       *count = ALEN(key_escape);       return key_escape;
    case XKB_KEY_Return:       *count = ALEN(key_return);       return key_return;
    case XKB_KEY_ISO_Left_Tab: *count = ALEN(key_iso_left_tab); return key_iso_left_tab;
    case XKB_KEY_Tab:          *count = ALEN(key_tab);          return key_tab;
    case XKB_KEY_BackSpace:    *count = ALEN(key_backspace);    return key_backspace;
    case XKB_KEY_Up:           *count = ALEN(key_up);           return key_up;
    case XKB_KEY_Down:         *count = ALEN(key_down);         return key_down;
    case XKB_KEY_Right:        *count = ALEN(key_right);        return key_right;
    case XKB_KEY_Left:         *count = ALEN(key_left);         return key_left;
    case XKB_KEY_Home:         *count = ALEN(key_home);         return key_home;
    case XKB_KEY_End:          *count = ALEN(key_end);          return key_end;
    case XKB_KEY_Insert:       *count = ALEN(key_insert);       return key_insert;
    case XKB_KEY_Delete:       *count = ALEN(key_delete);       return key_delete;
    case XKB_KEY_Page_Up:      *count = ALEN(key_pageup);       return key_pageup;
    case XKB_KEY_Page_Down:    *count = ALEN(key_pagedown);     return key_pagedown;
    case XKB_KEY_F1:           *count = ALEN(key_f1);           return key_f1;
    case XKB_KEY_F2:           *count = ALEN(key_f2);           return key_f2;
    case XKB_KEY_F3:           *count = ALEN(key_f3);           return key_f3;
    case XKB_KEY_F4:           *count = ALEN(key_f4);           return key_f4;
    case XKB_KEY_F5:           *count = ALEN(key_f5);           return key_f5;
    case XKB_KEY_F6:           *count = ALEN(key_f6);           return key_f6;
    case XKB_KEY_F7:           *count = ALEN(key_f7);           return key_f7;
    case XKB_KEY_F8:           *count = ALEN(key_f8);           return key_f8;
    case XKB_KEY_F9:           *count = ALEN(key_f9);           return key_f9;
    case XKB_KEY_F10:          *count = ALEN(key_f10);          return key_f10;
    case XKB_KEY_F11:          *count = ALEN(key_f11);          return key_f11;
    case XKB_KEY_F12:          *count = ALEN(key_f12);          return key_f12;
    case XKB_KEY_F13:          *count = ALEN(key_f13);          return key_f13;
    case XKB_KEY_F14:          *count = ALEN(key_f14);          return key_f14;
    case XKB_KEY_F15:          *count = ALEN(key_f15);          return key_f15;
    case XKB_KEY_F16:          *count = ALEN(key_f16);          return key_f16;
    case XKB_KEY_F17:          *count = ALEN(key_f17);          return key_f17;
    case XKB_KEY_F18:          *count = ALEN(key_f18);          return key_f18;
    case XKB_KEY_F19:          *count = ALEN(key_f19);          return key_f19;
    case XKB_KEY_F20:          *count = ALEN(key_f20);          return key_f20;
    case XKB_KEY_F21:          *count = ALEN(key_f21);          return key_f21;
    case XKB_KEY_F22:          *count = ALEN(key_f22);          return key_f22;
    case XKB_KEY_F23:          *count = ALEN(key_f23);          return key_f23;
    case XKB_KEY_F24:          *count = ALEN(key_f24);          return key_f24;
    case XKB_KEY_F25:          *count = ALEN(key_f25);          return key_f25;
    case XKB_KEY_F26:          *count = ALEN(key_f26);          return key_f26;
    case XKB_KEY_F27:          *count = ALEN(key_f27);          return key_f27;
    case XKB_KEY_F28:          *count = ALEN(key_f28);          return key_f28;
    case XKB_KEY_F29:          *count = ALEN(key_f29);          return key_f29;
    case XKB_KEY_F30:          *count = ALEN(key_f30);          return key_f30;
    case XKB_KEY_F31:          *count = ALEN(key_f31);          return key_f31;
    case XKB_KEY_F32:          *count = ALEN(key_f32);          return key_f32;
    case XKB_KEY_F33:          *count = ALEN(key_f33);          return key_f33;
    case XKB_KEY_F34:          *count = ALEN(key_f34);          return key_f34;
    case XKB_KEY_F35:          *count = ALEN(key_f35);          return key_f35;
    case XKB_KEY_KP_Up:        *count = ALEN(key_kp_up);        return key_kp_up;
    case XKB_KEY_KP_Down:      *count = ALEN(key_kp_down);      return key_kp_down;
    case XKB_KEY_KP_Right:     *count = ALEN(key_kp_right);     return key_kp_right;
    case XKB_KEY_KP_Left:      *count = ALEN(key_kp_left);      return key_kp_left;
    case XKB_KEY_KP_Begin:     *count = ALEN(key_kp_begin);     return key_kp_begin;
    case XKB_KEY_KP_Home:      *count = ALEN(key_kp_home);      return key_kp_home;
    case XKB_KEY_KP_End:       *count = ALEN(key_kp_end);       return key_kp_end;
    case XKB_KEY_KP_Insert:    *count = ALEN(key_kp_insert);    return key_kp_insert;
    case XKB_KEY_KP_Delete:    *count = ALEN(key_kp_delete);    return key_kp_delete;
    case XKB_KEY_KP_Page_Up:   *count = ALEN(key_kp_pageup);    return key_kp_pageup;
    case XKB_KEY_KP_Page_Down: *count = ALEN(key_kp_pagedown);  return key_kp_pagedown;
    case XKB_KEY_KP_Enter:     *count = ALEN(key_kp_enter);     return key_kp_enter;
    case XKB_KEY_KP_Divide:    *count = ALEN(key_kp_divide);    return key_kp_divide;
    case XKB_KEY_KP_Multiply:  *count = ALEN(key_kp_multiply);  return key_kp_multiply;
    case XKB_KEY_KP_Subtract:  *count = ALEN(key_kp_subtract);  return key_kp_subtract;
    case XKB_KEY_KP_Add:       *count = ALEN(key_kp_add);       return key_kp_add;
    case XKB_KEY_KP_Separator: *count = ALEN(key_kp_separator); return key_kp_separator;
    case XKB_KEY_KP_Decimal:   *count = ALEN(key_kp_decimal);   return key_kp_decimal;
    case XKB_KEY_KP_0:         *count = ALEN(key_kp_0);         return key_kp_0;
    case XKB_KEY_KP_1:         *count = ALEN(key_kp_1);         return key_kp_1;
    case XKB_KEY_KP_2:         *count = ALEN(key_kp_2);         return key_kp_2;
    case XKB_KEY_KP_3:         *count = ALEN(key_kp_3);         return key_kp_3;
    case XKB_KEY_KP_4:         *count = ALEN(key_kp_4);         return key_kp_4;
    case XKB_KEY_KP_5:         *count = ALEN(key_kp_5);         return key_kp_5;
    case XKB_KEY_KP_6:         *count = ALEN(key_kp_6);         return key_kp_6;
    case XKB_KEY_KP_7:         *count = ALEN(key_kp_7);         return key_kp_7;
    case XKB_KEY_KP_8:         *count = ALEN(key_kp_8);         return key_kp_8;
    case XKB_KEY_KP_9:         *count = ALEN(key_kp_9);         return key_kp_9;
    }

    return NULL;
}

static const struct key_data *
keymap_lookup(struct terminal *term, xkb_keysym_t sym, enum modifier mods)
{
    size_t count;
    const struct key_data *info = keymap_data_for_sym(sym, &count);

    if (info == NULL)
        return NULL;

    const enum cursor_keys cursor_keys_mode = term->cursor_keys_mode;
    const enum keypad_keys keypad_keys_mode
        = term->num_lock_modifier ? KEYPAD_NUMERICAL : term->keypad_keys_mode;

    LOG_DBG("keypad mode: %d", keypad_keys_mode);

    for (size_t j = 0; j < count; j++) {
        enum modifier modifiers = info[j].modifiers;

        if (modifiers & MOD_MODIFY_OTHER_KEYS_STATE1) {
            if (term->modify_other_keys_2)
                continue;
            modifiers &= ~MOD_MODIFY_OTHER_KEYS_STATE1;
        }
        if (modifiers & MOD_MODIFY_OTHER_KEYS_STATE2) {
            if (!term->modify_other_keys_2)
                continue;
            modifiers &= ~MOD_MODIFY_OTHER_KEYS_STATE2;
        }

        if (modifiers != MOD_ANY && modifiers != mods)
            continue;

        if (info[j].cursor_keys_mode != CURSOR_KEYS_DONTCARE &&
            info[j].cursor_keys_mode != cursor_keys_mode)
            continue;

        if (info[j].keypad_keys_mode != KEYPAD_DONTCARE &&
            info[j].keypad_keys_mode != keypad_keys_mode)
            continue;

        return &info[j];
    }

    return NULL;
}

UNITTEST
{
    struct terminal term = {
        .num_lock_modifier = false,
        .keypad_keys_mode = KEYPAD_NUMERICAL,
        .cursor_keys_mode = CURSOR_KEYS_NORMAL,
    };

    const struct key_data *info = keymap_lookup(&term, XKB_KEY_ISO_Left_Tab, MOD_SHIFT | MOD_CTRL);
    xassert(info != NULL);
    xassert(streq(info->seq, "\033[27;6;9~"));
}

UNITTEST
{
    struct terminal term = {
        .modify_other_keys_2 = false,
    };

    const struct key_data *info = keymap_lookup(&term, XKB_KEY_Return, MOD_ALT);
    xassert(info != NULL);
    xassert(streq(info->seq, "\033\r"));

    term.modify_other_keys_2 = true;
    info = keymap_lookup(&term, XKB_KEY_Return, MOD_ALT);
    xassert(info != NULL);
    xassert(streq(info->seq, "\033[27;3;13~"));
}

void
get_current_modifiers(const struct seat *seat,
                      xkb_mod_mask_t *effective,
                      xkb_mod_mask_t *consumed, uint32_t key,
                      bool filter_locked)
{
    if (unlikely(seat->kbd.xkb_state == NULL)) {
        if (effective != NULL)
            *effective = 0;
        if (consumed != NULL)
            *consumed = 0;
    }

    else {
        const xkb_mod_mask_t locked =
            xkb_state_serialize_mods(seat->kbd.xkb_state, XKB_STATE_MODS_LOCKED);

        if (effective != NULL) {
            *effective = xkb_state_serialize_mods(
                seat->kbd.xkb_state, XKB_STATE_MODS_EFFECTIVE);

            if (filter_locked)
                *effective &= ~locked;
        }

        if (consumed != NULL) {
            *consumed = xkb_state_key_get_consumed_mods2(
                seat->kbd.xkb_state, key, XKB_CONSUMED_MODE_XKB);

            if (filter_locked)
                *consumed &= ~locked;
        }
    }
}

struct kbd_ctx {
    xkb_layout_index_t layout;
    xkb_keycode_t key;
    xkb_keysym_t sym;

    struct {
        const xkb_keysym_t *syms;
        size_t count;
    } level0_syms;

    xkb_mod_mask_t mods;
    xkb_mod_mask_t consumed;

    struct {
        const uint8_t *buf;
        size_t count;
    } utf8;
    uint32_t *utf32;

    enum xkb_compose_status compose_status;
    enum wl_keyboard_key_state key_state;
};

static bool
legacy_kbd_protocol(struct seat *seat, struct terminal *term,
                    const struct kbd_ctx *ctx)
{
    if (ctx->key_state != WL_KEYBOARD_KEY_STATE_PRESSED)
        return false;
    if (ctx->compose_status == XKB_COMPOSE_COMPOSING)
        return false;

    enum modifier keymap_mods = MOD_NONE;
    keymap_mods |= seat->kbd.shift ? MOD_SHIFT : MOD_NONE;
    keymap_mods |= seat->kbd.alt ? MOD_ALT : MOD_NONE;
    keymap_mods |= seat->kbd.ctrl ? MOD_CTRL : MOD_NONE;
    keymap_mods |= seat->kbd.super ? MOD_META : MOD_NONE;

    const xkb_keysym_t sym = ctx->sym;
    const size_t count = ctx->utf8.count;
    const uint8_t *const utf8 = ctx->utf8.buf;

    const struct key_data *keymap = keymap_lookup(term, sym, keymap_mods);
    if (keymap != NULL) {
        term_to_slave(term, keymap->seq, strlen(keymap->seq));
        return true;
    }

    if (count == 0)
        return false;

#define is_control_key(x) ((x) >= 0x40 && (x) <= 0x7f)
#define IS_CTRL(x) ((x) < 0x20 || ((x) >= 0x7f && (x) <= 0x9f))

    //LOG_DBG("term->modify_other_keys=%d, count=%zu, is_ctrl=%d (utf8=0x%02x), sym=%d",
    //term->modify_other_keys_2, count, IS_CTRL(utf8[0]), utf8[0], sym);

    bool ctrl_is_in_effect = (keymap_mods & MOD_CTRL) != 0;
    bool ctrl_seq = is_control_key(sym) || (count == 1 && IS_CTRL(utf8[0]));

    bool modify_other_keys2_in_effect = false;

    if (term->modify_other_keys_2) {
        /*
         * Try to mimic XTerm's behavior, when holding shift:
         *
         *   - if other modifiers are pressed (e.g. Alt), emit a CSI escape
         *   - upper-case symbols A-Z are encoded as an CSI escape
         *   - other upper-case symbols (e.g 'Ö') or emitted as is
         *   - non-upper cased symbols are _mostly_ emitted as is (foot
         *     always emits as is)
         *
         * Examples (assuming Swedish layout):
         *   - Shift-a ('A') emits a CSI
         *   - Shift-, (';') emits ';'
         *   - Shift-Alt-, (Alt-;) emits a CSI
         *   - Shift-ö ('Ö') emits 'Ö'
         */

        /* Any modifiers, besides shift active? */
        const xkb_mod_mask_t shift_mask = 1 << seat->kbd.mod_shift;
        if ((ctx->mods & ~shift_mask & seat->kbd.legacy_significant) != 0)
            modify_other_keys2_in_effect = true;

        else {
            const xkb_layout_index_t layout_idx = xkb_state_key_get_layout(
                seat->kbd.xkb_state, ctx->key);

            /*
             * Get pressed key's base symbol.
             *   - for 'A' (shift-a), that's 'a'
             *   - for ';' (shift-,), that's ','
             */
            const xkb_keysym_t *base_syms = NULL;
            size_t base_count = xkb_keymap_key_get_syms_by_level(
                seat->kbd.xkb_keymap, ctx->key, layout_idx, 0, &base_syms);

            /* Check if base symbol(s) is a-z. If so, emit CSI */
            const xkb_keysym_t lower_cased_sym = xkb_keysym_to_lower(ctx->sym);
            for (size_t i = 0; i < base_count; i++) {
                const xkb_keysym_t s = base_syms[i];
                if (lower_cased_sym == s && s >= XKB_KEY_a && s <= XKB_KEY_z) {
                    modify_other_keys2_in_effect = true;
                    break;
                }
            }
        }
    }

    if (keymap_mods != MOD_NONE && (modify_other_keys2_in_effect ||
                                    (ctrl_is_in_effect && !ctrl_seq)))
    {
        static const int mod_param_map[32] = {
            [MOD_SHIFT] = 2,
            [MOD_ALT] = 3,
            [MOD_SHIFT | MOD_ALT] = 4,
            [MOD_CTRL] = 5,
            [MOD_SHIFT | MOD_CTRL] = 6,
            [MOD_ALT | MOD_CTRL] = 7,
            [MOD_SHIFT | MOD_ALT | MOD_CTRL] = 8,
            [MOD_META] = 9,
            [MOD_META | MOD_SHIFT] = 10,
            [MOD_META | MOD_ALT] = 11,
            [MOD_META | MOD_SHIFT | MOD_ALT] = 12,
            [MOD_META | MOD_CTRL] = 13,
            [MOD_META | MOD_SHIFT | MOD_CTRL] = 14,
            [MOD_META | MOD_ALT | MOD_CTRL] = 15,
            [MOD_META | MOD_SHIFT | MOD_ALT | MOD_CTRL] = 16,
        };

        xassert(keymap_mods < ALEN(mod_param_map));
        int modify_param = mod_param_map[keymap_mods];
        xassert(modify_param != 0);

        char reply[32];
        size_t n = xsnprintf(reply, sizeof(reply), "\x1b[27;%d;%d~", modify_param, sym);
        term_to_slave(term, reply, n);
    }

    else if (keymap_mods & MOD_ALT) {
        /*
         * When the alt modifier is pressed, we do one out of three things:
         *
         *  1. we prefix the output bytes with ESC
         *  2. we set the 8:th bit in the output byte
         *  3. we ignore the alt modifier
         *
         * #1 is configured with \E[?1036, and is on by default
         *
         * If #1 has been disabled, we use #2, *if* it's a single byte
         * we're emitting. Since this is a UTF-8 terminal, we then
         * UTF8-encode the 8-bit character. #2 is configured with
         * \E[?1034, and is on by default.
         *
         * Lastly, if both #1 and #2 have been disabled, the alt
         * modifier is ignored.
         */
        if (term->meta.esc_prefix) {
            term_to_slave(term, "\x1b", 1);
            term_to_slave(term, utf8, count);
        }

        else if (term->meta.eight_bit && count == 1) {
            const char32_t wc = 0x80 | utf8[0];

            char utf8_meta[MB_CUR_MAX];
            size_t chars = c32rtomb(utf8_meta, wc, &(mbstate_t){0});

            if (chars != (size_t)-1)
                term_to_slave(term, utf8_meta, chars);
            else
                term_to_slave(term, utf8, count);
        }

        else {
            /* Alt ignored */
            term_to_slave(term, utf8, count);
        }
    } else
        term_to_slave(term, utf8, count);

    return true;
}

UNITTEST
{
    /* Verify the kitty keymap is sorted */
    xkb_keysym_t last = 0;
    for (size_t i = 0; i < ALEN(kitty_keymap); i++) {
        const struct kitty_key_data *e = &kitty_keymap[i];
        xassert(e->sym > last);
        last = e->sym;
    }
}

static int
kitty_search(const void *_key, const void *_e)
{
    const xkb_keysym_t *key = _key;
    const struct kitty_key_data *e = _e;
    return *key - e->sym;
}

static bool
kitty_kbd_protocol(struct seat *seat, struct terminal *term,
                   const struct kbd_ctx *ctx)
{
    const bool repeating = seat->kbd.repeat.dont_re_repeat;
    const bool pressed = ctx->key_state == WL_KEYBOARD_KEY_STATE_PRESSED && !repeating;
    const bool released = ctx->key_state == WL_KEYBOARD_KEY_STATE_RELEASED;
    const bool composing = ctx->compose_status == XKB_COMPOSE_COMPOSING;
    const bool composed = ctx->compose_status == XKB_COMPOSE_COMPOSED;

    const enum kitty_kbd_flags flags =
        term->grid->kitty_kbd.flags[term->grid->kitty_kbd.idx];

    const bool disambiguate = flags & KITTY_KBD_DISAMBIGUATE;
    const bool report_events = flags & KITTY_KBD_REPORT_EVENT;
    const bool report_alternate = flags & KITTY_KBD_REPORT_ALTERNATE;
    const bool report_all_as_escapes = flags & KITTY_KBD_REPORT_ALL;

    if (!report_events && released)
        return false;

    /* TODO: should we even bother with this, or just say it's not supported? */
    if (!disambiguate && !report_all_as_escapes && pressed)
        return legacy_kbd_protocol(seat, term, ctx);

    const xkb_keysym_t sym = ctx->sym;
    const uint32_t *utf32 = ctx->utf32;
    const uint8_t *const utf8 = ctx->utf8.buf;
    const size_t count = ctx->utf8.count;

    /* Lookup sym in the pre-defined keysym table */
    const struct kitty_key_data *info = bsearch(
        &sym, kitty_keymap, ALEN(kitty_keymap), sizeof(kitty_keymap[0]),
        &kitty_search);
    xassert(info == NULL || info->sym == sym);

    xkb_mod_mask_t mods = 0;
    xkb_mod_mask_t locked = 0;
    xkb_mod_mask_t consumed = ctx->consumed;

    if (info != NULL && info->is_modifier) {
        /*
         * Special-case modifier keys.
         *
         * Normally, the "current" XKB state reflects the state
         * *before* the current key event. In other words, the
         * modifiers for key events that affect the modifier state
         * (e.g. one of the control keys, or shift keys etc) does
         * *not* include the key itself.
         *
         * Put another way, if you press "control", the modifier set
         * is empty in the key press event, but contains "ctrl" in the
         * release event.
         *
         * The kitty protocol mandates the modifier list contain the
         * key itself, in *both* the press and release event.
         *
         * We handle this by updating the XKB state to *include* the
         * current key, retrieve the set of modifiers (including the
         * set of consumed modifiers), and then revert the XKB update.
         */
        xkb_state_update_key(
            seat->kbd.xkb_state, ctx->key, pressed ? XKB_KEY_DOWN : XKB_KEY_UP);

        get_current_modifiers(seat, &mods, NULL, 0, false);

        locked = xkb_state_serialize_mods(
            seat->kbd.xkb_state, XKB_STATE_MODS_LOCKED);
        consumed = xkb_state_key_get_consumed_mods2(
            seat->kbd.xkb_state, ctx->key, XKB_CONSUMED_MODE_XKB);

#if 0
        /*
         * TODO: according to the XKB docs, state updates should
         * always be in pairs: each press should be followed by a
         * release. However, doing this just breaks the xkb state.
         *
         * *Not* pairing the above press/release with a corresponding
         * release/press appears to do exactly what we want.
         */
        xkb_state_update_key(
            seat->kbd.xkb_state, ctx->key, pressed ? XKB_KEY_UP : XKB_KEY_DOWN);
#endif
    } else {
        /* Same as ctx->mods, but *without* filtering locked modifiers */
        get_current_modifiers(seat, &mods, NULL, 0, false);
        locked = xkb_state_serialize_mods(
            seat->kbd.xkb_state, XKB_STATE_MODS_LOCKED);
    }

    mods &= seat->kbd.kitty_significant;
    consumed &= seat->kbd.kitty_significant;

    /*
     * A note on locked modifiers; they *are* a part of the protocol,
     * and *should* be included in the modifier set reported in the
     * key event.
     *
     * However, *only* if the key would result in a CSIu *without* the
     * locked modifier being enabled
     *
     * Translated: if *another* modifier is active, or if
     * report-all-keys-as-escapes is enabled, then we include the
     * locked modifier in the key event.
     *
     * But, if the key event would result in plain text output without
     * the locked modifier, then we "ignore" the locked modifier and
     * emit plain text anyway.
     */

    bool is_text = count > 0 && utf32 != NULL && (mods & ~locked & ~consumed) == 0;
    for (size_t i = 0; utf32[i] != U'\0'; i++) {
        if (!isc32print(utf32[i])) {
            is_text = false;
            break;
        }
    }

    const bool report_associated_text =
        (flags & KITTY_KBD_REPORT_ASSOCIATED) && is_text && !released;

    if (composing) {
        /* We never emit anything while composing, *except* modifiers
         * (and only in report-all-keys-as-escape-codes mode) */
        if (info != NULL && info->is_modifier)
            goto emit_escapes;

        return false;
    }

    if (report_all_as_escapes)
        goto emit_escapes;

    if ((mods & ~locked & ~consumed) == 0) {
        switch (sym) {
        case XKB_KEY_Return:
            if (!released)
                term_to_slave(term, "\r", 1);
            return  true;

        case XKB_KEY_BackSpace:
            if (!released)
                term_to_slave(term, "\x7f", 1);
            return true;

        case XKB_KEY_Tab:
            if (!released)
                term_to_slave(term, "\t", 1);
            return true;
        }
    }

    /* Plain-text without modifiers, or commposed text, is emitted as-is */
    if (is_text && !released) {
        term_to_slave(term, utf8, count);
        return true;
    }

emit_escapes:
    ;
    unsigned int encoded_mods = 0;
    if (seat->kbd.mod_shift != XKB_MOD_INVALID)
        encoded_mods |= mods & (1 << seat->kbd.mod_shift) ? (1 << 0) : 0;
    if (seat->kbd.mod_alt != XKB_MOD_INVALID)
        encoded_mods |= mods & (1 << seat->kbd.mod_alt)   ? (1 << 1) : 0;
    if (seat->kbd.mod_ctrl != XKB_MOD_INVALID)
        encoded_mods |= mods & (1 << seat->kbd.mod_ctrl)  ? (1 << 2) : 0;
    if (seat->kbd.mod_super != XKB_MOD_INVALID)
        encoded_mods |= mods & (1 << seat->kbd.mod_super)  ? (1 << 3) : 0;
    if (seat->kbd.mod_caps != XKB_MOD_INVALID)
        encoded_mods |= mods & (1 << seat->kbd.mod_caps)  ? (1 << 6) : 0;
    if (seat->kbd.mod_num != XKB_MOD_INVALID)
        encoded_mods |= mods & (1 << seat->kbd.mod_num)   ? (1 << 7) : 0;
    encoded_mods++;

    /*
     * Figure out the main, alternate and base key codes.
     *
     * The main key is the unshifted version of the generated symbol,
     * the alternate key is the shifted version, and base is the
     * (unshifted) key assuming the default layout.
     *
     * For example, the user presses shift+a, then:
     *   - unshifted = 'a'
     *   - shifted = 'A'
     *   - base = 'a'
     *
     * Base will in many cases be the same as the unshifted key, but
     * may differ if the active keyboard layout is non-ASCII (examples
     * would be russian, or alternative layouts like neo etc).
     *
     * The shifted key is what we get from XKB, i.e. the resulting key
     * from all active modifiers, plus the pressed key.
     */
    int unshifted = -1, shifted = -1, base = -1;
    char final;

    if (info != NULL) {
        /* Use code from lookup table (cursor keys, enter, tab etc)*/
        if (!info->is_modifier || report_all_as_escapes) {
            shifted = info->key;
            final = info->final;
        }
    } else {
        /* Use keysym (typically its Unicode codepoint value) */

        if (composed)
            shifted = utf32[0];  /* TODO: what if there are multiple codepoints? */
        else
            shifted = xkb_keysym_to_utf32(sym);

        final = 'u';
    }

    if (shifted <= 0)
        return false;

    /* Base layout key. I.e the symbol the pressed key produces in
     * the base/default layout (layout idx 0) */
    const xkb_keysym_t *base_syms;
    int base_sym_count = xkb_keymap_key_get_syms_by_level(
        seat->kbd.xkb_keymap, ctx->key, 0, 0, &base_syms);

    if (base_sym_count > 0)
        base = xkb_keysym_to_utf32(base_syms[0]);

    /*
     * If the keysym is shifted, use its unshifted codepoint
     * instead. In other words, ctrl+a and ctrl+shift+a should both
     * use the same value for 'key' (97 - i.a. 'a').
     *
     * However, don't do this if a non-significant modifier was used
     * to generate the symbol. This is needed since we cannot encode
     * non-significant modifiers, and thus the "extra" modifier(s)
     * would get lost.
     *
     * Example:
     *
     * the Swedish layout has '2', QUOTATION MARK ("double quote"),
     * '@', and '²' on the same key. '2' is the base symbol.
     *
     * Shift+2 results in QUOTATION MARK
     * AltGr+2 results in '@'
     * AltGr+Shift+2 results in '²'
     *
     * The kitty kbd protocol can't encode AltGr. So, if we always
     * used the base symbol ('2'), Alt+Shift+2 would result in the
     * same escape sequence as AltGr+Alt+Shift+2.
     *
     * (yes, this matches what kitty does, as of 0.23.1)
     */
    const bool use_level0_sym =
        (ctx->mods & ~seat->kbd.kitty_significant) == 0 && ctx->level0_syms.count > 0;

    unshifted = use_level0_sym ? xkb_keysym_to_utf32(ctx->level0_syms.syms[0]) : 0;

    xassert(encoded_mods >= 1);

    char event[4];
    if (report_events /*&& !pressed*/) {
        /* Note: this deviates slightly from Kitty, which omits the
         * ":1" subparameter for key press events */
        event[0] = ':';
        event[1] = '0' + (pressed ? 1 : repeating ? 2 : 3);
        event[2] = '\0';
    } else
        event[0] = '\0';

    char buf[128], *p = buf;
    size_t left = sizeof(buf);
    size_t bytes;

    const int key = unshifted > 0 && isc32print(unshifted) && !composed ? unshifted : shifted;
    const int alternate = shifted;

    if (final == 'u' || final == '~') {
        bytes = snprintf(p, left, "\x1b[%u", key);
        p += bytes; left -= bytes;

        if (report_alternate) {
            bool emit_alternate = alternate > 0 && alternate != key;
            bool emit_base = base > 0 && base != key && base != alternate && isc32print(base);

            if (emit_alternate) {
                bytes = snprintf(p, left, ":%u", alternate);
                p += bytes; left -= bytes;
            }

            if (emit_base) {
                bytes = snprintf(
                    p, left, "%s:%u", !emit_alternate ? ":" : "", base);
                p += bytes; left -= bytes;
            }
        }

        bool emit_mods = encoded_mods > 1 || event[0] != '\0';

        if (emit_mods) {
            bytes = snprintf(p, left, ";%u%s", encoded_mods, event);
            p += bytes; left -= bytes;
        }

        if (report_associated_text) {
            bytes = snprintf(p, left, "%s;%u", !emit_mods ? ";" : "", utf32[0]);
            p += bytes; left -= bytes;

            /* Additional text codepoints */
            if (utf32[0] != U'\0') {
                for (size_t i = 1; utf32[i] != U'\0'; i++) {
                    bytes = snprintf(p, left, ":%u", utf32[i]);
                    p += bytes; left -= bytes;
                }
            }
        }

        bytes = snprintf(p, left, "%c", final);
        p += bytes; left -= bytes;
    } else {
        if (encoded_mods > 1 || event[0] != '\0') {
            bytes = snprintf(p, left, "\x1b[1;%u%s%c", encoded_mods, event, final);
            p += bytes; left -= bytes;
        } else {
            bytes = snprintf(p, left, "\x1b[%c", final);
            p += bytes; left -= bytes;
        }
    }

    return term_to_slave(term, buf, sizeof(buf) - left);
}

/* Copied from libxkbcommon (internal function) */
static bool
keysym_is_modifier(xkb_keysym_t keysym)
{
    return
        (keysym >= XKB_KEY_Shift_L && keysym <= XKB_KEY_Hyper_R) ||
        /* libX11 only goes up to XKB_KEY_ISO_Level5_Lock. */
        (keysym >= XKB_KEY_ISO_Lock && keysym <= XKB_KEY_ISO_Last_Group_Lock) ||
        keysym == XKB_KEY_Mode_switch ||
        keysym == XKB_KEY_Num_Lock;
}

#if defined(_DEBUG)
static void
modifier_string(xkb_mod_mask_t mods, size_t sz, char mod_str[static sz], const struct seat *seat)
{
    if (sz == 0)
        return;

    mod_str[0] = '\0';

    for (size_t i = 0; i < sizeof(xkb_mod_mask_t) * 8; i++) {
        if (!(mods & (1u << i)))
            continue;

        strcat(mod_str, xkb_keymap_mod_get_name(seat->kbd.xkb_keymap, i));
        strcat(mod_str, "+");
    }

    if (mod_str[0] != '\0') {
        /* Strip the last '+' */
        mod_str[strlen(mod_str) - 1] = '\0';
    }

    if (mod_str[0] == '\0') {
        strcpy(mod_str, "<none>");
    }
}
#endif

static void
key_press_release(struct seat *seat, struct terminal *term, uint32_t serial,
                  uint32_t key, uint32_t state)
{
    xassert(serial != 0);

    seat->kbd.serial = serial;
    if (seat->kbd.xkb == NULL ||
        seat->kbd.xkb_keymap == NULL ||
        seat->kbd.xkb_state == NULL)
    {
        return;
    }

    const bool pressed = state == WL_KEYBOARD_KEY_STATE_PRESSED;
    //const bool repeated = pressed && seat->kbd.repeat.dont_re_repeat;
    const bool released = state == WL_KEYBOARD_KEY_STATE_RELEASED;

    if (released)
        stop_repeater(seat, key);

    bool should_repeat =
        pressed && xkb_keymap_key_repeats(seat->kbd.xkb_keymap, key);

    xkb_keysym_t sym = xkb_state_key_get_one_sym(seat->kbd.xkb_state, key);

    if (pressed && term->conf->mouse.hide_when_typing && !keysym_is_modifier(sym)) {
        seat->pointer.hidden = true;
        term_xcursor_update_for_seat(term, seat);
    }

    enum xkb_compose_status compose_status = XKB_COMPOSE_NOTHING;

    if (seat->kbd.xkb_compose_state != NULL) {
        if (pressed)
            xkb_compose_state_feed(seat->kbd.xkb_compose_state, sym);
        compose_status = xkb_compose_state_get_status(
            seat->kbd.xkb_compose_state);
    }

    const bool composed = compose_status == XKB_COMPOSE_COMPOSED;

    xkb_mod_mask_t mods, consumed;
    get_current_modifiers(seat, &mods, &consumed, key, true);

    xkb_layout_index_t layout_idx =
        xkb_state_key_get_layout(seat->kbd.xkb_state, key);

    const xkb_keysym_t *raw_syms = NULL;
    size_t raw_count = xkb_keymap_key_get_syms_by_level(
        seat->kbd.xkb_keymap, key, layout_idx, 0, &raw_syms);

    const struct key_binding_set *bindings = key_binding_for(
        seat->wayl->key_binding_manager, term->conf, seat);
    xassert(bindings != NULL);

    if (pressed) {
        if (term->unicode_mode.active) {
            unicode_mode_input(seat, term, sym);
            return;
        }

        else if (term->is_searching) {
            if (should_repeat)
                start_repeater(seat, key);

            search_input(
                seat, term, bindings, key, sym, mods, consumed,
                raw_syms, raw_count, serial);
            return;
        }

        else  if (urls_mode_is_active(term)) {
            if (should_repeat)
                start_repeater(seat, key);

            urls_input(
                seat, term, bindings, key, sym, mods, consumed,
                raw_syms, raw_count, serial);
            return;
        }
    }

#if defined(_DEBUG) && defined(LOG_ENABLE_DBG) && LOG_ENABLE_DBG
    char sym_name[100];
    xkb_keysym_get_name(sym, sym_name, sizeof(sym_name));

    char active_mods_str[256] = {0};
    char consumed_mods_str[256] = {0};
    char locked_mods_str[256] = {0};

    const xkb_mod_mask_t locked =
        xkb_state_serialize_mods(seat->kbd.xkb_state, XKB_STATE_MODS_LOCKED);

    modifier_string(mods, sizeof(active_mods_str), active_mods_str, seat);
    modifier_string(consumed, sizeof(consumed_mods_str), consumed_mods_str, seat);
    modifier_string(locked, sizeof(locked_mods_str), locked_mods_str, seat);

    LOG_DBG("%s: %s (%u/0x%x), seat=%s, term=%p, serial=%u, "
            "mods=%s (0x%08x), consumed=%s (0x%08x), locked=%s (0x%08x), "
            "repeats=%d",
            pressed ? "pressed" : "released", sym_name, sym, sym,
            seat->name, (void *)term, serial,
            active_mods_str, mods, consumed_mods_str, consumed,
            locked_mods_str, locked, should_repeat);
#endif

    /*
     * User configurable bindings
     */
    if (pressed) {
        /* Match untranslated symbols */
        tll_foreach(bindings->key, it) {
            const struct key_binding *bind = &it->item;

            if (bind->mods != mods || bind->mods == 0)
                continue;

            for (size_t i = 0; i < raw_count; i++) {
                if (bind->k.sym == raw_syms[i] &&
                    execute_binding(seat, term, bind, serial, 1))
                {
                    goto maybe_repeat;
                }
            }
        }

        /* Match translated symbol */
        tll_foreach(bindings->key, it) {
            const struct key_binding *bind = &it->item;

            if (bind->k.sym == sym &&
                bind->mods == (mods & ~consumed) &&
                execute_binding(seat, term, bind, serial, 1))
            {
                goto maybe_repeat;
            }
        }

        /* Match raw key code */
        tll_foreach(bindings->key, it) {
            const struct key_binding *bind = &it->item;

            if (bind->mods != mods || bind->mods == 0)
                continue;

            tll_foreach(bind->k.key_codes, code) {
                if (code->item == key &&
                    execute_binding(seat, term, bind, serial, 1))
                {
                    goto maybe_repeat;
                }
            }
        }
    }

    /*
     * Keys generating escape sequences
     */


    /*
     * Compose, and maybe emit "normal" character
     */

    xassert(seat->kbd.xkb_compose_state != NULL || !composed);

    if (compose_status == XKB_COMPOSE_CANCELLED)
        goto maybe_repeat;

    int count = composed
        ? xkb_compose_state_get_utf8(seat->kbd.xkb_compose_state, NULL, 0)
        : xkb_state_key_get_utf8(seat->kbd.xkb_state, key, NULL, 0);

    /* Buffer for translated key. Use a static buffer in most cases,
     * and use a malloc:ed buffer when necessary */
    uint8_t buf[32];
    uint8_t *utf8 = count < sizeof(buf) ? buf : xmalloc(count + 1);
    uint32_t *utf32 = NULL;

    if (composed) {
        xkb_compose_state_get_utf8(
            seat->kbd.xkb_compose_state, (char *)utf8, count + 1);

        if (count > 0)
            utf32 = ambstoc32((const char *)utf8);
    } else {
        xkb_state_key_get_utf8(
            seat->kbd.xkb_state, key, (char *)utf8, count + 1);

        utf32 = xcalloc(2, sizeof(utf32[0]));
        utf32[0] = xkb_state_key_get_utf32(seat->kbd.xkb_state, key);
    }

    struct kbd_ctx ctx = {
        .layout = layout_idx,
        .key = key,
        .sym = sym,
        .level0_syms = {
            .syms = raw_syms,
            .count = raw_count,
        },
        .mods = mods,
        .consumed = consumed,
        .utf8 = {
            .buf = utf8,
            .count = count,
        },
        .utf32 = utf32,
        .compose_status = compose_status,
        .key_state = state,
    };

    bool handled = term->grid->kitty_kbd.flags[term->grid->kitty_kbd.idx] != 0
        ? kitty_kbd_protocol(seat, term, &ctx)
        : legacy_kbd_protocol(seat, term, &ctx);

    if (composed && released)
        xkb_compose_state_reset(seat->kbd.xkb_compose_state);

    if (utf8 != buf)
        free(utf8);

    if (handled && !keysym_is_modifier(sym)) {
        term_reset_view(term);
        selection_cancel(term);
    }

    free(utf32);

maybe_repeat:
    clock_gettime(
        term->wl->presentation_clock_id, &term->render.input_time);

    if (should_repeat)
        start_repeater(seat, key);
}

static void
keyboard_key(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,
             uint32_t time, uint32_t key, uint32_t state)
{
    struct seat *seat = data;
    key_press_release(seat, seat->kbd_focus, serial, key + 8, state);
}

static void
keyboard_modifiers(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial,
                   uint32_t mods_depressed, uint32_t mods_latched,
                   uint32_t mods_locked, uint32_t group)
{
    struct seat *seat = data;

    mods_depressed &= ~seat->kbd.virtual_modifiers;
    mods_latched &= ~seat->kbd.virtual_modifiers;
    mods_locked &= ~seat->kbd.virtual_modifiers;

#if defined(_DEBUG)
    char depressed[256];
    char latched[256];
    char locked[256];

    modifier_string(mods_depressed, sizeof(depressed), depressed, seat);
    modifier_string(mods_latched, sizeof(latched), latched, seat);
    modifier_string(mods_locked, sizeof(locked), locked, seat);

    LOG_DBG(
        "modifiers: depressed=%s (0x%x), latched=%s (0x%x), locked=%s (0x%x), "
        "group=%u",
        depressed, mods_depressed, latched, mods_latched, locked, mods_locked,
        group);
#endif

    if (seat->kbd.xkb_state != NULL) {
        xkb_state_update_mask(
            seat->kbd.xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group);

        /* Update state of modifiers we're interested in for e.g mouse events */
        seat->kbd.shift = seat->kbd.mod_shift != XKB_MOD_INVALID
            ? xkb_state_mod_index_is_active(
                seat->kbd.xkb_state, seat->kbd.mod_shift, XKB_STATE_MODS_EFFECTIVE)
            : false;
        seat->kbd.alt = seat->kbd.mod_alt != XKB_MOD_INVALID
            ? xkb_state_mod_index_is_active(
                seat->kbd.xkb_state, seat->kbd.mod_alt, XKB_STATE_MODS_EFFECTIVE)
            : false;
        seat->kbd.ctrl = seat->kbd.mod_ctrl != XKB_MOD_INVALID
            ? xkb_state_mod_index_is_active(
                seat->kbd.xkb_state, seat->kbd.mod_ctrl, XKB_STATE_MODS_EFFECTIVE)
            : false;
        seat->kbd.super = seat->kbd.mod_super != XKB_MOD_INVALID
            ? xkb_state_mod_index_is_active(
                seat->kbd.xkb_state, seat->kbd.mod_super, XKB_STATE_MODS_EFFECTIVE)
            : false;
    }

    if (seat->kbd_focus && seat->kbd_focus->active_surface == TERM_SURF_GRID)
        term_xcursor_update_for_seat(seat->kbd_focus, seat);
}

UNITTEST
{
    int chan[2];
    xassert(pipe2(chan, O_CLOEXEC) == 0);

    xassert(chan[0] >= 0);
    xassert(chan[1] >= 0);

    struct config conf = {0};
    struct grid grid = {0};

    struct terminal term = {
        .conf = &conf,
        .grid = &grid,
        .ptmx = chan[1],
        .selection = {
            .coords = {
                .start = {-1, -1},
                .end = {-1, -1},
            },
            .auto_scroll = {
                .fd = -1,
             },
        },
    };

    struct key_binding_manager *key_binding_manager = key_binding_manager_new();

    struct wayland wayl = {
        .key_binding_manager = key_binding_manager,
        .terms = tll_init(),
    };

    struct seat seat = {
        .wayl = &wayl,
        .name = "unittest",
    };

    tll_push_back(wayl.terms, &term);
    term.wl = &wayl;

    seat.kbd.xkb = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
    xassert(seat.kbd.xkb != NULL);

    grid.kitty_kbd.flags[0] = KITTY_KBD_DISAMBIGUATE | KITTY_KBD_REPORT_ALTERNATE;

    /* Swedish keymap */
    {
        seat.kbd.xkb_keymap = xkb_keymap_new_from_names(
            seat.kbd.xkb, &(struct xkb_rule_names){.layout = "se"}, XKB_KEYMAP_COMPILE_NO_FLAGS);
        if (seat.kbd.xkb_keymap == NULL) {
            /* Skip test */
            goto no_keymap;
        }

        seat.kbd.xkb_state = xkb_state_new(seat.kbd.xkb_keymap);
        xassert(seat.kbd.xkb_state != NULL);

        seat.kbd.mod_shift = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_SHIFT);
        seat.kbd.mod_alt = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_ALT) ;
        seat.kbd.mod_ctrl = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_CTRL);
        seat.kbd.mod_super = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_LOGO);
        seat.kbd.mod_caps = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_CAPS);
        seat.kbd.mod_num = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_NUM);

        /* Significant modifiers in the legacy keyboard protocol */
        seat.kbd.legacy_significant = 0;
        if (seat.kbd.mod_shift != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_shift;
        if (seat.kbd.mod_alt != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_alt;
        if (seat.kbd.mod_ctrl != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_ctrl;
        if (seat.kbd.mod_super != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_super;

        /* Significant modifiers in the kitty keyboard protocol */
        seat.kbd.kitty_significant = seat.kbd.legacy_significant;
        if (seat.kbd.mod_caps != XKB_MOD_INVALID)
            seat.kbd.kitty_significant |= 1 << seat.kbd.mod_caps;
        if (seat.kbd.mod_num != XKB_MOD_INVALID)
            seat.kbd.kitty_significant |= 1 << seat.kbd.mod_num;

        key_binding_new_for_seat(key_binding_manager, &seat);
        key_binding_load_keymap(key_binding_manager, &seat);

        {
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_shift | 1u << seat.kbd.mod_ctrl;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_A + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key: 97 = 'a', alternate: 65 = 'A', base: N/A, mods: 6 = ctrl+shift */
            const char expected_ctrl_shift_a[] = "\033[97:65;6u";
            xassert(count == strlen(expected_ctrl_shift_a));
            xassert(streq(escape, expected_ctrl_shift_a));

            key_press_release(&seat, &term, 1337, KEY_A + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        {
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_shift | 1u << seat.kbd.mod_alt;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_2 + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key;. 50 = '2', alternate: 34 = '"', base: N/A, 4 = alt+shift */
            const char expected_alt_shift_2[] = "\033[50:34;4u";
            xassert(count == strlen(expected_alt_shift_2));
            xassert(streq(escape, expected_alt_shift_2));

            key_press_release(&seat, &term, 1337, KEY_2 + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        {
            xkb_mod_index_t alt_gr = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, "Mod5");
            xassert(alt_gr != XKB_MOD_INVALID);

            xkb_mod_mask_t mods = 1u << seat.kbd.mod_shift | 1u << seat.kbd.mod_alt | 1u << alt_gr;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_2 + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key; 178 = '²', alternate: N/A, base: 50 = '2', 4 = alt+shift (AltGr not part of the protocol) */
            const char expected_altgr_alt_shift_2[] = "\033[178::50;4u";
            xassert(count == strlen(expected_altgr_alt_shift_2));
            xassert(streq(escape, expected_altgr_alt_shift_2));

            key_press_release(&seat, &term, 1337, KEY_2 + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        {
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_alt;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_BACKSPACE + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key; 127 = <backspace>, alternate: N/A, base: N/A, 3 = alt */
            const char expected_alt_backspace[] = "\033[127;3u";
            xassert(count == strlen(expected_alt_backspace));
            xassert(streq(escape, expected_alt_backspace));

            key_press_release(&seat, &term, 1337, KEY_BACKSPACE + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        {
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_ctrl;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_ENTER + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key; 13 = <enter>, alternate: N/A, base: N/A, 5 = ctrl */
            const char expected_ctrl_enter[] = "\033[13;5u";
            xassert(count == strlen(expected_ctrl_enter));
            xassert(streq(escape, expected_ctrl_enter));

            key_press_release(&seat, &term, 1337, KEY_ENTER + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        {
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_ctrl;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_TAB + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key; 9 = <tab>, alternate: N/A, base: N/A, 5 = ctrl */
            const char expected_ctrl_tab[] = "\033[9;5u";
            xassert(count == strlen(expected_ctrl_tab));
            xassert(streq(escape, expected_ctrl_tab));

            key_press_release(&seat, &term, 1337, KEY_TAB + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        {
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_ctrl | 1u << seat.kbd.mod_shift;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 0);
            key_press_release(&seat, &term, 1337, KEY_LEFT + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            const char expected_ctrl_shift_left[] = "\033[1;6D";
            xassert(count == strlen(expected_ctrl_shift_left));
            xassert(streq(escape, expected_ctrl_shift_left));

            key_press_release(&seat, &term, 1337, KEY_LEFT + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }
        key_binding_unload_keymap(key_binding_manager, &seat);
        key_binding_remove_seat(key_binding_manager, &seat);

        xkb_state_unref(seat.kbd.xkb_state);
        xkb_keymap_unref(seat.kbd.xkb_keymap);

        seat.kbd.xkb_state = NULL;
        seat.kbd.xkb_keymap = NULL;
    }

    /* de(neo) keymap */
    {
        seat.kbd.xkb_keymap = xkb_keymap_new_from_names(
            seat.kbd.xkb, &(struct xkb_rule_names){.layout = "us,de(neo)"},
            XKB_KEYMAP_COMPILE_NO_FLAGS);

        if (seat.kbd.xkb_keymap == NULL) {
            /* Skip test */
            goto no_keymap;
        }

        seat.kbd.xkb_state = xkb_state_new(seat.kbd.xkb_keymap);
        xassert(seat.kbd.xkb_state != NULL);

        seat.kbd.mod_shift = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_SHIFT);
        seat.kbd.mod_alt = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_ALT) ;
        seat.kbd.mod_ctrl = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_CTRL);
        seat.kbd.mod_super = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_LOGO);
        seat.kbd.mod_caps = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_CAPS);
        seat.kbd.mod_num = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_NUM);

        /* Significant modifiers in the legacy keyboard protocol */
        seat.kbd.legacy_significant = 0;
        if (seat.kbd.mod_shift != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_shift;
        if (seat.kbd.mod_alt != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_alt;
        if (seat.kbd.mod_ctrl != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_ctrl;
        if (seat.kbd.mod_super != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_super;

        /* Significant modifiers in the kitty keyboard protocol */
        seat.kbd.kitty_significant = seat.kbd.legacy_significant;
        if (seat.kbd.mod_caps != XKB_MOD_INVALID)
            seat.kbd.kitty_significant |= 1 << seat.kbd.mod_caps;
        if (seat.kbd.mod_num != XKB_MOD_INVALID)
            seat.kbd.kitty_significant |= 1 << seat.kbd.mod_num;

        key_binding_new_for_seat(key_binding_manager, &seat);
        key_binding_load_keymap(key_binding_manager, &seat);

        {
            /*
             * In the de(neo) layout, the Y key generates 'k'. This
             * means we should get a key+alternate that indicates 'k',
             * but a base key that is 'y'.
             */
            xkb_mod_mask_t mods = 1u << seat.kbd.mod_shift | 1u << seat.kbd.mod_alt;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 1);
            key_press_release(&seat, &term, 1337, KEY_Y + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key: 107 = 'k', alternate: 75 = 'K', base: 121 = 'y', mods: 4 = alt+shift */
            const char expected_alt_shift_y[] = "\033[107:75:121;4u";
            xassert(count == strlen(expected_alt_shift_y));
            xassert(streq(escape, expected_alt_shift_y));

            key_press_release(&seat, &term, 1337, KEY_Y + 8, WL_KEYBOARD_KEY_STATE_RELEASED);
        }

        key_binding_unload_keymap(key_binding_manager, &seat);
        key_binding_remove_seat(key_binding_manager, &seat);

        xkb_state_unref(seat.kbd.xkb_state);
        xkb_keymap_unref(seat.kbd.xkb_keymap);

        seat.kbd.xkb_state = NULL;
        seat.kbd.xkb_keymap = NULL;
    }

    /* us(intl) keymap */
    {
        seat.kbd.xkb_keymap = xkb_keymap_new_from_names(
            seat.kbd.xkb, &(struct xkb_rule_names){.layout = "us", .variant = "intl"},
            XKB_KEYMAP_COMPILE_NO_FLAGS);

        if (seat.kbd.xkb_keymap == NULL) {
            /* Skip test */
            goto no_keymap;
        }

        seat.kbd.xkb_state = xkb_state_new(seat.kbd.xkb_keymap);
        xassert(seat.kbd.xkb_state != NULL);

        seat.kbd.xkb_compose_table = xkb_compose_table_new_from_locale(
            seat.kbd.xkb, setlocale(LC_CTYPE, NULL), XKB_COMPOSE_COMPILE_NO_FLAGS);
        if (seat.kbd.xkb_compose_table == NULL)
            goto no_keymap;

        seat.kbd.xkb_compose_state = xkb_compose_state_new(
            seat.kbd.xkb_compose_table, XKB_COMPOSE_STATE_NO_FLAGS);
        if (seat.kbd.xkb_compose_state == NULL) {
            xkb_compose_table_unref(seat.kbd.xkb_compose_table);
            goto no_keymap;
        }

        seat.kbd.mod_shift = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_SHIFT);
        seat.kbd.mod_alt = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_ALT) ;
        seat.kbd.mod_ctrl = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_CTRL);
        seat.kbd.mod_super = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_LOGO);
        seat.kbd.mod_caps = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_CAPS);
        seat.kbd.mod_num = xkb_keymap_mod_get_index(seat.kbd.xkb_keymap, XKB_MOD_NAME_NUM);

        /* Significant modifiers in the legacy keyboard protocol */
        seat.kbd.legacy_significant = 0;
        if (seat.kbd.mod_shift != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_shift;
        if (seat.kbd.mod_alt != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_alt;
        if (seat.kbd.mod_ctrl != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_ctrl;
        if (seat.kbd.mod_super != XKB_MOD_INVALID)
            seat.kbd.legacy_significant |= 1 << seat.kbd.mod_super;

        /* Significant modifiers in the kitty keyboard protocol */
        seat.kbd.kitty_significant = seat.kbd.legacy_significant;
        if (seat.kbd.mod_caps != XKB_MOD_INVALID)
            seat.kbd.kitty_significant |= 1 << seat.kbd.mod_caps;
        if (seat.kbd.mod_num != XKB_MOD_INVALID)
            seat.kbd.kitty_significant |= 1 << seat.kbd.mod_num;

        key_binding_new_for_seat(key_binding_manager, &seat);
        key_binding_load_keymap(key_binding_manager, &seat);

        {
            /*
             * Test the compose sequence "shift+', shift+space"
             *
             * Should result in a double quote, but a regression
             * caused it to instead emit a space. See #1987
             *
             * Note: "shift+', space" also results in a double quote,
             * but never regressed to a space.
             */
            grid.kitty_kbd.flags[0] = KITTY_KBD_DISAMBIGUATE;
            xkb_compose_state_reset(seat.kbd.xkb_compose_state);

            xkb_mod_mask_t mods = 1u << seat.kbd.mod_shift;
            keyboard_modifiers(&seat, NULL, 1337, mods, 0, 0, 1);

            key_press_release(&seat, &term, 1337, KEY_APOSTROPHE + 8, WL_KEYBOARD_KEY_STATE_PRESSED);
            key_press_release(&seat, &term, 1337, KEY_APOSTROPHE + 8, WL_KEYBOARD_KEY_STATE_RELEASED);

            key_press_release(&seat, &term, 1337, KEY_SPACE + 8, WL_KEYBOARD_KEY_STATE_PRESSED);

            char escape[64] = {0};
            ssize_t count = read(chan[0], escape, sizeof(escape));

            /* key: 34 = '"', alternate: N/A, base: N/A, mods: 2 = shift */
            const char expected_shift_apostrophe[] = "\033[34;2u";
            xassert(count == strlen(expected_shift_apostrophe));
            xassert(streq(escape, expected_shift_apostrophe));

            key_press_release(&seat, &term, 1337, KEY_SPACE + 8, WL_KEYBOARD_KEY_STATE_RELEASED);

            grid.kitty_kbd.flags[0] = KITTY_KBD_DISAMBIGUATE | KITTY_KBD_REPORT_ALTERNATE;
        }

        key_binding_unload_keymap(key_binding_manager, &seat);
        key_binding_remove_seat(key_binding_manager, &seat);

        xkb_compose_state_unref(seat.kbd.xkb_compose_state);
        xkb_compose_table_unref(seat.kbd.xkb_compose_table);

        xkb_state_unref(seat.kbd.xkb_state);
        xkb_keymap_unref(seat.kbd.xkb_keymap);

        seat.kbd.xkb_state = NULL;
        seat.kbd.xkb_keymap = NULL;
    }

no_keymap:
    xkb_context_unref(seat.kbd.xkb);
    key_binding_manager_destroy(key_binding_manager);

    tll_free(wayl.terms);
    close(chan[0]);
    close(chan[1]);
}

static void
keyboard_repeat_info(void *data, struct wl_keyboard *wl_keyboard,
                     int32_t rate, int32_t delay)
{
    struct seat *seat = data;
    LOG_DBG("keyboard repeat: rate=%d, delay=%d", rate, delay);
    seat->kbd.repeat.rate = rate;
    seat->kbd.repeat.delay = delay;
}

const struct wl_keyboard_listener keyboard_listener = {
    .keymap = &keyboard_keymap,
    .enter = &keyboard_enter,
    .leave = &keyboard_leave,
    .key = &keyboard_key,
    .modifiers = &keyboard_modifiers,
    .repeat_info = &keyboard_repeat_info,
};

void
input_repeat(struct seat *seat, uint32_t key)
{
    /* Should be cleared as soon as we loose focus */
    xassert(seat->kbd_focus != NULL);
    struct terminal *term = seat->kbd_focus;

    key_press_release(seat, term, seat->kbd.serial, key, XKB_KEY_DOWN);
}

static bool
is_top_left(const struct terminal *term, int x, int y)
{
    int csd_border_size = term->conf->csd.border_width;
    return (
        (!term->window->is_constrained_top && !term->window->is_constrained_left) &&
        ((term->active_surface == TERM_SURF_BORDER_LEFT && y < 10 * term->scale) ||
         (term->active_surface == TERM_SURF_BORDER_TOP && x < (10 + csd_border_size) * term->scale)));
}

static bool
is_top_right(const struct terminal *term, int x, int y)
{
    int csd_border_size = term->conf->csd.border_width;
    return (
        (!term->window->is_constrained_top && !term->window->is_constrained_right) &&
        ((term->active_surface == TERM_SURF_BORDER_RIGHT && y < 10 * term->scale) ||
         (term->active_surface == TERM_SURF_BORDER_TOP && x > term->width + 1 * csd_border_size * term->scale - 10 * term->scale)));
}

static bool
is_bottom_left(const struct terminal *term, int x, int y)
{
    int csd_title_size = term->conf->csd.title_height;
    int csd_border_size = term->conf->csd.border_width;
    return (
        (!term->window->is_constrained_bottom && !term->window->is_constrained_left) &&
        ((term->active_surface == TERM_SURF_BORDER_LEFT && y > csd_title_size * term->scale + term->height) ||
         (term->active_surface == TERM_SURF_BORDER_BOTTOM && x < (10 + csd_border_size) * term->scale)));
}

static bool
is_bottom_right(const struct terminal *term, int x, int y)
{
    int csd_title_size = term->conf->csd.title_height;
    int csd_border_size = term->conf->csd.border_width;
    return (
        (!term->window->is_constrained_bottom && !term->window->is_constrained_right) &&
        ((term->active_surface == TERM_SURF_BORDER_RIGHT && y > csd_title_size * term->scale + term->height) ||
         (term->active_surface == TERM_SURF_BORDER_BOTTOM && x > term->width + 1 * csd_border_size * term->scale - 10 * term->scale)));
}

enum cursor_shape
xcursor_for_csd_border(struct terminal *term, int x, int y)
{
    if (is_top_left(term, x, y))                              return CURSOR_SHAPE_TOP_LEFT_CORNER;
    else if (is_top_right(term, x, y))                        return CURSOR_SHAPE_TOP_RIGHT_CORNER;
    else if (is_bottom_left(term, x, y))                      return CURSOR_SHAPE_BOTTOM_LEFT_CORNER;
    else if (is_bottom_right(term, x, y))                     return CURSOR_SHAPE_BOTTOM_RIGHT_CORNER;

    else if (term->active_surface == TERM_SURF_BORDER_LEFT)
        return !term->window->is_constrained_left
            ? CURSOR_SHAPE_LEFT_SIDE : CURSOR_SHAPE_LEFT_PTR;

    else if (term->active_surface == TERM_SURF_BORDER_RIGHT)
        return !term->window->is_constrained_right
            ? CURSOR_SHAPE_RIGHT_SIDE : CURSOR_SHAPE_LEFT_PTR;

    else if (term->active_surface == TERM_SURF_BORDER_TOP)
        return !term->window->is_constrained_top
            ? CURSOR_SHAPE_TOP_SIDE : CURSOR_SHAPE_LEFT_PTR;

    else if (term->active_surface == TERM_SURF_BORDER_BOTTOM)
        return !term->window->is_constrained_bottom
            ? CURSOR_SHAPE_BOTTOM_SIDE : CURSOR_SHAPE_LEFT_PTR;

    else {
        BUG("Unreachable");
        return CURSOR_SHAPE_NONE;
    }
}

static void
mouse_button_state_reset(struct seat *seat)
{
    tll_free(seat->mouse.buttons);
    seat->mouse.count = 0;
    seat->mouse.last_released_button = 0;
    memset(&seat->mouse.last_time, 0, sizeof(seat->mouse.last_time));
}

static void
mouse_coord_pixel_to_cell(struct seat *seat, const struct terminal *term,
                          int x, int y)
{
    /*
     * Translate x,y pixel coordinate to a cell coordinate, or -1
     * if the cursor is outside the grid. I.e. if it is inside the
     * margins.
     */
    if (x < term->margins.left)
        seat->mouse.col = 0;
    else if (x >= term->width - term->margins.right)
        seat->mouse.col = term->cols - 1;
    else
        seat->mouse.col = (x - term->margins.left) / term->cell_width;

    if (y < term->margins.top)
        seat->mouse.row = 0;
    else if (y >= term->height - term->margins.bottom)
        seat->mouse.row = term->rows - 1;
    else
        seat->mouse.row = (y - term->margins.top) / term->cell_height;
}

static bool
touch_is_active(const struct seat *seat)
{
    if (seat->wl_touch == NULL) {
        return false;
    }

    switch (seat->touch.state) {
    case TOUCH_STATE_IDLE:
    case TOUCH_STATE_INHIBITED:
        return false;

    case TOUCH_STATE_HELD:
    case TOUCH_STATE_DRAGGING:
    case TOUCH_STATE_SCROLLING:
        return true;
    }

    BUG("Bad touch state: %d", seat->touch.state);
    return false;
}

static void
wl_pointer_enter(void *data, struct wl_pointer *wl_pointer,
                 uint32_t serial, struct wl_surface *surface,
                 wl_fixed_t surface_x, wl_fixed_t surface_y)
{
    if (unlikely(surface == NULL))  {
        /* Seen on mutter-3.38 */
        LOG_WARN("compositor sent pointer_enter event with a NULL surface");
        return;
    }

    struct seat *seat = data;

    struct wl_window *win = wl_surface_get_user_data(surface);
    struct terminal *term = win->term;

    seat->mouse_focus = term;
    term->active_surface = term_surface_kind(term, surface);

    if (touch_is_active(seat))
        return;

    int x = wl_fixed_to_int(surface_x) * term->scale;
    int y = wl_fixed_to_int(surface_y) * term->scale;

    seat->pointer.serial = serial;
    seat->pointer.hidden = false;
    seat->mouse.x = x;
    seat->mouse.y = y;

    LOG_DBG("pointer-enter: pointer=%p, serial=%u, surface = %p, new-moused = %p, "
            "x=%d, y=%d",
            (void *)wl_pointer, serial, (void *)surface, (void *)term,
            x, y);

    xassert(tll_length(seat->mouse.buttons) == 0);

    wayl_reload_xcursor_theme(seat, term->scale); /* Scale may have changed */
    term_xcursor_update_for_seat(term, seat);

    switch (term->active_surface) {
    case TERM_SURF_GRID: {
        mouse_coord_pixel_to_cell(seat, term, x, y);
        break;
    }

    case TERM_SURF_TITLE:
    case TERM_SURF_BORDER_LEFT:
    case TERM_SURF_BORDER_RIGHT:
    case TERM_SURF_BORDER_TOP:
    case TERM_SURF_BORDER_BOTTOM:
        break;

    case TERM_SURF_BUTTON_MINIMIZE:
    case TERM_SURF_BUTTON_MAXIMIZE:
    case TERM_SURF_BUTTON_CLOSE:
        render_refresh_csd(term);
        break;

    case TERM_SURF_NONE:
        BUG("Invalid surface type");
        break;
    }
}

static void
wl_pointer_leave(void *data, struct wl_pointer *wl_pointer,
                 uint32_t serial, struct wl_surface *surface)
{
    struct seat *seat = data;

    if (seat->wl_touch != NULL) {
        switch (seat->touch.state) {
        case TOUCH_STATE_IDLE:
            break;

        case TOUCH_STATE_INHIBITED:
            seat->touch.state = TOUCH_STATE_IDLE;
            break;

        case TOUCH_STATE_HELD:
        case TOUCH_STATE_DRAGGING:
        case TOUCH_STATE_SCROLLING:
            return;
        }
    }

    struct terminal *old_moused = seat->mouse_focus;

    LOG_DBG(
        "%s: pointer-leave: pointer=%p, serial=%u, surface = %p, old-moused = %p",
        seat->name, (void *)wl_pointer, serial, (void *)surface,
        (void *)old_moused);

    seat->pointer.hidden = false;

    if (seat->pointer.xcursor_callback != NULL) {
        /* A cursor frame callback may never be called if the pointer leaves our surface */
        wl_callback_destroy(seat->pointer.xcursor_callback);
        seat->pointer.xcursor_callback = NULL;
        seat->pointer.xcursor_pending = false;
    }

    /* Reset last-set-xcursor, to ensure we update it on a pointer-enter event */
    seat->pointer.shape = CURSOR_SHAPE_NONE;

    /* Reset mouse state */
    seat->mouse.x = seat->mouse.y = 0;
    seat->mouse.col = seat->mouse.row = 0;
    mouse_button_state_reset(seat);
    for (size_t i = 0; i < ALEN(seat->mouse.aggregated); i++)
        seat->mouse.aggregated[i] = 0.0;
    seat->mouse.have_discrete = false;

    seat->mouse_focus = NULL;
    if (old_moused == NULL) {
        LOG_WARN(
            "compositor sent pointer_leave event without a pointer_enter "
            "event: surface=%p", (void *)surface);
    } else {
        if (surface != NULL) {
            /* Sway 1.4 sends this event with a NULL surface when we destroy the window */
            const struct wl_window UNUSED *win = wl_surface_get_user_data(surface);
            xassert(old_moused == win->term);
        }

        enum term_surface active_surface = old_moused->active_surface;

        old_moused->active_surface = TERM_SURF_NONE;

        switch (active_surface) {
        case TERM_SURF_BUTTON_MINIMIZE:
        case TERM_SURF_BUTTON_MAXIMIZE:
        case TERM_SURF_BUTTON_CLOSE:
            if (old_moused->shutdown.in_progress)
                break;

            render_refresh_csd(old_moused);
            break;

        case TERM_SURF_GRID:
            selection_finalize(seat, old_moused, seat->pointer.serial);
            break;

        case TERM_SURF_NONE:
        case TERM_SURF_TITLE:
        case TERM_SURF_BORDER_LEFT:
        case TERM_SURF_BORDER_RIGHT:
        case TERM_SURF_BORDER_TOP:
        case TERM_SURF_BORDER_BOTTOM:
            break;
        }

    }
}

static bool
pointer_is_on_button(const struct terminal *term, const struct seat *seat,
                     enum csd_surface csd_surface)
{
    if (seat->mouse.x < 0)
        return false;
    if (seat->mouse.y < 0)
        return false;

    struct csd_data info = get_csd_data(term, csd_surface);
    if (seat->mouse.x > info.width)
        return false;

    if (seat->mouse.y > info.height)
        return false;

    return true;
}

static void
wl_pointer_motion(void *data, struct wl_pointer *wl_pointer,
                  uint32_t time, wl_fixed_t surface_x, wl_fixed_t surface_y)
{
    struct seat *seat = data;

    /* Touch-emulated pointer events have wl_pointer == NULL. */
    if (wl_pointer != NULL && touch_is_active(seat))
        return;

    struct wayland *wayl = seat->wayl;
    struct terminal *term = seat->mouse_focus;

    if (unlikely(term == NULL)) {
        /* Typically happens when the compositor sent a pointer enter
         * event with a NULL surface - see wl_pointer_enter().
         *
         * In this case, we never set seat->mouse_focus (since we
         * can't map the enter event to a specific window). */
        return;
    }

    struct wl_window *win = term->window;

    LOG_DBG("pointer_motion: pointer=%p, x=%d, y=%d", (void *)wl_pointer,
            wl_fixed_to_int(surface_x), wl_fixed_to_int(surface_y));

    xassert(term != NULL);

    int x = wl_fixed_to_int(surface_x) * term->scale;
    int y = wl_fixed_to_int(surface_y) * term->scale;

    enum term_surface surf_kind = term->active_surface;
    int button = 0;
    bool send_to_client = false;
    bool is_on_button = false;

    /* If current surface is a button, check if pointer was on it
       *before* the motion event */
    switch (surf_kind) {
    case TERM_SURF_BUTTON_MINIMIZE:
        is_on_button = pointer_is_on_button(term, seat, CSD_SURF_MINIMIZE);
        break;

    case TERM_SURF_BUTTON_MAXIMIZE:
        is_on_button = pointer_is_on_button(term, seat, CSD_SURF_MAXIMIZE);
        break;

    case TERM_SURF_BUTTON_CLOSE:
        is_on_button = pointer_is_on_button(term, seat, CSD_SURF_CLOSE);
        break;

    case TERM_SURF_NONE:
    case TERM_SURF_GRID:
    case TERM_SURF_TITLE:
    case TERM_SURF_BORDER_LEFT:
    case TERM_SURF_BORDER_RIGHT:
    case TERM_SURF_BORDER_TOP:
    case TERM_SURF_BORDER_BOTTOM:
        break;
    }

    seat->pointer.hidden = false;
    seat->mouse.x = x;
    seat->mouse.y = y;

    term_xcursor_update_for_seat(term, seat);

    if (tll_length(seat->mouse.buttons) > 0) {
        const struct button_tracker *tracker = &tll_front(seat->mouse.buttons);
        surf_kind = tracker->surf_kind;
        button = tracker->button;
        send_to_client = tracker->send_to_client;
    }

    switch (surf_kind) {
    case TERM_SURF_NONE:
        break;

    case TERM_SURF_BUTTON_MINIMIZE:
        if (pointer_is_on_button(term, seat, CSD_SURF_MINIMIZE) != is_on_button)
            render_refresh_csd(term);
        break;

    case TERM_SURF_BUTTON_MAXIMIZE:
        if (pointer_is_on_button(term, seat, CSD_SURF_MAXIMIZE) != is_on_button)
            render_refresh_csd(term);
        break;

    case TERM_SURF_BUTTON_CLOSE:
        if (pointer_is_on_button(term, seat, CSD_SURF_CLOSE) != is_on_button)
            render_refresh_csd(term);
        break;

    case TERM_SURF_TITLE:
        /* We've started a 'move' timer, but user started dragging
         * right away - abort the timer and initiate the actual move
         * right away */
        if (button == BTN_LEFT && win->csd.move_timeout_fd != -1) {
            fdm_del(wayl->fdm, win->csd.move_timeout_fd);
            win->csd.move_timeout_fd = -1;
            xdg_toplevel_move(win->xdg_toplevel, seat->wl_seat, win->csd.serial);
        }
        break;

    case TERM_SURF_BORDER_LEFT:
    case TERM_SURF_BORDER_RIGHT:
    case TERM_SURF_BORDER_TOP:
    case TERM_SURF_BORDER_BOTTOM:
        break;

    case TERM_SURF_GRID: {
        int old_col = seat->mouse.col;
        int old_row = seat->mouse.row;

        mouse_coord_pixel_to_cell(seat, term, seat->mouse.x, seat->mouse.y);

        xassert(seat->mouse.col >= 0 && seat->mouse.col < term->cols);
        xassert(seat->mouse.row >= 0 && seat->mouse.row < term->rows);

        /* Cursor has moved to a different cell since last time */
        bool cursor_is_on_new_cell
            = old_col != seat->mouse.col || old_row != seat->mouse.row;

        if (cursor_is_on_new_cell) {
            /* Prevent multiple/different mouse bindings from
             * triggering if the mouse has moved "too much" (to
             * another cell) */
            seat->mouse.count = 0;
        }

        /* Cursor is inside the grid, i.e. *not* in the margins */
        const bool cursor_is_on_grid = seat->mouse.col >= 0 && seat->mouse.row >= 0;

        enum selection_scroll_direction auto_scroll_direction
            = term->selection.coords.end.row < 0
                ? SELECTION_SCROLL_NOT
                : y < term->margins.top
                    ? SELECTION_SCROLL_UP
                    : y > term->height - term->margins.bottom
                        ? SELECTION_SCROLL_DOWN
                        : SELECTION_SCROLL_NOT;

        if (auto_scroll_direction == SELECTION_SCROLL_NOT)
            selection_stop_scroll_timer(term);

        /* Update selection */
        if (!term->is_searching) {
            if (auto_scroll_direction != SELECTION_SCROLL_NOT) {
                /*
                 * Start 'selection auto-scrolling'
                 *
                 * The speed of the scrolling is proportional to the
                 * distance between the mouse and the grid; the
                 * further away the mouse is, the faster we scroll.
                 *
                 * Note that the speed is measured in 'intervals (in
                 * ns) between each timed scroll of a single line'.
                 *
                 * Thus, the further away the mouse is, the smaller
                 * interval value we use.
                 */

                int distance = auto_scroll_direction == SELECTION_SCROLL_UP
                    ? term->margins.top - y
                    : y - (term->height - term->margins.bottom);

                xassert(distance > 0);
                int divisor
                    = distance * term->conf->scrollback.multiplier / term->scale;

                selection_start_scroll_timer(
                    term, 400000000 / (divisor > 0 ? divisor : 1),
                    auto_scroll_direction, seat->mouse.col);
            }

            if (term->selection.ongoing &&
                (cursor_is_on_new_cell ||
                 (term->selection.coords.end.row < 0 &&
                  seat->mouse.x >= term->margins.left &&
                  seat->mouse.x < term->width - term->margins.right &&
                  seat->mouse.y >= term->margins.top &&
                  seat->mouse.y < term->height - term->margins.bottom)))
            {
                selection_update(term, seat->mouse.col, seat->mouse.row);
            }
        }

        /* Send mouse event to client application */
        if (!term_mouse_grabbed(term, seat) &&
            (cursor_is_on_new_cell ||
                term->mouse_reporting == MOUSE_SGR_PIXELS) &&
            ((button == 0 && cursor_is_on_grid) ||
             (button != 0 && send_to_client)))
        {
            xassert(seat->mouse.col < term->cols);
            xassert(seat->mouse.row < term->rows);

            term_mouse_motion(
                term, button,
                seat->mouse.row, seat->mouse.col,
                seat->mouse.y - term->margins.top,
                seat->mouse.x - term->margins.left,
                seat->kbd.shift, seat->kbd.alt, seat->kbd.ctrl);
        }
        break;
    }
    }
}

static bool
fdm_csd_move(struct fdm *fdm, int fd, int events, void *data)
{
    struct seat *seat = data;
    fdm_del(fdm, fd);

    if (seat->mouse_focus == NULL) {
        LOG_WARN(
            "%s: CSD move timeout triggered, but seat's has no mouse focused terminal",
            seat->name);
        return true;
    }

    struct wl_window *win = seat->mouse_focus->window;

    win->csd.move_timeout_fd = -1;
    xdg_toplevel_move(win->xdg_toplevel, seat->wl_seat, win->csd.serial);
    return true;
}

static const struct key_binding *
match_mouse_binding(const struct seat *seat, const struct terminal *term,
                    int button)
{
    if (seat->wl_keyboard != NULL && seat->kbd.xkb_state != NULL) {
        /* Seat has keyboard - use mouse bindings *with* modifiers */

        const struct key_binding_set *bindings =
            key_binding_for(term->wl->key_binding_manager, term->conf, seat);
        xassert(bindings != NULL);

        xkb_mod_mask_t mods;
        get_current_modifiers(seat, &mods, NULL, 0, true);

        /* Ignore selection override modifiers when
         * matching modifiers */
        mods &= ~bindings->selection_overrides;

        const struct key_binding *match = NULL;

        tll_foreach(bindings->mouse, it) {
            const struct key_binding *binding = &it->item;

            if (binding->m.button != button) {
                /* Wrong button */
                continue;
            }

            if (binding->mods != mods) {
                /* Modifier mismatch */
                continue;
            }

            if (binding->m.count > seat->mouse.count) {
                /* Not correct click count */
                continue;
            }

            if (match == NULL || binding->m.count > match->m.count)
                match = binding;
        }

        return match;
    }

    else {
        /* Seat does NOT have a keyboard - use mouse bindings *without*
         * modifiers */
        const struct config_key_binding *match = NULL;
        const struct config *conf = term->conf;

        for (size_t i = 0; i < conf->bindings.mouse.count; i++) {
            const struct config_key_binding *binding =
                &conf->bindings.mouse.arr[i];

            if (binding->m.button != button) {
                /* Wrong button */
                continue;
            }

            if (binding->m.count > seat->mouse.count) {
                /* Incorrect click count */
                continue;
            }

            if (tll_length(binding->modifiers) > 0) {
                /* Binding has modifiers */
                continue;
            }

            if (match == NULL || binding->m.count > match->m.count)
                match = binding;
        }

        if (match != NULL) {
            static struct key_binding bind;
            bind.action = match->action;
            bind.aux = &match->aux;
            return &bind;
        }

        return NULL;
    }

    BUG("should not get here");
}

static void
wl_pointer_button(void *data, struct wl_pointer *wl_pointer,
                  uint32_t serial, uint32_t time, uint32_t button, uint32_t state)
{
    LOG_DBG("BUTTON: pointer=%p, serial=%u, button=%x, state=%u",
            (void *)wl_pointer, serial, button, state);

    xassert(serial != 0);

    struct seat *seat = data;

    /* Touch-emulated pointer events have wl_pointer == NULL. */
    if (wl_pointer != NULL && touch_is_active(seat))
        return;

    struct wayland *wayl = seat->wayl;
    struct terminal *term = seat->mouse_focus;

    seat->pointer.serial = serial;
    seat->pointer.hidden = false;

    xassert(term != NULL);

    enum term_surface surf_kind = TERM_SURF_NONE;
    bool send_to_client = false;

    if (state == WL_POINTER_BUTTON_STATE_PRESSED) {
        if (seat->wl_touch != NULL && seat->touch.state == TOUCH_STATE_IDLE) {
            seat->touch.state = TOUCH_STATE_INHIBITED;
        }

        /* Time since last click */
        struct timespec now, since_last;
        clock_gettime(CLOCK_MONOTONIC, &now);
        timespec_sub(&now, &seat->mouse.last_time, &since_last);

        if (seat->mouse.last_released_button == button &&
            since_last.tv_sec == 0 && since_last.tv_nsec <= 300 * 1000 * 1000)
        {
            seat->mouse.count++;
        } else
            seat->mouse.count = 1;

        /*
         * Workaround GNOME bug
         *
         * Dragging the window, then stopping the drag (releasing the
         * mouse button), *without* moving the mouse, and then
         * clicking twice, waiting for the CSD timer, and finally
         * clicking once more, results in the following sequence
         * (keyboard and other irrelevant events filtered out, unless
         * they're needed to prove a point):
         *
         * dbg: input.c:1551: cancelling drag timer, moving window
         * dbg: input.c:759: keyboard_leave: keyboard=0x607000003580, serial=873, surface=0x6070000036d0
         * dbg: input.c:1432: seat0: pointer-leave: pointer=0x607000003660, serial=874, surface = 0x6070000396e0, old-moused = 0x622000006100
         *
         * --> drag stopped here
         *
         * --> LMB clicked first time after the drag (generates the
         *     enter event on *release*, but no button events)
         * dbg: input.c:1360: pointer-enter: pointer=0x607000003660, serial=876, surface = 0x6070000396e0, new-moused = 0x622000006100
         *
         * --> LMB clicked, and held until the timer times out, second
         *     time after the drag
         * dbg: input.c:1712: BUTTON: pointer=0x607000003660, serial=877, button=110, state=1
         * dbg: input.c:1806: starting move timer
         * dbg: input.c:1692: move timer timed out
         * dbg: input.c:759: keyboard_leave: keyboard=0x607000003580, serial=878, surface=0x6070000036d0
         *
         * --> NOTE: ^^ no pointer leave event this time, only the
         *     keyboard leave
         *
         * --> LMB clicked one last time
         * dbg: input.c:697: seat0: keyboard_enter: keyboard=0x607000003580, serial=879, surface=0x6070000036d0
         * dbg: input.c:1712: BUTTON: pointer=0x607000003660, serial=880, button=110, state=1
         * err: input.c:1741: BUG in wl_pointer_button(): assertion failed: 'it->item.button != button'
         *
         * What are we seeing?
         *
         * - GNOME does *not* send a pointer *enter* event after the drag
         *   has stopped
         * - The second drag does *not* generate a pointer *leave* event
         * - The missing leave event means we're still tracking LMB as
         *   being held down in our seat struct.
         * - This leads to an assert (debug builds) when LMB is clicked
         *   again (seat's button list already contains LMB).
         *
         * Note: I've also observed variants of the above
         */
        tll_foreach(seat->mouse.buttons, it) {
            if (it->item.button == button) {
                LOG_WARN("multiple button press events for button %d "
                         "(compositor bug?)", button);
                tll_remove(seat->mouse.buttons, it);
                break;
            }
        }

#if defined(_DEBUG)
        tll_foreach(seat->mouse.buttons, it)
            xassert(it->item.button != button);
#endif

        /*
         * Remember which surface "owns" this button, so that we can
         * send motion and button release events to that surface, even
         * if the pointer is no longer over it.
         */
        tll_push_back(
            seat->mouse.buttons,
            ((struct button_tracker){
                .button = button,
                .surf_kind = term->active_surface,
                .send_to_client = false}));

        seat->mouse.last_time = now;

        surf_kind = term->active_surface;
        send_to_client = false;  /* For now, may be set to true if a binding consumes the button */
    } else {
        bool UNUSED have_button = false;
        tll_foreach(seat->mouse.buttons, it) {
            if (it->item.button == button) {
                have_button = true;
                surf_kind = it->item.surf_kind;
                send_to_client = it->item.send_to_client;
                tll_remove(seat->mouse.buttons, it);
                break;
            }
        }

        if (seat->wl_touch != NULL && seat->touch.state == TOUCH_STATE_INHIBITED) {
            if (tll_length(seat->mouse.buttons) == 0) {
                seat->touch.state = TOUCH_STATE_IDLE;
            }
        }

        if (!have_button) {
            /*
             * Seen on Sway with slurp
             *
             *  1. Run slurp
             *  2. Press, and hold left mouse button
             *  3. Press escape, to cancel slurp
             *  4. Release mouse button
             *  5. BAM!
             */
            LOG_WARN("stray button release event (compositor bug?)");
            return;
        }

        seat->mouse.last_released_button = button;
    }

    switch (surf_kind) {
    case TERM_SURF_TITLE:
        if (state == WL_POINTER_BUTTON_STATE_PRESSED) {

            struct wl_window *win = term->window;

            /* Toggle maximized state on double-click */
            if (term->conf->csd.double_click_to_maximize &&
                button == BTN_LEFT &&
                seat->mouse.count == 2)
            {
                if (win->is_maximized)
                    xdg_toplevel_unset_maximized(win->xdg_toplevel);
                else
                    xdg_toplevel_set_maximized(win->xdg_toplevel);
            }

            else if (button == BTN_LEFT && win->csd.move_timeout_fd < 0) {
                const struct itimerspec timeout = {
                    .it_value = {.tv_nsec = 200000000},
                };

                int fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
                if (fd >= 0 &&
                    timerfd_settime(fd, 0, &timeout, NULL) == 0 &&
                    fdm_add(wayl->fdm, fd, EPOLLIN, &fdm_csd_move, seat))
                {
                    win->csd.move_timeout_fd = fd;
                    win->csd.serial = serial;
                } else {
                    LOG_ERRNO("failed to configure XDG toplevel move timer FD");
                    if (fd >= 0)
                        close(fd);
                }
            }

            if (button == BTN_RIGHT && tll_length(seat->mouse.buttons) == 1) {
                const struct csd_data info = get_csd_data(term, CSD_SURF_TITLE);
                xdg_toplevel_show_window_menu(
                    win->xdg_toplevel,
                    seat->wl_seat,
                    seat->pointer.serial,
                    seat->mouse.x + info.x, seat->mouse.y + info.y);
            }
        }

        else if (state == WL_POINTER_BUTTON_STATE_RELEASED) {
            struct wl_window *win = term->window;
            if (win->csd.move_timeout_fd >= 0) {
                fdm_del(wayl->fdm, win->csd.move_timeout_fd);
                win->csd.move_timeout_fd = -1;
            }
        }
        return;

    case TERM_SURF_BORDER_LEFT:
    case TERM_SURF_BORDER_RIGHT:
    case TERM_SURF_BORDER_TOP:
    case TERM_SURF_BORDER_BOTTOM: {
        if (button == BTN_LEFT && state == WL_POINTER_BUTTON_STATE_PRESSED) {
            enum xdg_toplevel_resize_edge resize_type = XDG_TOPLEVEL_RESIZE_EDGE_NONE;

            int x = seat->mouse.x;
            int y = seat->mouse.y;

            if (is_top_left(term, x, y))
                resize_type = XDG_TOPLEVEL_RESIZE_EDGE_TOP_LEFT;
            else if (is_top_right(term, x, y))
                resize_type = XDG_TOPLEVEL_RESIZE_EDGE_TOP_RIGHT;
            else if (is_bottom_left(term, x, y))
                resize_type = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_LEFT;
            else if (is_bottom_right(term, x, y))
                resize_type = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM_RIGHT;
            else {
                if (term->active_surface == TERM_SURF_BORDER_LEFT &&
                    !term->window->is_constrained_left)
                {
                    resize_type = XDG_TOPLEVEL_RESIZE_EDGE_LEFT;
                }

                else if (term->active_surface == TERM_SURF_BORDER_RIGHT &&
                    !term->window->is_constrained_right)
                {
                    resize_type = XDG_TOPLEVEL_RESIZE_EDGE_RIGHT;
                }

                else if (term->active_surface == TERM_SURF_BORDER_TOP &&
                    !term->window->is_constrained_top)
                {
                    resize_type = XDG_TOPLEVEL_RESIZE_EDGE_TOP;
                }

                else if (term->active_surface == TERM_SURF_BORDER_BOTTOM &&
                    !term->window->is_constrained_bottom)
                {
                    resize_type = XDG_TOPLEVEL_RESIZE_EDGE_BOTTOM;
                }
            }

            if (resize_type != XDG_TOPLEVEL_RESIZE_EDGE_NONE) {
                xdg_toplevel_resize(
                    term->window->xdg_toplevel, seat->wl_seat, serial, resize_type);
            }
        }
        return;
    }

    case TERM_SURF_BUTTON_MINIMIZE:
        if (button == BTN_LEFT &&
            pointer_is_on_button(term, seat, CSD_SURF_MINIMIZE) &&
            state == WL_POINTER_BUTTON_STATE_RELEASED)
        {
            xdg_toplevel_set_minimized(term->window->xdg_toplevel);
        }
        break;

    case TERM_SURF_BUTTON_MAXIMIZE:
        if (button == BTN_LEFT &&
            pointer_is_on_button(term, seat, CSD_SURF_MAXIMIZE) &&
            state == WL_POINTER_BUTTON_STATE_RELEASED)
        {
            if (term->window->is_maximized)
                xdg_toplevel_unset_maximized(term->window->xdg_toplevel);
            else
                xdg_toplevel_set_maximized(term->window->xdg_toplevel);
        }
        break;

    case TERM_SURF_BUTTON_CLOSE:
        if (button == BTN_LEFT &&
            pointer_is_on_button(term, seat, CSD_SURF_CLOSE) &&
            state == WL_POINTER_BUTTON_STATE_RELEASED)
        {
            term_shutdown(term);
        }
        break;

    case TERM_SURF_GRID: {
        search_cancel(term);
        urls_reset(term);

        bool cursor_is_on_grid = seat->mouse.col >= 0 && seat->mouse.row >= 0;

        switch (state) {
        case WL_POINTER_BUTTON_STATE_PRESSED: {
            bool consumed = false;

            if (cursor_is_on_grid && term_mouse_grabbed(term, seat)) {
                const struct key_binding *match =
                    match_mouse_binding(seat, term, button);

                if (match != NULL)
                    consumed = execute_binding(seat, term, match, serial, 1);
            }

            send_to_client = !consumed && cursor_is_on_grid;

            if (send_to_client)
                tll_back(seat->mouse.buttons).send_to_client = true;

            if (send_to_client &&
                !term_mouse_grabbed(term, seat) &&
                cursor_is_on_grid)
            {
                term_mouse_down(
                    term, button, seat->mouse.row, seat->mouse.col,
                    seat->mouse.y - term->margins.top,
                    seat->mouse.x - term->margins.left,
                    seat->kbd.shift, seat->kbd.alt, seat->kbd.ctrl);
            }
            break;
        }

        case WL_POINTER_BUTTON_STATE_RELEASED:
            selection_finalize(seat, term, serial);

            if (send_to_client && !term_mouse_grabbed(term, seat)) {
                term_mouse_up(
                    term, button, seat->mouse.row, seat->mouse.col,
                    seat->mouse.y - term->margins.top,
                    seat->mouse.x - term->margins.left,
                    seat->kbd.shift, seat->kbd.alt, seat->kbd.ctrl);
            }
            break;
        }
        break;
    }

    case TERM_SURF_NONE:
        BUG("Invalid surface type");
        break;

    }
}

static void
alternate_scroll(struct seat *seat, int amount, int button)
{
    if (seat->wl_keyboard == NULL)
        return;

    /* Should be cleared in leave event */
    xassert(seat->mouse_focus != NULL);
    struct terminal *term = seat->mouse_focus;

    assert(button == BTN_BACK || button == BTN_FORWARD);

    xkb_keycode_t key = button == BTN_BACK
        ? seat->kbd.key_arrow_up : seat->kbd.key_arrow_down;

    for (int i = 0; i < amount; i++)
        key_press_release(seat, term, seat->kbd.serial, key, XKB_KEY_DOWN);
    key_press_release(seat, term, seat->kbd.serial, key, XKB_KEY_UP);
}

static void
mouse_scroll(struct seat *seat, int amount, enum wl_pointer_axis axis)
{
    struct terminal *term = seat->mouse_focus;
    xassert(term != NULL);

    int button = axis == WL_POINTER_AXIS_VERTICAL_SCROLL
        ? amount < 0 ? BTN_WHEEL_BACK : BTN_WHEEL_FORWARD
        : amount < 0 ? BTN_WHEEL_LEFT : BTN_WHEEL_RIGHT;
    amount = abs(amount);

    if (term_mouse_grabbed(term, seat)) {
        seat->mouse.count = 1;

        const struct key_binding *match =
            match_mouse_binding(seat, term, button);

        if (match != NULL)
            execute_binding(seat, term, match, seat->pointer.serial, amount);

        seat->mouse.last_released_button = button;
    }

    else if (seat->mouse.col >= 0 && seat->mouse.row >= 0) {
        xassert(seat->mouse.col < term->cols);
        xassert(seat->mouse.row < term->rows);

        for (int i = 0; i < amount; i++) {
            term_mouse_down(
                term, button, seat->mouse.row, seat->mouse.col,
                seat->mouse.y - term->margins.top,
                seat->mouse.x - term->margins.left,
                seat->kbd.shift, seat->kbd.alt, seat->kbd.ctrl);
        }

        term_mouse_up(
            term, button, seat->mouse.row, seat->mouse.col,
            seat->mouse.y - term->margins.top,
            seat->mouse.x - term->margins.left,
            seat->kbd.shift, seat->kbd.alt, seat->kbd.ctrl);
    }
}

static double
mouse_scroll_multiplier(const struct terminal *term, const struct seat *seat)
{
    return (term->grid == &term->normal ||
            (term_mouse_grabbed(term, seat) && term->alt_scrolling))
        ? term->conf->scrollback.multiplier
        : 1.0;
}

static void
wl_pointer_axis(void *data, struct wl_pointer *wl_pointer,
                uint32_t time, uint32_t axis, wl_fixed_t value)
{
    struct seat *seat = data;

    if (touch_is_active(seat))
        return;

    if (seat->mouse.have_discrete)
        return;

    xassert(seat->mouse_focus != NULL);
    xassert(axis < ALEN(seat->mouse.aggregated));

    const struct terminal *term = seat->mouse_focus;

    /*
     * Aggregate scrolled amount until we get at least 1.0
     *
     * Without this, very slow scrolling will never actually scroll
     * anything.
     */
    seat->mouse.aggregated[axis] +=
        mouse_scroll_multiplier(term, seat) * wl_fixed_to_double(value);
    if (fabs(seat->mouse.aggregated[axis]) < seat->mouse_focus->cell_height)
        return;

    int lines = seat->mouse.aggregated[axis] / seat->mouse_focus->cell_height;
    mouse_scroll(seat, lines, axis);
    seat->mouse.aggregated[axis] -= (double)lines * seat->mouse_focus->cell_height;
}

static void
wl_pointer_axis_discrete(void *data, struct wl_pointer *wl_pointer,
                         enum wl_pointer_axis axis, int32_t discrete)
{
    LOG_DBG("axis_discrete: %d", discrete);
    struct seat *seat = data;

    if (touch_is_active(seat))
        return;

    seat->mouse.have_discrete = true;
    int amount = discrete;

    if (axis == WL_POINTER_AXIS_HORIZONTAL_SCROLL) {
        /* Treat mouse wheel left/right as regular buttons */
    } else
        amount *= mouse_scroll_multiplier(seat->mouse_focus, seat);

    mouse_scroll(seat, amount, axis);
}

#if defined(WL_POINTER_AXIS_VALUE120_SINCE_VERSION)
static void
wl_pointer_axis_value120(void *data, struct wl_pointer *wl_pointer,
                         enum wl_pointer_axis axis, int32_t value120)
{
    LOG_DBG("axis_value120: %d -> %.2f", value120, (float)value120 / 120.);

    struct seat *seat = data;

    if (touch_is_active(seat))
        return;

    seat->mouse.have_discrete = true;

    /*
     * 120 corresponds to a single "low-res" scroll step.
     *
     * When doing high-res scrolling, take the scrollback.multiplier,
     * and calculate how many degrees there are per line.
     *
     * For example, with scrollback.multiplier = 3, we have 120 / 3 == 40.
     *
     * Then, accumulate high-res scroll events, until we have *at
     * least* that much. Translate the accumulated value to number of
     * lines, and scroll.
     *
     * Subtract the "used" degrees from the accumulated value, and
     * keep what's left (this value will always be less than the
     * per-line value).
     */
    const double multiplier = mouse_scroll_multiplier(seat->mouse_focus, seat);
    const double per_line = 120. / multiplier;

    seat->mouse.aggregated_120[axis] += (double)value120;

    if (fabs(seat->mouse.aggregated_120[axis]) < per_line)
        return;

    int lines = (int)(seat->mouse.aggregated_120[axis] / per_line);
    mouse_scroll(seat, lines, axis);
    seat->mouse.aggregated_120[axis] -= (double)lines * per_line;
}
#endif

static void
wl_pointer_frame(void *data, struct wl_pointer *wl_pointer)
{
    struct seat *seat = data;

    if (touch_is_active(seat))
        return;

    seat->mouse.have_discrete = false;
}

static void
wl_pointer_axis_source(void *data, struct wl_pointer *wl_pointer,
                       uint32_t axis_source)
{
}

static void
wl_pointer_axis_stop(void *data, struct wl_pointer *wl_pointer,
                     uint32_t time, uint32_t axis)
{
    struct seat *seat = data;

    if (touch_is_active(seat))
        return;

    xassert(axis < ALEN(seat->mouse.aggregated));
    seat->mouse.aggregated[axis] = 0.;
}

const struct wl_pointer_listener pointer_listener = {
    .enter = &wl_pointer_enter,
    .leave = &wl_pointer_leave,
    .motion = &wl_pointer_motion,
    .button = &wl_pointer_button,
    .axis = &wl_pointer_axis,
    .frame = &wl_pointer_frame,
    .axis_source = &wl_pointer_axis_source,
    .axis_stop = &wl_pointer_axis_stop,
    .axis_discrete = &wl_pointer_axis_discrete,
#if defined(WL_POINTER_AXIS_VALUE120_SINCE_VERSION)
    .axis_value120 = &wl_pointer_axis_value120,
#endif
};

static bool
touch_to_scroll(struct seat *seat, struct terminal *term,
                wl_fixed_t surface_x, wl_fixed_t surface_y)
{
    bool coord_updated = false;

    int y = wl_fixed_to_int(surface_y) * term->scale;
    int rows = (y - seat->mouse.y) / term->cell_height;
    if (rows != 0) {
        mouse_scroll(seat, -rows, WL_POINTER_AXIS_VERTICAL_SCROLL);
        seat->mouse.y += rows * term->cell_height;
        coord_updated = true;
    }

    int x = wl_fixed_to_int(surface_x) * term->scale;
    int cols = (x - seat->mouse.x) / term->cell_width;
    if (cols != 0) {
        mouse_scroll(seat, -cols, WL_POINTER_AXIS_HORIZONTAL_SCROLL);
        seat->mouse.x += cols * term->cell_width;
        coord_updated = true;
    }

    return coord_updated;
}

static void
wl_touch_down(void *data, struct wl_touch *wl_touch, uint32_t serial,
              uint32_t time, struct wl_surface *surface, int32_t id,
              wl_fixed_t surface_x, wl_fixed_t surface_y)
{
    struct seat *seat = data;

    if (seat->touch.state != TOUCH_STATE_IDLE)
        return;

    struct wl_window *win = wl_surface_get_user_data(surface);
    struct terminal *term = win->term;

    LOG_DBG("touch_down: touch=%p, x=%d, y=%d", (void *)wl_touch,
            wl_fixed_to_int(surface_x), wl_fixed_to_int(surface_y));

    int x = wl_fixed_to_int(surface_x) * term->scale;
    int y = wl_fixed_to_int(surface_y) * term->scale;

    seat->mouse.x = x;
    seat->mouse.y = y;
    mouse_coord_pixel_to_cell(seat, term, x, y);

    seat->touch.state = TOUCH_STATE_HELD;
    seat->touch.serial = serial;
    seat->touch.time = time + term->conf->touch.long_press_delay;
    seat->touch.surface = surface;
    seat->touch.surface_kind = term_surface_kind(term, surface);
    seat->touch.id = id;
}

static void
wl_touch_up(void *data, struct wl_touch *wl_touch, uint32_t serial,
            uint32_t time, int32_t id)
{
    struct seat *seat = data;

    if (seat->touch.state <= TOUCH_STATE_IDLE || id != seat->touch.id)
        return;

    LOG_DBG("touch_up: touch=%p", (void *)wl_touch);

    struct wl_window *win = wl_surface_get_user_data(seat->touch.surface);
    struct terminal *term = win->term;

    struct terminal *old_term = seat->mouse_focus;
    enum term_surface old_active_surface = term->active_surface;
    seat->mouse_focus = term;
    term->active_surface = seat->touch.surface_kind;

    switch (seat->touch.state) {
    case TOUCH_STATE_HELD:
        wl_pointer_button(seat, NULL, seat->touch.serial, time, BTN_LEFT,
                          WL_POINTER_BUTTON_STATE_PRESSED);
        /* fallthrough */
    case TOUCH_STATE_DRAGGING:
        wl_pointer_button(seat, NULL, serial, time, BTN_LEFT,
                          WL_POINTER_BUTTON_STATE_RELEASED);
        /* fallthrough */
    case TOUCH_STATE_SCROLLING:
        term->active_surface = TERM_SURF_NONE;
        seat->touch.state = TOUCH_STATE_IDLE;
        break;

    case TOUCH_STATE_INHIBITED:
    case TOUCH_STATE_IDLE:
        BUG("Bad touch state: %d", seat->touch.state);
        break;
    }

    seat->mouse_focus = old_term;
    term->active_surface = old_active_surface;
}

static void
wl_touch_motion(void *data, struct wl_touch *wl_touch, uint32_t time,
                int32_t id, wl_fixed_t surface_x, wl_fixed_t surface_y)
{
    struct seat *seat = data;
    if (seat->touch.state <= TOUCH_STATE_IDLE || id != seat->touch.id)
        return;

    LOG_DBG("touch_motion: touch=%p, x=%d, y=%d", (void *)wl_touch,
            wl_fixed_to_int(surface_x), wl_fixed_to_int(surface_y));

    struct wl_window *win = wl_surface_get_user_data(seat->touch.surface);
    struct terminal *term = win->term;

    struct terminal *old_term = seat->mouse_focus;
    enum term_surface old_active_surface = term->active_surface;
    seat->mouse_focus = term;
    term->active_surface = seat->touch.surface_kind;

    switch (seat->touch.state) {
    case TOUCH_STATE_HELD:
        if (time <= seat->touch.time && term->active_surface == TERM_SURF_GRID) {
            if (touch_to_scroll(seat, term, surface_x, surface_y))
                seat->touch.state = TOUCH_STATE_SCROLLING;
            break;
        } else {
            wl_pointer_button(seat, NULL, seat->touch.serial, time, BTN_LEFT,
                              WL_POINTER_BUTTON_STATE_PRESSED);
            seat->touch.state = TOUCH_STATE_DRAGGING;
            /* fallthrough */
        }
    case TOUCH_STATE_DRAGGING:
        wl_pointer_motion(seat, NULL, time, surface_x, surface_y);
        break;
    case TOUCH_STATE_SCROLLING:
        touch_to_scroll(seat, term, surface_x, surface_y);
        break;

    case TOUCH_STATE_INHIBITED:
    case TOUCH_STATE_IDLE:
        BUG("Bad touch state: %d", seat->touch.state);
        break;
    }

    seat->mouse_focus = old_term;
    term->active_surface = old_active_surface;
}

static void
wl_touch_frame(void *data, struct wl_touch *wl_touch)
{
}

static void
wl_touch_cancel(void *data, struct wl_touch *wl_touch)
{
    struct seat *seat = data;
    if (seat->touch.state == TOUCH_STATE_INHIBITED)
        return;

    seat->touch.state = TOUCH_STATE_IDLE;
}

const struct wl_touch_listener touch_listener = {
    .down = wl_touch_down,
    .up = wl_touch_up,
    .motion = wl_touch_motion,
    .frame = wl_touch_frame,
    .cancel = wl_touch_cancel,
};