crcbl-shell 0.8.0

Crucible windowing shell: own Wayland, X11, Web/canvas and headless backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
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
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
//! The Wayland backend: connection, registry, `xdg-shell` window lifecycle,
//! `wl_seat` input, pointer constraints, fractional scale, decorations and
//! layer-shell panels.
//!
//! Not `pub`: [`backend`](crate::backend) is the only way to reach a real
//! shell, because `WaylandShell::new()` in a consumer's source is the platform
//! leak this whole seam exists to prevent. `#[cfg(desktop_unix)]` — Linux and
//! FreeBSD, which `build.rs` sets it for — rather than `#[cfg(unix)]`, because
//! macOS is a Unix with no Wayland.
//!
//! The windowing rules' Linux policy (`docs/notes/backends.md`) in one sentence:
//! **libwayland-client owns the connection and the proxy objects; the protocol
//! layer above `wl_proxy_marshal_array_flags` is ours.** [`ffi`] is the first
//! half — hand-written `extern "C"` declarations, reached by `dlopen` for the
//! reasons that module states. [`protocol`] is the second — generated at build
//! time by `crcbl-wl-scanner` from the vendored XML. [`xkb`] applies the same
//! test to libxkbcommon and reaches the same answer, for reasons written out
//! there.
//!
//! # What is in this backend
//!
//! P0.5a landed the window lifecycle: connect, bind `wl_compositor` /
//! `xdg_wm_base` / `wl_output`, create `wl_surface` + `xdg_surface` +
//! `xdg_toplevel`, the configure/ack handshake, title, size constraints,
//! windowed ↔ borderless, the close request, and monitor enumeration.
//!
//! P0.5b added everything downstream of `wl_seat`:
//!
//! | Protocol | What it gives the engine |
//! | --- | --- |
//! | `wl_seat` / `wl_pointer` / `wl_keyboard` | [`ShellEvent::Key`], [`PointerMotion`](ShellEvent::PointerMotion), [`Button`](ShellEvent::Button), [`Wheel`](ShellEvent::Wheel), [`PointerFocus`](ShellEvent::PointerFocus), [`Focus`](ShellEvent::Focus), [`TextCommit`](ShellEvent::TextCommit) |
//! | `pointer-constraints-v1` | [`PointerMode::Locked`] and [`PointerMode::Confined`] |
//! | `relative-pointer-v1` | `raw_delta` — unaccelerated aim input |
//! | `fractional-scale-v1` + `wp_viewporter` | non-integer [`WindowConfiguration::scale_factor`] |
//! | `xdg-output-v1` | [`MonitorInfo::bounds`] that means something above scale 1 |
//! | `xdg-decoration-v1` | server-side title bars where the compositor does them |
//!
//! P0.5c added `wl_data_device_manager` and the three interfaces under it:
//!
//! | Protocol | What it gives the engine |
//! | --- | --- |
//! | `wl_data_device` + `wl_data_offer` | [`Shell::clipboard_request`] → [`ClipboardData`](ShellEvent::ClipboardData), and drops → [`DroppedFile`](ShellEvent::DroppedFile) |
//! | `wl_data_source` | [`Shell::clipboard_offer`] — we own the selection and produce the bytes on demand |
//!
//! Panels came with `wlr-layer-shell`:
//!
//! | Protocol | What it gives the engine |
//! | --- | --- |
//! | `zwlr_layer_shell_v1` + `zwlr_layer_surface_v1` | [`WindowRole::Panel`] — see [`layer`] |
//! | `xdg_popup` + `xdg_positioner` | [`WindowRole::Popup`] — see [`popup`] |
//!
//! And input methods with `text-input-v3`:
//!
//! | Protocol | What it gives the engine |
//! | --- | --- |
//! | `zwp_text_input_v3` | [`TextPreedit`](ShellEvent::TextPreedit) and composed [`TextCommit`](ShellEvent::TextCommit), for a window that named a field with [`Shell::set_text_input`] — see [`text_input`] |
//!
//! And a window's input region with core `wl_surface.set_input_region` — see
//! [`region`] and [`Shell::set_input_region`] — and frame pacing with core
//! `wl_surface.frame` — see [`frame`] and [`Shell::request_frame`].
//!
//! Still deliberately absent: touch, tablet, the *primary*
//! selection (`wp_primary_selection_v1` — middle-click paste, which the seam
//! has no vocabulary for) and starting a drag from one of our own windows. That
//! last one is a real gap and is stated as one: the destination half is here,
//! the origin half needs a seam request and a drag icon, and an icon is a
//! surface with a buffer, which is the renderer's. [`ShellCaps`] reflects all of
//! this exactly — see [`WaylandShell::caps`].
//!
//! # What a real compositor does that `HeadlessShell` does not model
//!
//! Findings from the nested-sway suite, in the order they cost time:
//!
//! 1. **The first configure usually carries no size.** `xdg-shell` says the
//!    compositor answers the initial commit with an `xdg_surface.configure`,
//!    and that a `0 × 0` in the accompanying `xdg_toplevel.configure` means
//!    "you choose". [`HeadlessShell`](crate::HeadlessShell) always dictates a
//!    size. Both shapes satisfy the seam's contract, but a backend has to
//!    supply the fallback, and this one falls back to
//!    [`WindowDesc::size`](crate::WindowDesc::size) scaled by the current
//!    factor.
//! 2. **Size arrives before scale.** A window's integer scale comes from
//!    `wl_surface.enter`, which a compositor only sends once the surface is
//!    *mapped* — and mapping requires a buffer. So the first configure is
//!    necessarily at scale 1.0 and the true scale arrives later as a
//!    [`ShellEvent::ScaleFactorChanged`]. `fractional-scale-v1` improves on
//!    this but does not fix it: `wp_fractional_scale_v1.preferred_scale` is
//!    also only sent for a mapped surface.
//! 3. **Configures arrive in two messages and take effect on the third.**
//!    `xdg_toplevel.configure` carries the size and the states,
//!    `xdg_surface.configure` carries the serial and means "that is the whole
//!    update", and `ack_configure` + `commit` is the reply. This backend
//!    accumulates and only publishes a [`WindowConfiguration`] on the
//!    `xdg_surface.configure`, which is what keeps a consumer from ever seeing
//!    a size without its states.
//! 4. **Configured is not the same as managed.** A surface is mapped exactly
//!    while it has a *buffer*, and an unmapped `xdg_toplevel` gets its one
//!    initial configure and nothing else ever again: no compositor-chosen
//!    geometry, no answer to `set_fullscreen`, no entry in the window
//!    manager's tree, **and no `wl_pointer.enter` or `wl_keyboard.enter`** —
//!    an unmapped surface cannot receive input, because there is nothing on
//!    screen to point at. Attaching a buffer is the renderer's job, so this
//!    backend cannot map a window on its own, by design; see [`e2e`].
//! 5. **A seat can have no devices at all.** `wl_seat.capabilities` is `0` on
//!    a headless compositor and changes at runtime when a device is plugged
//!    in. There is no "the keyboard" — there is whatever the seat currently
//!    has, and it can go away mid-session.
//! 6. **The clipboard is focus-gated and arrives late.**
//!    `wl_data_device.selection` is delivered *only* to the client that has
//!    keyboard focus on that seat, and again whenever focus arrives — so a
//!    client's knowledge of the clipboard is acquired on focus and goes stale
//!    when focus leaves, and a background window cannot read the clipboard at
//!    all. This is what [`Shell::clipboard_readable`] reports and why
//!    [`clipboard_request`](Shell::clipboard_request) *holds* a read it cannot
//!    yet answer: answering "empty" would be indistinguishable from an empty
//!    clipboard, and the end-to-end suite proved the cost of that by needing a
//!    retry loop no editor would contain.
//!
//!    A corollary that only showed up once "held, not empty" was enforced:
//!    **claiming the selection invalidates what we know until the compositor
//!    echoes it back.** Between `set_selection` and the `selection` event it
//!    provokes, this client's own offer describes the clipboard it *replaced*
//!    — so pasting one's own copy answered `Empty` until
//!    [`clipboard_offer`](Shell::clipboard_offer) started clearing
//!    `selection_seen` too.
//! 7. **Claiming the selection needs an input serial.** A client that has
//!    received no input on a seat cannot take the clipboard, because
//!    `set_selection` quotes the serial of the event that caused it and a
//!    compositor checks it. That is a *feature* — it is what stops a background
//!    process stealing the clipboard — and it means
//!    [`clipboard_offer`](Shell::clipboard_offer) can legitimately fail on a
//!    window nobody has touched.
//!
//! # Decision: the shell synthesizes key repeats
//!
//! `wl_keyboard.repeat_info` hands the client a rate and a delay and **no
//! repeat events**: on Wayland, generating them is the client's job by
//! protocol design. The choice is therefore where in the client they are
//! generated, and this backend does it, marking every one
//! [`repeat: true`](ShellEvent::Key).
//!
//! The case for pushing it up to `crcbl-input`'s action layer is
//! real — a shell that fabricates edges can confuse hold-pattern detection —
//! and it loses on three counts:
//!
//! * **The seam already decided.** [`ShellEvent::Key`] carries `repeat`, and
//!   its documentation is explicit that filtering repeats at the source breaks
//!   text fields while dropping the flag breaks jump buttons, "so the fact is
//!   carried and the consumer decides".
//!   [`HeadlessShell::key_repeat`](crate::HeadlessShell::key_repeat) already
//!   produces them. A Wayland backend that never did would make the flag dead
//!   on the only real platform and `HeadlessShell` a model of nothing.
//! * **Hold patterns are protected by construction, not by luck.** A repeat is
//!   `repeat: true` and never `Released`, so `hold(400ms)` — which measures
//!   press edge to release edge — cannot see one. A pattern evaluator that
//!   keys on `repeat == false` is correct with no coordination.
//! * **Nobody else can do it better.** The timer has to live next to the
//!   socket. Repeats here are scheduled on `CLOCK_MONOTONIC` and stamped with
//!   the instant they were *due*, not the instant the queue was drained, so a
//!   16 ms frame does not quantize them — the exact property
//!   [`event`](crate::event) says timestamps exist for.
//!   [`wait_events`](Shell::wait_events) shortens its timeout to the next
//!   repeat, so an editor idling at zero frames per second still repeats.
//!
//! Guards, because a fabricated event stream needs them: no repeat is
//! generated for a key XKB says does not repeat (modifiers, Caps Lock); a
//! repeat stops on release, on focus loss, on the pointer's seat losing its
//! keyboard, and on a keymap change; and a run that falls more than four
//! intervals behind resynchronises instead of emitting the backlog.

mod cursor_shape;
mod data;
mod data_device;
mod dmabuf;
mod fd;
pub mod ffi;
mod frame;
mod input;
mod layer;
mod popup;
pub mod protocol;
mod region;
mod text_input;

/// The evdev table and libxkbcommon, which are Linux facts rather than Wayland
/// ones and are therefore shared with the X11 backend.
///
/// Re-exported under this module's own namespace so that everything below
/// spells them `keymap::` and `xkb::` the way it always did; see
/// [`crate::linux`] for why they live one level up.
pub(crate) use crate::linux::{keymap, xkb};

/// Test-only: maps a window's surface with a stand-in buffer, and drives real
/// input through virtual devices.
///
/// Behind the `wayland-e2e` feature because it is scaffolding, not shell — see
/// the module's own docs for why the end-to-end suite cannot do without it and
/// why the shipping backend must not contain it.
#[cfg(feature = "wayland-e2e")]
pub mod e2e;

use core::ffi::{CStr, c_int, c_void};
use core::ptr::{self, NonNull};
use core::time::Duration;
use std::collections::VecDeque;
use std::ffi::CString;

use crcbl_core::input::{DeviceId, Keysym, Modifiers, ScrollDelta};
use crcbl_core::{EventTime, KeyCode, Pool, SurfaceTarget};

use crate::{
    ClipboardContent, ClipboardOffer, ClipboardRequestId, CloseReply, CursorIcon, DisplayMode,
    LogicalSize, MimeType, MonitorId, MonitorInfo, PhysicalPoint, PhysicalRect, PointerMode,
    ReceivedMime, Shell, ShellBackend, ShellCaps, ShellError, ShellEvent, SizeConstraints,
    TextPurpose, WindowConfiguration, WindowDesc, WindowId, WindowRole, WindowState,
};

use data::{Delivery, HeldRead, Resolution, Transfer};
use ffi::{Lib, WlArgument, WlDisplay, WlMessage, WlProxy};
use protocol::cursor_shape::{wp_cursor_shape_device_v1, wp_cursor_shape_manager_v1};
use protocol::fractional_scale::{wp_fractional_scale_manager_v1, wp_fractional_scale_v1};
use protocol::layer_shell::{zwlr_layer_shell_v1, zwlr_layer_surface_v1};
use protocol::linux_dmabuf::{zwp_linux_dmabuf_feedback_v1, zwp_linux_dmabuf_v1};
use protocol::pointer_constraints::{zwp_locked_pointer_v1, zwp_pointer_constraints_v1};
use protocol::relative_pointer::{zwp_relative_pointer_manager_v1, zwp_relative_pointer_v1};
use protocol::text_input::zwp_text_input_manager_v3;
use protocol::viewporter::{wp_viewport, wp_viewporter};
use protocol::wayland::{
    wl_callback, wl_compositor, wl_data_device, wl_data_device_manager, wl_data_offer,
    wl_data_source, wl_keyboard, wl_output, wl_pointer, wl_registry, wl_seat, wl_surface,
};
use protocol::xdg_decoration::{zxdg_decoration_manager_v1, zxdg_toplevel_decoration_v1};
use protocol::xdg_output::{zxdg_output_manager_v1, zxdg_output_v1};
use protocol::xdg_shell::{xdg_popup, xdg_surface, xdg_toplevel, xdg_wm_base};

/// Versions this backend binds globals at.
///
/// Capped at what the code actually implements, never at what the compositor
/// offers: binding a higher version means promising to handle events this build
/// has never seen. `wl_output` 4 is the lowest version that reports
/// [`wl_output.name`](protocol::wayland::wl_output), which is the only stable
/// identifier a monitor has.
const COMPOSITOR_VERSION: u32 = 4;
/// See [`COMPOSITOR_VERSION`]. `xdg_wm_base` 1 is all the window lifecycle
/// needs, and 3 adds `xdg_popup.reposition`, which
/// [`ShellCaps::POPUP_REPOSITION`] reports; 4 and 5 add `configure_bounds` and
/// `wm_capabilities`, which this backend does not act on. Neither 2 nor 3
/// sends an event a client did not ask for.
const WM_BASE_VERSION: u32 = 3;
/// See [`COMPOSITOR_VERSION`].
const OUTPUT_VERSION: u32 = 4;
/// `wl_seat` 8 is the lowest version whose `wl_pointer` sends
/// [`axis_value120`](protocol::wayland::wl_pointer) — the high-resolution wheel
/// event a smooth-scrolling UI needs, and the reason not to stop at 5.
///
/// 9 adds `axis_relative_direction` (which physical direction produced an
/// already-inverted value — informational) and 10 adds
/// `key_state.repeated`, a compositor-generated repeat. Neither is acted on
/// here, and binding 10 in particular would give this backend two repeat
/// sources with no way to reconcile them — see the [module docs](self).
const SEAT_VERSION: u32 = 8;
/// `zxdg_output_manager_v1` 2 deprecates `name`/`description` in favour of
/// `wl_output` 4's, and 3 stops sending `zxdg_output_v1.done` in favour of
/// `wl_output.done`. This backend settles outputs on `wl_output.done` either
/// way, so 3 is free.
const XDG_OUTPUT_VERSION: u32 = 3;
/// `zxdg_decoration_manager_v1` 1 is the whole protocol; 2 only adds an error
/// code for a case this backend cannot reach (it never orphans a decoration).
const DECORATION_VERSION: u32 = 1;
/// `wl_data_device_manager` 3 is the version that has drag-and-drop actions:
/// `wl_data_offer.set_actions`/`finish` and `wl_data_source.set_actions`. A
/// version-1 or -2 device works for the clipboard and negotiates no action at
/// all, which is why every `set_actions` below is version-guarded.
///
/// 4 adds only `wl_data_device_manager.release`, a destructor for the manager
/// itself. This backend destroys the manager proxy client-side at shutdown, on
/// a connection that is being closed in the same breath, so there is nothing to
/// tell the compositor and nothing to gain — see [`COMPOSITOR_VERSION`] for the
/// rule about binding versions the code does not implement.
const DATA_DEVICE_VERSION: u32 = 3;
/// `wp_fractional_scale_v1` reports scale as a fraction of this.
const FRACTIONAL_SCALE_DENOMINATOR: f64 = 120.0;
/// The longest [`wait_events`](Shell::wait_events) may sleep while a clipboard
/// transfer is in flight.
///
/// The descriptors are in the poll, so a peer that writes wakes the wait
/// immediately; this bounds only the case where nothing happens at all, so that
/// [`fd::TIMEOUT`] is reached instead of slept through.
const TRANSFER_POLL: Duration = Duration::from_millis(50);

// ---------------------------------------------------------------------------
// Timestamps
// ---------------------------------------------------------------------------

/// Converts Wayland's `CLOCK_MONOTONIC` milliseconds onto the engine epoch.
///
/// [`EventTime`] requires "a duration measured from the same origin as the
/// [`TimeSource`](crcbl_core::time::TimeSource) driving
/// [`FrameClock::update`](crcbl_core::FrameClock::update)". Wayland gives a
/// **32-bit** millisecond counter sampled from `CLOCK_MONOTONIC`, which is a
/// different origin *and* wraps every 49.7 days, so a backend that forwards it
/// produces an input pipeline that silently breaks after a month and a half of
/// uptime.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct TimeBase {
    /// `CLOCK_MONOTONIC` nanoseconds at the engine epoch.
    epoch_nanos: u64,
}

impl TimeBase {
    /// An epoch of "now", which is the shell's creation.
    fn now() -> Self {
        Self {
            epoch_nanos: ffi::monotonic_nanos(),
        }
    }

    /// Moves the epoch so that this instant reads as `elapsed`.
    ///
    /// See [`WaylandShell::align_event_clock`].
    fn align(&mut self, elapsed: Duration) {
        let now = ffi::monotonic_nanos();
        self.epoch_nanos =
            now.saturating_sub(u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX));
    }

    /// Widens a 32-bit Wayland timestamp and rebases it.
    ///
    /// Pure so it can be tested without a compositor, which matters because the
    /// wrap is unobservable in any session shorter than seven weeks.
    ///
    /// `wayland_millis` is a raw `u32` off the wire, carried by every pointer
    /// and keyboard event and validated by nobody, so the widening is written as
    /// "pick the nearest candidate that exists" rather than as an adjustment.
    /// The candidate one wrap *below* the current one only exists on a machine
    /// that has been up for 49.7 days; before that `now_millis` has no high bits
    /// and subtracting a wrap underflows — which is what the earlier
    /// `full -= WRAP` did, panicking in debug and producing a timestamp around
    /// 1.8 × 10¹⁹ ms in release for any event whose stamp merely ran ahead of
    /// our sample.
    fn rebase(epoch_nanos: u64, now_nanos: u64, wayland_millis: u32) -> EventTime {
        const WRAP: u64 = 1 << 32;
        let now_millis = now_nanos / 1_000_000;
        // An event is always within a few milliseconds of the present, so of
        // the reconstructions that are representable at all, the one nearest
        // `now` is the right one.
        let current = (now_millis & !(WRAP - 1)) | u64::from(wayland_millis);
        let full = [
            current.checked_sub(WRAP),
            Some(current),
            current.checked_add(WRAP),
        ]
        .into_iter()
        .flatten()
        .min_by_key(|candidate| candidate.abs_diff(now_millis))
        .expect("the current wrap is always a candidate");
        let epoch_millis = epoch_nanos / 1_000_000;
        EventTime::from_millis(full.saturating_sub(epoch_millis))
    }

    /// This base applied to a compositor millisecond timestamp.
    ///
    /// What every `wl_pointer` and `wl_keyboard` event goes through.
    fn event_time(self, wayland_millis: u32) -> EventTime {
        Self::rebase(self.epoch_nanos, ffi::monotonic_nanos(), wayland_millis)
    }

    /// This base applied to a 64-bit `CLOCK_MONOTONIC` microsecond timestamp.
    ///
    /// `zwp_relative_pointer_v1.relative_motion` carries one, split across two
    /// `uint`s. It needs no wrap handling at all — 64 bits of microseconds is
    /// half a million years — which is why relative motion is the more accurate
    /// of the two clocks a pointer event can arrive on, and why a merged
    /// motion event prefers it.
    fn event_time_micros(self, micros: u64) -> EventTime {
        EventTime::from_micros(micros.saturating_sub(self.epoch_nanos / 1_000))
    }

    /// The current instant, on the engine epoch.
    ///
    /// For the events a compositor sends with **no timestamp at all**:
    /// `wl_pointer.enter` and `wl_pointer.leave` carry a serial and a position
    /// and no time, and neither does a focus change synthesized because a seat
    /// lost its pointer. [`EventTime`] states the rule for exactly this case —
    /// "it stamps the event with the *current* time rather than
    /// [`EventTime::ZERO`], because a zero timestamp reads as 'this happened at
    /// process start' to every consumer downstream".
    fn event_time_now(self) -> EventTime {
        self.event_time_nanos(ffi::monotonic_nanos())
    }

    /// This base applied to a raw `CLOCK_MONOTONIC` nanosecond reading.
    ///
    /// Used for synthesized key repeats, which are stamped with the instant
    /// they were *due* rather than the instant the queue happened to be
    /// drained.
    fn event_time_nanos(self, nanos: u64) -> EventTime {
        EventTime::from_duration(Duration::from_nanos(nanos.saturating_sub(self.epoch_nanos)))
    }
}

// ---------------------------------------------------------------------------
// The dispatcher's side of the world
// ---------------------------------------------------------------------------

/// Which interface a proxy we attached a dispatcher to belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ObjectKind {
    Registry,
    WmBase,
    Output,
    XdgOutput,
    Surface,
    XdgSurface,
    XdgToplevel,
    XdgPopup,
    LayerSurface,
    Decoration,
    FractionalScale,
    /// A `wl_callback` from `wl_surface.frame`; see [`frame`].
    FrameCallback,
    /// The default `zwp_linux_dmabuf_feedback_v1`; see [`dmabuf`].
    DmabufFeedback,
    Seat,
    Pointer,
    Keyboard,
    RelativePointer,
    TextInput,
    DataDevice,
    DataOffer,
    DataSource,
    /// A proxy whose events we deliberately do not read.
    ///
    /// Attaching a do-nothing dispatcher rather than leaving the proxy bare:
    /// libwayland logs a warning for every event delivered to a listener-less
    /// proxy, which buries the compositor log the e2e harness prints on failure.
    Ignored,
}

/// One decoded event, with every borrow already copied out.
///
/// The dispatcher runs *inside* libwayland, where strings and arrays point into
/// closure storage that dies when it returns. Copying here rather than
/// borrowing is what lets [`Sink`] be a plain queue that the pump drains
/// afterwards, with no reentrancy and no lifetimes crossing the FFI boundary.
#[derive(Clone, Debug)]
enum RawEvent {
    Global {
        name: u32,
        interface: String,
        version: u32,
    },
    GlobalRemove {
        name: u32,
    },
    Ping {
        serial: u32,
    },
    OutputGeometry {
        output: usize,
        x: i32,
        y: i32,
    },
    OutputMode {
        output: usize,
        flags: u32,
        width: i32,
        height: i32,
        refresh: i32,
    },
    OutputScale {
        output: usize,
        factor: i32,
    },
    OutputName {
        output: usize,
        name: String,
    },
    OutputDone {
        output: usize,
    },
    XdgOutputPosition {
        xdg_output: usize,
        x: i32,
        y: i32,
    },
    XdgOutputSize {
        xdg_output: usize,
        width: i32,
        height: i32,
    },
    SurfaceEnter {
        surface: usize,
        output: usize,
    },
    SurfaceLeave {
        surface: usize,
        output: usize,
    },
    FrameDone {
        callback: usize,
    },
    XdgSurfaceConfigure {
        xdg_surface: usize,
        serial: u32,
    },
    ToplevelConfigure {
        toplevel: usize,
        width: i32,
        height: i32,
        states: Vec<u32>,
    },
    ToplevelClose {
        toplevel: usize,
    },
    /// The size and place the compositor gave a popup; completed by the
    /// `xdg_surface.configure` that follows, as a toplevel's is.
    PopupConfigure {
        popup: usize,
        width: i32,
        height: i32,
    },
    /// The compositor dismissed a popup: a click outside a grabbing one, or its
    /// parent going.
    PopupDone {
        popup: usize,
    },
    LayerConfigure {
        layer_surface: usize,
        serial: u32,
        width: u32,
        height: u32,
    },
    /// The compositor will not show the panel again: its output went, or the
    /// user removed it.
    LayerClosed {
        layer_surface: usize,
    },
    DecorationConfigure {
        decoration: usize,
        mode: u32,
    },
    PreferredScale {
        object: usize,
        scale: u32,
    },
    SeatCapabilities {
        seat: usize,
        capabilities: u32,
    },
    PointerEnter {
        pointer: usize,
        serial: u32,
        surface: usize,
        x: i32,
        y: i32,
    },
    PointerLeave {
        pointer: usize,
        serial: u32,
        surface: usize,
    },
    PointerMotion {
        pointer: usize,
        time: u32,
        x: i32,
        y: i32,
    },
    PointerButton {
        pointer: usize,
        serial: u32,
        time: u32,
        button: u32,
        state: u32,
    },
    PointerAxis {
        pointer: usize,
        time: u32,
        axis: u32,
        value: i32,
    },
    PointerAxisSource {
        pointer: usize,
        source: u32,
    },
    PointerAxisDiscrete {
        pointer: usize,
        axis: u32,
        discrete: i32,
    },
    PointerAxisValue120 {
        pointer: usize,
        axis: u32,
        value120: i32,
    },
    PointerFrame {
        pointer: usize,
    },
    RelativeMotion {
        relative: usize,
        utime_hi: u32,
        utime_lo: u32,
        dx_unaccel: i32,
        dy_unaccel: i32,
    },
    TextInput {
        text_input: usize,
        event: text_input::Event,
    },
    DmabufMainDevice {
        feedback: usize,
        device: Option<u64>,
    },
    DmabufDone {
        feedback: usize,
    },
    KeyboardKeymap {
        keyboard: usize,
        format: u32,
        fd: i32,
        size: u32,
    },
    KeyboardEnter {
        keyboard: usize,
        serial: u32,
        surface: usize,
    },
    KeyboardLeave {
        keyboard: usize,
        serial: u32,
        surface: usize,
    },
    KeyboardKey {
        keyboard: usize,
        serial: u32,
        time: u32,
        key: u32,
        state: u32,
    },
    KeyboardModifiers {
        keyboard: usize,
        serial: u32,
        depressed: u32,
        latched: u32,
        locked: u32,
        group: u32,
    },
    KeyboardRepeatInfo {
        keyboard: usize,
        rate: i32,
        delay: i32,
    },
    /// A `wl_data_offer` has been created. The dispatcher has already attached
    /// itself to it; see [`Sink::watch`].
    DataOffer {
        device: usize,
        offer: usize,
    },
    /// One `wl_data_offer.offer` — a mime type the peer can produce.
    OfferMime {
        offer: usize,
        mime: String,
    },
    /// The clipboard changed. `offer` is zero when it was cleared.
    Selection {
        device: usize,
        offer: usize,
    },
    DragEnter {
        device: usize,
        serial: u32,
        surface: usize,
        x: i32,
        y: i32,
        offer: usize,
    },
    DragLeave {
        device: usize,
    },
    DragMotion {
        device: usize,
        time: u32,
        x: i32,
        y: i32,
    },
    DragDrop {
        device: usize,
    },
    /// A peer wants the bytes behind a format we published.
    ///
    /// **Carries an owned file descriptor.** Every path out of
    /// [`WaylandShell::process_data`] either adopts it or closes it; a leak
    /// here is one descriptor per paste, in a process that may run for days.
    SourceSend {
        source: usize,
        mime: String,
        fd: i32,
    },
    /// Another client took the selection, so our source is dead.
    SourceCancelled {
        source: usize,
    },
}

/// Everything the C dispatcher touches.
///
/// Reached **only** through a raw pointer, never through a Rust reference held
/// by [`WaylandShell`]. That is deliberate: the dispatcher runs synchronously
/// inside `wl_display_dispatch_pending`, so if the shell held a live `&mut` to
/// this allocation at the same time the two would alias. Keeping the raw
/// pointer as the sole root means the shell's `&mut Sink` and the dispatcher's
/// exist at strictly disjoint times.
#[derive(Debug)]
struct Sink {
    /// libwayland, so that [`watch`](Self::watch) can be called from inside the
    /// dispatcher — see that method for the event that forces it.
    lib: &'static Lib,
    /// This allocation's own address, as it came out of `Box::into_raw`.
    ///
    /// The pointer every `wl_proxy_add_dispatcher` is given, and the reason it
    /// is a stored field rather than a `ptr::from_mut(self)` at the call site:
    /// `self` there is a transient reborrow — of `Conn::sink()`'s `&mut *self.sink`,
    /// or of the dispatcher's own `&mut *user_data` — and every *later*
    /// `Conn::sink()` re-derives from the raw root, which invalidates that
    /// reborrow and everything descended from it. libwayland would then be
    /// holding pointers whose provenance is dead, and the dispatcher's
    /// `&mut *user_data` would be undefined behaviour from the second `watch`
    /// onward. Handing over the root itself is what makes each dispatcher entry
    /// a fresh, valid derivation.
    root: *mut Sink,
    /// Proxies we have attached the dispatcher to, and what they are.
    objects: Vec<(usize, ObjectKind)>,
    /// Decoded events awaiting the pump.
    events: Vec<RawEvent>,
}

impl Sink {
    /// Allocates a sink and records its own address.
    ///
    /// Returns the raw pointer rather than the value because [`root`](Self::root)
    /// can only be filled in once the allocation has an address — which is the
    /// whole point of the field.
    fn boxed(lib: &'static Lib) -> *mut Sink {
        let raw = Box::into_raw(Box::new(Self {
            lib,
            root: ptr::null_mut(),
            objects: Vec::new(),
            events: Vec::new(),
        }));
        // SAFETY: `raw` was just returned by `Box::into_raw`, so it is live,
        // aligned and uniquely owned; nothing else refers to the allocation
        // yet.
        unsafe { (*raw).root = raw };
        raw
    }

    fn kind_of(&self, proxy: usize) -> Option<ObjectKind> {
        self.objects
            .iter()
            .find(|(candidate, _)| *candidate == proxy)
            .map(|(_, kind)| *kind)
    }

    fn forget(&mut self, proxy: usize) {
        self.objects.retain(|(candidate, _)| *candidate != proxy);
    }

    /// Starts routing `proxy`'s events, recording what it is.
    ///
    /// # Why this is on the sink rather than only on [`Conn`]
    ///
    /// Almost every object this backend owns is created by a request *it*
    /// sends, so the dispatcher can be attached from ordinary code with the
    /// connection in hand. `wl_data_offer` is the exception: the **compositor**
    /// creates it, with `wl_data_device.data_offer`, and then immediately sends
    /// the `wl_data_offer.offer` events listing its mime types — all inside the
    /// same `wl_display_dispatch_pending`. An offer whose dispatcher were
    /// attached afterwards, from `process_raw`, would have missed every one of
    /// them, and a clipboard offer with no mime types is a clipboard that is
    /// always empty.
    ///
    /// So the dispatcher attaches to the new object from inside itself, which
    /// is ordinary libwayland usage — `wl_proxy_add_dispatcher` is not
    /// reentrant into the client — and the reason the sink holds [`Lib`] at
    /// all.
    fn watch(&mut self, proxy: *mut WlProxy, kind: ObjectKind) {
        if proxy.is_null() {
            return;
        }
        self.objects.push((proxy as usize, kind));
        // SAFETY: `proxy` is live on this connection and has no dispatcher yet;
        // `dispatch` matches libwayland's `wl_dispatcher_func_t`; and the
        // `*mut Sink` handed over is `self.root` — the pointer `Box::into_raw`
        // produced, *not* a reborrow of the `&mut self` this method holds, so it
        // stays valid across every later `Conn::sink()`. The allocation outlives
        // every proxy, because `WaylandShell::drop` destroys them all before
        // freeing it.
        unsafe {
            (self.lib.proxy_add_dispatcher)(proxy, dispatch, self.root.cast(), ptr::null_mut());
        }
    }
}

/// libwayland's generic event dispatcher, for every object this backend owns.
///
/// One function rather than a listener struct per interface: `wl_proxy_add_dispatcher`
/// hands over the opcode and the raw argument array, so the *only* per-interface
/// code is the generated decoder. A listener struct would instead need one
/// `extern "C" fn` per event with a hand-written C signature — dozens of
/// hand-transcribed ABIs, each silently wrong if it drifts from the XML, which
/// is exactly what the generator exists to avoid.
unsafe extern "C" fn dispatch(
    user_data: *const c_void,
    target: *mut c_void,
    opcode: u32,
    _message: *const WlMessage,
    args: *mut WlArgument,
) -> c_int {
    // SAFETY: `user_data` is `Sink::root` — the pointer `Box::into_raw`
    // produced in `Sink::boxed`, which every `watch` hands over verbatim and
    // which stays live until `WaylandShell::drop`. Deriving a `&mut` from the
    // allocation's root here is what keeps it valid across the shell's own
    // `Conn::sink()` reborrows. No Rust reference to the allocation is alive at
    // this point: the shell only takes one outside the
    // `dispatch_pending`/`roundtrip`/`read_events` calls that can reach this
    // function.
    let sink = unsafe { &mut *user_data.cast::<Sink>().cast_mut() };
    let proxy = target as usize;
    let Some(kind) = sink.kind_of(proxy) else {
        // An event for an object we already destroyed. libwayland can deliver
        // one that was in flight when the destructor was sent; dropping it is
        // the documented behaviour.
        return 0;
    };
    // SAFETY: libwayland always hands the dispatcher its closure's argument
    // array, which has one slot per signature character and lives for the
    // duration of this call. Borrowing it here rather than passing the raw
    // pointer is what pins the decoders' `'a` to this stack frame: with a raw
    // pointer the lifetime is inferred, and a `&CStr` field could outlive the
    // closure storage it points into.
    let args: &WlArgument = unsafe { &*args.cast_const() };

    // SAFETY (all decoders): `kind` records which interface this proxy was
    // created as, so `args` is that interface's argument array for `opcode` —
    // which is exactly the dispatcher contract — and every borrow is copied out
    // before this function returns, which is the lifetime the decoders
    // document.
    match kind {
        ObjectKind::Ignored => {}
        ObjectKind::Registry => {
            if let Some(event) = unsafe { wl_registry::decode_event(opcode, args) } {
                sink.events.push(match event {
                    wl_registry::Event::Global {
                        name,
                        interface,
                        version,
                    } => RawEvent::Global {
                        name,
                        interface: interface.to_string_lossy().into_owned(),
                        version,
                    },
                    wl_registry::Event::GlobalRemove { name } => RawEvent::GlobalRemove { name },
                });
            }
        }
        ObjectKind::WmBase => {
            // SAFETY: see the note above the `match`.
            if let Some(xdg_wm_base::Event::Ping { serial }) =
                unsafe { xdg_wm_base::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::Ping { serial });
            }
        }
        ObjectKind::Output => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { wl_output::decode_event(opcode, args) } {
                let raw = match event {
                    wl_output::Event::Geometry { x, y, .. } => Some(RawEvent::OutputGeometry {
                        output: proxy,
                        x,
                        y,
                    }),
                    wl_output::Event::Mode {
                        flags,
                        width,
                        height,
                        refresh,
                    } => Some(RawEvent::OutputMode {
                        output: proxy,
                        flags,
                        width,
                        height,
                        refresh,
                    }),
                    wl_output::Event::Scale { factor } => Some(RawEvent::OutputScale {
                        output: proxy,
                        factor,
                    }),
                    wl_output::Event::Name { name } => Some(RawEvent::OutputName {
                        output: proxy,
                        name: name.to_string_lossy().into_owned(),
                    }),
                    wl_output::Event::Done => Some(RawEvent::OutputDone { output: proxy }),
                    wl_output::Event::Description { .. } => None,
                };
                sink.events.extend(raw);
            }
        }
        ObjectKind::XdgOutput => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { zxdg_output_v1::decode_event(opcode, args) } {
                let raw = match event {
                    zxdg_output_v1::Event::LogicalPosition { x, y } => {
                        Some(RawEvent::XdgOutputPosition {
                            xdg_output: proxy,
                            x,
                            y,
                        })
                    }
                    zxdg_output_v1::Event::LogicalSize { width, height } => {
                        Some(RawEvent::XdgOutputSize {
                            xdg_output: proxy,
                            width,
                            height,
                        })
                    }
                    // `done` is deprecated from version 3: `wl_output.done` is
                    // the atomic signal, and this backend settles on that one
                    // for every version so the two paths cannot disagree.
                    _ => None,
                };
                sink.events.extend(raw);
            }
        }
        ObjectKind::Surface => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { wl_surface::decode_event(opcode, args) } {
                let raw = match event {
                    wl_surface::Event::Enter { output } => Some(RawEvent::SurfaceEnter {
                        surface: proxy,
                        output: output as usize,
                    }),
                    wl_surface::Event::Leave { output } => Some(RawEvent::SurfaceLeave {
                        surface: proxy,
                        output: output as usize,
                    }),
                    // `preferred_buffer_scale`/`preferred_buffer_transform` are
                    // version 6; this backend binds 4 and never sees them.
                    _ => None,
                };
                sink.events.extend(raw);
            }
        }
        ObjectKind::DmabufFeedback => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { zwp_linux_dmabuf_feedback_v1::decode_event(opcode, args) }
            {
                sink.events.extend(dmabuf::decode_event(proxy, event));
            }
        }
        ObjectKind::FrameCallback => {
            // SAFETY: see the note above the `match`.
            if let Some(wl_callback::Event::Done { .. }) =
                unsafe { wl_callback::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::FrameDone { callback: proxy });
            }
        }
        ObjectKind::XdgSurface => {
            // SAFETY: see the note above the `match`.
            if let Some(xdg_surface::Event::Configure { serial }) =
                unsafe { xdg_surface::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::XdgSurfaceConfigure {
                    xdg_surface: proxy,
                    serial,
                });
            }
        }
        ObjectKind::XdgToplevel => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { xdg_toplevel::decode_event(opcode, args) } {
                let raw = match event {
                    xdg_toplevel::Event::Configure {
                        width,
                        height,
                        states,
                    } => Some(RawEvent::ToplevelConfigure {
                        toplevel: proxy,
                        width,
                        height,
                        states: decode_state_array(states),
                    }),
                    xdg_toplevel::Event::Close => Some(RawEvent::ToplevelClose { toplevel: proxy }),
                    _ => None,
                };
                sink.events.extend(raw);
            }
        }
        ObjectKind::XdgPopup => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { xdg_popup::decode_event(opcode, args) } {
                let raw = match event {
                    xdg_popup::Event::Configure { width, height, .. } => {
                        Some(RawEvent::PopupConfigure {
                            popup: proxy,
                            width,
                            height,
                        })
                    }
                    xdg_popup::Event::PopupDone => Some(RawEvent::PopupDone { popup: proxy }),
                    // `repositioned` answers `xdg_popup.reposition` with the
                    // token it was sent; the configure that follows it is what
                    // carries the new geometry, so nothing waits on this.
                    _ => None,
                };
                sink.events.extend(raw);
            }
        }
        ObjectKind::LayerSurface => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { zwlr_layer_surface_v1::decode_event(opcode, args) } {
                sink.events.push(match event {
                    zwlr_layer_surface_v1::Event::Configure {
                        serial,
                        width,
                        height,
                    } => RawEvent::LayerConfigure {
                        layer_surface: proxy,
                        serial,
                        width,
                        height,
                    },
                    zwlr_layer_surface_v1::Event::Closed => RawEvent::LayerClosed {
                        layer_surface: proxy,
                    },
                });
            }
        }
        ObjectKind::Decoration => {
            // SAFETY: see the note above the `match`.
            if let Some(zxdg_toplevel_decoration_v1::Event::Configure { mode }) =
                unsafe { zxdg_toplevel_decoration_v1::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::DecorationConfigure {
                    decoration: proxy,
                    mode,
                });
            }
        }
        ObjectKind::FractionalScale => {
            // SAFETY: see the note above the `match`.
            if let Some(wp_fractional_scale_v1::Event::PreferredScale { scale }) =
                unsafe { wp_fractional_scale_v1::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::PreferredScale {
                    object: proxy,
                    scale,
                });
            }
        }
        ObjectKind::Seat => {
            // SAFETY: see the note above the `match`.
            if let Some(wl_seat::Event::Capabilities { capabilities }) =
                unsafe { wl_seat::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::SeatCapabilities {
                    seat: proxy,
                    capabilities,
                });
            }
        }
        ObjectKind::Pointer => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { wl_pointer::decode_event(opcode, args) } {
                sink.events.extend(decode_pointer(proxy, event));
            }
        }
        ObjectKind::Keyboard => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { wl_keyboard::decode_event(opcode, args) } {
                sink.events.extend(decode_keyboard(proxy, event));
            }
        }
        ObjectKind::DataDevice => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { wl_data_device::decode_event(opcode, args) } {
                // `data_offer` introduces an object the compositor created for
                // us, and its mime types follow immediately — so the dispatcher
                // has to be attached here rather than after the drain. See
                // `Sink::watch`.
                if let wl_data_device::Event::DataOffer { id } = event {
                    sink.watch(id, ObjectKind::DataOffer);
                }
                sink.events.extend(decode_data_device(proxy, event));
            }
        }
        ObjectKind::DataOffer => {
            // SAFETY: see the note above the `match`.
            if let Some(wl_data_offer::Event::Offer { mime_type }) =
                unsafe { wl_data_offer::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::OfferMime {
                    offer: proxy,
                    mime: mime_type.to_string_lossy().into_owned(),
                });
            }
            // `source_actions` and `action` report which drag action the
            // compositor settled on. This backend asks for `copy` and nothing
            // else, so there is no negotiation to observe.
        }
        ObjectKind::DataSource => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { wl_data_source::decode_event(opcode, args) } {
                let raw = match event {
                    wl_data_source::Event::Send { mime_type, fd } => Some(RawEvent::SourceSend {
                        source: proxy,
                        mime: mime_type.to_string_lossy().into_owned(),
                        fd,
                    }),
                    wl_data_source::Event::Cancelled => {
                        Some(RawEvent::SourceCancelled { source: proxy })
                    }
                    // `target`, `dnd_drop_performed`, `dnd_finished` and
                    // `action` are all drag-*source* events, and this backend
                    // starts no drags outside its own test scaffolding.
                    _ => None,
                };
                sink.events.extend(raw);
            }
        }
        ObjectKind::RelativePointer => {
            // SAFETY: see the note above the `match`.
            if let Some(zwp_relative_pointer_v1::Event::RelativeMotion {
                utime_hi,
                utime_lo,
                dx_unaccel,
                dy_unaccel,
                ..
            }) = unsafe { zwp_relative_pointer_v1::decode_event(opcode, args) }
            {
                sink.events.push(RawEvent::RelativeMotion {
                    relative: proxy,
                    utime_hi,
                    utime_lo,
                    dx_unaccel,
                    dy_unaccel,
                });
            }
        }
        ObjectKind::TextInput => {
            // SAFETY: see the note above the `match`.
            if let Some(event) = unsafe { text_input::decode(opcode, args) } {
                sink.events.push(RawEvent::TextInput {
                    text_input: proxy,
                    event,
                });
            }
        }
    }
    0
}

/// Splits `wl_pointer`'s ten events out of the dispatcher, purely so
/// [`dispatch`] stays readable.
fn decode_pointer(proxy: usize, event: wl_pointer::Event) -> Option<RawEvent> {
    Some(match event {
        wl_pointer::Event::Enter {
            serial,
            surface,
            surface_x,
            surface_y,
        } => RawEvent::PointerEnter {
            pointer: proxy,
            serial,
            surface: surface as usize,
            x: surface_x,
            y: surface_y,
        },
        wl_pointer::Event::Leave { serial, surface } => RawEvent::PointerLeave {
            pointer: proxy,
            serial,
            surface: surface as usize,
        },
        wl_pointer::Event::Motion {
            time,
            surface_x,
            surface_y,
        } => RawEvent::PointerMotion {
            pointer: proxy,
            time,
            x: surface_x,
            y: surface_y,
        },
        wl_pointer::Event::Button {
            serial,
            time,
            button,
            state,
        } => RawEvent::PointerButton {
            pointer: proxy,
            serial,
            time,
            button,
            state,
        },
        wl_pointer::Event::Axis { time, axis, value } => RawEvent::PointerAxis {
            pointer: proxy,
            time,
            axis,
            value,
        },
        wl_pointer::Event::AxisSource { axis_source } => RawEvent::PointerAxisSource {
            pointer: proxy,
            source: axis_source,
        },
        wl_pointer::Event::AxisDiscrete { axis, discrete } => RawEvent::PointerAxisDiscrete {
            pointer: proxy,
            axis,
            discrete,
        },
        wl_pointer::Event::AxisValue120 { axis, value120 } => RawEvent::PointerAxisValue120 {
            pointer: proxy,
            axis,
            value120,
        },
        wl_pointer::Event::Frame => RawEvent::PointerFrame { pointer: proxy },
        // `axis_stop` says a kinetic scroll ended, which produces no delta and
        // nothing this seam reports; `axis_relative_direction` is version 9,
        // which this backend does not bind.
        _ => return None,
    })
}

/// Splits `wl_keyboard`'s six events out of the dispatcher; see
/// [`decode_pointer`].
fn decode_keyboard(proxy: usize, event: wl_keyboard::Event<'_>) -> Option<RawEvent> {
    Some(match event {
        wl_keyboard::Event::Keymap { format, fd, size } => RawEvent::KeyboardKeymap {
            keyboard: proxy,
            format,
            fd,
            size,
        },
        // The `keys` array lists what was already held when focus arrived. It
        // is deliberately dropped: those presses happened before this window
        // had focus, and synthesizing edges for them would make the action
        // layer fire a jump for a key the player was holding in another
        // application. `ShellEvent::Focus` already tells a consumer to treat
        // focus as a clean slate.
        wl_keyboard::Event::Enter {
            serial, surface, ..
        } => RawEvent::KeyboardEnter {
            keyboard: proxy,
            serial,
            surface: surface as usize,
        },
        wl_keyboard::Event::Leave { serial, surface } => RawEvent::KeyboardLeave {
            keyboard: proxy,
            serial,
            surface: surface as usize,
        },
        wl_keyboard::Event::Key {
            serial,
            time,
            key,
            state,
        } => RawEvent::KeyboardKey {
            keyboard: proxy,
            serial,
            time,
            key,
            state,
        },
        wl_keyboard::Event::Modifiers {
            serial,
            mods_depressed,
            mods_latched,
            mods_locked,
            group,
        } => RawEvent::KeyboardModifiers {
            keyboard: proxy,
            serial,
            depressed: mods_depressed,
            latched: mods_latched,
            locked: mods_locked,
            group,
        },
        wl_keyboard::Event::RepeatInfo { rate, delay } => RawEvent::KeyboardRepeatInfo {
            keyboard: proxy,
            rate,
            delay,
        },
    })
}

/// Splits `wl_data_device`'s six events out of the dispatcher; see
/// [`decode_pointer`].
///
/// The proxy arguments are flattened to addresses here, exactly as the pointer
/// and keyboard decoders flatten surfaces: the raw pointer must not outlive the
/// dispatcher, and an address is all `process_data` needs to find the object
/// again.
fn decode_data_device(proxy: usize, event: wl_data_device::Event) -> Option<RawEvent> {
    Some(match event {
        wl_data_device::Event::DataOffer { id } => RawEvent::DataOffer {
            device: proxy,
            offer: id as usize,
        },
        wl_data_device::Event::Selection { id } => RawEvent::Selection {
            device: proxy,
            offer: id as usize,
        },
        wl_data_device::Event::Enter {
            serial,
            surface,
            x,
            y,
            id,
        } => RawEvent::DragEnter {
            device: proxy,
            serial,
            surface: surface as usize,
            x,
            y,
            offer: id as usize,
        },
        wl_data_device::Event::Leave => RawEvent::DragLeave { device: proxy },
        wl_data_device::Event::Motion { time, x, y } => RawEvent::DragMotion {
            device: proxy,
            time,
            x,
            y,
        },
        wl_data_device::Event::Drop => RawEvent::DragDrop { device: proxy },
    })
}

/// `xdg_toplevel.configure`'s states array is a `wl_array` of native-endian
/// `uint32_t`.
fn decode_state_array(bytes: &[u8]) -> Vec<u32> {
    bytes
        .as_chunks::<4>()
        .0
        .iter()
        .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
        .collect()
}

// ---------------------------------------------------------------------------
// Connection
// ---------------------------------------------------------------------------

/// The connection and the globals bound on it.
struct Conn {
    lib: &'static Lib,
    display: NonNull<WlDisplay>,
    fd: c_int,
    registry: *mut WlProxy,
    compositor: *mut WlProxy,
    wm_base: *mut WlProxy,
    xdg_output_manager: *mut WlProxy,
    decoration_manager: *mut WlProxy,
    fractional_scale_manager: *mut WlProxy,
    viewporter: *mut WlProxy,
    relative_pointer_manager: *mut WlProxy,
    pointer_constraints: *mut WlProxy,
    data_device_manager: *mut WlProxy,
    layer_shell: *mut WlProxy,
    text_input_manager: *mut WlProxy,
    cursor_shape_manager: *mut WlProxy,
    dmabuf: *mut WlProxy,
    /// Owned by the connection, reached only as a raw pointer; see [`Sink`].
    sink: *mut Sink,
}

/// A global this backend binds exactly **one** of.
///
/// [`Conn`]'s fields are bare pointers with no memory of where they came from,
/// and `wl_registry.global_remove` names only a registry id — so a shell that
/// wants to let go of a withdrawn global has to have written the two down
/// together. That is what [`WaylandShell::singletons`] holds and this names.
///
/// `wl_output` and `wl_seat` are not here: a compositor advertises many of
/// each, so they are kept in [`Output`] and [`Seat`] with their own `global`
/// fields, and removed one instance at a time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Singleton {
    Compositor,
    WmBase,
    Viewporter,
    FractionalScaleManager,
    XdgOutputManager,
    DecorationManager,
    RelativePointerManager,
    PointerConstraints,
    DataDeviceManager,
    LayerShell,
    TextInputManager,
    CursorShapeManager,
    Dmabuf,
}

impl Singleton {
    /// The [`Conn`] field this global is kept in.
    fn slot(self, conn: &mut Conn) -> &mut *mut WlProxy {
        match self {
            Self::Compositor => &mut conn.compositor,
            Self::WmBase => &mut conn.wm_base,
            Self::Viewporter => &mut conn.viewporter,
            Self::FractionalScaleManager => &mut conn.fractional_scale_manager,
            Self::XdgOutputManager => &mut conn.xdg_output_manager,
            Self::DecorationManager => &mut conn.decoration_manager,
            Self::RelativePointerManager => &mut conn.relative_pointer_manager,
            Self::PointerConstraints => &mut conn.pointer_constraints,
            Self::DataDeviceManager => &mut conn.data_device_manager,
            Self::LayerShell => &mut conn.layer_shell,
            Self::TextInputManager => &mut conn.text_input_manager,
            Self::CursorShapeManager => &mut conn.cursor_shape_manager,
            Self::Dmabuf => &mut conn.dmabuf,
        }
    }

    /// The interface's own name, taken from the generated descriptor rather
    /// than spelled again here.
    fn interface(self) -> &'static CStr {
        match self {
            Self::Compositor => wl_compositor::NAME,
            Self::WmBase => xdg_wm_base::NAME,
            Self::Viewporter => wp_viewporter::NAME,
            Self::FractionalScaleManager => wp_fractional_scale_manager_v1::NAME,
            Self::XdgOutputManager => zxdg_output_manager_v1::NAME,
            Self::DecorationManager => zxdg_decoration_manager_v1::NAME,
            Self::RelativePointerManager => zwp_relative_pointer_manager_v1::NAME,
            Self::PointerConstraints => zwp_pointer_constraints_v1::NAME,
            Self::DataDeviceManager => wl_data_device_manager::NAME,
            Self::LayerShell => zwlr_layer_shell_v1::NAME,
            Self::TextInputManager => zwp_text_input_manager_v3::NAME,
            Self::CursorShapeManager => wp_cursor_shape_manager_v1::NAME,
            Self::Dmabuf => zwp_linux_dmabuf_v1::NAME,
        }
    }
}

impl Conn {
    /// The event queue, as a mutable reference.
    ///
    /// Takes `&mut self` even though the pointer would allow `&self`: the
    /// dispatcher's `&mut Sink` and this one must never overlap, and requiring
    /// a unique borrow of the connection to get one is the cheapest way to make
    /// that visible at every call site.
    fn sink(&mut self) -> &mut Sink {
        // SAFETY: `self.sink` came from `Box::into_raw` and is live for the
        // connection's lifetime. The dispatcher is the only other holder of a
        // reference to it, and it runs strictly inside the libwayland calls in
        // `Conn::drain`, where this method is not called.
        unsafe { &mut *self.sink }
    }

    /// Attaches the dispatcher to `proxy` and records what it is.
    fn watch(&mut self, proxy: *mut WlProxy, kind: ObjectKind) {
        self.sink().watch(proxy, kind);
    }

    /// Destroys a proxy client-side and stops routing its events.
    ///
    /// For an object whose interface has **no** destructor request. Anything
    /// with one must go through [`release`](Self::release) instead, or the
    /// compositor never learns the object is gone — which for a
    /// `zwp_locked_pointer_v1` means the pointer stays locked forever.
    fn destroy(&mut self, proxy: *mut WlProxy) {
        if proxy.is_null() {
            return;
        }
        self.sink().forget(proxy as usize);
        // SAFETY: `proxy` is live on this connection and is not used again —
        // every caller clears its own copy of the pointer.
        unsafe { (self.lib.proxy_destroy)(proxy) };
    }

    /// Sends a protocol destructor and stops routing the proxy's events.
    ///
    /// The generated destructor wrappers marshal with `WL_MARSHAL_FLAG_DESTROY`,
    /// which both tells the compositor and frees the proxy, so this must not be
    /// followed by a [`destroy`](Self::destroy).
    ///
    /// # Safety
    ///
    /// `destructor` must be the generated destructor request of `proxy`'s own
    /// interface, and `proxy` must be live on this connection.
    unsafe fn release(&mut self, proxy: *mut WlProxy, destructor: unsafe fn(*mut WlProxy)) {
        if proxy.is_null() {
            return;
        }
        self.sink().forget(proxy as usize);
        // SAFETY: the caller guarantees `destructor` belongs to this proxy's
        // interface and that the proxy is live.
        unsafe { destructor(proxy) };
    }

    /// [`release`](Self::release), but only if the proxy was bound at a
    /// version that has the destructor.
    ///
    /// `wl_pointer.release` and `wl_keyboard.release` arrived in `wl_seat`
    /// version 3. Sending a request a proxy's bound version does not have is a
    /// protocol error that disconnects the client — so on a hypothetical
    /// version-1 or -2 seat the proxy is dropped client-side instead. The
    /// server keeps its object until the seat goes, which is the same outcome
    /// those versions offered in the first place.
    ///
    /// # Safety
    ///
    /// As [`release`](Self::release).
    unsafe fn release_since(
        &mut self,
        proxy: *mut WlProxy,
        since: u32,
        destructor: unsafe fn(*mut WlProxy),
    ) {
        if proxy.is_null() {
            return;
        }
        // SAFETY: the caller guarantees the proxy is live.
        if unsafe { ffi::proxy_version(proxy) } >= since {
            // SAFETY: the caller guarantees `destructor` is this interface's.
            unsafe { self.release(proxy, destructor) };
        } else {
            self.destroy(proxy);
        }
    }

    fn display_proxy(&self) -> *mut WlProxy {
        ffi::display_as_proxy(self.display.as_ptr())
    }

    /// Sends everything queued.
    fn flush(&self) {
        // SAFETY: the display is live for the connection's lifetime.
        unsafe { (self.lib.display_flush)(self.display.as_ptr()) };
    }

    /// A blocking round trip: send everything, then wait for the server to
    /// answer a `wl_display.sync`.
    ///
    /// Used only during [`WaylandShell::open`], where blocking is correct —
    /// there is no frame loop yet, and the alternative is a shell that reports
    /// no monitors for the first few frames.
    fn roundtrip(&self) -> Result<(), ShellError> {
        // SAFETY: the display is live.
        if unsafe { (self.lib.display_roundtrip)(self.display.as_ptr()) } < 0 {
            return Err(self.disconnected());
        }
        Ok(())
    }

    /// Non-blocking read + dispatch. See [`WaylandShell::pump`].
    ///
    /// `aux` are clipboard-transfer pipes: they never drive the protocol, and
    /// they are in the wait so that a blocked editor wakes when a paste's bytes
    /// arrive rather than sleeping on them.
    fn drain(&self, timeout_ms: c_int, aux: &[c_int]) -> Result<(), ShellError> {
        let display = self.display.as_ptr();
        // SAFETY (whole block): `display` is live, and this is libwayland's
        // documented non-blocking read sequence. Every `prepare_read` is paired
        // with exactly one `read_events` or `cancel_read`, which is the
        // invariant that keeps other threads from deadlocking on the read
        // barrier — and the reason the sequence is written out rather than
        // replaced by `wl_display_dispatch`, which blocks.
        unsafe {
            if (self.lib.display_dispatch_pending)(display) < 0 {
                return Err(self.disconnected());
            }
            // `prepare_read` fails while this thread still has queued events;
            // dispatch them and try again. Bounded by the queue, not by time.
            while (self.lib.display_prepare_read)(display) != 0 {
                if (self.lib.display_dispatch_pending)(display) < 0 {
                    return Err(self.disconnected());
                }
            }
            if (self.lib.display_flush)(display) < 0 && timeout_ms != 0 {
                // A full socket with nothing to read would otherwise block for
                // the whole timeout waiting for a peer that is waiting for us.
                (self.lib.display_cancel_read)(display);
                return Ok(());
            }
            if !ffi::poll_readable_with(self.fd, aux, timeout_ms) {
                (self.lib.display_cancel_read)(display);
            } else if (self.lib.display_read_events)(display) < 0 {
                return Err(self.disconnected());
            }
            if (self.lib.display_dispatch_pending)(display) < 0 {
                return Err(self.disconnected());
            }
        }
        Ok(())
    }

    fn disconnected(&self) -> ShellError {
        // SAFETY: the display is live; `wl_display_get_error` is pure.
        let code = unsafe { (self.lib.display_get_error)(self.display.as_ptr()) };
        ShellError::Disconnected {
            backend: ShellBackend::Wayland,
            detail: format!("errno {code}"),
        }
    }
}

// ---------------------------------------------------------------------------
// Monitors
// ---------------------------------------------------------------------------

/// A `wl_output` and what it has told us so far.
#[derive(Debug)]
struct Output {
    proxy: usize,
    /// The matching `zxdg_output_v1`, or null before the manager was bound.
    xdg: *mut WlProxy,
    /// `wl_registry.global`'s name, for the matching `global_remove`.
    global: u32,
    id: MonitorId,
    x: i32,
    y: i32,
    width: i32,
    height: i32,
    refresh_millihertz: u32,
    scale: i32,
    /// `zxdg_output_v1.logical_position`, in the compositor's logical space.
    logical_x: i32,
    logical_y: i32,
    /// `zxdg_output_v1.logical_size`; zero until it arrives.
    logical_width: i32,
    logical_height: i32,
    name: String,
    /// Whether a `wl_output.done` has been seen, i.e. whether the fields above
    /// are a consistent snapshot rather than a half-applied update.
    settled: bool,
}

impl Output {
    /// The output's true scale, which is not necessarily `wl_output.scale`.
    ///
    /// `wl_output.scale` is an **integer**, so a compositor running an output
    /// at 150 % reports `2` — it is defined as the buffer scale a client should
    /// use, not as the desktop's scale. `xdg_output`'s logical size is the same
    /// output measured in the desktop's own units, so the ratio between the
    /// mode and it is the real number. This is how a monitor at 1.5 stops
    /// claiming to be at 2.
    fn scale_factor(&self) -> f64 {
        if self.logical_width > 0 && self.width > 0 {
            f64::from(self.width) / f64::from(self.logical_width)
        } else {
            f64::from(self.scale.max(1))
        }
    }

    #[expect(
        clippy::cast_possible_truncation,
        reason = "a desktop coordinate that overflows i32 after scaling would \
                  need a monitor layout billions of pixels wide; the clamp \
                  keeps it defined regardless"
    )]
    fn info(&self, is_primary: bool) -> MonitorInfo {
        let width = self.width.max(0).unsigned_abs();
        let height = self.height.max(0).unsigned_abs();
        let scale = self.scale_factor();
        // Position from `xdg_output`, scaled back into this output's device
        // pixels so that it and the size below are in one unit.
        //
        // The honest caveat, which nothing may paper over: on a desktop whose
        // outputs have *different* scales there is no single device-pixel
        // coordinate space, and these rectangles will not tile. The compositor's
        // logical space is the only globally coherent one, and `PhysicalRect`
        // cannot express it. `ShellCaps::WINDOW_POSITION` stays clear, so
        // nothing is entitled to treat this as a desktop layout — it is good
        // enough to name a monitor and to tell a settings screen which one is
        // on the left.
        let (x, y) = if self.logical_width > 0 {
            let to_pixels = |value: i32| (f64::from(value) * scale).round();
            (
                to_pixels(self.logical_x).clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32,
                to_pixels(self.logical_y).clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32,
            )
        } else {
            // No `xdg_output`: `wl_output.geometry`'s position is logical while
            // the size is physical, so they only agree at scale 1. Kept as the
            // fallback because it is what the protocol guarantees.
            (self.x, self.y)
        };
        MonitorInfo {
            id: self.id,
            name: self.name.clone(),
            bounds: PhysicalRect::new(x, y, width, height),
            // Wayland has no work-area protocol at all. `MonitorInfo` documents
            // that a backend which cannot find out reports the full area.
            work_area: PhysicalRect::new(x, y, width, height),
            scale_factor: scale,
            refresh_millihertz: self.refresh_millihertz,
            is_primary,
        }
    }
}

// ---------------------------------------------------------------------------
// Seats
// ---------------------------------------------------------------------------

/// One `wl_seat` and the devices it currently has.
///
/// # One [`DeviceId`] per seat, not per physical device
///
/// The input design wants per-device ids so that local multiplayer can
/// assign devices to players later. On Wayland the *seat* is that unit and
/// there is no finer one: libinput merges every physical keyboard on a seat
/// into one `wl_keyboard` and every mouse into one `wl_pointer`, and the
/// protocol exposes no device list at all. Reporting a made-up id per physical
/// device would be a fiction; reporting the seat is the true grouping, and a
/// multi-seat session — which is exactly how Linux does local multiplayer —
/// produces exactly the distinct ids that layer needs.
struct Seat {
    proxy: *mut WlProxy,
    global: u32,
    device: DeviceId,
    capabilities: u32,
    pointer: *mut WlProxy,
    keyboard: *mut WlProxy,
    relative_pointer: *mut WlProxy,
    /// This pointer's `wp_cursor_shape_device_v1`, once the manager global
    /// exists; see [`cursor_shape`].
    cursor_shape: *mut WlProxy,
    /// This seat's `wl_data_device`, once the manager global exists.
    ///
    /// One per seat, not one per shell: the clipboard *is* a seat's, and a
    /// multi-seat session has as many independent clipboards as it has seats.
    data: Option<data::Device>,
    /// The serial of the last `wl_pointer.enter`, which `set_cursor` and
    /// `set_shape` both have to quote.
    enter_serial: u32,
    /// The serial of the most recent input event of **any** kind on this seat.
    ///
    /// `wl_data_device.set_selection` takes "the serial of the event that
    /// triggered this request", and a compositor is entitled to check it —
    /// wlroots compares it against the serial of the selection currently in
    /// effect and drops a request that looks older, so a backend that passed
    /// zero would have its clipboard writes silently ignored. Tracking every
    /// serial the seat delivers is what makes "the user pressed Ctrl+C, so this
    /// copy is current" expressible from a seam that has no serials in it.
    last_serial: u32,
    /// The serial of the last pointer **press**, which is the implicit grab a
    /// `wl_data_device.start_drag` has to name. Distinct from
    /// [`last_serial`](Self::last_serial) because any later event would
    /// invalidate the grab.
    press_serial: u32,
    pointer_focus: Option<WindowId>,
    /// Last known position, in the focused window's device pixels.
    pointer_position: PhysicalPoint,
    frame: PointerFrame,
    keyboard_focus: Option<WindowId>,
    keymap: Option<xkb::Keymap>,
    modifiers: Modifiers,
    /// Held keys, for the degraded modifier path only; see [`xkb`].
    held: Vec<KeyCode>,
    repeat: Repeat,
    /// This seat's `zwp_text_input_v3`, once the manager global exists.
    text_input: Option<text_input::TextInput>,
}

impl core::fmt::Debug for Seat {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Seat")
            .field("device", &self.device)
            .field("capabilities", &self.capabilities)
            .field("keymap", &self.keymap.is_some())
            .field("data_device", &self.data.is_some())
            .finish()
    }
}

/// Everything a `wl_pointer` said between two `wl_pointer.frame`s.
///
/// The protocol groups pointer events into frames precisely so a client does
/// not treat one physical movement as several logical ones: a diagonal move
/// arrives as one `motion`, a wheel click as an `axis` plus an `axis_value120`
/// plus an `axis_source`, and a locked pointer's motion arrives on a *different
/// object* (`zwp_relative_pointer_v1`) inside the same frame. Accumulating and
/// emitting once per frame is what turns that into one
/// [`ShellEvent::PointerMotion`] and one [`ShellEvent::Wheel`].
#[derive(Clone, Copy, Debug, Default)]
struct PointerFrame {
    /// Compositor milliseconds, from whichever event carried one.
    time: u32,
    /// Surface-local position, in logical units.
    motion: Option<(f64, f64)>,
    /// Unaccelerated relative motion, in the device's own units.
    raw: Option<(f64, f64)>,
    /// `CLOCK_MONOTONIC` microseconds from `relative_motion`, which is the more
    /// precise of the two clocks a motion can arrive on.
    raw_micros: Option<u64>,
    /// `[vertical, horizontal]`, in 1/120ths of a detent.
    value120: [f64; 2],
    /// `[vertical, horizontal]`, in whole detents (`wl_pointer` 5 to 7).
    discrete: [f64; 2],
    /// `[vertical, horizontal]`, in surface-local units.
    continuous: [f64; 2],
    axis_source: Option<u32>,
    has_axis: bool,
}

impl PointerFrame {
    fn is_empty(&self) -> bool {
        self.motion.is_none() && self.raw.is_none() && !self.has_axis
    }

    /// The scroll this frame describes, or `None` when it describes none.
    ///
    /// # Detents versus pixels
    ///
    /// [`ScrollDelta`] refuses to collapse the two, and this is where the
    /// distinction is made. A notched wheel reports `axis_value120` (or
    /// `axis_discrete` before version 8) *in addition to* a continuous `axis`
    /// value, so preferring the discrete number is what stops a wheel click
    /// being reported as "15 pixels" — a number the compositor made up from its
    /// own scroll-speed setting. A touchpad reports only `axis`, and gets
    /// pixels, which is the truth about a touchpad.
    ///
    /// # Sign
    ///
    /// Wayland's vertical axis is positive **downwards** (content moves up as
    /// the value grows) and its horizontal axis positive rightwards.
    /// [`ScrollDelta`] documents positive `y` as "scrolls the content up (away
    /// from the user)", the convention every other platform uses, so both axes
    /// are negated here — once, in one place.
    fn scroll(&self, scale: f64) -> Option<ScrollDelta> {
        if !self.has_axis {
            return None;
        }
        let detents = |raw: [f64; 2], divisor: f64| ScrollDelta::Lines {
            #[expect(
                clippy::cast_possible_truncation,
                reason = "ScrollDelta::Lines is f32 by seam definition; a detent \
                          count is a small integer"
            )]
            x: (-raw[1] / divisor) as f32,
            #[expect(clippy::cast_possible_truncation, reason = "as above")]
            y: (-raw[0] / divisor) as f32,
        };
        if self.value120 != [0.0, 0.0] {
            return Some(detents(self.value120, 120.0));
        }
        if self.discrete != [0.0, 0.0] {
            return Some(detents(self.discrete, 1.0));
        }
        if self.continuous != [0.0, 0.0] {
            return Some(ScrollDelta::Pixels {
                x: -self.continuous[1] * scale,
                y: -self.continuous[0] * scale,
            });
        }
        // An `axis_stop`, or a frame whose only axis content was a zero. The
        // seam's `ScrollDelta::is_zero` exists for consumers that want these;
        // producing one here would mean a `Wheel` event per kinetic-scroll
        // teardown, which is noise.
        None
    }
}

/// Key-repeat parameters and the key currently repeating.
///
/// See the [module docs](self) for why this lives in the backend at all.
#[derive(Clone, Copy, Debug, Default)]
struct Repeat {
    /// Repeats per second; `0` disables repeat entirely, which is what
    /// `wl_keyboard.repeat_info` means by it.
    rate: i32,
    /// Milliseconds before the first repeat.
    delay: i32,
    key: Option<RepeatKey>,
}

/// The one key a seat is repeating.
#[derive(Clone, Copy, Debug)]
struct RepeatKey {
    window: WindowId,
    scancode: u32,
    key_code: Option<KeyCode>,
    keysym: Keysym,
    /// `CLOCK_MONOTONIC` nanoseconds at which the next repeat is due.
    next_nanos: u64,
    /// Nanoseconds between repeats.
    interval_nanos: u64,
}

impl Repeat {
    /// Starts repeating `key`, if repeat is enabled at all.
    fn start(&mut self, now_nanos: u64, key: RepeatKeyRequest) {
        if self.rate <= 0 {
            self.key = None;
            return;
        }
        let interval_nanos = 1_000_000_000 / u64::try_from(self.rate).unwrap_or(1).max(1);
        let delay_nanos = u64::try_from(self.delay.max(0)).unwrap_or(0) * 1_000_000;
        self.key = Some(RepeatKey {
            window: key.window,
            scancode: key.scancode,
            key_code: key.key_code,
            keysym: key.keysym,
            next_nanos: now_nanos.saturating_add(delay_nanos),
            interval_nanos,
        });
    }

    /// Stops repeating, if `scancode` is what is repeating.
    fn stop(&mut self, scancode: u32) {
        if self.key.is_some_and(|key| key.scancode == scancode) {
            self.key = None;
        }
    }

    /// `CLOCK_MONOTONIC` nanoseconds at which the next repeat is due.
    fn due_at(&self) -> Option<u64> {
        self.key.map(|key| key.next_nanos)
    }
}

/// What [`Repeat::start`] needs to know, so it does not take six arguments.
#[derive(Clone, Copy, Debug)]
struct RepeatKeyRequest {
    window: WindowId,
    scancode: u32,
    key_code: Option<KeyCode>,
    keysym: Keysym,
}

// ---------------------------------------------------------------------------
// Windows
// ---------------------------------------------------------------------------

/// State accumulated from an `xdg_toplevel.configure` that has not been
/// completed by an `xdg_surface.configure` yet.
#[derive(Clone, Debug, Default)]
struct PendingConfigure {
    /// Logical size, or `None` when the compositor sent `0 × 0` — "you choose".
    size: Option<LogicalSize>,
    states: Vec<u32>,
}

/// One window and its surface stack: an `xdg_toplevel`, or a layer surface
/// for a panel.
///
/// The role objects of the other role are null, which every request on them
/// is guarded against: a request marshalled on a null proxy is a crash inside
/// libwayland.
#[derive(Debug)]
struct WlWindow {
    surface: *mut WlProxy,
    xdg_surface: *mut WlProxy,
    toplevel: *mut WlProxy,
    /// The `zwlr_layer_surface_v1` of a panel.
    layer_surface: *mut WlProxy,
    /// The `xdg_popup` of a popup.
    popup: *mut WlProxy,
    /// The window a popup belongs to, which destroys it when it goes.
    parent: Option<WindowId>,
    /// Where a popup is placed against its anchor, kept so it can be placed
    /// again when it is repositioned.
    placement: Option<crate::PopupPlacement>,
    /// What input a popup takes, which decides whether `Escape` dismisses it.
    popup_input: Option<crate::PopupInput>,
    /// What a panel was created with, or last given by [`Shell::set_panel`];
    /// its monitor's removal asks it to close. `None` for every other window.
    panel: Option<crate::role::KeptPanel>,
    decoration: *mut WlProxy,
    fractional_scale: *mut WlProxy,
    viewport: *mut WlProxy,
    /// The `wl_callback` of a [`Shell::request_frame`] not yet answered, or
    /// null; see [`frame`].
    frame_callback: *mut WlProxy,
    title: String,
    requested_size: LogicalSize,
    requested_mode: DisplayMode,
    requested_constraints: SizeConstraints,
    /// [`WindowDesc::resizable`], kept because xdg-shell has no way to *ask*
    /// what it is: the flag is expressed as `min == max`, so every later
    /// `set_min_size`/`set_max_size` has to restate it. Without the field,
    /// `set_constraints` had to guess `true`, and a window created
    /// `resizable: false` became user-resizable the first time a caller touched
    /// its constraints — with no way back. The X11 backend keeps the same flag
    /// for the same reason.
    resizable: bool,
    configuration: Option<WindowConfiguration>,
    pending: PendingConfigure,
    /// Outputs the surface is on, in `wl_surface.enter` order. Empty until the
    /// surface is mapped, which is why the first configure is always scale 1.
    outputs: Vec<usize>,
    scale: i32,
    /// `wp_fractional_scale_v1.preferred_scale`, in 1/120ths, once it arrives.
    preferred_scale: Option<u32>,
    pointer_mode: PointerMode,
    /// Live `zwp_locked_pointer_v1`/`zwp_confined_pointer_v1` objects as
    /// `(the wl_pointer they name, the constraint)`.
    ///
    /// Keyed by the pointer because a constraint is a per-`(surface, pointer)`
    /// object: when one seat unplugs its mouse, only *its* constraint may be
    /// torn down, and another seat's has to keep working.
    constraints: Vec<(usize, *mut WlProxy)>,
    /// The cursor last asked for. The outer `Option` distinguishes "never set",
    /// where the compositor's default stands, from "set to hidden".
    cursor: Option<Option<CursorIcon>>,
    /// [`WindowDesc::accept_drops`], which this backend enforces rather than
    /// records: a window that did not ask for drops answers
    /// `wl_data_offer.accept(null)` and never reads the dropped data.
    accept_drops: bool,
    /// [`WindowDesc::transparent`], which [`surface_target`](Shell::surface_target)
    /// hands on. Nothing here changes for it: the compositor blends by the
    /// buffer's alpha either way, so the swapchain's alpha is the whole of it.
    transparent: bool,
    /// What a text field in the window asked of the input method; see
    /// [`text_input`].
    text_input: text_input::Field,
    focused: bool,
    visible: bool,
    close_pending: bool,
}

impl WlWindow {
    /// The logical size to use when the compositor declines to pick one.
    fn logical_size(&self) -> LogicalSize {
        self.pending.size.unwrap_or_else(|| {
            self.configuration.map_or(self.requested_size, |config| {
                LogicalSize::new(
                    f64::from(config.size.width) / config.scale_factor,
                    f64::from(config.size.height) / config.scale_factor,
                )
            })
        })
    }

    /// Device pixels per logical unit for this window.
    ///
    /// `fractional-scale-v1` when the compositor offered it, and the integer
    /// `wl_surface.enter` scale otherwise. The two are mutually exclusive by
    /// protocol: a surface using a `wp_viewport` to express its size must not
    /// also set a buffer scale.
    ///
    /// **A fractionally scaled window ignores the integer scale while its
    /// `preferred_scale` is on the way.** `wl_output.scale` and
    /// `wl_surface.enter` arrive first, so following them meant a swapchain at
    /// the rounded-up integer scale, rebuilt again a moment later at the real
    /// one (Hyprland at 1.5: 1x, then 2x, then 1.5x).
    fn scale_factor(&self) -> f64 {
        match self.preferred_scale {
            Some(scale) if scale > 0 => f64::from(scale) / FRACTIONAL_SCALE_DENOMINATOR,
            None if self.is_fractional() => 1.0,
            _ => f64::from(self.scale.max(1)),
        }
    }

    /// Whether the compositor scales this window through `fractional-scale-v1`
    /// and a `wp_viewport`, which takes the place of `set_buffer_scale`.
    fn is_fractional(&self) -> bool {
        !self.fractional_scale.is_null() && !self.viewport.is_null()
    }
}

// ---------------------------------------------------------------------------
// The shell
// ---------------------------------------------------------------------------

/// A [`Shell`] backed by a real Wayland compositor.
///
/// Constructed through [`open`](crate::open) or
/// [`open_backend`](crate::open_backend); see the [module docs](self) for what
/// this backend implements and how a real compositor differs from
/// [`HeadlessShell`](crate::HeadlessShell).
pub struct WaylandShell {
    conn: Conn,
    windows: Pool<WlWindow>,
    outputs: Vec<Output>,
    seats: Vec<Seat>,
    monitors: Vec<MonitorInfo>,
    next_monitor_id: u32,
    next_device_id: u32,
    next_request_id: u32,
    /// Pipes being drained into a clipboard answer or a drop, and the payloads
    /// being fed into pipes a peer is reading. Both are serviced once per
    /// [`pump`](Shell::pump) and neither ever blocks; see [`fd`].
    transfers: Vec<Transfer>,
    writes: fd::Writes,
    /// Reads accepted while the clipboard was not readable; see [`HeldRead`].
    held: Vec<HeldRead>,
    /// The registry name every bound [`Singleton`] came from.
    ///
    /// Written by [`bind_global`](Self::bind_global) and read by
    /// [`withdraw_singleton`](Self::withdraw_singleton), which is the only way
    /// a `global_remove` — an integer and nothing else — can be matched to the
    /// proxy it withdrew.
    singletons: Vec<(u32, Singleton)>,
    queue: VecDeque<ShellEvent>,
    /// The epoch every event timestamp is measured from.
    time: TimeBase,
    /// Latched at [`open`](Self::open); see [`caps`](Shell::caps).
    caps: ShellCaps,
    /// The doorbell [`waker`](Shell::waker) hands out, made on the first ask
    /// and polled beside the connection from then on.
    wake: Option<std::sync::Arc<crate::linux::wake::WakePipe>>,
    lost: Option<String>,
    /// The default dmabuf feedback, and the main device its last whole batch
    /// named and the one its batch in flight names; see [`dmabuf`].
    dmabuf_feedback: *mut WlProxy,
    main_device: Option<u64>,
    pending_main_device: Option<u64>,
    /// Each window's AT-SPI adapter; see [`access`](crate::linux::access).
    #[cfg(feature = "accesskit")]
    access: crate::linux::access::Adapters,
}

impl core::fmt::Debug for WaylandShell {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("WaylandShell")
            .field("windows", &self.windows.len())
            .field("monitors", &self.monitors.len())
            .field("seats", &self.seats.len())
            .field(
                "transfers",
                &(self.transfers.len() + self.writes.len() + self.held.len()),
            )
            .field("queued_events", &self.queue.len())
            .field("connected", &self.lost.is_none())
            .finish()
    }
}

impl WaylandShell {
    /// Connects to the compositor named by `WAYLAND_DISPLAY`.
    ///
    /// Binds every global this backend understands and round-trips twice: once
    /// for the registry listing, once for the properties of what was bound.
    /// Blocking here is correct — there is no frame loop yet, and the
    /// alternative is a shell that reports no monitors and no capabilities for
    /// the first few frames.
    ///
    /// # Errors
    ///
    /// [`ShellError::Connect`] if libwayland-client cannot be loaded, if there
    /// is no compositor socket, or if the compositor does not implement
    /// `xdg_wm_base` — a compositor without it cannot show a window at all, and
    /// pretending otherwise produces a process with an invisible window and no
    /// error.
    pub fn open() -> Result<Self, ShellError> {
        let lib = ffi::load().map_err(|detail| ShellError::Connect {
            backend: ShellBackend::Wayland,
            detail: detail.to_string(),
        })?;

        // SAFETY: a null name means "read WAYLAND_DISPLAY", which is
        // `wl_display_connect`'s documented behaviour.
        let display = unsafe { (lib.display_connect)(ptr::null()) };
        let Some(display) = NonNull::new(display) else {
            return Err(ShellError::Connect {
                backend: ShellBackend::Wayland,
                detail: match std::env::var("WAYLAND_DISPLAY") {
                    Ok(name) => format!("no compositor at WAYLAND_DISPLAY={name}"),
                    Err(_) => "WAYLAND_DISPLAY is not set".to_string(),
                },
            });
        };

        // SAFETY: the display was just returned live by `wl_display_connect`.
        let fd = unsafe { (lib.display_get_fd)(display.as_ptr()) };
        let conn = Conn {
            lib,
            display,
            fd,
            registry: ptr::null_mut(),
            compositor: ptr::null_mut(),
            wm_base: ptr::null_mut(),
            xdg_output_manager: ptr::null_mut(),
            decoration_manager: ptr::null_mut(),
            fractional_scale_manager: ptr::null_mut(),
            viewporter: ptr::null_mut(),
            relative_pointer_manager: ptr::null_mut(),
            pointer_constraints: ptr::null_mut(),
            data_device_manager: ptr::null_mut(),
            layer_shell: ptr::null_mut(),
            text_input_manager: ptr::null_mut(),
            cursor_shape_manager: ptr::null_mut(),
            dmabuf: ptr::null_mut(),
            sink: Sink::boxed(lib),
        };

        let mut shell = Self {
            conn,
            windows: Pool::new(),
            outputs: Vec::new(),
            seats: Vec::new(),
            monitors: Vec::new(),
            next_monitor_id: 1,
            next_device_id: 1,
            next_request_id: 1,
            transfers: Vec::new(),
            writes: fd::Writes::new(),
            held: Vec::new(),
            singletons: Vec::new(),
            queue: VecDeque::new(),
            time: TimeBase::now(),
            caps: ShellCaps::empty(),
            wake: None,
            lost: None,
            dmabuf_feedback: ptr::null_mut(),
            main_device: None,
            pending_main_device: None,
            #[cfg(feature = "accesskit")]
            access: crate::linux::access::Adapters::default(),
        };

        // SAFETY: the display proxy is live and `wl_display.get_registry` takes
        // no arguments beyond the new object.
        shell.conn.registry =
            unsafe { protocol::wayland::wl_display::get_registry(shell.conn.display_proxy()) };
        if shell.conn.registry.is_null() {
            return Err(ShellError::Connect {
                backend: ShellBackend::Wayland,
                detail: "wl_display.get_registry failed".to_string(),
            });
        }
        let registry = shell.conn.registry;
        shell.conn.watch(registry, ObjectKind::Registry);

        // First round trip: the registry listing.
        shell.conn.roundtrip()?;
        shell.process_raw();
        // Second: the properties of everything bound in the first, including
        // the `xdg_output`s and the seat capabilities the first round created.
        shell.conn.roundtrip()?;
        shell.process_raw();

        if shell.conn.compositor.is_null() {
            return Err(ShellError::Connect {
                backend: ShellBackend::Wayland,
                detail: "the compositor does not advertise wl_compositor".to_string(),
            });
        }
        if shell.conn.wm_base.is_null() {
            return Err(ShellError::Connect {
                backend: ShellBackend::Wayland,
                detail: "the compositor does not advertise xdg_wm_base, so it cannot show \
                         a window"
                    .to_string(),
            });
        }
        shell.caps = shell.latch_caps();
        // The registry listing and the initial output properties are startup
        // facts, not events anyone asked for.
        shell.queue.clear();
        Ok(shell)
    }

    /// The capability set, computed once from the globals that actually bound.
    ///
    /// [`caps`](crate::caps) requires this to be latched: a Wayland compositor
    /// may advertise a global after startup, and a renderer that chose the blit
    /// path at init cannot be told mid-frame that it should have chosen the
    /// viewport path. So this runs at the end of [`open`](Self::open) and never
    /// again — a protocol that appears later stays unavailable until the next
    /// run.
    fn latch_caps(&self) -> ShellCaps {
        let mut caps = ShellCaps::MULTI_WINDOW | ShellCaps::EVENT_WAIT;
        caps.set(ShellCaps::HW_UPSCALE, !self.conn.viewporter.is_null());
        caps.set(
            ShellCaps::FRACTIONAL_SCALE,
            !self.conn.fractional_scale_manager.is_null() && !self.conn.viewporter.is_null(),
        );
        caps.set(
            ShellCaps::SERVER_DECORATIONS,
            !self.conn.decoration_manager.is_null(),
        );
        caps.set(
            ShellCaps::RAW_POINTER_MOTION,
            !self.conn.relative_pointer_manager.is_null(),
        );
        // `pointer-constraints` advertises both forms in one global; the seam
        // keeps them as separate bits because other platforms do not.
        let constraints = !self.conn.pointer_constraints.is_null();
        caps.set(ShellCaps::POINTER_LOCK, constraints);
        caps.set(ShellCaps::POINTER_CONFINE, constraints);
        // Both bits come from one global, because on Wayland they are one
        // protocol: a `wl_data_device` is the clipboard *and* the drop target,
        // and a compositor cannot offer one without the other. The seam keeps
        // them separate because other platforms can — a browser has a clipboard
        // behind a permission prompt and file drops without one.
        let data_device = !self.conn.data_device_manager.is_null();
        caps.set(ShellCaps::CLIPBOARD, data_device);
        caps.set(ShellCaps::DRAG_DROP, data_device);
        // Dead keys and Compose sequences are libxkbcommon's compose module,
        // so they need the library and nothing from the compositor. An input
        // method's pre-edit and commits come only through `text-input-v3`
        // (see `text_input`), which the registry listing has bound by now or
        // will not bind this run.
        caps.set(ShellCaps::TEXT_COMPOSE, xkb::available());
        caps.set(ShellCaps::TEXT_IME, !self.conn.text_input_manager.is_null());
        // A layer surface's exclusive zone is how it reserves an edge, so the
        // one global gives both.
        let layer_shell = !self.conn.layer_shell.is_null();
        caps.set(ShellCaps::PANEL, layer_shell);
        caps.set(ShellCaps::PANEL_RESERVE, layer_shell);
        // `keyboard_interactivity = exclusive`, which the compositor holds.
        caps.set(ShellCaps::PANEL_EXCLUSIVE_KEYBOARD, layer_shell);
        // Each pointer's shape device hangs off the manager, which the registry
        // listing has bound by now or will not bind this run.
        caps.set(
            ShellCaps::CURSOR_SHAPE,
            !self.conn.cursor_shape_manager.is_null(),
        );
        // A compositor blends every surface by its buffer's alpha unless the
        // client declares a region opaque, which this backend never does, so a
        // swapchain with premultiplied alpha is all a transparent window needs.
        caps.insert(ShellCaps::TRANSPARENT);
        // `wl_surface.set_input_region` is core protocol on every surface.
        caps.insert(ShellCaps::INPUT_REGION);
        // So is `wl_surface.frame`, which the compositor answers when it wants
        // the surface's next frame.
        caps.insert(ShellCaps::FRAME_CALLBACK);
        // `xdg_wm_base`, which `open` requires, has had popups from version 1,
        // and moves them from version 3.
        caps.insert(ShellCaps::POPUP);
        // AT-SPI is D-Bus, not Wayland: every window gets an adapter, which
        // reaches a reader whenever the session has an accessibility bus.
        #[cfg(feature = "accesskit")]
        caps.insert(ShellCaps::ACCESSIBILITY);
        caps.set(
            ShellCaps::POPUP_REPOSITION,
            !self.conn.wm_base.is_null()
                // SAFETY: a live proxy, checked non-null just above.
                && unsafe { ffi::proxy_version(self.conn.wm_base) } >= popup::REPOSITION_SINCE,
        );
        caps
    }

    /// Aligns event timestamps with an engine
    /// [`TimeSource`](crcbl_core::time::TimeSource).
    ///
    /// See [`Shell::align_event_clock`], which this implements.
    pub fn align_time_base(&mut self, elapsed: Duration) {
        self.time.align(elapsed);
    }

    fn window(&self, window: WindowId) -> Result<&WlWindow, ShellError> {
        self.windows
            .get(window.cast())
            .ok_or_else(|| ShellError::invalid_window(window))
    }

    fn window_mut(&mut self, window: WindowId) -> Result<&mut WlWindow, ShellError> {
        self.windows
            .get_mut(window.cast())
            .ok_or_else(|| ShellError::invalid_window(window))
    }

    fn unsupported(what: &'static str) -> ShellError {
        ShellError::Unsupported {
            backend: ShellBackend::Wayland,
            what,
        }
    }

    fn window_by_proxy(&self, proxy: usize, pick: fn(&WlWindow) -> usize) -> Option<WindowId> {
        self.windows
            .iter()
            .find(|(_, window)| pick(window) == proxy)
            .map(|(handle, _)| handle.cast())
    }

    fn seat_index(&self, proxy: usize, pick: fn(&Seat) -> usize) -> Option<usize> {
        self.seats.iter().position(|seat| pick(seat) == proxy)
    }

    /// Binds one global, if it is one we want.
    #[expect(
        clippy::too_many_lines,
        reason = "one arm per protocol; splitting it would only move the same \
                  list somewhere a reader has to follow to"
    )]
    fn bind_global(&mut self, name: u32, interface: &str, version: u32) {
        let registry = self.conn.registry;
        /// Binds a global into a field of [`Conn`], at the version we cap it to.
        macro_rules! bind {
            ($field:ident, $module:path, $version:expr, $slot:expr) => {{
                use $module as target;
                if self.conn.$field.is_null() {
                    // SAFETY: `registry` is live, and `bind` marshals the
                    // interface descriptor's own name and the version asked for.
                    self.conn.$field = unsafe {
                        wl_registry::bind(registry, name, &target::INTERFACE, version.min($version))
                    };
                    if !self.conn.$field.is_null() {
                        // Which registry name this slot was filled from, so a
                        // later `global_remove` can be matched to it — see
                        // [`withdraw_singleton`](Self::withdraw_singleton).
                        self.singletons.push((name, $slot));
                    }
                }
            }};
        }
        match interface {
            "wl_compositor" => bind!(
                compositor,
                wl_compositor,
                COMPOSITOR_VERSION,
                Singleton::Compositor
            ),
            "xdg_wm_base" => {
                // Only watch the proxy the *first* time. A compositor may
                // advertise two globals of the same interface, and re-watching
                // an already-bound one pushed a duplicate into `Sink::objects`
                // and made libwayland log "proxy already has a dispatcher".
                let fresh = self.conn.wm_base.is_null();
                bind!(wm_base, xdg_wm_base, WM_BASE_VERSION, Singleton::WmBase);
                if fresh {
                    let proxy = self.conn.wm_base;
                    self.conn.watch(proxy, ObjectKind::WmBase);
                }
            }
            "wp_viewporter" => bind!(viewporter, wp_viewporter, 1, Singleton::Viewporter),
            "wp_fractional_scale_manager_v1" => {
                bind!(
                    fractional_scale_manager,
                    wp_fractional_scale_manager_v1,
                    1,
                    Singleton::FractionalScaleManager
                );
            }
            "zxdg_output_manager_v1" => {
                bind!(
                    xdg_output_manager,
                    zxdg_output_manager_v1,
                    XDG_OUTPUT_VERSION,
                    Singleton::XdgOutputManager
                );
            }
            "zxdg_decoration_manager_v1" => {
                bind!(
                    decoration_manager,
                    zxdg_decoration_manager_v1,
                    DECORATION_VERSION,
                    Singleton::DecorationManager
                );
            }
            "zwp_relative_pointer_manager_v1" => {
                bind!(
                    relative_pointer_manager,
                    zwp_relative_pointer_manager_v1,
                    1,
                    Singleton::RelativePointerManager
                );
            }
            "zwp_pointer_constraints_v1" => {
                bind!(
                    pointer_constraints,
                    zwp_pointer_constraints_v1,
                    1,
                    Singleton::PointerConstraints
                );
            }
            "wl_data_device_manager" => {
                bind!(
                    data_device_manager,
                    wl_data_device_manager,
                    DATA_DEVICE_VERSION,
                    Singleton::DataDeviceManager
                );
            }
            "zwlr_layer_shell_v1" => {
                bind!(
                    layer_shell,
                    zwlr_layer_shell_v1,
                    layer::LAYER_SHELL_VERSION,
                    Singleton::LayerShell
                );
            }
            "zwp_text_input_manager_v3" => {
                bind!(
                    text_input_manager,
                    zwp_text_input_manager_v3,
                    text_input::TEXT_INPUT_VERSION,
                    Singleton::TextInputManager
                );
            }
            // Below version 4 there is no feedback to read, and binding the
            // manager would buy nothing.
            "zwp_linux_dmabuf_v1" if version >= dmabuf::DMABUF_VERSION => {
                bind!(
                    dmabuf,
                    zwp_linux_dmabuf_v1,
                    dmabuf::DMABUF_VERSION,
                    Singleton::Dmabuf
                );
                self.add_dmabuf_feedback();
            }
            "wp_cursor_shape_manager_v1" => {
                bind!(
                    cursor_shape_manager,
                    wp_cursor_shape_manager_v1,
                    cursor_shape::CURSOR_SHAPE_VERSION,
                    Singleton::CursorShapeManager
                );
            }
            "wl_output" => {
                // SAFETY: `registry` is live; see the macro above.
                let proxy = unsafe {
                    wl_registry::bind(
                        registry,
                        name,
                        &wl_output::INTERFACE,
                        version.min(OUTPUT_VERSION),
                    )
                };
                if proxy.is_null() {
                    return;
                }
                self.conn.watch(proxy, ObjectKind::Output);
                let id = MonitorId(self.next_monitor_id);
                // Never reused within a session, which is the obligation
                // `monitor`'s docs put on a backend in place of a generation.
                self.next_monitor_id += 1;
                self.outputs.push(Output {
                    proxy: proxy as usize,
                    xdg: ptr::null_mut(),
                    global: name,
                    id,
                    x: 0,
                    y: 0,
                    width: 0,
                    height: 0,
                    refresh_millihertz: 0,
                    scale: 1,
                    logical_x: 0,
                    logical_y: 0,
                    logical_width: 0,
                    logical_height: 0,
                    name: format!("wl-output-{}", id.0),
                    settled: false,
                });
            }
            "wl_seat" => {
                // SAFETY: `registry` is live; see the macro above.
                let proxy = unsafe {
                    wl_registry::bind(
                        registry,
                        name,
                        &wl_seat::INTERFACE,
                        version.min(SEAT_VERSION),
                    )
                };
                if proxy.is_null() {
                    return;
                }
                self.conn.watch(proxy, ObjectKind::Seat);
                let device = DeviceId(self.next_device_id);
                self.next_device_id += 1;
                self.seats.push(Seat {
                    proxy,
                    global: name,
                    device,
                    capabilities: 0,
                    pointer: ptr::null_mut(),
                    keyboard: ptr::null_mut(),
                    relative_pointer: ptr::null_mut(),
                    cursor_shape: ptr::null_mut(),
                    data: None,
                    enter_serial: 0,
                    last_serial: 0,
                    press_serial: 0,
                    pointer_focus: None,
                    pointer_position: PhysicalPoint::ORIGIN,
                    frame: PointerFrame::default(),
                    keyboard_focus: None,
                    keymap: None,
                    modifiers: Modifiers::empty(),
                    held: Vec::new(),
                    repeat: Repeat::default(),
                    text_input: None,
                });
            }
            _ => {}
        }
    }

    /// Lets go of a singleton global the compositor has withdrawn.
    ///
    /// **A withdrawn global is not a dead session, and the proxy must not stay
    /// in its slot.** `wl_registry.global_remove` says the bound object is
    /// inert from that point: requests to it are ignored. It is not null,
    /// though, so [`bind_global`](Self::bind_global)'s `is_null` guard would
    /// refuse to bind the *replacement* a compositor advertises when the same
    /// interface comes back — and every later request would go to the inert
    /// object. Clearing the slot is the whole of what makes a re-advertisement
    /// bind, and it is why the call sites that marshal on these read them for
    /// null: after this, "the compositor has one" is a question with two
    /// answers again.
    ///
    /// **Objects already created from the global are not affected**, which is
    /// each protocol's own wording for its destructor and the reason a window
    /// survives its factory going away. What a withdrawal costs is the ability
    /// to make *new* ones until it returns.
    ///
    /// [`caps`](Shell::caps) is latched at [`open`](Self::open) and is
    /// deliberately not recomputed here: the seam requires a capability set
    /// that does not move under a caller. So a withdrawal is never a bit going
    /// out. The two requests that cannot be served without their global —
    /// [`create_window`](Shell::create_window) and
    /// [`clipboard_offer`](Shell::clipboard_offer) — fail by name instead;
    /// the optional ones (a decoration, a viewport, a pointer constraint) go
    /// on reporting the capability and quietly doing nothing, which is what
    /// the inert proxy did before this and is a gap this does not close.
    fn withdraw_singleton(&mut self, name: u32) {
        let Some(index) = self.singletons.iter().position(|(bound, _)| *bound == name) else {
            return;
        };
        let (_, slot) = self.singletons.remove(index);
        // Taken out of the slot first: both destructors below free the proxy,
        // and a copy left in `Conn` would be a dangling pointer for whatever
        // reads the field next.
        let proxy = core::mem::replace(slot.slot(&mut self.conn), ptr::null_mut());
        match slot {
            // Neither has a destructor at the version this backend binds —
            // `wl_compositor.release` arrived in 7 and
            // `wl_data_device_manager.release` in 4, and see
            // [`COMPOSITOR_VERSION`] for why the cap is what the code
            // implements. The compositor keeps the object until the connection
            // closes, which is the same bargain `Drop` already makes for them.
            Singleton::Compositor | Singleton::DataDeviceManager => self.conn.destroy(proxy),
            // `xdg_wm_base.destroy` is a **protocol error** — `defunct_surfaces`,
            // which disconnects the client — while any `xdg_surface` made from
            // it is still alive, and every open window holds one. So the
            // destructor is sent only when there are none, and the proxy is
            // dropped client-side otherwise.
            Singleton::WmBase => {
                if self.windows.is_empty() {
                    // SAFETY: `proxy` is live on this connection and
                    // `destroy` is `xdg_wm_base`'s own destructor.
                    unsafe { self.conn.release(proxy, xdg_wm_base::destroy) };
                } else {
                    self.conn.destroy(proxy);
                }
            }
            // The rest each say, in their own protocol, that destroying the
            // manager leaves the objects it created alone.
            // SAFETY: `proxy` is live on this connection and each destructor is
            // its own interface's.
            Singleton::Viewporter => unsafe { self.conn.release(proxy, wp_viewporter::destroy) },
            Singleton::FractionalScaleManager => unsafe {
                self.conn
                    .release(proxy, wp_fractional_scale_manager_v1::destroy);
            },
            Singleton::XdgOutputManager => unsafe {
                self.conn.release(proxy, zxdg_output_manager_v1::destroy);
            },
            Singleton::DecorationManager => unsafe {
                self.conn
                    .release(proxy, zxdg_decoration_manager_v1::destroy);
            },
            Singleton::RelativePointerManager => unsafe {
                self.conn
                    .release(proxy, zwp_relative_pointer_manager_v1::destroy);
            },
            Singleton::PointerConstraints => unsafe {
                self.conn
                    .release(proxy, zwp_pointer_constraints_v1::destroy);
            },
            // `zwlr_layer_shell_v1.destroy` arrived in version 3.
            Singleton::LayerShell => unsafe {
                self.conn
                    .release_since(proxy, 3, zwlr_layer_shell_v1::destroy);
            },
            Singleton::TextInputManager => unsafe {
                self.conn.release(proxy, zwp_text_input_manager_v3::destroy);
            },
            Singleton::CursorShapeManager => unsafe {
                self.conn
                    .release(proxy, wp_cursor_shape_manager_v1::destroy);
            },
            // The feedback first: it was made from the manager, and the
            // device it named goes with it.
            Singleton::Dmabuf => {
                self.remove_dmabuf_feedback();
                // SAFETY: as above.
                unsafe { self.conn.release(proxy, zwp_linux_dmabuf_v1::destroy) };
            }
        }
        self.conn.flush();
        crcbl_core::log::warn!(
            "the compositor withdrew {}; it will be bound again if it is re-advertised",
            slot.interface().to_string_lossy()
        );
    }

    /// Gives every seat a `wl_data_device`, once there is a manager to make one
    /// with.
    ///
    /// Called after each registry batch for the same reason
    /// [`ensure_xdg_outputs`](Self::ensure_xdg_outputs) is: the order globals
    /// arrive in is the compositor's choice, and a `wl_seat` announced before
    /// `wl_data_device_manager` would otherwise never get a clipboard. A seat
    /// that appears *later* is covered too, because it goes through the same
    /// registry batch.
    fn ensure_data_devices(&mut self) {
        if self.conn.data_device_manager.is_null() {
            return;
        }
        let manager = self.conn.data_device_manager;
        for index in 0..self.seats.len() {
            if self.seats[index].data.is_some() {
                continue;
            }
            let seat = self.seats[index].proxy;
            // SAFETY: the manager and the seat are both live on this
            // connection; `get_data_device` creates the per-seat endpoint.
            let device = unsafe { wl_data_device_manager::get_data_device(manager, seat) };
            if device.is_null() {
                continue;
            }
            self.conn.watch(device, ObjectKind::DataDevice);
            self.seats[index].data = Some(data::Device::new(device));
        }
        self.conn.flush();
    }

    fn output_mut(&mut self, proxy: usize) -> Option<&mut Output> {
        self.outputs.iter_mut().find(|output| output.proxy == proxy)
    }

    /// Creates a `zxdg_output_v1` for every output that has none.
    ///
    /// Called after each registry batch rather than inside
    /// [`bind_global`](Self::bind_global) because the order globals arrive in
    /// is the compositor's choice: `wl_output` can and does precede
    /// `zxdg_output_manager_v1`, and an output bound before the manager would
    /// otherwise never get its logical geometry.
    fn ensure_xdg_outputs(&mut self) {
        if self.conn.xdg_output_manager.is_null() {
            return;
        }
        let manager = self.conn.xdg_output_manager;
        let pending: Vec<usize> = self
            .outputs
            .iter()
            .filter(|output| output.xdg.is_null())
            .map(|output| output.proxy)
            .collect();
        for proxy in pending {
            // SAFETY: the manager and the `wl_output` are both live on this
            // connection; `get_xdg_output` creates the add-on object.
            let xdg =
                unsafe { zxdg_output_manager_v1::get_xdg_output(manager, proxy as *mut WlProxy) };
            self.conn.watch(xdg, ObjectKind::XdgOutput);
            if let Some(output) = self.output_mut(proxy) {
                output.xdg = xdg;
            }
        }
    }

    /// Rebuilds [`monitors`](Shell::monitors) from the settled outputs.
    fn republish_monitors(&mut self) {
        let monitors: Vec<MonitorInfo> = self
            .outputs
            .iter()
            .filter(|output| output.settled)
            .enumerate()
            // Wayland has no primary-output concept, so the first one seen is
            // the default, exactly as `MonitorInfo::is_primary` prescribes.
            .map(|(index, output)| output.info(index == 0))
            .collect();
        if monitors != self.monitors {
            for monitor in crate::monitor::queue_removed(&self.monitors, &monitors, &mut self.queue)
            {
                // The compositor sends a layer surface on a removed output its
                // own `closed`, usually first; this covers one that does not,
                // and `close_requested` makes the two one request.
                let panels: Vec<WindowId> = self
                    .windows
                    .iter()
                    .filter(|(_, window)| {
                        window.panel.as_ref().and_then(|panel| panel.desc().monitor)
                            == Some(monitor)
                    })
                    .map(|(handle, _)| handle.cast())
                    .collect();
                for panel in panels {
                    self.close_requested(panel);
                }
            }
            self.monitors = monitors;
            self.queue.push_back(ShellEvent::MonitorsChanged);
        }
    }

    /// Turns everything the dispatcher queued into state changes and
    /// [`ShellEvent`]s.
    ///
    /// Runs *after* libwayland has returned, never inside it, so it can take
    /// `&mut self` freely.
    #[expect(
        clippy::too_many_lines,
        reason = "a flat routing table from wire events to handlers; every arm \
                  is one or two lines and splitting it hides the routing"
    )]
    fn process_raw(&mut self) {
        let events = core::mem::take(&mut self.conn.sink().events);
        let mut monitors_dirty = false;
        for event in events {
            match event {
                RawEvent::Global {
                    name,
                    interface,
                    version,
                } => self.bind_global(name, &interface, version),
                RawEvent::GlobalRemove { name } => {
                    if let Some(index) =
                        self.outputs.iter().position(|output| output.global == name)
                    {
                        let output = self.outputs.remove(index);
                        let proxy = output.proxy as *mut WlProxy;
                        // Both interfaces have a protocol destructor, which
                        // `Conn::destroy`'s own documentation forbids using it
                        // for: a client-side destroy frees the proxy without
                        // telling the compositor, so on every hotplug the
                        // compositor kept the object until we disconnected.
                        // `zxdg_output_v1.destroy` has existed since version 1;
                        // `wl_output.release` since 3, and this binds 4.
                        // SAFETY: both proxies are live, and each destructor is
                        // its own interface's.
                        unsafe {
                            self.conn.release(output.xdg, zxdg_output_v1::destroy);
                            self.conn.release_since(proxy, 3, wl_output::release);
                        }
                        monitors_dirty = true;
                    }
                    if let Some(index) = self.seats.iter().position(|seat| seat.global == name) {
                        self.remove_seat(index);
                    }
                    self.withdraw_singleton(name);
                }
                RawEvent::Ping { serial } => {
                    // Answer or be killed: a compositor that does not get a
                    // pong marks the client unresponsive. Nothing to answer
                    // with once the global has been withdrawn, and a request
                    // marshalled on the null that leaves behind would take the
                    // process down instead.
                    if !self.conn.wm_base.is_null() {
                        // SAFETY: `wm_base` is live and is what the ping arrived on.
                        unsafe { xdg_wm_base::pong(self.conn.wm_base, serial) };
                        self.conn.flush();
                    }
                }
                RawEvent::OutputGeometry { output, x, y } => {
                    if let Some(output) = self.output_mut(output) {
                        output.x = x;
                        output.y = y;
                    }
                }
                RawEvent::OutputMode {
                    output,
                    flags,
                    width,
                    height,
                    refresh,
                } => {
                    // Bit 0 is `current`; a compositor lists every mode it
                    // supports and only one of them is in effect.
                    if flags & wl_output::mode::CURRENT != 0
                        && let Some(output) = self.output_mut(output)
                    {
                        output.width = width;
                        output.height = height;
                        output.refresh_millihertz = refresh.max(0).unsigned_abs();
                    }
                }
                RawEvent::OutputScale { output, factor } => {
                    if let Some(output) = self.output_mut(output) {
                        output.scale = factor.max(1);
                    }
                }
                RawEvent::OutputName { output, name } => {
                    if let Some(output) = self.output_mut(output) {
                        output.name = name;
                    }
                }
                RawEvent::OutputDone { output } => {
                    if let Some(output) = self.output_mut(output) {
                        output.settled = true;
                        monitors_dirty = true;
                    }
                }
                // Both arms mark the monitor list dirty. On a version-3
                // manager that is belt and braces — the protocol requires a
                // `wl_output.done` after the `xdg_output` burst, and that is
                // what settles the output. On version 1 and 2 it is the only
                // thing that works: those send `zxdg_output_v1.done` instead,
                // which this backend does not listen for (it would be a second
                // settle signal that could disagree with the first), so without
                // this the monitor list would keep the pre-`xdg_output`
                // fallback for the whole session and every fractional scale
                // would read as an integer.
                RawEvent::XdgOutputPosition { xdg_output, x, y } => {
                    if let Some(output) = self.output_by_xdg(xdg_output) {
                        output.logical_x = x;
                        output.logical_y = y;
                        monitors_dirty = true;
                    }
                }
                RawEvent::XdgOutputSize {
                    xdg_output,
                    width,
                    height,
                } => {
                    if let Some(output) = self.output_by_xdg(xdg_output) {
                        output.logical_width = width;
                        output.logical_height = height;
                        monitors_dirty = true;
                    }
                }
                RawEvent::SurfaceEnter { surface, output } => {
                    self.surface_output_changed(surface, output, true);
                }
                RawEvent::SurfaceLeave { surface, output } => {
                    self.surface_output_changed(surface, output, false);
                }
                RawEvent::FrameDone { callback } => self.frame_done(callback),
                RawEvent::ToplevelConfigure {
                    toplevel,
                    width,
                    height,
                    states,
                } => {
                    let Some(id) = self.window_by_proxy(toplevel, |w| w.toplevel as usize) else {
                        continue;
                    };
                    let Ok(window) = self.window_mut(id) else {
                        continue;
                    };
                    // `0 × 0` means "you choose" — the usual content of a first
                    // configure, and the single biggest difference from what
                    // `HeadlessShell` models.
                    window.pending.size = (width > 0 && height > 0)
                        .then(|| LogicalSize::new(f64::from(width), f64::from(height)));
                    window.pending.states = states;
                }
                RawEvent::XdgSurfaceConfigure {
                    xdg_surface,
                    serial,
                } => {
                    if let Some(id) = self.window_by_proxy(xdg_surface, |w| w.xdg_surface as usize)
                    {
                        self.apply_configure(id, serial);
                    }
                }
                RawEvent::LayerConfigure {
                    layer_surface,
                    serial,
                    width,
                    height,
                } => self.layer_configured(layer_surface, serial, width, height),
                RawEvent::PopupConfigure {
                    popup,
                    width,
                    height,
                } => {
                    if let Some(id) = self.window_by_proxy(popup, |w| w.popup as usize)
                        && let Ok(window) = self.window_mut(id)
                    {
                        window.pending.size = (width > 0 && height > 0)
                            .then(|| LogicalSize::new(f64::from(width), f64::from(height)));
                    }
                }
                RawEvent::PopupDone { popup } => {
                    if let Some(id) = self.window_by_proxy(popup, |w| w.popup as usize) {
                        self.close_requested(id);
                    }
                }
                RawEvent::ToplevelClose { toplevel } => {
                    if let Some(id) = self.window_by_proxy(toplevel, |w| w.toplevel as usize) {
                        self.close_requested(id);
                    }
                }
                RawEvent::LayerClosed { layer_surface } => {
                    if let Some(id) =
                        self.window_by_proxy(layer_surface, |w| w.layer_surface as usize)
                    {
                        self.close_requested(id);
                    }
                }
                RawEvent::DecorationConfigure { decoration, mode } => {
                    self.decoration_configured(decoration, mode);
                }
                RawEvent::PreferredScale { object, scale } => {
                    self.preferred_scale_changed(object, scale);
                }
                RawEvent::SeatCapabilities { seat, capabilities } => {
                    self.seat_capabilities_changed(seat, capabilities);
                }
                RawEvent::DmabufMainDevice { feedback, device } => {
                    self.dmabuf_main_device(feedback, device);
                }
                RawEvent::DmabufDone { feedback } => self.dmabuf_done(feedback),
                event @ (RawEvent::DataOffer { .. }
                | RawEvent::OfferMime { .. }
                | RawEvent::Selection { .. }
                | RawEvent::DragEnter { .. }
                | RawEvent::DragLeave { .. }
                | RawEvent::DragMotion { .. }
                | RawEvent::DragDrop { .. }
                | RawEvent::SourceSend { .. }
                | RawEvent::SourceCancelled { .. }) => self.process_data(event),
                RawEvent::TextInput { text_input, event } => {
                    self.text_input_event(text_input, event);
                }
                other => self.process_input(other),
            }
        }
        self.ensure_xdg_outputs();
        self.ensure_data_devices();
        self.ensure_text_inputs();
        self.ensure_cursor_shapes();
        if monitors_dirty {
            self.republish_monitors();
        }
        // A compositor is not obliged to end a burst with a `wl_pointer.frame`
        // before the socket goes quiet — and a version-4 pointer has no frame
        // event at all. Flushing here as well means a motion is never held back
        // to the next pump.
        self.flush_pointer_frames();
    }

    /// The compositor asked for a window to go: an `xdg_toplevel.close`, a
    /// layer surface's `closed`, or a panel's monitor being removed.
    ///
    /// One request until it is answered: a panel whose output is unplugged is
    /// told by the compositor and by the monitor list, and a consumer must see
    /// one question, not two.
    fn close_requested(&mut self, id: WindowId) {
        let Ok(window) = self.window_mut(id) else {
            return;
        };
        if window.close_pending {
            return;
        }
        window.close_pending = true;
        self.queue
            .push_back(ShellEvent::CloseRequested { window: id });
    }

    /// The window a key typed into `focused` belongs to: its innermost open
    /// [grabbing](crate::PopupInput::Grab) popup, or `focused` itself.
    ///
    /// An `xdg_popup` grab need not move keyboard focus: the protocol leaves
    /// the compositor free to keep `wl_keyboard` on the toplevel.
    /// `PopupInput::Grab` promises the popup the keyboard while it is open,
    /// so the routing is done here, whichever surface the compositor
    /// focused.
    fn keyboard_target(&self, focused: WindowId) -> WindowId {
        let mut target = focused;
        while let Some(child) = self
            .windows
            .iter()
            .filter(|(_, state)| {
                state.parent == Some(target) && state.popup_input == Some(crate::PopupInput::Grab)
            })
            .map(|(handle, _)| handle.cast())
            .last()
        {
            target = child;
        }
        target
    }

    fn output_by_xdg(&mut self, xdg: usize) -> Option<&mut Output> {
        self.outputs
            .iter_mut()
            .find(|output| output.xdg as usize == xdg)
    }

    // -----------------------------------------------------------------------
    // Scale, configure, cursor, constraints
    // -----------------------------------------------------------------------

    /// The monitor a surface is on, when there is exactly one answer.
    ///
    /// `entered` is a list of `wl_output` **proxies** — what
    /// `wl_surface.enter` carries — not indices into
    /// [`outputs`](Self::outputs).
    ///
    /// `None` when the surface is on no output (not mapped yet) or on more
    /// than one (straddling two displays): both are "the backend cannot say
    /// which", which is a different statement from a *request* that did not
    /// care. See [`DisplayMode::satisfied_by`].
    fn monitor_of(&self, entered: &[usize]) -> Option<MonitorId> {
        let [only] = entered else {
            return None;
        };
        self.outputs
            .iter()
            .find(|output| output.proxy == *only)
            .map(|output| output.id)
    }

    fn surface_output_changed(&mut self, surface: usize, output: usize, entered: bool) {
        let Some(id) = self.window_by_proxy(surface, |w| w.surface as usize) else {
            return;
        };
        // The scale of an output the surface is on, resolved before the
        // borrow of the window.
        let scales: Vec<(usize, i32)> = self
            .outputs
            .iter()
            .map(|output| (output.proxy, output.scale))
            .collect();
        let Ok(window) = self.window_mut(id) else {
            return;
        };
        if entered {
            if !window.outputs.contains(&output) {
                window.outputs.push(output);
            }
        } else {
            window.outputs.retain(|candidate| *candidate != output);
        }
        // **A surface can change output without being reconfigured.** A window
        // fullscreened onto another monitor is configured at the new size
        // first; the `wl_surface.enter` for the monitor it landed on arrives
        // afterwards, and no further configure follows it. So the effective
        // mode's monitor is refreshed here as well as in `apply_configure`, or
        // it would be whatever the surface was on at the last configure —
        // which for the move that matters is the monitor it came *from*.
        let entered = window.outputs.clone();
        let monitor = self.monitor_of(&entered);
        if let Ok(window) = self.window_mut(id)
            && let Some(config) = window.configuration.as_mut()
            && config.mode.is_borderless()
        {
            config.mode = DisplayMode::Borderless { monitor };
        }
        let Ok(window) = self.window_mut(id) else {
            return;
        };
        // Without `fractional-scale-v1` the only correct integer scale for a
        // surface spanning several outputs is the largest of them: anything
        // smaller is visibly blurry on the sharpest one.
        let scale = window
            .outputs
            .iter()
            .filter_map(|proxy| {
                scales
                    .iter()
                    .find(|(candidate, _)| candidate == proxy)
                    .map(|(_, scale)| *scale)
            })
            .max()
            .unwrap_or(1)
            .max(1);
        if scale == window.scale {
            return;
        }
        window.scale = scale;
        // `wl_surface.set_buffer_scale` and a `wp_viewport` destination are two
        // ways of saying the same thing, and the viewporter protocol forbids
        // using both. When the compositor is driving the scale fractionally,
        // the viewport is the one in effect — from the start, not only once
        // `preferred_scale` has arrived: a buffer scale set before it stayed
        // set, and a strict compositor refuses a buffer whose size is not a
        // multiple of it, which an odd width at 1.5 is.
        if !window.is_fractional() {
            let surface_proxy = window.surface;
            // SAFETY: the surface is live and `set_buffer_scale` takes one int.
            unsafe { wl_surface::set_buffer_scale(surface_proxy, scale) };
        }
        self.rescale(id);
    }

    /// A `wp_fractional_scale_v1.preferred_scale`.
    fn preferred_scale_changed(&mut self, object: usize, scale: u32) {
        let Some(id) = self.window_by_proxy(object, |w| w.fractional_scale as usize) else {
            return;
        };
        let Ok(window) = self.window_mut(id) else {
            return;
        };
        if window.preferred_scale == Some(scale) {
            return;
        }
        window.preferred_scale = Some(scale);
        self.rescale(id);
    }

    /// Republishes a window's configuration after its scale changed.
    fn rescale(&mut self, id: WindowId) {
        let Ok(window) = self.window_mut(id) else {
            return;
        };
        let Some(config) = window.configuration else {
            // Not configured yet: the scale folds into the first configure
            // rather than being announced on its own.
            return;
        };
        let scale_factor = window.scale_factor();
        if (config.scale_factor - scale_factor).abs() < f64::EPSILON {
            return;
        }
        let logical = window.logical_size();
        let size = logical.to_physical(scale_factor);
        window.configuration = Some(WindowConfiguration {
            size,
            scale_factor,
            mode: config.mode,
        });
        let (surface, viewport) = (window.surface, window.viewport);
        // SAFETY: both proxies are live; a scale change is only in effect after
        // a commit, and the viewport destination is what tells the compositor
        // how large the (physical) buffer should appear.
        unsafe {
            set_viewport(viewport, logical);
            wl_surface::commit(surface);
        }
        self.queue.push_back(ShellEvent::ScaleFactorChanged {
            window: id,
            scale_factor,
            size,
        });
        self.conn.flush();
    }

    /// Completes a configure: acknowledge it, publish the new configuration,
    /// and commit.
    ///
    /// For either role. A layer surface has no states, so it is always
    /// [`DisplayMode::Windowed`], and its focus comes from `wl_keyboard`
    /// alone.
    fn apply_configure(&mut self, id: WindowId, serial: u32) {
        // **Which monitor a fullscreen surface ended up on is observable, even
        // though asking for one is only a hint.** `wl_surface.enter` names the
        // outputs the surface is on, and a fullscreen surface is on exactly
        // one — so the *answer* can name a monitor where the *request* could
        // only suggest it. Without this a request for `Borderless { monitor:
        // Some(second) }` was answered `Borderless { monitor: None }` and
        // `mode_request_honoured` said no, for a window covering exactly the
        // monitor that was asked for.
        //
        // Exactly one, deliberately: a surface straddling two outputs has no
        // single answer, and `None` there means "the backend cannot say", which
        // is what it is. See `DisplayMode::satisfied_by` for how the two
        // meanings of `None` differ.
        let on = {
            let Ok(window) = self.window(id) else {
                return;
            };
            self.monitor_of(window.outputs.as_slice())
        };
        let Ok(window) = self.window_mut(id) else {
            return;
        };

        let fullscreen = window
            .pending
            .states
            .contains(&xdg_toplevel::state::FULLSCREEN);
        let mode = if fullscreen {
            DisplayMode::Borderless { monitor: on }
        } else {
            DisplayMode::Windowed
        };
        let scale_factor = window.scale_factor();
        let logical = window.logical_size();
        // Constraints are hints the compositor may ignore, so they are applied
        // here too — the same thing `SizeConstraints::apply` does for
        // `HeadlessShell`, and the reason the seam has no "effective
        // constraints".
        let size = window
            .requested_constraints
            .apply(logical.to_physical(scale_factor), scale_factor);
        let config = WindowConfiguration {
            size,
            scale_factor,
            mode,
        };
        let changed = window.configuration != Some(config);
        let scale_changed = window
            .configuration
            .is_some_and(|previous| previous.scale_factor != scale_factor);
        window.configuration = Some(config);
        // `xdg_toplevel.state.activated` is a focus signal a compositor sets
        // even before a `wl_seat` has a keyboard. Compare against the previous
        // value rather than emitting on every configure: a compositor restates
        // the full state set every time.
        let focused = window
            .pending
            .states
            .contains(&xdg_toplevel::state::ACTIVATED);
        let xdg = window.xdg_surface;
        let layer = window.layer_surface;
        let toplevel = window.toplevel;
        let surface = window.surface;
        let viewport = window.viewport;

        // SAFETY: every proxy is live, and the configure came from whichever
        // of the two role objects is not null. `ack_configure` must precede
        // the commit, and the commit is what makes the acknowledged state
        // current. The viewport destination is the logical size the compositor
        // just asked for, which is exactly what `wp_viewport` wants.
        unsafe {
            set_viewport(viewport, logical);
            if layer.is_null() {
                xdg_surface::ack_configure(xdg, serial);
            } else {
                zwlr_layer_surface_v1::ack_configure(layer, serial);
            }
            wl_surface::commit(surface);
        }
        self.conn.flush();

        if changed {
            if scale_changed {
                self.queue.push_back(ShellEvent::ScaleFactorChanged {
                    window: id,
                    scale_factor,
                    size,
                });
            }
            self.queue.push_back(ShellEvent::Resized {
                window: id,
                size,
                scale_factor,
            });
        }
        // `activated` is a toplevel state. A layer surface or a popup has none,
        // and reading its empty set as "not activated" would undo the focus
        // its `wl_keyboard.enter` gave it on every configure.
        if !toplevel.is_null() {
            self.set_focus(id, focused);
        }
    }

    /// Sends the cursor a window asked for on a seat that has just entered it.
    ///
    /// A shape needs the seat's `cursor-shape-v1` device; see
    /// [`Shell::set_cursor`].
    fn apply_cursor(&mut self, index: usize, window: WindowId) {
        let Ok(state) = self.window(window) else {
            return;
        };
        // Never set: the compositor's own cursor stays.
        let Some(cursor) = state.cursor else {
            return;
        };
        let seat = &self.seats[index];
        let (pointer, device, serial) = (seat.pointer, seat.cursor_shape, seat.enter_serial);
        if pointer.is_null() {
            return;
        }
        match cursor {
            // SAFETY: the pointer is live and a null surface argument is the
            // documented way to say "no cursor" in core Wayland.
            None => unsafe { wl_pointer::set_cursor(pointer, serial, ptr::null_mut(), 0, 0) },
            Some(icon) if !device.is_null() => {
                // SAFETY: the device is live, made from this seat's pointer,
                // and `shape_of` only names entries the bound version has.
                unsafe {
                    wp_cursor_shape_device_v1::set_shape(
                        device,
                        serial,
                        cursor_shape::shape_of(icon),
                    );
                }
            }
            // No device: `CURSOR_SHAPE` is clear, and the compositor's cursor
            // stays until the next `wl_pointer.enter` resets it.
            Some(_) => return,
        }
        self.conn.flush();
    }

    /// Rebuilds every window's pointer constraint against the current seats.
    ///
    /// Called when a mode changes and when a seat gains a pointer, because a
    /// constraint is a per-`(surface, pointer)` object and a pointer that did
    /// not exist yet could not have one.
    fn reapply_constraints(&mut self) {
        let windows: Vec<WindowId> = self
            .windows
            .iter()
            .filter(|(_, window)| window.pointer_mode.is_captured())
            .map(|(handle, _)| handle.cast())
            .collect();
        for window in windows {
            let mode = self
                .window(window)
                .map_or(PointerMode::Free, |w| w.pointer_mode);
            self.rebuild_constraint(window, mode);
        }
    }

    /// Destroys and recreates one window's constraints for `mode`.
    fn rebuild_constraint(&mut self, window: WindowId, mode: PointerMode) {
        let existing = match self.window_mut(window) {
            Ok(state) => {
                state.pointer_mode = mode;
                core::mem::take(&mut state.constraints)
            }
            Err(_) => return,
        };
        for (_, proxy) in existing {
            // SAFETY: each proxy is a live constraint object created below, and
            // the two interfaces share one destructor — see
            // `constraint_destructor`.
            unsafe { self.conn.release(proxy, constraint_destructor()) };
        }
        if mode == PointerMode::Free || self.conn.pointer_constraints.is_null() {
            self.conn.flush();
            return;
        }
        let Ok(surface) = self.window(window).map(|state| state.surface) else {
            return;
        };
        let manager = self.conn.pointer_constraints;
        let pointers: Vec<*mut WlProxy> = self
            .seats
            .iter()
            .map(|seat| seat.pointer)
            .filter(|pointer| !pointer.is_null())
            .collect();
        let mut created = Vec::with_capacity(pointers.len());
        for pointer in pointers {
            // A null region means "the whole surface", and `persistent` means
            // the constraint reactivates whenever the compositor is willing
            // again — the behaviour a game wants across an alt-tab, rather than
            // a one-shot that silently never comes back.
            // SAFETY: the manager, surface and pointer are all live on this
            // connection; a null region is the protocol's own "entire surface".
            let proxy = unsafe {
                match mode {
                    PointerMode::Locked => zwp_pointer_constraints_v1::lock_pointer(
                        manager,
                        surface,
                        pointer,
                        ptr::null_mut(),
                        zwp_pointer_constraints_v1::lifetime::PERSISTENT,
                    ),
                    _ => zwp_pointer_constraints_v1::confine_pointer(
                        manager,
                        surface,
                        pointer,
                        ptr::null_mut(),
                        zwp_pointer_constraints_v1::lifetime::PERSISTENT,
                    ),
                }
            };
            // The `locked`/`unlocked` and `confined`/`unconfined` events say
            // whether the constraint is currently active. Nothing in the seam
            // reports that — `WindowState::pointer_mode` is what was asked for
            // — so they are swallowed rather than left to warn.
            self.conn.watch(proxy, ObjectKind::Ignored);
            created.push((pointer as usize, proxy));
        }
        if let Ok(state) = self.window_mut(window) {
            state.constraints = created;
        }
        self.conn.flush();
    }

    /// Destroys the constraints that name a seat's pointer, because it is going
    /// away.
    ///
    /// Sent as the protocol destructor and sent **first**, before the
    /// `wl_pointer` itself is released: a constraint whose proxy is merely
    /// freed client-side leaves the server-side object alive for the rest of
    /// the session, and on a compositor that keys the lock off the object
    /// rather than the pointer that is a pointer that never comes back.
    ///
    /// Only this seat's constraints go — another seat's mouse is still plugged
    /// in and still locked. The windows keep their
    /// [`PointerMode`], so
    /// [`add_pointer`](Self::add_pointer) restores this seat's when a pointer
    /// reappears.
    fn drop_window_constraints_for_seat(&mut self, index: usize) {
        let pointer = self.seats[index].pointer as usize;
        let windows: Vec<WindowId> = self
            .windows
            .iter()
            .filter(|(_, window)| {
                window
                    .constraints
                    .iter()
                    .any(|(owner, _)| *owner == pointer)
            })
            .map(|(handle, _)| handle.cast())
            .collect();
        for window in windows {
            let doomed: Vec<*mut WlProxy> = match self.window_mut(window) {
                Ok(state) => {
                    let (mine, theirs) = state
                        .constraints
                        .iter()
                        .partition::<Vec<_>, _>(|(owner, _)| *owner == pointer);
                    state.constraints = theirs;
                    mine.into_iter().map(|(_, proxy)| proxy).collect()
                }
                Err(_) => continue,
            };
            for proxy in doomed {
                // SAFETY: each is a live constraint object created by
                // `rebuild_constraint`, destroyed exactly once.
                unsafe { self.conn.release(proxy, constraint_destructor()) };
            }
        }
        self.conn.flush();
    }

    /// What every new window gets once it is in the table: its AT-SPI
    /// adapter, behind the `accesskit` feature.
    fn opened(&mut self, window: WindowId) {
        #[cfg(feature = "accesskit")]
        {
            let waker = self.waker();
            self.access.open(window, waker);
        }
        #[cfg(not(feature = "accesskit"))]
        let _ = window;
    }

    /// Tears one window's objects down, innermost first.
    fn destroy_objects(&mut self, id: WindowId, window: &WlWindow) {
        for (_, proxy) in &window.constraints {
            // SAFETY: each is a live constraint object; see `rebuild_constraint`.
            unsafe { self.conn.release(*proxy, constraint_destructor()) };
        }
        // SAFETY: each proxy is live and each destructor is its own interface's.
        unsafe {
            self.conn
                .release(window.decoration, zxdg_toplevel_decoration_v1::destroy);
            self.conn
                .release(window.fractional_scale, wp_fractional_scale_v1::destroy);
            self.conn.release(window.viewport, wp_viewport::destroy);
        }
        // An unanswered frame request goes with its window, and is never
        // answered: the seam promises no `FrameReady` for a destroyed window.
        // `wl_callback` has no destructor request, so this is client-side.
        self.conn.destroy(window.frame_callback);
        // Protocol destructors, not client-side frees: a `wl_surface` the
        // compositor was never told about stays on screen, with its last
        // buffer, until the connection closes. Order matters: the role object
        // before `xdg_surface` before `wl_surface`. Destroying a `wl_surface`
        // that still has a role object is a protocol error and disconnects the
        // client, and so is destroying an `xdg_toplevel` before its decoration,
        // which went above.
        // SAFETY: each proxy is null or live, and each destructor is its own
        // interface's.
        unsafe {
            self.conn
                .release(window.layer_surface, zwlr_layer_surface_v1::destroy);
            self.conn.release(window.popup, xdg_popup::destroy);
            self.conn.release(window.toplevel, xdg_toplevel::destroy);
            self.conn.release(window.xdg_surface, xdg_surface::destroy);
            self.conn.release(window.surface, wl_surface::destroy);
        }
        // A seat pointing at a window that no longer exists would keep
        // reporting motion into a stale handle. Only *this* window's focus is
        // cleared: destroying one window must not make a seat forget that it is
        // pointing at another.
        // A transfer whose answer names a window that no longer exists would
        // deliver an event with a stale handle, which the seam forbids. The
        // descriptors close with the transfer, and a drop's offer — which
        // nothing else owns once the drag became a transfer — is destroyed
        // rather than leaked.
        let doomed: Vec<usize> = self
            .transfers
            .iter()
            .filter(|transfer| transfer.delivery.window() == id)
            .filter_map(|transfer| transfer.delivery.drop_offer())
            .collect();
        self.transfers
            .retain(|transfer| transfer.delivery.window() != id);
        for offer in doomed {
            self.destroy_offer(&data::Offer::new(offer as *mut WlProxy));
        }
        let drags: Vec<data::Offer> = self
            .seats
            .iter_mut()
            .filter_map(|seat| {
                let device = seat.data.as_mut()?;
                let over_this_window = device
                    .drag
                    .as_ref()
                    .is_some_and(|drag| drag.window == Some(id));
                over_this_window.then(|| device.drag.take()).flatten()
            })
            .map(|drag| drag.offer)
            .collect();
        for offer in &drags {
            self.destroy_offer(offer);
        }
        for seat in &mut self.seats {
            if seat.pointer_focus == Some(id) {
                seat.pointer_focus = None;
                seat.frame = PointerFrame::default();
            }
            if seat.keyboard_focus == Some(id) {
                seat.keyboard_focus = None;
                seat.held.clear();
            }
            if seat.repeat.key.is_some_and(|key| key.window == id) {
                seat.repeat.key = None;
            }
        }
        self.forget_text_input_focus(id);
        self.conn.flush();
    }
}

/// The destructor request shared by both constraint interfaces.
///
/// `zwp_locked_pointer_v1.destroy` and `zwp_confined_pointer_v1.destroy` are
/// opcode 0 on both interfaces, take no arguments, and are the only requests
/// this backend ever sends on either — so one function genuinely serves both,
/// and which of the two names it is spelled with is a documentation choice, not
/// a dispatch. Nothing here can dispatch on the kind anyway:
/// [`WlWindow::constraints`] records the pointer and the proxy, not which
/// interface the proxy is. This used to carry a
/// `let _ = zwp_confined_pointer_v1::REQ_DESTROY;` that did nothing but make
/// the call sites' "named per kind" comments look substantiated.
const fn constraint_destructor() -> unsafe fn(*mut WlProxy) {
    zwp_locked_pointer_v1::destroy
}

/// `wl_pointer.axis`'s enum as an index into a `[vertical, horizontal]` pair.
const fn axis_slot(axis: u32) -> Option<usize> {
    match axis {
        wl_pointer::axis::VERTICAL_SCROLL => Some(0),
        wl_pointer::axis::HORIZONTAL_SCROLL => Some(1),
        _ => None,
    }
}

/// A logical length as the whole number the protocols take: rounded, and
/// clamped into `0..=i32::MAX`, with a non-finite value read as zero.
#[expect(
    clippy::cast_possible_truncation,
    reason = "clamped into i32's range before the cast, and a NaN casts to 0"
)]
fn round_logical(value: f64) -> i32 {
    value.round().clamp(0.0, f64::from(i32::MAX)) as i32
}

/// Sets a viewport's destination to a logical size, if there is a viewport.
///
/// # Safety
///
/// `viewport` must be null or a live `wp_viewport`.
unsafe fn set_viewport(viewport: *mut WlProxy, logical: LogicalSize) {
    if viewport.is_null() {
        return;
    }
    // `wp_viewport` rejects a non-positive destination with `bad_value`, and a
    // window can legitimately be asked to be zero-sized before its first real
    // configure.
    let round = |value: f64| round_logical(value).max(1);
    // SAFETY: the caller guarantees the proxy is live; both arguments are
    // positive integers, which is what the protocol requires.
    unsafe { wp_viewport::set_destination(viewport, round(logical.width), round(logical.height)) };
}

impl Drop for WaylandShell {
    fn drop(&mut self) {
        // Popups before the windows they belong to, at every depth: a surface
        // destroyed under a live popup is a protocol error. Each pass takes
        // the windows nothing names as a parent.
        while !self.windows.is_empty() {
            let leaves: Vec<WindowId> = self
                .windows
                .iter()
                .filter(|(handle, _)| {
                    let id: WindowId = handle.cast();
                    !self
                        .windows
                        .iter()
                        .any(|(_, window)| window.parent == Some(id))
                })
                .map(|(handle, _)| handle.cast())
                .collect();
            for id in leaves {
                if let Some(window) = self.windows.remove(id.cast()) {
                    self.destroy_objects(id, &window);
                }
            }
        }
        for index in (0..self.seats.len()).rev() {
            self.remove_seat(index);
        }
        let outputs: Vec<(*mut WlProxy, *mut WlProxy)> = self
            .outputs
            .iter()
            .map(|output| (output.xdg, output.proxy as *mut WlProxy))
            .collect();
        for (xdg, output) in outputs {
            // SAFETY: both proxies are live and each destructor is its own
            // interface's; see the hotplug path for why these are protocol
            // destructors rather than `Conn::destroy`.
            unsafe {
                self.conn.release(xdg, zxdg_output_v1::destroy);
                self.conn.release_since(output, 3, wl_output::release);
            }
        }
        self.remove_dmabuf_feedback();
        let globals = [
            self.conn.dmabuf,
            self.conn.cursor_shape_manager,
            self.conn.layer_shell,
            self.conn.data_device_manager,
            self.conn.pointer_constraints,
            self.conn.relative_pointer_manager,
            self.conn.fractional_scale_manager,
            self.conn.viewporter,
            self.conn.decoration_manager,
            self.conn.xdg_output_manager,
            self.conn.wm_base,
            self.conn.compositor,
            self.conn.registry,
        ];
        for global in globals {
            self.conn.destroy(global);
        }
        self.conn.flush();
        // SAFETY: the display was returned live by `wl_display_connect` and no
        // proxy on it survives — every window, seat and output was destroyed
        // above, and the globals with them.
        unsafe { (self.conn.lib.display_disconnect)(self.conn.display.as_ptr()) };
        // SAFETY: `sink` came from `Box::into_raw` in `open`, is freed exactly
        // once here, and no proxy that could dispatch into it is alive.
        drop(unsafe { Box::from_raw(self.conn.sink) });
    }
}

impl Shell for WaylandShell {
    fn backend(&self) -> ShellBackend {
        ShellBackend::Wayland
    }

    /// What the compositor and this build between them can actually do.
    ///
    /// Latched at connection time by [`latch_caps`](Self::latch_caps) — a bit
    /// here is a promise to every consumer that checked it at startup, so it
    /// never changes afterwards even though a Wayland global can appear
    /// mid-session.
    ///
    /// Two bits are absent permanently rather than pending:
    ///
    /// * [`POINTER_WARP`](ShellCaps::POINTER_WARP) — Wayland has no request to
    ///   move the cursor and will not grow one, because a client that can move
    ///   the cursor can spoof clicks.
    /// * [`WINDOW_POSITION`](ShellCaps::WINDOW_POSITION) — `xdg_output` now
    ///   gives a real *monitor* layout, but the bit is about *windows*, and a
    ///   Wayland client is neither told where its window is nor allowed to ask
    ///   to be moved. `xdg-shell` has no equivalent of `XMoveWindow` by design.
    ///
    /// [`ASPECT_HINT_HONORED`](ShellCaps::ASPECT_HINT_HONORED) is also absent
    /// permanently: `xdg_toplevel` has min and max size and no aspect hint, so
    /// the renderer letterboxes.
    ///
    /// [`CLIPBOARD`](ShellCaps::CLIPBOARD) and
    /// [`DRAG_DROP`](ShellCaps::DRAG_DROP) are one bit's worth of information
    /// on this platform — both come from `wl_data_device_manager` — and are
    /// set together or not at all.
    fn caps(&self) -> ShellCaps {
        self.caps
    }

    fn create_window(&mut self, desc: &WindowDesc<'_>) -> Result<WindowId, ShellError> {
        crate::role::check(desc, self.caps(), self.backend(), |monitor| {
            self.monitor(monitor).is_some()
        })?;
        let panel = match desc.role {
            WindowRole::Toplevel => None,
            WindowRole::Panel(panel) => Some(panel),
            WindowRole::Popup(popup) => return self.create_popup(desc, &popup),
        };
        if let DisplayMode::Borderless {
            monitor: Some(monitor),
        } = desc.mode
            && self.monitor(monitor).is_none()
        {
            return Err(ShellError::NoSuchMonitor(monitor.0));
        }
        let title = CString::new(desc.title)
            .map_err(|_| ShellError::InvalidDescriptor("title contains a NUL byte".to_string()))?;
        let app_id = CString::new(desc.app_id)
            .map_err(|_| ShellError::InvalidDescriptor("app_id contains a NUL byte".to_string()))?;
        let namespace = match panel {
            Some(panel) if !panel.namespace.is_empty() => {
                CString::new(panel.namespace).map_err(|_| {
                    ShellError::InvalidDescriptor("namespace contains a NUL byte".to_string())
                })?
            }
            _ => app_id.clone(),
        };

        // `open` refuses a compositor that has neither, but a global can also
        // be **withdrawn** mid-session — see
        // [`withdraw_singleton`](Self::withdraw_singleton). Marshalling a
        // request on a null proxy is a segfault inside libwayland, so the
        // globals this window is built out of are read for null here rather
        // than assumed. A panel's is checked where it is made.
        if self.conn.compositor.is_null() {
            return Err(ShellError::WindowCreation(
                "the compositor withdrew wl_compositor".to_string(),
            ));
        }
        if panel.is_none() && self.conn.wm_base.is_null() {
            return Err(ShellError::WindowCreation(
                "the compositor withdrew xdg_wm_base".to_string(),
            ));
        }
        // SAFETY: `compositor` was just checked non-null.
        let surface = unsafe { wl_compositor::create_surface(self.conn.compositor) };
        if surface.is_null() {
            return Err(ShellError::WindowCreation(
                "wl_compositor.create_surface failed".to_string(),
            ));
        }
        let roles = match panel {
            Some(panel) => self
                .create_layer_surface(surface, &panel, &namespace, desc.size)
                .map(|layer| (ptr::null_mut(), ptr::null_mut(), layer)),
            // SAFETY: `wm_base` was checked non-null above, and `surface` was
            // just created with no role.
            None => unsafe { self.create_toplevel(surface) }
                .map(|(xdg, toplevel)| (xdg, toplevel, ptr::null_mut())),
        };
        let (xdg, toplevel, layer_surface) = match roles {
            Ok(roles) => roles,
            Err(error) => {
                // SAFETY: `surface` is live and has no role object, so its own
                // destructor is the whole of it.
                unsafe { self.conn.release(surface, wl_surface::destroy) };
                return Err(error);
            }
        };
        self.conn.watch(surface, ObjectKind::Surface);
        self.conn.watch(xdg, ObjectKind::XdgSurface);
        self.conn.watch(toplevel, ObjectKind::XdgToplevel);
        self.conn.watch(layer_surface, ObjectKind::LayerSurface);

        // Every add-on object has to exist before the initial commit:
        // `xdg-decoration` says so explicitly, and a `wp_viewport` or
        // `wp_fractional_scale_v1` created afterwards would miss the first
        // configure — which is the one a swapchain is built from.
        // SAFETY: every manager is either null (checked inside each helper) or
        // a live global, and `surface`/`toplevel` were just created. A panel
        // has no toplevel and so no decoration.
        let (decoration, fractional_scale, viewport) = unsafe {
            (
                if toplevel.is_null() {
                    ptr::null_mut()
                } else {
                    optional(self.conn.decoration_manager, |manager| {
                        zxdg_decoration_manager_v1::get_toplevel_decoration(manager, toplevel)
                    })
                },
                optional(self.conn.fractional_scale_manager, |manager| {
                    wp_fractional_scale_manager_v1::get_fractional_scale(manager, surface)
                }),
                optional(self.conn.viewporter, |manager| {
                    wp_viewporter::get_viewport(manager, surface)
                }),
            )
        };
        self.conn.watch(decoration, ObjectKind::Decoration);
        self.conn
            .watch(fractional_scale, ObjectKind::FractionalScale);
        // `wp_viewport` has no events.
        self.conn.watch(viewport, ObjectKind::Ignored);

        let fullscreen_output = match desc.mode {
            DisplayMode::Windowed => None,
            DisplayMode::Borderless { monitor } => Some(self.output_proxy_for(monitor)),
        };

        // SAFETY: every proxy above is live on this connection, and the strings
        // outlive the marshalling call.
        unsafe {
            if !toplevel.is_null() {
                xdg_toplevel::set_title(toplevel, &title);
                xdg_toplevel::set_app_id(toplevel, &app_id);
                apply_constraints(toplevel, desc.constraints, desc.resizable, desc.size);
                if let Some(output) = fullscreen_output {
                    xdg_toplevel::set_fullscreen(toplevel, output);
                }
            }
            if !decoration.is_null() {
                // Always ask for server side. The seam has no per-window
                // decoration request, the engine has no renderer to draw
                // client-side decorations with until P1, and a compositor that
                // only does CSD answers `client_side` — which is then a known
                // state in `WindowState`, not a surprise.
                zxdg_toplevel_decoration_v1::set_mode(
                    decoration,
                    zxdg_toplevel_decoration_v1::mode::SERVER_SIDE,
                );
            }
            // The initial commit with **no buffer**: xdg-shell and layer-shell
            // both require it, and it is what makes the compositor answer with
            // the first configure.
            wl_surface::commit(surface);
        }
        self.conn.flush();

        let handle: WindowId = self
            .windows
            .insert(WlWindow {
                surface,
                xdg_surface: xdg,
                toplevel,
                layer_surface,
                popup: ptr::null_mut(),
                parent: None,
                placement: None,
                popup_input: None,
                panel: panel.as_ref().map(crate::role::KeptPanel::new),
                decoration,
                fractional_scale,
                viewport,
                frame_callback: ptr::null_mut(),
                title: desc.title.to_string(),
                requested_size: desc.size,
                requested_mode: desc.mode,
                requested_constraints: desc.constraints,
                resizable: desc.resizable,
                // Unconfigured, and it stays that way until the compositor
                // answers — a round trip away. This is the contract P0.4 was
                // shaped around and the reason it was shaped that way.
                configuration: None,
                pending: PendingConfigure::default(),
                outputs: Vec::new(),
                scale: 1,
                preferred_scale: None,
                pointer_mode: PointerMode::Free,
                constraints: Vec::new(),
                cursor: None,
                accept_drops: desc.accept_drops,
                transparent: desc.transparent,
                text_input: text_input::Field::default(),
                focused: false,
                visible: desc.visible,
                close_pending: false,
            })
            .cast();
        self.opened(handle);
        Ok(handle)
    }

    /// Destroys the window and, first, every popup that belongs to it — each
    /// with its own [`ShellEvent::WindowDestroyed`]. Destroying a surface whose
    /// popups are still alive is a protocol error, and the seam promises a
    /// popup goes with its parent.
    fn destroy_window(&mut self, window: WindowId) -> Result<(), ShellError> {
        self.window(window)?;
        let popups: Vec<WindowId> = self
            .windows
            .iter()
            .filter(|(_, state)| state.parent == Some(window))
            .map(|(handle, _)| handle.cast())
            .collect();
        for popup in popups {
            self.destroy_window(popup)?;
        }
        let removed = self
            .windows
            .remove(window.cast())
            .ok_or_else(|| ShellError::invalid_window(window))?;
        self.destroy_objects(window, &removed);
        #[cfg(feature = "accesskit")]
        self.access.close(window);
        self.queue.push_back(ShellEvent::WindowDestroyed { window });
        Ok(())
    }

    fn window_state(&self, window: WindowId) -> Result<WindowState, ShellError> {
        let state = self.window(window)?;
        Ok(WindowState {
            configuration: state.configuration,
            requested_mode: state.requested_mode,
            requested_constraints: state.requested_constraints,
            focused: state.focused,
            visible: state.visible,
            pointer_mode: state.pointer_mode,
            close_pending: state.close_pending,
        })
    }

    fn set_title(&mut self, window: WindowId, title: &str) -> Result<(), ShellError> {
        let encoded = CString::new(title)
            .map_err(|_| ShellError::InvalidDescriptor("title contains a NUL byte".to_string()))?;
        let state = self.window_mut(window)?;
        state.title = title.to_string();
        let toplevel = state.toplevel;
        // A panel has no title to send; the one recorded is all it has.
        if toplevel.is_null() {
            return Ok(());
        }
        // SAFETY: the toplevel is live and the string outlives the call.
        unsafe { xdg_toplevel::set_title(toplevel, &encoded) };
        self.conn.flush();
        Ok(())
    }

    /// Records the requested visibility. **Intent only, and it will stay that
    /// way until P1.**
    ///
    /// Wayland has no hide request: a surface is mapped exactly while it has a
    /// buffer. Hiding is therefore `wl_surface.attach(null)` — which this
    /// backend *could* send today — and showing is attaching a real buffer,
    /// which it cannot, because buffers are the renderer's and the renderer is
    /// P1.
    ///
    /// Implementing only the direction that works would be worse than
    /// implementing neither: `xdg-shell` says an unmapped toplevel returns to
    /// its initial state and has to redo the whole configure handshake before
    /// it can be shown again, so a window hidden through this call would be a
    /// window that can never be shown again. So this records the intent,
    /// [`WindowState::visible`] reports it — matching
    /// [`HeadlessShell`](crate::HeadlessShell) — and the pair closes when the
    /// swapchain lands.
    fn set_visible(&mut self, window: WindowId, visible: bool) -> Result<(), ShellError> {
        self.window_mut(window)?.visible = visible;
        Ok(())
    }

    fn set_mode(&mut self, window: WindowId, mode: DisplayMode) -> Result<(), ShellError> {
        let output = match mode {
            DisplayMode::Windowed => None,
            DisplayMode::Borderless { monitor } => {
                if let Some(id) = monitor
                    && self.monitor(id).is_none()
                {
                    return Err(ShellError::NoSuchMonitor(id.0));
                }
                Some(self.output_proxy_for(monitor))
            }
        };
        let state = self.window_mut(window)?;
        // Recorded immediately because we said it; the *effective* mode changes
        // only when a configure arrives, and may never match.
        state.requested_mode = mode;
        let toplevel = state.toplevel;
        let surface = state.surface;
        // A panel has no full-screen state, so the request stays one: its
        // effective mode is always windowed.
        if toplevel.is_null() {
            return Ok(());
        }
        // SAFETY: both proxies are live; a null output means "the compositor
        // chooses", which is the only thing a Wayland client may ask for.
        unsafe {
            match output {
                Some(output) => xdg_toplevel::set_fullscreen(toplevel, output),
                None => xdg_toplevel::unset_fullscreen(toplevel),
            }
            wl_surface::commit(surface);
        }
        self.conn.flush();
        Ok(())
    }

    fn set_constraints(
        &mut self,
        window: WindowId,
        constraints: SizeConstraints,
    ) -> Result<(), ShellError> {
        let state = self.window_mut(window)?;
        state.requested_constraints = constraints;
        let toplevel = state.toplevel;
        let surface = state.surface;
        let requested = state.requested_size;
        let resizable = state.resizable;
        // A panel's size is the layer surface's; the constraints recorded are
        // applied to each configure, as for any window.
        if toplevel.is_null() {
            return Ok(());
        }
        // SAFETY: both proxies are live; the sizes are plain integers.
        unsafe {
            apply_constraints(toplevel, constraints, resizable, requested);
            wl_surface::commit(surface);
        }
        self.conn.flush();
        Ok(())
    }

    fn reposition_popup(
        &mut self,
        popup: WindowId,
        anchor: crate::LogicalRect,
        size: LogicalSize,
    ) -> Result<(), ShellError> {
        self.move_popup(popup, anchor, size)
    }

    fn set_panel(
        &mut self,
        window: WindowId,
        size: LogicalSize,
        panel: &crate::PanelDesc<'_>,
    ) -> Result<(), ShellError> {
        self.reconfigure_layer_surface(window, size, panel)
    }

    fn set_text_input(
        &mut self,
        window: WindowId,
        field: Option<TextPurpose>,
    ) -> Result<(), ShellError> {
        self.enable_text_input(window, field)
    }

    /// Handed to the window's AT-SPI adapter, which keeps it only while a
    /// reader is active.
    #[cfg(feature = "accesskit")]
    fn update_accessibility(
        &mut self,
        window: WindowId,
        update: crate::accesskit::TreeUpdate,
    ) -> Result<(), ShellError> {
        self.window(window)?;
        self.access.update(window, update);
        Ok(())
    }

    fn set_text_input_area(
        &mut self,
        window: WindowId,
        area: Option<PhysicalRect>,
    ) -> Result<(), ShellError> {
        self.place_text_input(window, area)
    }

    /// `wl_surface.set_input_region`, committed at once; see [`region`]. A
    /// passthrough popup keeps the empty region it was made with.
    fn set_input_region(
        &mut self,
        window: WindowId,
        region: Option<&[PhysicalRect]>,
    ) -> Result<(), ShellError> {
        self.apply_input_region(window, region)
    }

    fn request_frame(&mut self, window: WindowId) -> Result<(), ShellError> {
        self.request_frame_callback(window)
    }

    fn monitors(&self) -> &[MonitorInfo] {
        &self.monitors
    }

    /// Drains the socket without blocking, then delivers what arrived.
    ///
    /// The sequence is libwayland's `prepare_read`/`read_events` protocol
    /// rather than `wl_display_dispatch`, for one reason:
    /// `wl_display_dispatch` **blocks** when nothing is queued, and
    /// [`Shell::pump`] promises to be finite and non-blocking. `prepare_read`
    /// plus a zero-timeout `poll` gives the same delivery with a decision point
    /// in the middle — and it is the same sequence [`wait_events`](Shell::wait_events)
    /// runs with a real timeout, so the blocking and non-blocking paths cannot
    /// drift apart.
    ///
    /// Key repeats are generated here, after the socket and before delivery, so
    /// that a repeat and the real events around it arrive in one batch and in
    /// timestamp order.
    fn pump(&mut self, sink: &mut dyn FnMut(ShellEvent)) {
        self.keep_alive();
        // Drain by count, not `while let`: a sink that creates a window must
        // not be able to spin this loop, and whatever it queued belongs to the
        // next frame — which is what the socket would have done anyway.
        for _ in 0..self.queue.len() {
            let Some(event) = self.queue.pop_front() else {
                break;
            };
            sink(event);
        }
    }

    /// Drains the socket, answers what the compositor asked, and keeps the
    /// rest.
    ///
    /// The answer that matters for a long load is the `xdg_wm_base.pong` in
    /// [`process_raw`](Self::process_raw): a compositor that pings and hears
    /// nothing marks the client unresponsive.
    fn keep_alive(&mut self) {
        if self.lost.is_none()
            && let Err(error) = self.conn.drain(0, &[])
        {
            crcbl_core::log::error!("wayland connection lost: {error}");
            self.lost = Some(error.to_string());
        }
        self.process_raw();
        // After the socket, because a `wl_data_source.send` that arrived in
        // this batch is what a read of our own selection is waiting for, and
        // before delivery, so a transfer that completed here is answered in
        // the same frame it finished.
        self.service_transfers();
        // After the socket, so a `selection` that arrived in this batch has
        // already been recorded: a held read most often becomes answerable the
        // instant keyboard focus does.
        self.resolve_held_reads();
        self.drive_repeats();
        #[cfg(feature = "accesskit")]
        self.queue.extend(self.access.take_events());
    }

    /// Blocks until an event arrives, `timeout` elapses, or a key repeat comes
    /// due.
    ///
    /// The last clause is what makes repeat work for an editor that idles at
    /// zero frames per second: without it, holding Backspace in a text field
    /// would delete one character and then wait for an unrelated event.
    fn wait_events(&mut self, timeout: Option<Duration>) {
        if self.lost.is_some() {
            return;
        }
        let mut deadline = match (timeout, self.next_repeat_in()) {
            (Some(timeout), Some(repeat)) => Some(timeout.min(repeat)),
            (Some(timeout), None) => Some(timeout),
            (None, repeat) => repeat,
        };
        // A transfer in flight is waited on two ways: its descriptor goes into
        // the poll below, which wakes the moment a peer writes, and the wait is
        // capped so that a peer which *never* writes still has its deadline
        // checked. Without the cap, an editor idling with `timeout: None` would
        // sleep through a stalled paste's timeout and answer nothing.
        let mut aux = self.transfer_fds();
        if !aux.is_empty() || !self.writes.is_empty() || !self.held.is_empty() {
            deadline = Some(deadline.map_or(TRANSFER_POLL, |deadline| deadline.min(TRANSFER_POLL)));
        }
        let timeout_ms = deadline.map_or(-1, |deadline| {
            c_int::try_from(deadline.as_millis()).unwrap_or(c_int::MAX)
        });
        // The wake pipe joins the transfers after the cap is decided: a
        // waker that never rings must not turn an idle wait into a polling one.
        if let Some(wake) = &self.wake {
            aux.push(wake.fd());
        }
        if let Err(error) = self.conn.drain(timeout_ms, &aux) {
            crcbl_core::log::error!("wayland connection lost: {error}");
            self.lost = Some(error.to_string());
        }
        if let Some(wake) = &self.wake {
            wake.clear();
        }
    }

    /// A pipe polled beside the compositor connection — see
    /// [`wake`](crate::linux::wake). `None` only if the process is out of
    /// descriptors, which is logged.
    fn waker(&mut self) -> Option<crate::ShellWaker> {
        crate::waker::lazy_waker(&mut self.wake, "Wayland", crate::linux::wake::WakePipe::new)
    }

    /// The handles `crcbl-vk` needs for `vkCreateWaylandSurfaceKHR`.
    ///
    /// Both are available the instant the window exists — a `wl_surface` is
    /// created up front and only its *size* is pending — so a HAL surface can
    /// be created immediately and only the swapchain waits for the first
    /// configure. That is the split [`Shell::surface_target`] documents, and
    /// Wayland is the platform it was written for.
    ///
    /// Lifetime: the `wl_display` lives as long as this shell and the
    /// `wl_surface` as long as the window, so a HAL surface built from these
    /// must be destroyed before [`destroy_window`](Shell::destroy_window) and
    /// before the shell is dropped.
    fn surface_target(&self, window: WindowId) -> Result<SurfaceTarget, ShellError> {
        let state = self.window(window)?;
        let surface = NonNull::new(state.surface.cast::<c_void>())
            .ok_or_else(|| ShellError::invalid_window(window))?;
        Ok(SurfaceTarget::Wayland {
            display: self.conn.display.cast::<c_void>(),
            surface,
            transparent: state.transparent,
            main_device: self.main_device,
        })
    }

    /// Locks or confines the pointer through `pointer-constraints-v1`.
    ///
    /// The constraint is created per seat that currently has a pointer, and is
    /// rebuilt when one appears later — so a game that locks the pointer before
    /// a mouse is plugged in is locked the moment it is.
    ///
    /// `persistent` lifetime, not `oneshot`: the compositor deactivates a
    /// constraint whenever it wants (an alt-tab, a compositor keybinding) and a
    /// one-shot constraint would then be gone for good, leaving a first-person
    /// camera with a free cursor and no indication why.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] if the compositor has no
    /// `zwp_pointer_constraints_v1`, or [`ShellError::InvalidWindow`] for a
    /// stale handle.
    fn set_pointer_mode(&mut self, window: WindowId, mode: PointerMode) -> Result<(), ShellError> {
        self.window(window)?;
        if !self.caps.contains(mode.required_cap()) {
            return Err(Self::unsupported(mode.as_str()));
        }
        self.rebuild_constraint(window, mode);
        Ok(())
    }

    /// Hides the cursor with `None`, and names a shape through
    /// `cursor-shape-v1` where the compositor offers it.
    ///
    /// # Hiding works on every compositor
    ///
    /// `wl_pointer.set_cursor` with a **null** surface *is* "no cursor" in core
    /// Wayland. It needs no buffer, no theme and no extra protocol — which is
    /// the case a first-person game and [`PointerMode::Locked`] actually need.
    ///
    /// # A shape needs `cursor-shape-v1`
    ///
    /// `wp_cursor_shape_device_v1.set_shape` hands the compositor a name from
    /// the CSS vocabulary [`CursorIcon::as_css_name`] already speaks, and the
    /// compositor draws the user's own themed, correctly scaled cursor; the
    /// [`cursor_shape`] module says why that beats loading a theme here.
    /// [`ShellCaps::CURSOR_SHAPE`] is set when the manager was bound by the end
    /// of [`open`](Self::open). A shape also ends a hide, because the shape
    /// replaces the null surface.
    ///
    /// On a compositor without the protocol a shape is **accepted and
    /// recorded** rather than failed, and the cap being clear is the loud part:
    /// a UI calls this on every hover, and erroring there would make every
    /// caller handle it. The shape is not seen; a hide it follows lasts until
    /// the next `wl_pointer.enter`, where the compositor resets the cursor.
    /// [`WindowState`] does not claim otherwise, because the seam has no
    /// effective-cursor field.
    ///
    /// Either request is re-sent on every `wl_pointer.enter`, because a
    /// compositor resets the cursor when it crosses a surface boundary; a
    /// client that set it once would watch it flicker back on every re-entry.
    ///
    /// # Errors
    ///
    /// [`ShellError::InvalidWindow`] if the handle is stale.
    fn set_cursor(
        &mut self,
        window: WindowId,
        cursor: Option<CursorIcon>,
    ) -> Result<(), ShellError> {
        self.window_mut(window)?.cursor = Some(cursor);
        let focused: Vec<usize> = (0..self.seats.len())
            .filter(|index| self.seats[*index].pointer_focus == Some(window))
            .collect();
        for index in focused {
            self.apply_cursor(index, window);
        }
        Ok(())
    }

    fn warp_pointer(
        &mut self,
        window: WindowId,
        position: PhysicalPoint,
    ) -> Result<(), ShellError> {
        let _ = position;
        self.window(window)?;
        // Not "not yet" — never. A client that can move the cursor can spoof
        // clicks, so Wayland has no such request and will not grow one.
        Err(Self::unsupported("pointer warp"))
    }

    fn reply_close_request(
        &mut self,
        window: WindowId,
        reply: CloseReply,
    ) -> Result<(), ShellError> {
        let state = self.window_mut(window)?;
        if !state.close_pending {
            return Err(ShellError::NoPendingCloseRequest { window });
        }
        state.close_pending = false;
        match reply {
            CloseReply::Close => self.destroy_window(window),
            CloseReply::Keep => Ok(()),
        }
    }

    /// Claims the seat's selection and holds the bytes until somebody asks.
    ///
    /// # The serial, and why a window with no input cannot copy
    ///
    /// `wl_data_device.set_selection` takes "the serial of the event that
    /// triggered this request", and a compositor may check it — wlroots
    /// compares it against the serial of the selection currently in effect and
    /// silently drops anything that looks older. The seam has no serials in it,
    /// so this quotes the seat's most recent input serial, which is the one
    /// belonging to whatever the user did to cause the copy.
    ///
    /// A window that has never received input on any seat therefore cannot
    /// claim the selection, and this reports
    /// [`ShellError::NeedsUserInteraction`] rather than sending a request the
    /// compositor will ignore. That is not a limitation this backend invented:
    /// a Wayland client genuinely may not take the clipboard without user
    /// interaction, which is the whole point of the serial — it is what stops a
    /// background process stealing the clipboard, and the browser gates its own
    /// clipboard write the same way.
    ///
    /// An empty `offers` slice releases the selection.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] if the compositor has no
    /// `wl_data_device_manager`, [`ShellError::InvalidWindow`] for a stale
    /// handle, [`ShellError::NeedsUserInteraction`] if no seat can name a
    /// serial, or [`ShellError::Backend`] if there is no seat at all.
    fn clipboard_offer(
        &mut self,
        window: WindowId,
        offers: &[ClipboardOffer<'_>],
    ) -> Result<(), ShellError> {
        self.window(window)?;
        if !self.caps.contains(ShellCaps::CLIPBOARD) {
            return Err(Self::unsupported("clipboard"));
        }
        // The capability is latched and the seat's `wl_data_device` outlives
        // its manager, so neither of those answers whether the manager is
        // still there; a withdrawn one is null and must not be marshalled on.
        if self.conn.data_device_manager.is_null() {
            return Err(ShellError::Backend(
                "the compositor withdrew wl_data_device_manager".to_string(),
            ));
        }
        let index = *self
            .seats_for_window(window)
            .first()
            .ok_or_else(|| ShellError::Backend("no seat has a wl_data_device".to_string()))?;
        // Replacing our own selection: the old source is destroyed *after* the
        // new one is in effect, so nothing observes a moment with no clipboard.
        let previous = self.seats[index]
            .data
            .as_mut()
            .and_then(|device| device.source.take());

        let serial = self.seats[index].last_serial;
        let mut published = None;
        if !offers.is_empty() {
            if serial == 0 {
                if let Some(source) = previous.as_ref() {
                    // SAFETY: a live `wl_data_source` this backend created.
                    unsafe { self.conn.release(source.proxy, wl_data_source::destroy) };
                }
                if let Some(device) = self.seats[index].data.as_mut() {
                    device.source = None;
                }
                return Err(ShellError::NeedsUserInteraction {
                    backend: ShellBackend::Wayland,
                    what: "claiming the clipboard",
                });
            }
            let manager = self.conn.data_device_manager;
            // SAFETY: the manager is a live global; `create_data_source` takes
            // no arguments beyond the object it creates.
            let source = unsafe { wl_data_device_manager::create_data_source(manager) };
            if source.is_null() {
                // The previous source was `take`n out of the device above.
                // Returning without putting it back left the compositor still
                // believing we owned the selection while nothing on this side
                // did — so the next `wl_data_source.send` found no seat, and the
                // selection could never be released either. Nothing changed, so
                // nothing should have moved: put it back.
                if let Some(device) = self.seats[index].data.as_mut() {
                    device.source = previous;
                }
                return Err(ShellError::Backend(
                    "wl_data_device_manager.create_data_source failed".to_string(),
                ));
            }
            self.conn.watch(source, ObjectKind::DataSource);
            let mut payload = Vec::with_capacity(offers.len());
            for offer in offers {
                let Ok(mime) = CString::new(offer.mime.as_str()) else {
                    continue;
                };
                // SAFETY: the source is live and the string outlives the call.
                unsafe { wl_data_source::offer(source, &mime) };
                payload.push((offer.mime.as_str().to_string(), offer.bytes.to_vec()));
            }
            published = Some(data::Source {
                proxy: source,
                payload,
            });
        }

        let device = self.seats[index]
            .data
            .as_ref()
            .map_or(ptr::null_mut(), |device| device.proxy);
        let source = published
            .as_ref()
            .map_or(ptr::null_mut(), |source| source.proxy);
        // SAFETY: the device is live, and a null source is the protocol's own
        // way of releasing the selection.
        unsafe { wl_data_device::set_selection(device, source, serial) };
        self.conn.flush();
        if let Some(previous) = previous.as_ref() {
            // SAFETY: a live `wl_data_source` this backend created, destroyed
            // exactly once.
            unsafe { self.conn.release(previous.proxy, wl_data_source::destroy) };
        }
        if let Some(device) = self.seats[index].data.as_mut() {
            device.source = published;
            // We have just changed the clipboard and have **not** been told the
            // result. The offer this device still holds describes the *old*
            // selection, and answering a read from it — or worse, answering
            // `Empty` because the old one had no matching format — would report
            // a clipboard that no longer exists. The compositor echoes the new
            // selection back to us (a client sees its own, which is what makes
            // pasting one's own copy work at all), and that event is what makes
            // this true again.
            //
            // Found by the end-to-end suite the moment "held, not empty" was
            // enforced: pasting our own copy answered `Empty`, because the
            // answer was computed from what we knew a microsecond before we
            // changed it.
            device.selection_seen = false;
        }
        Ok(())
    }

    /// Starts reading the selection, over a pipe, without blocking.
    ///
    /// The answer arrives as [`ShellEvent::ClipboardData`] from a later
    /// [`pump`](Shell::pump) — never from this call, and never from a `read`
    /// on the event-loop thread. See [`fd`] for the mechanism and for what
    /// happens when the peer never writes.
    ///
    /// # There is nothing to read unless a window of ours has focus
    ///
    /// `wl_data_device.selection` is delivered only to the client with keyboard
    /// focus on that seat, and again whenever focus arrives — so a Wayland
    /// client's clipboard knowledge is *acquired on focus* and goes stale when
    /// focus leaves. A read issued while this shell has not been told what is
    /// on the clipboard is therefore **held** until it has been, and only then
    /// answered. It is not answered `Empty`, which would be indistinguishable
    /// from a clipboard that really is empty and is what forced a retry loop
    /// into the end-to-end suite before this was fixed.
    ///
    /// The wait is bounded by [`fd::TIMEOUT`], after which the answer is
    /// [`ClipboardContent::Unavailable`] — obligation 4 requires every accepted
    /// request to end. [`clipboard_readable`](Shell::clipboard_readable) is how
    /// a UI finds out in advance that the answer will not be immediate.
    ///
    /// # Errors
    ///
    /// [`ShellError::Unsupported`] if the compositor has no
    /// `wl_data_device_manager`, or [`ShellError::InvalidWindow`] for a stale
    /// handle. A clipboard that holds nothing compatible is *not* an error —
    /// it is an answer — and neither is one this client cannot see yet, which
    /// is a wait.
    fn clipboard_request(
        &mut self,
        window: WindowId,
        mime: MimeType,
    ) -> Result<ClipboardRequestId, ShellError> {
        self.window(window)?;
        if !self.caps.contains(ShellCaps::CLIPBOARD) {
            return Err(Self::unsupported("clipboard"));
        }
        let request = ClipboardRequestId(self.next_request_id);
        self.next_request_id += 1;

        match self.resolve_selection(window, mime) {
            Resolution::Ready { offer, spelling } => {
                let delivery = Delivery::Clipboard {
                    window,
                    request,
                    // The *peer's* spelling, not the one that was asked for: a
                    // peer offering bare `text/plain` answers a request for
                    // `text/plain;charset=utf-8`, and `ReceivedMime` exists so
                    // the difference survives to the consumer.
                    mime: ReceivedMime::new(&spelling),
                };
                if let Err(error) = self.start_receive(offer, &spelling, delivery) {
                    crcbl_core::log::warn!("clipboard read could not be started: {error}");
                    self.answer_read(
                        window,
                        request,
                        ReceivedMime::new(&spelling),
                        ClipboardContent::Unavailable,
                    );
                }
            }
            // Queued rather than returned, so that a consumer written against
            // the asynchronous shape takes the same path whether or not there
            // was anything on the clipboard.
            Resolution::Empty => self.answer_read(
                window,
                request,
                ReceivedMime::from(mime),
                ClipboardContent::Empty,
            ),
            // **Held**, not answered. See this method's docs and the seam's
            // obligation 5: answering `Empty` here would be a lie a consumer
            // cannot detect, and it is the lie that made the end-to-end suite
            // grow a retry loop no editor would contain.
            Resolution::Unknown => self.held.push(HeldRead {
                window,
                request,
                mime,
                deadline_nanos: ffi::monotonic_nanos()
                    .saturating_add(u64::try_from(fd::TIMEOUT.as_nanos()).unwrap_or(u64::MAX)),
            }),
        }
        Ok(request)
    }

    /// Whether a read issued now could be answered without waiting.
    ///
    /// True exactly when the compositor has told us what is on the clipboard
    /// and has not since taken keyboard focus away — which is the honest
    /// Wayland answer, and the reason this method is on the seam at all. A
    /// background window reports `false` and a paste button greys out, instead
    /// of a paste that appears to do nothing.
    fn clipboard_readable(&self, window: WindowId) -> bool {
        self.caps.contains(ShellCaps::CLIPBOARD)
            && self.window(window).is_ok()
            && self.seats_for_window(window).into_iter().any(|index| {
                self.seats[index]
                    .data
                    .as_ref()
                    .is_some_and(|device| device.selection_seen)
            })
    }

    fn align_event_clock(&mut self, elapsed: Duration) {
        self.align_time_base(elapsed);
    }
}

impl WaylandShell {
    /// The `wl_output` proxy for a monitor, or null for "the compositor
    /// chooses".
    ///
    /// Null is not a fallback: `xdg_toplevel.set_fullscreen` takes a nullable
    /// output *by design*, and `DisplayMode::Borderless { monitor: None }`
    /// exists because that is the only thing a Wayland client can reliably ask
    /// for.
    /// Gives `surface` the `xdg_surface` and `xdg_toplevel` of an
    /// application window.
    ///
    /// # Safety
    ///
    /// `wm_base` must be live, and `surface` live with no role.
    unsafe fn create_toplevel(
        &mut self,
        surface: *mut WlProxy,
    ) -> Result<(*mut WlProxy, *mut WlProxy), ShellError> {
        // SAFETY: the caller guarantees both proxies; each request creates the
        // next object in the stack, and each is checked before use.
        unsafe {
            let xdg = xdg_wm_base::get_xdg_surface(self.conn.wm_base, surface);
            if xdg.is_null() {
                return Err(ShellError::WindowCreation(
                    "xdg_wm_base.get_xdg_surface failed".to_string(),
                ));
            }
            let toplevel = xdg_surface::get_toplevel(xdg);
            if toplevel.is_null() {
                self.conn.release(xdg, xdg_surface::destroy);
                return Err(ShellError::WindowCreation(
                    "xdg_surface.get_toplevel failed".to_string(),
                ));
            }
            Ok((xdg, toplevel))
        }
    }

    fn output_proxy_for(&self, monitor: Option<MonitorId>) -> *mut WlProxy {
        let Some(id) = monitor else {
            return ptr::null_mut();
        };
        self.outputs
            .iter()
            .find(|output| output.id == id)
            .map_or(ptr::null_mut(), |output| output.proxy as *mut WlProxy)
    }

    /// Records the compositor's answer to our `set_mode(server_side)`.
    ///
    /// Deliberately **not** exposed as state on the seam.
    /// [`ShellCaps::SERVER_DECORATIONS`] is the portable question — "can this
    /// session have server-side decorations at all" — and it is latched from
    /// whether `zxdg_decoration_manager_v1` bound. The per-window answer is a
    /// Wayland-shaped detail with no equivalent anywhere else, and adding a
    /// `u32` from an unstable protocol to [`WindowState`] would put a platform
    /// type in the seam this crate exists to keep platform-free.
    ///
    /// What matters is that a compositor answering `client_side` is a *known*
    /// state rather than a surprise when the UI layer starts drawing at P1, so
    /// it is logged at warning level — the engine has no client-side
    /// decorations, so on such a compositor a window has no title bar and no
    /// resize grips, and somebody has to be told why.
    fn decoration_configured(&mut self, decoration: usize, mode: u32) {
        let Some(window) = self.window_by_proxy(decoration, |state| state.decoration as usize)
        else {
            return;
        };
        if mode == zxdg_toplevel_decoration_v1::mode::SERVER_SIDE {
            crcbl_core::log::debug!("{window:?}: the compositor draws this window's decorations");
        } else {
            crcbl_core::log::warn!(
                "{window:?}: the compositor refused server-side decorations \
                 (xdg-decoration mode {mode}); this window has no title bar until \
                 the UI layer can draw one"
            );
        }
    }
}

/// Creates an add-on object, or nothing if the manager global was never bound.
///
/// # Safety
///
/// `manager` must be null or a live global, and `create` must marshal a request
/// on it.
unsafe fn optional(
    manager: *mut WlProxy,
    create: impl FnOnce(*mut WlProxy) -> *mut WlProxy,
) -> *mut WlProxy {
    if manager.is_null() {
        return ptr::null_mut();
    }
    create(manager)
}

/// Sends `set_min_size`/`set_max_size` for a constraint set.
///
/// Wayland has **no aspect hint**, which is why the backend does not set
/// [`ShellCaps::ASPECT_HINT_HONORED`] and why the renderer letterboxes instead.
/// `resizable: false` becomes min == max, which is the only way to say it.
///
/// # Safety
///
/// `toplevel` must be a live `xdg_toplevel`.
unsafe fn apply_constraints(
    toplevel: *mut WlProxy,
    constraints: SizeConstraints,
    resizable: bool,
    requested: LogicalSize,
) {
    // xdg-shell takes these in logical units, and zero means "no limit".
    let to_pair = |size: Option<LogicalSize>| {
        size.map_or((0, 0), |size| {
            (round_logical(size.width), round_logical(size.height))
        })
    };
    let (min, max) = if resizable {
        (to_pair(constraints.min), to_pair(constraints.max))
    } else {
        let fixed = to_pair(Some(requested));
        (fixed, fixed)
    };
    // SAFETY: the caller guarantees `toplevel` is live; both requests take two
    // plain integers.
    unsafe {
        xdg_toplevel::set_min_size(toplevel, min.0, min.1);
        xdg_toplevel::set_max_size(toplevel, max.0, max.1);
    }
}

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

    /// A handle to nothing, for the pure-logic tests: `Repeat` stores one and
    /// never dereferences it.
    fn window_id() -> WindowId {
        let mut pool: Pool<u8> = Pool::new();
        pool.insert(0).cast()
    }

    #[test]
    fn wayland_timestamps_rebase_onto_the_engine_epoch() {
        // The shell was opened 5s after the engine clock started, and the
        // compositor stamps an event 1.25s later still.
        let epoch = 95_000_000_000; // engine epoch, in CLOCK_MONOTONIC nanos
        let now = 101_250_000_000;
        #[expect(
            clippy::cast_possible_truncation,
            reason = "the value fits by construction"
        )]
        let stamp = (now / 1_000_000) as u32;
        assert_eq!(
            TimeBase::rebase(epoch, now, stamp),
            EventTime::from_millis(6_250),
            "6.25s after the engine epoch, not 101s after boot"
        );
    }

    #[test]
    fn a_wrapped_timestamp_is_widened_towards_now_not_forwarded_raw() {
        // 49.7 days of uptime: the compositor's 32-bit counter has just
        // wrapped, and the event's low bits are tiny while `now` is huge. A
        // backend that forwarded the raw value would report an event from
        // process start.
        const WRAP: u64 = 1 << 32;
        let now_millis = WRAP + 10;
        let now = now_millis * 1_000_000;
        let epoch = 0;
        assert_eq!(
            TimeBase::rebase(epoch, now, 5),
            EventTime::from_millis(WRAP + 5),
            "the event is 5ms after the wrap, not 5ms after boot"
        );

        // The other side of the wrap: an event stamped just *before* it, read
        // just after. Widening must not push it a whole period into the future.
        let now_millis = WRAP + 3;
        assert_eq!(
            TimeBase::rebase(epoch, now_millis * 1_000_000, u32::MAX),
            EventTime::from_millis(WRAP - 1),
        );
    }

    #[test]
    fn a_timestamp_ahead_of_now_before_the_first_wrap_does_not_underflow() {
        // The whole `time` argument is an unvalidated `u32` off the wire, and on
        // a machine with an uptime under 49.7 days there is no earlier wrap to
        // move a too-large stamp into. Subtracting one anyway panicked in debug
        // and produced ~1.8e19 ms in release — for a hostile compositor, and for
        // an honest one whose event merely ran a few milliseconds ahead of the
        // `CLOCK_MONOTONIC` sample taken here.
        let now = 60_000_000_000; // one minute of uptime, in nanoseconds
        assert_eq!(
            TimeBase::rebase(0, now, u32::MAX),
            EventTime::from_millis(u64::from(u32::MAX)),
            "the only reconstruction that exists is the raw value"
        );
        // The nearby, ordinary case is unaffected.
        assert_eq!(
            TimeBase::rebase(0, now, 60_001),
            EventTime::from_millis(60_001)
        );
    }

    #[test]
    fn timestamps_never_go_negative_when_an_event_predates_the_epoch() {
        // A compositor can stamp an event microseconds before the shell was
        // created. Saturation is the documented answer; `EventTime` is a
        // duration and has no negative values.
        assert_eq!(
            TimeBase::rebase(10_000_000_000, 10_000_000_000, 9_000),
            EventTime::ZERO
        );
    }

    #[test]
    fn events_the_protocol_gives_no_time_for_are_stamped_now_not_zero() {
        // `wl_pointer.enter` and `leave` carry a serial and no timestamp at
        // all. Stamping them with the last frame's time reads as "at process
        // start" before the pointer has ever moved — which is what
        // `EventTime`'s own rule about missing timestamps forbids.
        let base = TimeBase {
            epoch_nanos: ffi::monotonic_nanos().saturating_sub(3_000_000_000),
        };
        let stamped = base.event_time_now();
        assert!(
            stamped >= EventTime::from_millis(2_900),
            "an event with no compositor time is stamped now, got {stamped:?}"
        );
        assert_ne!(stamped, EventTime::ZERO);
    }

    #[test]
    fn the_microsecond_clock_needs_no_wrap_handling_and_keeps_its_precision() {
        // `relative_motion`'s 64-bit microseconds are the more precise of the
        // two clocks a pointer event arrives on, which is why a merged motion
        // event prefers them.
        let base = TimeBase {
            epoch_nanos: 5_000_000_000,
        };
        assert_eq!(
            base.event_time_micros(5_000_500),
            EventTime::from_micros(500),
            "half a millisecond after the epoch, not rounded to zero"
        );
        // A timestamp before the epoch saturates rather than wrapping.
        assert_eq!(base.event_time_micros(1), EventTime::ZERO);
    }

    #[test]
    fn aligning_the_time_base_moves_the_epoch_backwards() {
        // The contract `Shell::align_event_clock` exists for: after alignment,
        // "now" reads as the elapsed time the engine clock reports.
        let mut base = TimeBase::now();
        let before = base.epoch_nanos;
        base.align(Duration::from_secs(2));
        assert!(
            base.epoch_nanos <= before,
            "an epoch two seconds ago is earlier than one taken now"
        );
        assert!(
            before.saturating_sub(base.epoch_nanos) >= 1_900_000_000,
            "the shift is the elapsed time, give or take the call overhead"
        );
    }

    #[test]
    fn repeats_start_after_the_delay_and_then_run_at_the_rate() {
        let mut repeat = Repeat {
            rate: 25,
            delay: 600,
            key: None,
        };
        let now = 1_000_000_000;
        repeat.start(
            now,
            RepeatKeyRequest {
                window: window_id(),
                scancode: 30,
                key_code: Some(KeyCode::KeyA),
                keysym: Keysym::from_char('a'),
            },
        );
        let key = repeat.key.expect("repeat armed");
        assert_eq!(
            key.next_nanos - now,
            600_000_000,
            "the first repeat waits the whole delay"
        );
        assert_eq!(key.interval_nanos, 40_000_000, "25 Hz is 40ms apart");

        // Releasing the key that is repeating stops it; releasing another does
        // not, which is what makes Shift+held-A keep repeating A.
        repeat.stop(31);
        assert!(repeat.key.is_some());
        repeat.stop(30);
        assert!(repeat.key.is_none());
    }

    #[test]
    fn a_zero_rate_disables_repeat_entirely() {
        // `wl_keyboard.repeat_info` defines rate 0 as "no repeat", and a user
        // who turned repeat off in their compositor must not get repeats from
        // us.
        let mut repeat = Repeat {
            rate: 0,
            delay: 300,
            key: None,
        };
        repeat.start(
            0,
            RepeatKeyRequest {
                window: window_id(),
                scancode: 30,
                key_code: Some(KeyCode::KeyA),
                keysym: Keysym::NONE,
            },
        );
        assert!(repeat.key.is_none());
        assert_eq!(repeat.due_at(), None);
    }

    #[test]
    fn value120_accumulates_into_detents_with_the_engine_sign_convention() {
        // One notch of a real wheel, scrolled away from the user: Wayland
        // reports -120 on the vertical axis, and the engine's convention is
        // that away-from-the-user is positive.
        let mut frame = PointerFrame {
            has_axis: true,
            ..PointerFrame::default()
        };
        frame.value120[0] = -120.0;
        assert_eq!(
            frame.scroll(1.0),
            Some(ScrollDelta::Lines { x: 0.0, y: 1.0 })
        );

        // A high-resolution wheel sends fractions of a detent, and they add up
        // across the frame rather than each becoming an event.
        let mut frame = PointerFrame {
            has_axis: true,
            ..PointerFrame::default()
        };
        frame.value120[0] = -30.0;
        frame.value120[0] += -30.0;
        assert_eq!(
            frame.scroll(1.0),
            Some(ScrollDelta::Lines { x: 0.0, y: 0.5 }),
            "two eighth-turns are a quarter of a detent, not two detents"
        );

        // Horizontal lands in `x`, and the sign flips there too.
        let mut frame = PointerFrame {
            has_axis: true,
            ..PointerFrame::default()
        };
        frame.value120[1] = 120.0;
        assert_eq!(
            frame.scroll(1.0),
            Some(ScrollDelta::Lines { x: -1.0, y: 0.0 })
        );
    }

    #[test]
    fn a_wheel_prefers_detents_and_a_touchpad_gets_pixels() {
        // The distinction `ScrollDelta` refuses to collapse. A notched wheel
        // sends both a discrete count and a continuous value; reporting the
        // continuous one would turn a click into whatever number the
        // compositor's scroll-speed setting produced.
        let mut frame = PointerFrame {
            has_axis: true,
            axis_source: Some(wl_pointer::axis_source::WHEEL),
            ..PointerFrame::default()
        };
        frame.value120[0] = -120.0;
        frame.continuous[0] = -15.0;
        assert_eq!(
            frame.scroll(1.0),
            Some(ScrollDelta::Lines { x: 0.0, y: 1.0 })
        );

        // A touchpad sends only the continuous value, and gets pixels — scaled
        // into device pixels, because the wire value is surface-local.
        let frame = PointerFrame {
            has_axis: true,
            axis_source: Some(wl_pointer::axis_source::FINGER),
            continuous: [-13.0, 0.0],
            ..PointerFrame::default()
        };
        assert_eq!(
            frame.scroll(2.0),
            Some(ScrollDelta::Pixels { x: 0.0, y: 26.0 })
        );

        // `axis_discrete` is the pre-version-8 spelling and behaves the same.
        let frame = PointerFrame {
            has_axis: true,
            discrete: [1.0, 0.0],
            ..PointerFrame::default()
        };
        assert_eq!(
            frame.scroll(1.0),
            Some(ScrollDelta::Lines { x: 0.0, y: -1.0 })
        );
    }

    #[test]
    fn an_axis_frame_with_no_movement_produces_no_wheel_event() {
        // `axis_stop` ends a kinetic scroll and carries no delta; emitting a
        // zero-length `Wheel` for it would be one event per touchpad lift.
        let frame = PointerFrame {
            has_axis: true,
            ..PointerFrame::default()
        };
        assert_eq!(frame.scroll(1.0), None);
        assert!(PointerFrame::default().is_empty());
        assert_eq!(PointerFrame::default().scroll(1.0), None);
    }

    #[test]
    fn a_frame_carrying_only_relative_motion_is_not_empty() {
        // The locked-pointer case: no `wl_pointer.motion` arrives at all, and a
        // flush that keyed on absolute motion would drop every aim sample.
        let frame = PointerFrame {
            raw: Some((3.0, -2.0)),
            ..PointerFrame::default()
        };
        assert!(!frame.is_empty());
    }

    #[test]
    fn axis_slots_are_vertical_then_horizontal() {
        assert_eq!(axis_slot(wl_pointer::axis::VERTICAL_SCROLL), Some(0));
        assert_eq!(axis_slot(wl_pointer::axis::HORIZONTAL_SCROLL), Some(1));
        assert_eq!(axis_slot(7), None, "an axis a later version might add");
    }

    #[test]
    fn an_outputs_scale_comes_from_the_logical_size_not_from_wl_output_scale() {
        // The finding `xdg_output` exists to fix. A 1920x1080 output run at
        // 150% reports `wl_output.scale = 2`, because that field is an integer
        // buffer scale and not the desktop's scale. The logical size says 1.5.
        let mut output = Output {
            proxy: 1,
            xdg: ptr::null_mut(),
            global: 1,
            id: MonitorId(1),
            x: 0,
            y: 0,
            width: 1920,
            height: 1080,
            refresh_millihertz: 60_000,
            scale: 2,
            logical_x: 0,
            logical_y: 0,
            logical_width: 1280,
            logical_height: 720,
            name: "HEADLESS-1".to_string(),
            settled: true,
        };
        assert!((output.scale_factor() - 1.5).abs() < 1e-9);
        let info = output.info(true);
        assert_eq!(
            info.size(),
            PhysicalSize::new(1920, 1080),
            "the size stays the mode, which is what a swapchain is built from"
        );

        // Without xdg_output there is nothing better than the integer.
        output.logical_width = 0;
        assert!((output.scale_factor() - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn a_monitors_position_is_scaled_out_of_the_logical_desktop_space() {
        // A second output placed to the right of a 1280-logical-wide first one,
        // itself at 2x. Its logical position is 1280; in its own device pixels
        // that is 2560. Reporting the raw 1280 next to a physical size would
        // put the two monitors on top of each other.
        let output = Output {
            proxy: 2,
            xdg: ptr::null_mut(),
            global: 2,
            id: MonitorId(2),
            x: 1280,
            y: 0,
            width: 3840,
            height: 2160,
            refresh_millihertz: 60_000,
            scale: 2,
            logical_x: 1280,
            logical_y: 0,
            logical_width: 1920,
            logical_height: 1080,
            name: "DP-2".to_string(),
            settled: true,
        };
        assert_eq!(output.info(false).bounds.x, 2560);
        assert_eq!(output.info(false).bounds.y, 0);
        assert_eq!(output.info(false).work_area, output.info(false).bounds);
    }

    #[test]
    fn a_windows_scale_prefers_the_fractional_one() {
        let mut window = test_window();
        window.scale = 2;
        assert!((window.scale_factor() - 2.0).abs() < f64::EPSILON);
        // With `fractional-scale-v1` in use the integer scale is not a step
        // on the way: the window stays at 1 until `preferred_scale` says.
        window.fractional_scale = ptr::NonNull::<WlProxy>::dangling().as_ptr();
        window.viewport = ptr::NonNull::<WlProxy>::dangling().as_ptr();
        assert!(window.is_fractional());
        assert!((window.scale_factor() - 1.0).abs() < f64::EPSILON);
        // 150%, in the 1/120ths the protocol reports.
        window.preferred_scale = Some(180);
        assert!((window.scale_factor() - 1.5).abs() < 1e-9);
        // A compositor that sends a nonsense zero falls back rather than
        // dividing the window down to nothing.
        window.preferred_scale = Some(0);
        assert!((window.scale_factor() - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn the_toplevel_state_array_decodes_as_native_endian_u32s() {
        // `xdg_toplevel.configure` carries its states as a `wl_array` of
        // `uint32_t`. Reading it a byte at a time — or as big endian — would
        // make "fullscreen" indistinguishable from "maximized", which is
        // exactly the bit `WindowConfiguration::mode` is computed from.
        let mut bytes = Vec::new();
        bytes.extend_from_slice(&xdg_toplevel::state::ACTIVATED.to_ne_bytes());
        bytes.extend_from_slice(&xdg_toplevel::state::FULLSCREEN.to_ne_bytes());
        assert_eq!(
            decode_state_array(&bytes),
            vec![
                xdg_toplevel::state::ACTIVATED,
                xdg_toplevel::state::FULLSCREEN
            ]
        );
        assert!(decode_state_array(&[]).is_empty());
        // A trailing partial element is dropped rather than read past.
        assert_eq!(decode_state_array(&[1, 0, 0, 0, 9]).len(), 1);
    }

    #[test]
    fn the_protocol_descriptors_carry_the_names_the_registry_advertises() {
        // A sanity check that the generated code is wired to the right
        // interfaces at all: `bind_global` matches on these strings, and a
        // wrong one means a global is silently never bound.
        assert_eq!(wl_compositor::NAME, c"wl_compositor");
        assert_eq!(xdg_wm_base::NAME, c"xdg_wm_base");
        assert_eq!(wl_output::NAME, c"wl_output");
        assert_eq!(wl_seat::NAME, c"wl_seat");
        assert_eq!(zxdg_output_manager_v1::NAME, c"zxdg_output_manager_v1");
        assert_eq!(
            zxdg_decoration_manager_v1::NAME,
            c"zxdg_decoration_manager_v1"
        );
        assert_eq!(
            wp_fractional_scale_manager_v1::NAME,
            c"wp_fractional_scale_manager_v1"
        );
        assert_eq!(wp_viewporter::NAME, c"wp_viewporter");
        assert_eq!(
            zwp_relative_pointer_manager_v1::NAME,
            c"zwp_relative_pointer_manager_v1"
        );
        assert_eq!(
            zwp_pointer_constraints_v1::NAME,
            c"zwp_pointer_constraints_v1"
        );
        assert_eq!(zwlr_layer_shell_v1::NAME, c"zwlr_layer_shell_v1");
        assert_eq!(
            zwp_text_input_manager_v3::NAME,
            c"zwp_text_input_manager_v3"
        );
        assert_eq!(
            wp_cursor_shape_manager_v1::NAME,
            c"wp_cursor_shape_manager_v1"
        );
        assert_eq!(xdg_toplevel::state::FULLSCREEN, 2);
        assert_eq!(wl_output::mode::CURRENT, 1);
        assert_eq!(wl_seat::capability::POINTER, 1);
        assert_eq!(wl_seat::capability::KEYBOARD, 2);
        assert_eq!(wl_keyboard::keymap_format::XKB_V1, 1);
        assert_eq!(zxdg_toplevel_decoration_v1::mode::SERVER_SIDE, 2);
    }

    #[test]
    fn opening_without_a_compositor_fails_cleanly_rather_than_aborting() {
        // The property the whole `dlopen` decision exists for: on a machine
        // with no Wayland session this is an ordinary error the registry can
        // fall through, not a loader failure before `main`.
        //
        // Skipped when the machine *does* have a session, since then the
        // correct behaviour is to succeed — and opening a real connection in a
        // unit test is not this test's job.
        if std::env::var_os("WAYLAND_DISPLAY").is_some() {
            return;
        }
        let error = WaylandShell::open().expect_err("no compositor");
        assert!(
            matches!(
                error,
                ShellError::Connect {
                    backend: ShellBackend::Wayland,
                    ..
                }
            ),
            "{error}"
        );
    }

    /// A window with no proxies, for the pure-logic tests above.
    fn test_window() -> WlWindow {
        WlWindow {
            surface: ptr::null_mut(),
            xdg_surface: ptr::null_mut(),
            toplevel: ptr::null_mut(),
            layer_surface: ptr::null_mut(),
            popup: ptr::null_mut(),
            parent: None,
            placement: None,
            popup_input: None,
            panel: None,
            decoration: ptr::null_mut(),
            fractional_scale: ptr::null_mut(),
            viewport: ptr::null_mut(),
            frame_callback: ptr::null_mut(),
            title: String::new(),
            requested_size: LogicalSize::new(640.0, 480.0),
            requested_mode: DisplayMode::Windowed,
            requested_constraints: SizeConstraints::default(),
            resizable: true,
            configuration: None,
            pending: PendingConfigure::default(),
            outputs: Vec::new(),
            scale: 1,
            preferred_scale: None,
            pointer_mode: PointerMode::Free,
            constraints: Vec::new(),
            cursor: None,
            accept_drops: false,
            transparent: false,
            text_input: text_input::Field::default(),
            focused: false,
            visible: true,
            close_pending: false,
        }
    }
}