stipple 0.0.3

Stipple: a cross-platform, self-drawn UI toolkit in Rust.
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
//! A native Wayland backend implemented directly against the wire protocol.
//!
//! No `wayland-client`/`smithay` crate — just a `UnixStream` to the compositor
//! and the Wayland byte protocol (core `wl_*` plus `xdg-shell`), matching the
//! hand-authored X11 backend. It connects to `$WAYLAND_DISPLAY`, binds the
//! `wl_compositor` / `wl_shm` / `xdg_wm_base` globals, creates an `xdg_toplevel`
//! window, and presents the software [`Pixmap`] through a `wl_shm` buffer the
//! compositor maps directly.
//!
//! Scope: connection, the `xdg-shell` configure/ack handshake, shared-memory
//! presentation (window create + paint + close), and `wl_seat` input —
//! **keyboard** (decodes the compositor's `wl_keyboard.keymap`, received as an
//! fd via `recvmsg`/`SCM_RIGHTS`, by parsing the XKB_V1 text to map keycodes to
//! keysyms and to find the Alt/Super modifier bits for `wl_keyboard.modifiers`;
//! falls back to a layout-independent evdev table if none) and **pointer**
//! (motion, buttons and `axis` scrolling via `wl_pointer`, coordinates from
//! `wl_fixed`). The clipboard goes through `wl_data_device` (`wayland/clipboard.rs`).
//! The FFI footprint — `memfd_create`/`mmap`, `sendmsg`/`recvmsg` for fd
//! passing — is the reason for the module-level `allow(unsafe_code)`.
//!
//! **Verification:** the `Visual` workflow's headless-`sway` job screenshots the
//! render with `grim` and types into a field with `wtype` (whose virtual
//! keyboard exercises the keymap-decode path end to end); the evdev/xkb mappings
//! are unit-tested.

#![allow(unsafe_code)]

mod clipboard;
mod text_input;

use std::cell::RefCell;
use std::collections::VecDeque;
use std::io::{self, Write};
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;
use std::sync::{Arc, Mutex};

use crate::geometry::{PhysicalSize, Point, ScaleFactor, Size};
use crate::platform::ControlFlow;
use crate::platform::error::PlatformError;
use crate::platform::event::{ButtonState, Event, KeyCode, Modifiers, ScrollDelta};
use crate::platform::window::{CursorIcon, Window, WindowAttributes, fit_icon};
use crate::render::{Pixmap, Surface};

use core::ffi::{c_char, c_void};

// ---- libc FFI for the shared-memory buffer + fd passing ---------------------

unsafe extern "C" {
    fn memfd_create(name: *const c_char, flags: u32) -> i32;
    fn ftruncate(fd: i32, length: i64) -> i32;
    fn mmap(addr: *mut c_void, len: usize, prot: i32, flags: i32, fd: i32, off: i64)
    -> *mut c_void;
    fn munmap(addr: *mut c_void, len: usize) -> i32;
    fn close(fd: i32) -> i32;
    fn sendmsg(sockfd: i32, msg: *const Msghdr, flags: i32) -> isize;
    fn recvmsg(sockfd: i32, msg: *mut Msghdr, flags: i32) -> isize;
}
const PROT_READ: i32 = 1;
const PROT_WRITE: i32 = 2;
const MAP_SHARED: i32 = 1;
const MAP_PRIVATE: i32 = 2;
const SOL_SOCKET: i32 = 1;
const SCM_RIGHTS: i32 = 1;

// `sendmsg` scatter/gather + control-message structs (Linux x86_64 layout;
// `repr(C)` inserts the alignment padding glibc expects).
#[repr(C)]
struct Iovec {
    iov_base: *mut c_void,
    iov_len: usize,
}
#[repr(C)]
struct Msghdr {
    msg_name: *mut c_void,
    msg_namelen: u32,
    msg_iov: *mut Iovec,
    msg_iovlen: usize,
    msg_control: *mut c_void,
    msg_controllen: usize,
    msg_flags: i32,
}
#[repr(C)]
struct Cmsghdr {
    cmsg_len: usize,
    cmsg_level: i32,
    cmsg_type: i32,
}

/// Send `bytes` over `sock` with a single file descriptor attached as an
/// `SCM_RIGHTS` control message (one `sendmsg`).
fn sendmsg_fd(sock: i32, bytes: &[u8], fd: i32) -> io::Result<()> {
    // Control buffer: CMSG_SPACE(sizeof(int)) = align8(sizeof(cmsghdr)) + align8(4).
    let mut control = [0u8; 24];
    let cmsg = control.as_mut_ptr() as *mut Cmsghdr;
    unsafe {
        (*cmsg).cmsg_len = 20; // CMSG_LEN(4) = 16 + 4
        (*cmsg).cmsg_level = SOL_SOCKET;
        (*cmsg).cmsg_type = SCM_RIGHTS;
        // CMSG_DATA sits after the aligned header (offset 16).
        let data = control.as_mut_ptr().add(16) as *mut i32;
        data.write_unaligned(fd);
    }
    let mut iov = Iovec {
        iov_base: bytes.as_ptr() as *mut c_void,
        iov_len: bytes.len(),
    };
    let msg = Msghdr {
        msg_name: std::ptr::null_mut(),
        msg_namelen: 0,
        msg_iov: &mut iov,
        msg_iovlen: 1,
        msg_control: control.as_mut_ptr() as *mut c_void,
        msg_controllen: control.len(),
        msg_flags: 0,
    };
    let n = unsafe { sendmsg(sock, &msg, 0) };
    if n < 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

// ---- Wayland object ids + opcodes -------------------------------------------

const WL_DISPLAY: u32 = 1;

// Request opcodes (client → server).
const WL_DISPLAY_GET_REGISTRY: u16 = 1;
const WL_DISPLAY_SYNC: u16 = 0;
const WL_REGISTRY_BIND: u16 = 0;
const WL_COMPOSITOR_CREATE_SURFACE: u16 = 0;
const WL_SHM_CREATE_POOL: u16 = 0;
const WL_SHM_POOL_CREATE_BUFFER: u16 = 0;
const WL_SURFACE_ATTACH: u16 = 1;
const WL_SURFACE_DAMAGE: u16 = 2;
const WL_SURFACE_COMMIT: u16 = 6;
const WL_SURFACE_SET_BUFFER_SCALE: u16 = 8;
const WL_SURFACE_ENTER: u16 = 0;
const WL_OUTPUT_SCALE: u16 = 3;
const WL_SEAT_GET_KEYBOARD: u16 = 1;
const XDG_WM_BASE_PONG: u16 = 3;
const XDG_WM_BASE_GET_XDG_SURFACE: u16 = 2;
const XDG_SURFACE_GET_TOPLEVEL: u16 = 1;
const XDG_SURFACE_ACK_CONFIGURE: u16 = 4;
const XDG_TOPLEVEL_SET_TITLE: u16 = 2;
const XDG_TOPLEVEL_SET_MAX_SIZE: u16 = 7;
const XDG_TOPLEVEL_SET_MIN_SIZE: u16 = 8;
const XDG_TOPLEVEL_SET_MAXIMIZED: u16 = 9;
const XDG_TOPLEVEL_UNSET_MAXIMIZED: u16 = 10;
const XDG_TOPLEVEL_SET_FULLSCREEN: u16 = 11;
const XDG_TOPLEVEL_UNSET_FULLSCREEN: u16 = 12;
// cursor-shape-v1: `wp_cursor_shape_manager_v1.get_pointer` and
// `wp_cursor_shape_device_v1.set_shape`.
const CURSOR_SHAPE_GET_POINTER: u16 = 1;
const CURSOR_SHAPE_SET_SHAPE: u16 = 1;
// xdg-toplevel-icon-v1: the manager's `create_icon` / `set_icon` and the
// icon's `add_buffer`.
const TOPLEVEL_ICON_CREATE_ICON: u16 = 1;
const TOPLEVEL_ICON_SET_ICON: u16 = 2;
const TOPLEVEL_ICON_ADD_BUFFER: u16 = 2;

// Event opcodes (server → client) for the objects we track.
const WL_DISPLAY_ERROR: u16 = 0;
const WL_REGISTRY_GLOBAL: u16 = 0;
const WL_CALLBACK_DONE: u16 = 0;
const XDG_WM_BASE_PING: u16 = 0;
const XDG_SURFACE_CONFIGURE: u16 = 0;
const XDG_TOPLEVEL_CONFIGURE: u16 = 0;
const XDG_TOPLEVEL_CLOSE: u16 = 1;
const WL_SEAT_CAPABILITIES: u16 = 0;
const WL_SEAT_CAP_POINTER: u32 = 1;
const WL_SEAT_CAP_KEYBOARD: u32 = 2;
const WL_SEAT_GET_POINTER: u16 = 0;
const WL_KEYBOARD_KEYMAP: u16 = 0;
const WL_KEYBOARD_KEY: u16 = 3;
const WL_KEYBOARD_MODIFIERS: u16 = 4;
const WL_POINTER_ENTER: u16 = 0;
const WL_POINTER_MOTION: u16 = 2;
const WL_POINTER_BUTTON: u16 = 3;
const WL_POINTER_AXIS: u16 = 4;
/// Since `wl_seat` v5: a wheel's notch count, sent before its `axis` event.
const WL_POINTER_AXIS_DISCRETE: u16 = 8;
/// The highest `wl_seat` version we speak. v5 adds `axis_discrete`; the other
/// events it adds (`frame`, `axis_source`, `axis_stop`, `repeat_info`, `name`)
/// are ignored. v8 would replace `axis_discrete` with `axis_value120`.
const WL_SEAT_VERSION: u32 = 5;

// `wl_shm` pixel format: 32-bit little-endian XRGB → bytes `[B, G, R, X]`.
const WL_SHM_FORMAT_XRGB8888: u32 = 1;
// The same with premultiplied alpha → bytes `[B, G, R, A]`.
const WL_SHM_FORMAT_ARGB8888: u32 = 0;

/// The largest icon we hand the compositor (it scales down from there).
const MAX_ICON: u32 = 256;

/// The `wp_cursor_shape_device_v1.shape` value for each [`CursorIcon`].
fn cursor_shape(icon: CursorIcon) -> u32 {
    match icon {
        CursorIcon::Default => 1,
        CursorIcon::Pointer => 4,
        CursorIcon::Crosshair => 8,
        CursorIcon::Text => 9,
        CursorIcon::Move => 13,
        CursorIcon::NotAllowed => 15,
        CursorIcon::Grab => 16,
        CursorIcon::Grabbing => 17,
        CursorIcon::EwResize => 26,
        CursorIcon::NsResize => 27,
        CursorIcon::NeswResize => 28,
        CursorIcon::NwseResize => 29,
    }
}

/// An icon as a square `wl_shm` ARGB8888 image (premultiplied `[B, G, R, A]`),
/// centered on a transparent square if it isn't one: xdg-toplevel-icon needs
/// square buffers. Returns the side length and the bytes.
fn icon_argb(icon: &Pixmap) -> (u32, Vec<u8>) {
    let icon = fit_icon(icon, MAX_ICON);
    let size = icon.size();
    let side = size.width.max(size.height).max(1);
    let (ox, oy) = ((side - size.width) / 2, (side - size.height) / 2);
    let mut out = vec![0u8; (side * side * 4) as usize];
    for y in 0..size.height {
        for x in 0..size.width {
            let [r, g, b, a] = icon.pixel(x, y).unwrap_or_default();
            let pre = |c: u8| ((c as u32 * a as u32 + 127) / 255) as u8;
            let o = (((y + oy) * side + x + ox) * 4) as usize;
            out[o..o + 4].copy_from_slice(&[pre(b), pre(g), pre(r), a]);
        }
    }
    (side, out)
}

/// Whether a Wayland compositor is reachable (cheap check of `$WAYLAND_DISPLAY`).
pub fn available() -> bool {
    std::env::var_os("WAYLAND_DISPLAY").is_some()
}

fn dbg(args: std::fmt::Arguments<'_>) {
    if std::env::var_os("STIPPLE_WAYLAND_DEBUG").is_some() {
        eprintln!("stipple wayland: {args}");
    }
}

fn os(e: io::Error) -> PlatformError {
    PlatformError::Os(e.to_string())
}

/// Translate a Linux evdev key code + press/release into a Stipple event.
///
/// Editing/navigation keys have layout-independent evdev codes, so they map
/// directly. Printable keys use a best-effort US-QWERTY table for [`Event::Text`]
/// (full layout handling needs the compositor's xkb keymap, preferred when it
/// was received); Shift upper-cases letters, and with Ctrl/logo held a printable
/// key becomes a [`KeyCode::Char`] shortcut, as on X11.
fn evdev_to_event(code: u32, pressed: bool, modifiers: Modifiers) -> Option<Event> {
    let state = if pressed {
        ButtonState::Pressed
    } else {
        ButtonState::Released
    };
    // Editing / navigation keys (Linux input-event-codes.h).
    let key = match code {
        15 => Some(KeyCode::Tab),
        28 | 96 => Some(KeyCode::Enter), // Enter, KP-Enter
        14 => Some(KeyCode::Backspace),
        111 => Some(KeyCode::Delete),
        105 => Some(KeyCode::ArrowLeft),
        106 => Some(KeyCode::ArrowRight),
        103 => Some(KeyCode::ArrowUp),
        108 => Some(KeyCode::ArrowDown),
        102 => Some(KeyCode::Home),
        107 => Some(KeyCode::End),
        104 => Some(KeyCode::PageUp),
        109 => Some(KeyCode::PageDown),
        110 => Some(KeyCode::Insert),
        1 => Some(KeyCode::Escape),
        59..=68 => Some(FUNCTION_KEYS[(code - 59) as usize]), // F1 … F10
        87 => Some(KeyCode::F11),
        88 => Some(KeyCode::F12),
        56 => Some(KeyCode::Alt), // KEY_LEFTALT (right Alt is often AltGr)
        127 => Some(KeyCode::ContextMenu), // KEY_COMPOSE, the Menu key
        _ => None,
    };
    if let Some(code) = key {
        return Some(Event::Key {
            code,
            state,
            modifiers,
        });
    }
    // Printable keys (US QWERTY).
    let ch = match code {
        16..=25 => Some(b"qwertyuiop"[(code - 16) as usize]),
        30..=38 => Some(b"asdfghjkl"[(code - 30) as usize]),
        44..=50 => Some(b"zxcvbnm"[(code - 44) as usize]),
        2..=10 => Some(b"123456789"[(code - 2) as usize]),
        11 => Some(b'0'),
        57 => Some(b' '),
        _ => None,
    };
    let c = ch? as char;
    let c = if modifiers.shift {
        c.to_ascii_uppercase()
    } else {
        c
    };
    char_event(c, state, modifiers)
}

/// F1 … F12, indexed from F1.
const FUNCTION_KEYS: [KeyCode; 12] = [
    KeyCode::F1,
    KeyCode::F2,
    KeyCode::F3,
    KeyCode::F4,
    KeyCode::F5,
    KeyCode::F6,
    KeyCode::F7,
    KeyCode::F8,
    KeyCode::F9,
    KeyCode::F10,
    KeyCode::F11,
    KeyCode::F12,
];

/// The event for a printable character: a [`KeyCode::Char`] shortcut while
/// Ctrl, Alt or the logo key is held (press and release), otherwise
/// [`Event::Text`] on press only. AltGr is another modifier, so it still types.
fn char_event(c: char, state: ButtonState, modifiers: Modifiers) -> Option<Event> {
    if modifiers.ctrl || modifiers.meta || modifiers.alt {
        return Some(Event::Key {
            code: KeyCode::Char(c),
            state,
            modifiers,
        });
    }
    (state == ButtonState::Pressed).then(|| Event::Text(c.to_string()))
}

/// Convert a `wl_fixed` (signed 24.8 fixed-point) to logical pixels.
fn fixed_to_f64(raw: u32) -> f64 {
    (raw as i32) as f64 / 256.0
}

/// The scroll delta for a `wl_pointer.axis` event: `axis` 0 is vertical, 1
/// horizontal, and `value` (a `wl_fixed`) is in surface pixels, positive down
/// or right. A wheel also sends `axis_discrete` with its notch count first;
/// then the delta is one line per notch, as on the other backends, rather than
/// the compositor's per-notch distance (often 10 or 15 px).
fn axis_delta(axis: u32, value: u32, discrete: i32) -> Option<ScrollDelta> {
    let px = if discrete != 0 {
        f64::from(discrete) * crate::platform::input::LINE_PX
    } else {
        fixed_to_f64(value)
    };
    match axis {
        0 => Some(ScrollDelta { dx: 0.0, dy: px }),
        1 => Some(ScrollDelta { dx: px, dy: 0.0 }),
        _ => None,
    }
}

/// Translate an evdev pointer button code into a Stipple [`PointerButton`].
fn pointer_button(code: u32) -> Option<crate::platform::event::PointerButton> {
    use crate::platform::event::PointerButton;
    match code {
        0x110 => Some(PointerButton::Left),
        0x111 => Some(PointerButton::Right),
        0x112 => Some(PointerButton::Middle),
        _ => None,
    }
}

// ---- xkb keymap (text format) -----------------------------------------------

/// `wl_keyboard.modifiers` bits for xkb's fixed real modifiers (Shift, Lock,
/// Control); Alt and the logo key are whichever of Mod1…Mod5 the keymap binds
/// them to.
const XKB_SHIFT: u32 = 1 << 0;
const XKB_LOCK: u32 = 1 << 1;
const XKB_CONTROL: u32 = 1 << 2;
/// The usual bindings, used when the keymap doesn't say: Alt on Mod1, the logo
/// key on Mod4.
const XKB_MOD1: u32 = 1 << 3;
const XKB_MOD4: u32 = 1 << 6;

/// What we read from the compositor's XKB_V1 keymap.
#[derive(Debug)]
struct XkbKeymap {
    /// xkb keycode (evdev + 8) → keysym names at shift levels 1 and 2.
    keys: std::collections::HashMap<u32, (String, Option<String>)>,
    /// The modifier bits that mean Alt and the logo (Super) key.
    alt_mask: u32,
    meta_mask: u32,
}

impl XkbKeymap {
    /// The keysym name for `keycode` under the given modifier state: the
    /// level-2 symbol when Shift (or Caps Lock, for letters) selects it, else
    /// level 1.
    fn sym(&self, keycode: u32, mask: u32) -> Option<&str> {
        let (base, shifted) = self.keys.get(&keycode)?;
        let letter = base.chars().count() == 1 && base.chars().all(char::is_alphabetic);
        let shift = mask & XKB_SHIFT != 0;
        let caps = mask & XKB_LOCK != 0 && letter;
        match shifted {
            // Named keys (Tab → ISO_Left_Tab, …) stay themselves: Shift is
            // reported through the modifiers instead.
            Some(s) if shift != caps && keysym_name_to_key(base).is_none() => Some(s),
            _ => Some(base),
        }
    }
}

/// Translate a `wl_keyboard.modifiers` state (depressed | latched | locked)
/// into [`Modifiers`].
fn wl_modifiers(mask: u32, keymap: Option<&XkbKeymap>) -> Modifiers {
    let (alt, meta) = keymap.map_or((XKB_MOD1, XKB_MOD4), |k| (k.alt_mask, k.meta_mask));
    Modifiers {
        shift: mask & XKB_SHIFT != 0,
        ctrl: mask & XKB_CONTROL != 0,
        alt: mask & alt != 0,
        meta: mask & meta != 0,
    }
}

/// The substring of `s` between the first `a` and the next `b`.
fn between(s: &str, a: char, b: char) -> Option<&str> {
    let start = s.find(a)? + 1;
    let end = s[start..].find(b)? + start;
    Some(&s[start..end])
}

/// The symbol list in a `key` line: the `[ a, A ]` after `{` or after
/// `symbols[Group1]=`, never an `actions[…]` list. `None` if the line has none.
fn symbol_list(t: &str) -> Option<Vec<&str>> {
    let from = match t.find("symbols[") {
        Some(i) => i + t[i..].find(']')? + 1,
        None => 0,
    };
    let lb = t[from..].find('[')? + from;
    // `actions[` / `vmods[`-style subscripts aren't symbol lists.
    if from == 0
        && t[..lb]
            .chars()
            .next_back()
            .is_some_and(|c| c.is_alphanumeric() || c == '_')
    {
        return None;
    }
    let inner = &t[lb + 1..];
    let inner = &inner[..inner.find(']')?];
    Some(inner.split(',').map(str::trim).collect())
}

/// Parse an XKB_V1 keymap. We read keycode definitions `<NAME> = N;`, per-key
/// symbols (`key <NAME> { [ sym1, sym2 ] };`, or the multi-line form with a
/// `symbols[Group1]= [ … ]` line), and `modifier_map ModN { … };` to learn
/// which modifier bits Alt and Super use.
/// A keysym name as the rest of the backend expects it. Keymaps written by
/// tools like `wtype` name keysyms by value (`0x61`, `0xff09`, `0x100263a`)
/// rather than by name; those become the name (`Tab`), the character (`a`) or
/// the `UXXXX` form, which [`keysym_name_to_event`] understands.
fn keysym_canonical_name(sym: &str) -> String {
    let Some(value) = sym
        .strip_prefix("0x")
        .and_then(|hex| u32::from_str_radix(hex, 16).ok())
    else {
        return sym.to_string();
    };
    let named = match value {
        0xff09 => "Tab",
        0xfe20 => "ISO_Left_Tab",
        0xff0d => "Return",
        0xff8d => "KP_Enter",
        0xff08 => "BackSpace",
        0xffff => "Delete",
        0xff51 => "Left",
        0xff52 => "Up",
        0xff53 => "Right",
        0xff54 => "Down",
        0xff50 => "Home",
        0xff57 => "End",
        0xff55 => "Prior",
        0xff56 => "Next",
        0xff63 => "Insert",
        0xff1b => "Escape",
        0x20 => "space",
        0xffbe..=0xffc9 => return format!("F{}", value - 0xffbe + 1),
        // Latin-1 keysyms are the code point; 0x01000000 + cp is Unicode.
        0x21..=0x7e | 0xa0..=0xff => {
            return char::from_u32(value).map_or_else(|| sym.to_string(), String::from);
        }
        0x0100_0000..=0x0110_ffff => return format!("U{:04X}", value - 0x0100_0000),
        _ => return sym.to_string(),
    };
    named.to_string()
}

fn parse_xkb(text: &str) -> XkbKeymap {
    use std::collections::HashMap;
    let mut codes: HashMap<&str, u32> = HashMap::new();
    let mut syms: HashMap<&str, (String, Option<String>)> = HashMap::new();
    // (modifier bit, members: `<KEY>` names or keysym names)
    let mut mod_maps: Vec<(u32, Vec<&str>)> = Vec::new();
    // A multi-line `key <NAME> {` block whose symbols are still to come.
    let mut open_key: Option<&str> = None;
    let mut record = |name, list: Vec<&str>| {
        let level = |i: usize| {
            list.get(i)
                .copied()
                .filter(|s| !s.is_empty() && *s != "NoSymbol")
                .map(keysym_canonical_name)
        };
        if let Some(base) = level(0) {
            syms.insert(name, (base, level(1)));
        }
    };
    for line in text.lines() {
        let t = line.trim();
        // `key <NAME>`, with any run of spaces (xkbcomp pads short names).
        let key_line = t
            .strip_prefix("key ")
            .and_then(|r| r.trim_start().strip_prefix('<'));
        if let Some(rest) = key_line {
            // key <NAME> { [ sym1, sym2 ] };
            open_key = None;
            if let Some(end) = rest.find('>') {
                let name = &rest[..end];
                match symbol_list(t) {
                    Some(list) => record(name, list),
                    None if !t.ends_with("};") => open_key = Some(name),
                    None => {}
                }
            }
        } else if let Some(name) = open_key {
            if t.starts_with('}') {
                open_key = None;
            } else if (t.starts_with("symbols[") || t.starts_with('['))
                && let Some(list) = symbol_list(t)
            {
                // Only the first group's symbols.
                record(name, list);
                open_key = None;
            }
        } else if let Some(rest) = t.strip_prefix("modifier_map ") {
            // modifier_map Mod1 { <LALT>, <META> };
            let modifier = rest.split_whitespace().next().unwrap_or("");
            let bit = match modifier {
                "Mod1" => 3,
                "Mod2" => 4,
                "Mod3" => 5,
                "Mod4" => 6,
                "Mod5" => 7,
                _ => continue, // Shift/Lock/Control have fixed bits
            };
            if let Some(members) = between(t, '{', '}') {
                mod_maps.push((1 << bit, members.split(',').map(str::trim).collect()));
            }
        } else if t.starts_with('<') && t.contains('=') {
            // <NAME> = N;
            if let Some(name) = between(t, '<', '>')
                && let Some(eq) = t.find('=')
            {
                let num: String = t[eq + 1..].chars().filter(|c| c.is_ascii_digit()).collect();
                if let Ok(code) = num.parse::<u32>() {
                    codes.insert(name, code);
                }
            }
        }
    }
    // Which modifier bits hold Alt/Meta and Super keys.
    let (mut alt_mask, mut meta_mask) = (0, 0);
    for (bit, members) in &mod_maps {
        for member in members {
            let sym = match member.strip_prefix('<').and_then(|m| m.strip_suffix('>')) {
                Some(key) => syms.get(key).map_or("", |(base, _)| base.as_str()),
                None => member,
            };
            if sym.starts_with("Alt_") || sym.starts_with("Meta_") {
                alt_mask |= bit;
            } else if sym.starts_with("Super_") {
                meta_mask |= bit;
            }
        }
    }
    let keys = codes
        .into_iter()
        .filter_map(|(name, code)| syms.get(name).map(|s| (code, s.clone())))
        .collect();
    XkbKeymap {
        keys,
        alt_mask: if alt_mask == 0 { XKB_MOD1 } else { alt_mask },
        meta_mask: if meta_mask == 0 { XKB_MOD4 } else { meta_mask },
    }
}

/// The named key an xkb keysym name stands for, if it isn't printable.
fn keysym_name_to_key(name: &str) -> Option<KeyCode> {
    Some(match name {
        "Tab" | "ISO_Left_Tab" => KeyCode::Tab,
        "Return" | "KP_Enter" => KeyCode::Enter,
        "BackSpace" => KeyCode::Backspace,
        "Delete" => KeyCode::Delete,
        "Left" => KeyCode::ArrowLeft,
        "Right" => KeyCode::ArrowRight,
        "Up" => KeyCode::ArrowUp,
        "Down" => KeyCode::ArrowDown,
        "Home" => KeyCode::Home,
        "End" => KeyCode::End,
        "Prior" | "Page_Up" => KeyCode::PageUp,
        "Next" | "Page_Down" => KeyCode::PageDown,
        "Insert" => KeyCode::Insert,
        "Escape" => KeyCode::Escape,
        "F1" => KeyCode::F1,
        "F2" => KeyCode::F2,
        "F3" => KeyCode::F3,
        "F4" => KeyCode::F4,
        "F5" => KeyCode::F5,
        "F6" => KeyCode::F6,
        "F7" => KeyCode::F7,
        "F8" => KeyCode::F8,
        "F9" => KeyCode::F9,
        "F10" => KeyCode::F10,
        "F11" => KeyCode::F11,
        "F12" => KeyCode::F12,
        "Alt_L" | "Alt_R" | "Meta_L" | "Meta_R" => KeyCode::Alt,
        "Menu" => KeyCode::ContextMenu,
        _ => return None,
    })
}

/// Translate an xkb keysym name into a Stipple event (editing/navigation keys →
/// [`Event::Key`], printable keysyms → [`Event::Text`] on press, or a
/// [`KeyCode::Char`] shortcut with Ctrl/logo held).
fn keysym_name_to_event(name: &str, pressed: bool, modifiers: Modifiers) -> Option<Event> {
    let state = if pressed {
        ButtonState::Pressed
    } else {
        ButtonState::Released
    };
    if let Some(code) = keysym_name_to_key(name) {
        return Some(Event::Key {
            code,
            state,
            modifiers,
        });
    }
    // Printable: a one-character keysym name is the character itself; other
    // names (`space`, `eacute`, `Cyrillic_a`, `UXXXX`, …) go through the
    // keysym table.
    let ch = crate::platform::compose::keysym_to_char(keysym_value(name)?);
    char_event(ch?, state, modifiers)
}

/// The keysym value of a keysym name as [`XkbKeymap::sym`] gives it: a
/// one-character name is that character's keysym, anything else a name from
/// the keysym table (`dead_acute`, `eacute`, `UXXXX`, …).
fn keysym_value(name: &str) -> Option<u32> {
    let mut chars = name.chars();
    match (chars.next(), chars.next()) {
        (Some(c), None) if (c as u32) < 0x100 => Some(c as u32),
        (Some(c), None) => Some(0x0100_0000 + c as u32),
        _ => crate::platform::compose::keysym_from_name(name),
    }
}

/// Map a keymap `fd` of `size` bytes (the `wl_keyboard.keymap` payload) and
/// parse it. Closes the fd; returns `None` on failure.
fn read_keymap(fd: i32, size: usize) -> Option<XkbKeymap> {
    if size == 0 {
        unsafe { close(fd) };
        return None;
    }
    let addr = unsafe { mmap(std::ptr::null_mut(), size, PROT_READ, MAP_PRIVATE, fd, 0) };
    unsafe { close(fd) }; // the mapping outlives the fd
    if addr as isize == -1 {
        return None;
    }
    let bytes = unsafe { std::slice::from_raw_parts(addr as *const u8, size) };
    let text = String::from_utf8_lossy(bytes).into_owned();
    let map = parse_xkb(&text);
    unsafe { munmap(addr, size) };
    Some(map)
}

// ---- Wire connection --------------------------------------------------------

/// The compositor connection plus the client-side object-id allocator.
struct WlConn {
    stream: UnixStream,
    next_id: u32,
    /// File descriptors received with messages (the `wl_keyboard.keymap` fd, a
    /// `wl_data_source.send` fd), in arrival order, taken by the handler of the
    /// message that carries each.
    fds: VecDeque<i32>,
    /// Messages read while a paste waited on its pipe, for the event loop.
    queue: VecDeque<(u32, u16, Vec<u8>)>,
    clip: clipboard::Clipboard,
    /// Buffer pixels per surface unit: the scale of the output we're on.
    buffer_scale: u32,
    /// The `wp_cursor_shape_device_v1` for our pointer, when the compositor
    /// supports cursor-shape-v1.
    cursor_device: Option<u32>,
    /// The serial of the pointer's last `enter`, which `set_shape` must quote.
    enter_serial: Option<u32>,
    /// The cursor the app asked for, re-applied on each `enter`.
    cursor: CursorIcon,
    /// The seat's `zwp_text_input_v3`, when the compositor offers it.
    text_input: text_input::TextInput,
}

impl WlConn {
    /// Connect to the compositor socket named by `$WAYLAND_DISPLAY` (relative
    /// names resolve under `$XDG_RUNTIME_DIR`).
    fn connect() -> Result<Self, PlatformError> {
        let disp = std::env::var_os("WAYLAND_DISPLAY")
            .ok_or_else(|| PlatformError::Os("WAYLAND_DISPLAY not set".into()))?;
        let path = std::path::PathBuf::from(&disp);
        let full = if path.is_absolute() {
            path
        } else {
            let dir = std::env::var_os("XDG_RUNTIME_DIR")
                .ok_or_else(|| PlatformError::Os("XDG_RUNTIME_DIR not set".into()))?;
            std::path::Path::new(&dir).join(path)
        };
        let stream = UnixStream::connect(&full).map_err(os)?;
        Ok(Self {
            stream,
            next_id: 2,
            fds: VecDeque::new(),
            queue: VecDeque::new(),
            clip: clipboard::Clipboard::default(),
            buffer_scale: 1,
            cursor_device: None,
            enter_serial: None,
            cursor: CursorIcon::Default,
            text_input: text_input::TextInput::default(),
        })
    }

    /// Show the current cursor shape, if the compositor supports
    /// cursor-shape-v1 and the pointer has entered our surface.
    fn apply_cursor(&mut self) {
        if let (Some(device), Some(serial)) = (self.cursor_device, self.enter_serial) {
            let mut a = Vec::new();
            arg_u32(&mut a, serial);
            arg_u32(&mut a, cursor_shape(self.cursor));
            let _ = self.send(device, CURSOR_SHAPE_SET_SHAPE, &a);
            let _ = self.stream.flush();
        }
    }

    /// Allocate the next client object id.
    fn new_id(&mut self) -> u32 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }

    /// Send a request `(object, opcode, args)`; `args` is the already-encoded
    /// argument block (a multiple of 4 bytes).
    fn send(&mut self, object: u32, opcode: u16, args: &[u8]) -> io::Result<()> {
        let size = (8 + args.len()) as u32;
        let mut msg = Vec::with_capacity(size as usize);
        msg.extend_from_slice(&object.to_le_bytes());
        msg.extend_from_slice(&((size << 16) | opcode as u32).to_le_bytes());
        msg.extend_from_slice(args);
        self.stream.write_all(&msg)
    }

    /// Send a request carrying a file descriptor via an `SCM_RIGHTS` control
    /// message (used by `wl_shm.create_pool`).
    fn send_with_fd(&mut self, object: u32, opcode: u16, args: &[u8], fd: i32) -> io::Result<()> {
        let size = (8 + args.len()) as u32;
        let mut msg = Vec::with_capacity(size as usize);
        msg.extend_from_slice(&object.to_le_bytes());
        msg.extend_from_slice(&((size << 16) | opcode as u32).to_le_bytes());
        msg.extend_from_slice(args);
        sendmsg_fd(self.stream.as_raw_fd(), &msg, fd)
    }

    /// Fill `buf` exactly via `recvmsg`, queueing any `SCM_RIGHTS` file
    /// descriptors that arrive with it in `self.fds`. Used instead of
    /// `read_exact` so the `wl_keyboard.keymap` fd isn't silently dropped.
    fn recv_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        let sock = self.stream.as_raw_fd();
        let mut got = 0;
        while got < buf.len() {
            let mut iov = Iovec {
                iov_base: buf[got..].as_mut_ptr() as *mut c_void,
                iov_len: buf.len() - got,
            };
            let mut control = [0u8; 32];
            let mut msg = Msghdr {
                msg_name: std::ptr::null_mut(),
                msg_namelen: 0,
                msg_iov: &mut iov,
                msg_iovlen: 1,
                msg_control: control.as_mut_ptr() as *mut c_void,
                msg_controllen: control.len(),
                msg_flags: 0,
            };
            let n = unsafe { recvmsg(sock, &mut msg, 0) };
            if n <= 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "wayland socket closed",
                ));
            }
            got += n as usize;
            // Collect the SCM_RIGHTS fds if the kernel attached any.
            if msg.msg_controllen >= core::mem::size_of::<Cmsghdr>() {
                let cmsg = control.as_ptr() as *const Cmsghdr;
                let (len, level, ty) =
                    unsafe { ((*cmsg).cmsg_len, (*cmsg).cmsg_level, (*cmsg).cmsg_type) };
                if level == SOL_SOCKET && ty == SCM_RIGHTS {
                    let count = (len.min(msg.msg_controllen).saturating_sub(16)) / 4;
                    for i in 0..count {
                        let fd = unsafe {
                            (control.as_ptr().add(16 + i * 4) as *const i32).read_unaligned()
                        };
                        self.fds.push_back(fd);
                    }
                }
            }
        }
        Ok(())
    }

    /// Read exactly one message: returns `(object, opcode, args)`. Any attached
    /// fd lands in `self.fds`.
    fn recv(&mut self) -> io::Result<(u32, u16, Vec<u8>)> {
        let mut header = [0u8; 8];
        self.recv_exact(&mut header)?;
        let object = u32::from_le_bytes([header[0], header[1], header[2], header[3]]);
        let word = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
        let size = (word >> 16) as usize;
        let opcode = (word & 0xffff) as u16;
        let mut args = vec![0u8; size.saturating_sub(8)];
        self.recv_exact(&mut args)?;
        Ok((object, opcode, args))
    }
}

// ---- Argument encoding helpers ----------------------------------------------

/// Append a 32-bit argument (int / uint / object / new_id).
fn arg_u32(buf: &mut Vec<u8>, v: u32) {
    buf.extend_from_slice(&v.to_le_bytes());
}

/// Append a string argument: length (incl NUL) + bytes + NUL, padded to 4.
fn arg_str(buf: &mut Vec<u8>, s: &str) {
    let len = s.len() + 1; // include the trailing NUL
    arg_u32(buf, len as u32);
    buf.extend_from_slice(s.as_bytes());
    buf.push(0);
    while !buf.len().is_multiple_of(4) {
        buf.push(0);
    }
}

/// Deliver drag-and-drop messages from the data device to the app, answering
/// the drag source after each enter and move with what the app said through
/// `set_drop_accepted`.
fn deliver_dnd(
    shared: &Shared,
    win: &WaylandWindow,
    messages: Vec<clipboard::DndMessage>,
    handler: &mut dyn FnMut(Event, &dyn Window) -> ControlFlow,
) -> ControlFlow {
    use clipboard::DndMessage;
    for message in messages {
        let flow = match message {
            DndMessage::Enter { x, y, offer } => {
                let position = Point::new(x, y);
                win.drop_accepted.set(false);
                dbg(format_args!("dnd: enter at {position:?} {offer:?}"));
                let flow = handler(Event::DragEnter { position, offer }, win);
                clipboard::answer_drag(&mut shared.lock().unwrap(), win.drop_accepted.get());
                flow
            }
            DndMessage::Motion { x, y } => {
                let position = Point::new(x, y);
                let was = win.drop_accepted.get();
                let flow = handler(Event::DragOver { position }, win);
                if win.drop_accepted.get() != was {
                    clipboard::answer_drag(&mut shared.lock().unwrap(), win.drop_accepted.get());
                }
                flow
            }
            DndMessage::Leave => {
                dbg(format_args!("dnd: leave"));
                handler(Event::DragLeave, win)
            }
            DndMessage::Drop { x, y } => {
                let data =
                    clipboard::take_drop(&mut shared.lock().unwrap(), win.drop_accepted.get());
                dbg(format_args!("dnd: drop {data:?}"));
                match data {
                    Some(data) => handler(
                        Event::Drop {
                            position: Point::new(x, y),
                            data,
                        },
                        win,
                    ),
                    None => handler(Event::DragLeave, win),
                }
            }
        };
        if flow == ControlFlow::Exit {
            return flow;
        }
    }
    ControlFlow::Wait
}

/// Read a length-prefixed string from an event arg block at `off`, returning the
/// text (without the trailing NUL) and the next offset (the string bytes are
/// padded to a 4-byte boundary).
fn read_str(args: &[u8], off: usize) -> Option<(String, usize)> {
    let len = u32::from_le_bytes([
        *args.get(off)?,
        *args.get(off + 1)?,
        *args.get(off + 2)?,
        *args.get(off + 3)?,
    ]) as usize;
    let start = off + 4;
    let bytes = args.get(start..start + len)?;
    let text = String::from_utf8_lossy(&bytes[..len.saturating_sub(1)]).into_owned();
    let next = start + len.div_ceil(4) * 4;
    Some((text, next))
}

/// Convert a straight-RGBA8 pixmap into `wl_shm` XRGB8888 bytes (`[B, G, R, 0]`).
fn rgba_to_xrgb(rgba: &[u8], dst: &mut [u8]) {
    for (s, d) in rgba
        .as_chunks::<4>()
        .0
        .iter()
        .zip(dst.as_chunks_mut::<4>().0.iter_mut())
    {
        d[0] = s[2];
        d[1] = s[1];
        d[2] = s[0];
        d[3] = 0;
    }
}

// ---- Shared-memory buffer ---------------------------------------------------

/// A `memfd`-backed region mapped into this process and shared with the
/// compositor as a `wl_shm` pool.
struct ShmBuffer {
    fd: i32,
    ptr: *mut u8,
    capacity: usize,
    buffer: u32,
    size: PhysicalSize,
}

impl ShmBuffer {
    fn bytes(&mut self) -> &mut [u8] {
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.capacity) }
    }
}

impl Drop for ShmBuffer {
    fn drop(&mut self) {
        unsafe {
            munmap(self.ptr as *mut c_void, self.capacity);
            close(self.fd);
        }
    }
}

/// Create a `memfd` of `bytes`, map it, and make a `wl_shm` pool + buffer of
/// `size` over it in `format`. Sends `create_pool` (with the fd) and
/// `create_buffer`.
fn make_shm(
    conn: &mut WlConn,
    shm: u32,
    size: PhysicalSize,
    format: u32,
) -> Result<ShmBuffer, PlatformError> {
    let stride = size.width as usize * 4;
    let bytes = stride * size.height as usize;
    let name = c"stipple-wl";
    let fd = unsafe { memfd_create(name.as_ptr(), 0) };
    if fd < 0 {
        return Err(PlatformError::Os("memfd_create failed".into()));
    }
    if unsafe { ftruncate(fd, bytes as i64) } < 0 {
        unsafe { close(fd) };
        return Err(PlatformError::Os("ftruncate failed".into()));
    }
    let addr = unsafe {
        mmap(
            std::ptr::null_mut(),
            bytes,
            PROT_READ | PROT_WRITE,
            MAP_SHARED,
            fd,
            0,
        )
    };
    if addr as isize == -1 {
        unsafe { close(fd) };
        return Err(PlatformError::Os("mmap failed".into()));
    }

    let pool = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, pool);
    arg_u32(&mut a, bytes as u32);
    conn.send_with_fd(shm, WL_SHM_CREATE_POOL, &a, fd)
        .map_err(os)?;

    let buffer = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, buffer);
    arg_u32(&mut a, 0); // offset
    arg_u32(&mut a, size.width);
    arg_u32(&mut a, size.height);
    arg_u32(&mut a, stride as u32);
    arg_u32(&mut a, format);
    conn.send(pool, WL_SHM_POOL_CREATE_BUFFER, &a).map_err(os)?;

    Ok(ShmBuffer {
        fd,
        ptr: addr as *mut u8,
        capacity: bytes,
        buffer,
        size,
    })
}

// ---- Window + Surface -------------------------------------------------------

type Shared = Arc<Mutex<WlConn>>;

struct WaylandWindow {
    conn: Shared,
    surface: u32,
    shm: u32,
    size: PhysicalSize,
    toplevel: u32,
    /// The `xdg_toplevel_icon_manager_v1`, when the compositor has one.
    icon_manager: Option<u32>,
    /// The icon's pixels, which must stay mapped while the compositor uses them.
    icon: RefCell<Option<ShmBuffer>>,
    /// Whether the app takes the drag over the surface (see
    /// `set_drop_accepted`).
    drop_accepted: std::cell::Cell<bool>,
}

impl WaylandWindow {
    /// Send a toplevel request, then commit so it applies (xdg-shell state is
    /// double-buffered).
    fn toplevel_request(&self, opcode: u16, args: &[u8]) {
        let mut conn = self.conn.lock().unwrap();
        let _ = conn.send(self.toplevel, opcode, args);
        let _ = conn.send(self.surface, WL_SURFACE_COMMIT, &[]);
        let _ = conn.stream.flush();
    }
}

/// The arguments of `xdg_toplevel.set_min_size` / `set_max_size`: a size in
/// surface coordinates (logical pixels), 0 for "no limit".
fn size_args(size: Option<Size>) -> Vec<u8> {
    let (w, h) = size.map_or((0, 0), |s| {
        (
            s.width.round().max(1.0) as u32,
            s.height.round().max(1.0) as u32,
        )
    });
    let mut a = Vec::new();
    arg_u32(&mut a, w);
    arg_u32(&mut a, h);
    a
}

/// Set (or clear) the toplevel's icon through xdg-toplevel-icon-v1, returning
/// the buffer holding its pixels.
fn set_toplevel_icon(
    conn: &mut WlConn,
    shm: u32,
    manager: u32,
    toplevel: u32,
    icon: Option<&Pixmap>,
) -> Option<ShmBuffer> {
    let mut a = Vec::new();
    let Some(icon) = icon else {
        arg_u32(&mut a, toplevel);
        arg_u32(&mut a, 0); // null icon: back to the default
        let _ = conn.send(manager, TOPLEVEL_ICON_SET_ICON, &a);
        return None;
    };
    let (side, bytes) = icon_argb(icon);
    let mut buf = make_shm(
        conn,
        shm,
        PhysicalSize::new(side, side),
        WL_SHM_FORMAT_ARGB8888,
    )
    .ok()?;
    buf.bytes()[..bytes.len()].copy_from_slice(&bytes);
    let id = conn.new_id();
    arg_u32(&mut a, id);
    conn.send(manager, TOPLEVEL_ICON_CREATE_ICON, &a).ok()?;
    let mut a = Vec::new();
    arg_u32(&mut a, buf.buffer);
    arg_u32(&mut a, 1); // scale
    conn.send(id, TOPLEVEL_ICON_ADD_BUFFER, &a).ok()?;
    let mut a = Vec::new();
    arg_u32(&mut a, toplevel);
    arg_u32(&mut a, id);
    conn.send(manager, TOPLEVEL_ICON_SET_ICON, &a).ok()?;
    Some(buf)
}

impl std::fmt::Debug for WaylandWindow {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WaylandWindow")
            .field("surface", &self.surface)
            .field("size", &self.size)
            .finish()
    }
}

impl Window for WaylandWindow {
    fn id(&self) -> crate::platform::WindowId {
        crate::platform::WindowId(self.surface as u64)
    }
    fn set_tray(&self, tray: Option<&crate::platform::NativeTray>) -> bool {
        crate::platform::shell::sni::set_tray(tray)
    }
    fn inner_size(&self) -> PhysicalSize {
        self.size
    }
    fn scale_factor(&self) -> ScaleFactor {
        ScaleFactor::new(self.conn.lock().unwrap().buffer_scale as f64)
    }
    fn request_redraw(&self) {}
    fn set_title(&self, _title: &str) {}
    fn clipboard(&self) -> Option<String> {
        clipboard::text(&mut self.conn.lock().unwrap())
    }
    fn set_drop_accepted(&self, accepted: bool) {
        self.drop_accepted.set(accepted);
    }
    fn set_clipboard(&self, text: &str) {
        clipboard::set_text(&mut self.conn.lock().unwrap(), text);
    }
    fn set_ime(&self, state: Option<&crate::platform::ImeState>) {
        text_input::set_state(&mut self.conn.lock().unwrap(), state);
    }
    fn set_cursor(&self, cursor: CursorIcon) {
        let mut conn = self.conn.lock().unwrap();
        conn.cursor = cursor;
        conn.apply_cursor();
    }
    fn set_min_size(&self, size: Option<Size>) {
        self.toplevel_request(XDG_TOPLEVEL_SET_MIN_SIZE, &size_args(size));
    }
    fn set_max_size(&self, size: Option<Size>) {
        self.toplevel_request(XDG_TOPLEVEL_SET_MAX_SIZE, &size_args(size));
    }
    fn set_maximized(&self, maximized: bool) {
        let opcode = if maximized {
            XDG_TOPLEVEL_SET_MAXIMIZED
        } else {
            XDG_TOPLEVEL_UNSET_MAXIMIZED
        };
        self.toplevel_request(opcode, &[]);
    }
    fn set_fullscreen(&self, fullscreen: bool) {
        if fullscreen {
            // A null output lets the compositor pick.
            self.toplevel_request(XDG_TOPLEVEL_SET_FULLSCREEN, &0u32.to_le_bytes());
        } else {
            self.toplevel_request(XDG_TOPLEVEL_UNSET_FULLSCREEN, &[]);
        }
    }
    fn set_icon(&self, icon: Option<&Pixmap>) {
        let Some(manager) = self.icon_manager else {
            return;
        };
        let mut conn = self.conn.lock().unwrap();
        let buf = set_toplevel_icon(&mut conn, self.shm, manager, self.toplevel, icon);
        // The icon is double-buffered toplevel state: commit to apply it.
        let _ = conn.send(self.surface, WL_SURFACE_COMMIT, &[]);
        let _ = conn.stream.flush();
        *self.icon.borrow_mut() = buf;
    }
    fn create_surface(&self) -> Box<dyn Surface> {
        Box::new(WaylandSurface {
            conn: self.conn.clone(),
            surface: self.surface,
            shm: self.shm,
            size: self.size,
            buffer: None,
        })
    }
}

struct WaylandSurface {
    conn: Shared,
    surface: u32,
    shm: u32,
    size: PhysicalSize,
    buffer: Option<ShmBuffer>,
}

impl std::fmt::Debug for WaylandSurface {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WaylandSurface")
            .field("surface", &self.surface)
            .field("size", &self.size)
            .finish()
    }
}

impl Surface for WaylandSurface {
    fn resize(&mut self, size: PhysicalSize) {
        if size != self.size {
            self.size = size;
            self.buffer = None; // reallocate at the new size on next present
        }
    }
    fn size(&self) -> PhysicalSize {
        self.size
    }
    fn present(&mut self, pixmap: &Pixmap, _damage: &[crate::geometry::Rect]) {
        let size = pixmap.size();
        if size.width == 0 || size.height == 0 {
            return;
        }
        let mut conn = self.conn.lock().unwrap();
        // (Re)create the shm buffer if missing or the size changed.
        if self.buffer.as_ref().map(|b| b.size) != Some(size) {
            self.buffer = make_shm(&mut conn, self.shm, size, WL_SHM_FORMAT_XRGB8888).ok();
        }
        let Some(buf) = self.buffer.as_mut() else {
            return;
        };
        let stride = size.width as usize * 4;
        let bytes = stride * size.height as usize;
        let buffer = buf.buffer;
        rgba_to_xrgb(pixmap.as_bytes(), &mut buf.bytes()[..bytes]);

        let surface = self.surface;
        // attach(buffer, 0, 0); damage(0, 0, w, h); commit.
        let scale = conn.buffer_scale.max(1);
        let mut a = Vec::new();
        arg_u32(&mut a, scale);
        let _ = conn.send(surface, WL_SURFACE_SET_BUFFER_SCALE, &a);
        let mut a = Vec::new();
        arg_u32(&mut a, buffer);
        arg_u32(&mut a, 0);
        arg_u32(&mut a, 0);
        let _ = conn.send(surface, WL_SURFACE_ATTACH, &a);
        // Damage is in surface units, which the scale divides the buffer into.
        let mut a = Vec::new();
        arg_u32(&mut a, 0);
        arg_u32(&mut a, 0);
        arg_u32(&mut a, size.width / scale);
        arg_u32(&mut a, size.height / scale);
        let _ = conn.send(surface, WL_SURFACE_DAMAGE, &a);
        request_frame_callback(&mut conn, surface);
        let _ = conn.send(surface, WL_SURFACE_COMMIT, &[]);
        let _ = conn.stream.flush();
        dbg(format_args!("present {}x{}", size.width, size.height));
    }
}

/// `wl_surface.frame`: a `wl_callback` that fires when the compositor wants the
/// next frame.
const WL_SURFACE_FRAME: u16 = 3;

/// The outstanding frame callback's object id, or 0 for none.
static FRAME_CALLBACK: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// If an animation wants a frame, ask the compositor for a frame callback with
/// the commit that's about to go out, so the next frame is paced by its repaint
/// (and stops while the window is hidden). Call just before `commit`.
fn request_frame_callback(conn: &mut WlConn, surface: u32) {
    use std::sync::atomic::Ordering;
    if !crate::platform::frame::wanted() {
        return;
    }
    if FRAME_CALLBACK.load(Ordering::Acquire) == 0 {
        let callback = conn.new_id();
        let mut a = Vec::new();
        arg_u32(&mut a, callback);
        if conn.send(surface, WL_SURFACE_FRAME, &a).is_err() {
            return;
        }
        FRAME_CALLBACK.store(callback, Ordering::Release);
    }
    crate::platform::frame::claim();
}

/// Whether `(object, opcode)` is the outstanding frame callback firing; if so,
/// deliver the frame.
fn frame_callback_done(object: u32, opcode: u16) -> bool {
    use std::sync::atomic::Ordering;
    let ours = object != 0
        && opcode == WL_CALLBACK_DONE
        && FRAME_CALLBACK
            .compare_exchange(object, 0, Ordering::AcqRel, Ordering::Acquire)
            .is_ok();
    if ours {
        crate::platform::frame::tick();
    }
    ours
}

// ---- Run loop ---------------------------------------------------------------

/// Connect to the compositor, create a window, and drive `handler` over its
/// event stream until it returns [`ControlFlow::Exit`] or the toplevel closes.
pub fn run<H>(attrs: WindowAttributes, mut handler: H) -> Result<(), PlatformError>
where
    H: FnMut(Event, &dyn Window) -> ControlFlow,
{
    let mut conn = WlConn::connect()?;
    let size = ScaleFactor::IDENTITY.to_physical(attrs.logical_size);
    let size = PhysicalSize::new(size.width.max(1), size.height.max(1));

    // get_registry, then sync so the compositor flushes all globals before the
    // sync callback's `done` event.
    let registry = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, registry);
    conn.send(WL_DISPLAY, WL_DISPLAY_GET_REGISTRY, &a)
        .map_err(os)?;
    let sync_cb = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, sync_cb);
    conn.send(WL_DISPLAY, WL_DISPLAY_SYNC, &a).map_err(os)?;

    // Collect globals until the sync callback fires.
    let mut compositor_name = None;
    let mut shm_name = None;
    let mut wm_base_name = None;
    let mut seat_name = None;
    let mut seat_version = 1;
    let mut data_manager = None;
    let mut output_names = Vec::new();
    let mut cursor_shape_name = None;
    let mut icon_manager_name = None;
    let mut text_input_name = None;
    loop {
        let (object, opcode, args) = conn.recv().map_err(os)?;
        if object == registry && opcode == WL_REGISTRY_GLOBAL {
            let name = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            if let Some((iface, next)) = read_str(&args, 4) {
                let version = args
                    .get(next..next + 4)
                    .map_or(1, |v| u32::from_le_bytes([v[0], v[1], v[2], v[3]]));
                match iface.as_str() {
                    "wl_compositor" => compositor_name = Some(name),
                    "wl_shm" => shm_name = Some(name),
                    "xdg_wm_base" => wm_base_name = Some(name),
                    "wl_seat" => {
                        seat_name = Some(name);
                        seat_version = version.clamp(1, WL_SEAT_VERSION);
                    }
                    "wl_output" => output_names.push(name),
                    "wl_data_device_manager" => {
                        data_manager = Some((name, version.clamp(1, clipboard::MANAGER_VERSION)));
                    }
                    "wp_cursor_shape_manager_v1" => cursor_shape_name = Some(name),
                    "xdg_toplevel_icon_manager_v1" => icon_manager_name = Some(name),
                    text_input::MANAGER => text_input_name = Some(name),
                    _ => {}
                }
            }
        } else if object == sync_cb && opcode == WL_CALLBACK_DONE {
            break;
        } else if object == WL_DISPLAY && opcode == WL_DISPLAY_ERROR {
            return Err(PlatformError::Os("wl_display error during setup".into()));
        }
    }

    let bind = |conn: &mut WlConn, name: u32, iface: &str, version: u32| -> u32 {
        let id = conn.new_id();
        let mut a = Vec::new();
        arg_u32(&mut a, name);
        arg_str(&mut a, iface);
        arg_u32(&mut a, version);
        arg_u32(&mut a, id);
        let _ = conn.send(registry, WL_REGISTRY_BIND, &a);
        id
    };
    let compositor = bind(
        &mut conn,
        compositor_name.ok_or_else(|| PlatformError::Os("no wl_compositor".into()))?,
        "wl_compositor",
        4,
    );
    let shm = bind(
        &mut conn,
        shm_name.ok_or_else(|| PlatformError::Os("no wl_shm".into()))?,
        "wl_shm",
        1,
    );
    let wm_base = bind(
        &mut conn,
        wm_base_name.ok_or_else(|| PlatformError::Os("no xdg_wm_base".into()))?,
        "xdg_wm_base",
        1,
    );

    // Outputs report their scale; the surface's `enter` says which one we're on.
    let mut outputs: Vec<(u32, u32)> = output_names
        .into_iter()
        .map(|name| (bind(&mut conn, name, "wl_output", 2), 1))
        .collect();
    let mut current_output: Option<u32> = None;

    // Optional seat. The keyboard is created lazily from its `capabilities`
    // event — calling get_keyboard on a seat that never had the keyboard
    // capability (e.g. a headless compositor with no devices) is a protocol
    // error, so we wait until one is advertised.
    let seat = seat_name.map(|name| bind(&mut conn, name, "wl_seat", seat_version));
    // Optional protocols: cursor shapes, and the toplevel icon.
    let cursor_shape_manager =
        cursor_shape_name.map(|name| bind(&mut conn, name, "wp_cursor_shape_manager_v1", 1));
    let icon_manager =
        icon_manager_name.map(|name| bind(&mut conn, name, "xdg_toplevel_icon_manager_v1", 1));
    dbg(format_args!("seat={seat:?} v{seat_version}"));
    // The clipboard goes through the seat's data device.
    if let (Some(seat), Some((name, version))) = (seat, data_manager) {
        let manager = bind(&mut conn, name, "wl_data_device_manager", version);
        clipboard::setup(&mut conn, manager, version, seat);
    }
    // Input methods go through the seat's text input.
    if let (Some(seat), Some(name)) = (seat, text_input_name) {
        let manager = bind(&mut conn, name, text_input::MANAGER, 1);
        text_input::setup(&mut conn, manager, seat);
    }

    // Surface → xdg_surface → xdg_toplevel.
    let surface = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, surface);
    conn.send(compositor, WL_COMPOSITOR_CREATE_SURFACE, &a)
        .map_err(os)?;

    let xdg_surface = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, xdg_surface);
    arg_u32(&mut a, surface);
    conn.send(wm_base, XDG_WM_BASE_GET_XDG_SURFACE, &a)
        .map_err(os)?;

    let toplevel = conn.new_id();
    let mut a = Vec::new();
    arg_u32(&mut a, toplevel);
    conn.send(xdg_surface, XDG_SURFACE_GET_TOPLEVEL, &a)
        .map_err(os)?;

    let mut a = Vec::new();
    arg_str(&mut a, &attrs.title);
    conn.send(toplevel, XDG_TOPLEVEL_SET_TITLE, &a)
        .map_err(os)?;

    // Size limits and initial state, applied by the initial commit below.
    let (min, max) = if attrs.resizable {
        (attrs.min_size, attrs.max_size)
    } else {
        (Some(attrs.logical_size), Some(attrs.logical_size))
    };
    if min.is_some() {
        conn.send(toplevel, XDG_TOPLEVEL_SET_MIN_SIZE, &size_args(min))
            .map_err(os)?;
    }
    if max.is_some() {
        conn.send(toplevel, XDG_TOPLEVEL_SET_MAX_SIZE, &size_args(max))
            .map_err(os)?;
    }
    if attrs.maximized {
        conn.send(toplevel, XDG_TOPLEVEL_SET_MAXIMIZED, &[])
            .map_err(os)?;
    }
    if attrs.fullscreen {
        conn.send(toplevel, XDG_TOPLEVEL_SET_FULLSCREEN, &0u32.to_le_bytes())
            .map_err(os)?;
    }
    let icon = match (icon_manager, attrs.icon.as_ref()) {
        (Some(manager), Some(icon)) => {
            set_toplevel_icon(&mut conn, shm, manager, toplevel, Some(icon))
        }
        _ => None,
    };

    // Initial commit: the compositor responds with an xdg_surface.configure.
    conn.send(surface, WL_SURFACE_COMMIT, &[]).map_err(os)?;
    conn.stream.flush().map_err(os)?;
    dbg(format_args!(
        "window: surface={surface} xdg={xdg_surface} toplevel={toplevel} size={}x{}",
        size.width, size.height
    ));

    let shared: Shared = Arc::new(Mutex::new(conn));
    let mut win = WaylandWindow {
        conn: shared.clone(),
        surface,
        shm,
        size,
        toplevel,
        icon_manager,
        icon: RefCell::new(icon),
        drop_accepted: std::cell::Cell::new(false),
    };

    // Event loop. The keyboard/pointer are created when the seat advertises
    // them; `pointer_pos` tracks the latest cursor position for button events,
    // and `keymap` decodes keycodes to characters once the compositor sends it.
    let mut keyboard: Option<u32> = None;
    // Keyboards we dropped: a keymap still in flight for one carries an fd that
    // must be taken off the queue (and closed), or the next keymap would get it.
    let mut old_keyboards: Vec<u32> = Vec::new();
    let mut pointer: Option<u32> = None;
    let mut pointer_pos = Point::new(0.0, 0.0);
    let mut keymap: Option<XkbKeymap> = None;
    // The keyboard's modifier state (depressed | latched | locked xkb bits).
    let mut mods_mask = 0u32;
    // Dead keys and compose sequences: the client's job on Wayland.
    let mut compose = crate::platform::compose::ComposeState::default();
    // Wheel notches from `axis_discrete`, per axis, for the `axis` that follows.
    let mut discrete = [0i32; 2];
    // Toplevel sizes are in surface units; the buffer is that times the scale.
    let mut logical = size;
    let mut pending_size: Option<PhysicalSize> = None;
    // Between messages, wait on the connection and on wakeups (timers, other
    // threads) together.
    crate::platform::wake::install_unix();
    let fd = shared.lock().unwrap().stream.as_raw_fd();
    loop {
        // Messages a paste read while it waited come first.
        let queued = shared.lock().unwrap().queue.pop_front();
        if queued.is_none() && !crate::platform::wake::wait_readable(fd) {
            if crate::platform::wake::take(std::time::Instant::now())
                && handler(Event::Wake, &win) == ControlFlow::Exit
            {
                break;
            }
            continue;
        }
        let (object, opcode, args) = {
            let mut conn = shared.lock().unwrap();
            let message = match queued {
                Some(message) => message,
                None => conn.recv().map_err(os)?,
            };
            if clipboard::handle(&mut conn, message.0, message.1, &message.2) {
                let dnd = std::mem::take(&mut conn.clip.dnd);
                drop(conn);
                if deliver_dnd(&shared, &win, dnd, &mut handler) == ControlFlow::Exit {
                    break;
                }
                continue;
            }
            message
        };
        // Input-method updates for the focused text field.
        let ime = text_input::handle(&mut shared.lock().unwrap(), object, opcode, &args, surface);
        if let Some(events) = ime {
            if events
                .into_iter()
                .any(|ime| handler(Event::Ime(ime), &win) == ControlFlow::Exit)
            {
                break;
            }
            continue;
        }
        // The compositor is ready for the next animation frame: it arrives as
        // a wake once this loop goes back to waiting.
        if frame_callback_done(object, opcode) {
            continue;
        }
        // Moving to another output, or an output's scale changing, means rendering
        // at a new resolution.
        let moved = object == surface && opcode == WL_SURFACE_ENTER;
        let rescaled = opcode == WL_OUTPUT_SCALE && outputs.iter().any(|(id, _)| *id == object);
        if moved || rescaled {
            let value = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            if moved {
                current_output = Some(value);
            } else if let Some(entry) = outputs.iter_mut().find(|(id, _)| *id == object) {
                entry.1 = value.max(1);
            }
            let scale = outputs
                .iter()
                .find(|(id, _)| Some(*id) == current_output)
                .map_or(1, |(_, scale)| *scale);
            let changed = {
                let mut conn = shared.lock().unwrap();
                let changed = conn.buffer_scale != scale;
                conn.buffer_scale = scale;
                changed
            };
            if changed {
                dbg(format_args!("buffer scale {scale}"));
                win.size = PhysicalSize::new(logical.width * scale, logical.height * scale);
                if handler(Event::Resized(win.size), &win) == ControlFlow::Exit
                    || handler(Event::RedrawRequested, &win) == ControlFlow::Exit
                {
                    break;
                }
            }
            continue;
        }
        if Some(object) == seat && opcode == WL_SEAT_CAPABILITIES {
            let caps = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            dbg(format_args!("seat capabilities: {caps}"));
            let mut conn = shared.lock().unwrap();
            if caps & WL_SEAT_CAP_KEYBOARD != 0 {
                if keyboard.is_none() {
                    let kbd = conn.new_id();
                    let mut a = Vec::new();
                    arg_u32(&mut a, kbd);
                    if conn.send(seat.unwrap(), WL_SEAT_GET_KEYBOARD, &a).is_ok() {
                        keyboard = Some(kbd);
                        dbg(format_args!("keyboard={kbd} (caps={caps})"));
                    }
                }
            } else if let Some(old) = keyboard.take() {
                old_keyboards.push(old);
                // The keyboard went away (e.g. a virtual keyboard was destroyed).
                // The compositor makes the wl_keyboard inert on capability loss,
                // so we simply drop our reference (and its keymap) and acquire a
                // fresh one if the capability returns — sending an explicit
                // release races the compositor's own teardown and can error.
                keymap = None;
                mods_mask = 0;
                dbg(format_args!("keyboard dropped (caps={caps})"));
            }
            if pointer.is_none() && caps & WL_SEAT_CAP_POINTER != 0 {
                let ptr = conn.new_id();
                let mut a = Vec::new();
                arg_u32(&mut a, ptr);
                if conn.send(seat.unwrap(), WL_SEAT_GET_POINTER, &a).is_ok() {
                    pointer = Some(ptr);
                    dbg(format_args!("pointer={ptr} (caps={caps})"));
                    if let Some(manager) = cursor_shape_manager {
                        let device = conn.new_id();
                        let mut a = Vec::new();
                        arg_u32(&mut a, device);
                        arg_u32(&mut a, ptr);
                        if conn.send(manager, CURSOR_SHAPE_GET_POINTER, &a).is_ok() {
                            conn.cursor_device = Some(device);
                        }
                    }
                }
            }
        } else if Some(object) == pointer
            && (opcode == WL_POINTER_ENTER || opcode == WL_POINTER_MOTION)
        {
            // enter: serial, surface, x, y. motion: time, x, y. Both end in two
            // wl_fixed coordinates.
            let n = args.len();
            if opcode == WL_POINTER_ENTER {
                // The compositor resets the cursor on enter; set ours again.
                let serial = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
                let mut conn = shared.lock().unwrap();
                conn.enter_serial = Some(serial);
                conn.apply_cursor();
            }
            let x = u32::from_le_bytes([args[n - 8], args[n - 7], args[n - 6], args[n - 5]]);
            let y = u32::from_le_bytes([args[n - 4], args[n - 3], args[n - 2], args[n - 1]]);
            pointer_pos = Point::new(fixed_to_f64(x), fixed_to_f64(y));
            if handler(
                Event::PointerMoved {
                    position: pointer_pos,
                },
                &win,
            ) == ControlFlow::Exit
            {
                break;
            }
        } else if Some(object) == pointer && opcode == WL_POINTER_BUTTON {
            // serial, time, button(evdev), state(0 released / 1 pressed).
            shared.lock().unwrap().clip.serial =
                u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            let button = u32::from_le_bytes([args[8], args[9], args[10], args[11]]);
            let pressed = u32::from_le_bytes([args[12], args[13], args[14], args[15]]) == 1;
            if let Some(button) = pointer_button(button) {
                let state = if pressed {
                    ButtonState::Pressed
                } else {
                    ButtonState::Released
                };
                crate::platform::set_pointer_modifiers(wl_modifiers(mods_mask, keymap.as_ref()));
                if handler(
                    Event::PointerButton {
                        button,
                        state,
                        position: pointer_pos,
                    },
                    &win,
                ) == ControlFlow::Exit
                {
                    break;
                }
            }
        } else if Some(object) == pointer && opcode == WL_POINTER_AXIS_DISCRETE {
            // axis(4), discrete(4: signed notches).
            let axis = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            let steps = i32::from_le_bytes([args[4], args[5], args[6], args[7]]);
            if let Some(slot) = discrete.get_mut(axis as usize) {
                *slot = steps;
            }
        } else if Some(object) == pointer && opcode == WL_POINTER_AXIS {
            // time(4), axis(4: 0 vertical, 1 horizontal), value(wl_fixed).
            let axis = u32::from_le_bytes([args[4], args[5], args[6], args[7]]);
            let value = u32::from_le_bytes([args[8], args[9], args[10], args[11]]);
            let steps = discrete.get_mut(axis as usize).map_or(0, std::mem::take);
            if let Some(delta) = axis_delta(axis, value, steps)
                && handler(Event::Scroll { delta }, &win) == ControlFlow::Exit
            {
                break;
            }
        } else if object == wm_base && opcode == XDG_WM_BASE_PING {
            let serial = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            let mut a = Vec::new();
            arg_u32(&mut a, serial);
            let mut conn = shared.lock().unwrap();
            let _ = conn.send(wm_base, XDG_WM_BASE_PONG, &a);
            let _ = conn.stream.flush();
        } else if object == xdg_surface && opcode == XDG_SURFACE_CONFIGURE {
            let serial = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            {
                let mut conn = shared.lock().unwrap();
                let mut a = Vec::new();
                arg_u32(&mut a, serial);
                let _ = conn.send(xdg_surface, XDG_SURFACE_ACK_CONFIGURE, &a);
            }
            // Apply the size from the toplevel.configure this one completes.
            if let Some(size) = pending_size.take().filter(|s| *s != logical) {
                logical = size;
                let scale = shared.lock().unwrap().buffer_scale;
                win.size = PhysicalSize::new(size.width * scale, size.height * scale);
                if handler(Event::Resized(win.size), &win) == ControlFlow::Exit {
                    break;
                }
            }
            // Paint the frame for this configure.
            if handler(Event::RedrawRequested, &win) == ControlFlow::Exit {
                break;
            }
        } else if object == toplevel && opcode == XDG_TOPLEVEL_CONFIGURE {
            // width, height, states[]: a 0 size means "client picks".
            let w = i32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            let h = i32::from_le_bytes([args[4], args[5], args[6], args[7]]);
            dbg(format_args!("toplevel configure {w}x{h}"));
            if w > 0 && h > 0 {
                pending_size = Some(PhysicalSize::new(w as u32, h as u32));
            }
        } else if object == toplevel && opcode == XDG_TOPLEVEL_CLOSE {
            handler(Event::CloseRequested, &win);
            break;
        } else if old_keyboards.contains(&object) {
            if opcode == WL_KEYBOARD_KEYMAP
                && let Some(fd) = shared.lock().unwrap().fds.pop_front()
            {
                unsafe { close(fd) };
            }
        } else if Some(object) == keyboard && opcode == WL_KEYBOARD_KEYMAP {
            // format(4), [fd via ancillary], size(4). Format 1 = XKB_V1 text.
            let format = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            let size = u32::from_le_bytes([args[4], args[5], args[6], args[7]]) as usize;
            let fd = shared.lock().unwrap().fds.pop_front();
            if let (1, Some(fd)) = (format, fd) {
                keymap = read_keymap(fd, size);
                dbg(format_args!(
                    "keymap parsed: {} keys",
                    keymap.as_ref().map(|m| m.keys.len()).unwrap_or(0)
                ));
            } else if let Some(fd) = fd {
                unsafe { close(fd) };
            }
        } else if Some(object) == keyboard && opcode == WL_KEYBOARD_KEY {
            // serial(4), time(4), key(4 evdev), state(4: 1 = pressed). A copy
            // cites the serial of the key that made it.
            shared.lock().unwrap().clip.serial =
                u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
            let key = u32::from_le_bytes([args[8], args[9], args[10], args[11]]);
            let pressed = u32::from_le_bytes([args[12], args[13], args[14], args[15]]) == 1;
            dbg(format_args!(
                "raw key {key} pressed={pressed} sym={:?}",
                keymap.as_ref().and_then(|m| m.sym(key + 8, mods_mask))
            ));
            // Prefer the compositor's keymap (xkb keycode = evdev + 8); fall back
            // to the layout-independent evdev table when none was parsed.
            let modifiers = wl_modifiers(mods_mask, keymap.as_ref());
            let sym = keymap.as_ref().and_then(|m| m.sym(key + 8, mods_mask));
            let shortcut = modifiers.ctrl || modifiers.meta;
            let composed = sym
                .filter(|_| pressed)
                .and_then(keysym_value)
                .and_then(|ks| crate::platform::compose::feed_event(&mut compose, ks, shortcut));
            let ev = match (composed, sym) {
                (Some(ime), _) => Some(Event::Ime(ime)),
                (None, Some(sym)) => keysym_name_to_event(sym, pressed, modifiers),
                (None, None) => evdev_to_event(key, pressed, modifiers),
            };
            if let Some(ev) = ev {
                dbg(format_args!("key {key} pressed={pressed} -> {ev:?}"));
                if handler(ev, &win) == ControlFlow::Exit {
                    break;
                }
            }
        } else if Some(object) == keyboard && opcode == WL_KEYBOARD_MODIFIERS {
            // serial, mods_depressed, mods_latched, mods_locked, group.
            let word =
                |i: usize| u32::from_le_bytes([args[i], args[i + 1], args[i + 2], args[i + 3]]);
            mods_mask = word(4) | word(8) | word(12);
            dbg(format_args!("modifiers {mods_mask:#x}"));
        } else if Some(object) == keyboard {
            // enter (1) / leave (2) / repeat_info (5).
            dbg(format_args!("keyboard event {opcode}"));
        } else if object == WL_DISPLAY && opcode == WL_DISPLAY_ERROR {
            return Err(PlatformError::Os("wl_display error".into()));
        }
    }
    Ok(())
}

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

    /// Decode a message header `[object][size<<16|opcode]` as the wire encodes it.
    fn decode_header(msg: &[u8]) -> (u32, u32, u16) {
        let object = u32::from_le_bytes([msg[0], msg[1], msg[2], msg[3]]);
        let word = u32::from_le_bytes([msg[4], msg[5], msg[6], msg[7]]);
        (object, word >> 16, (word & 0xffff) as u16)
    }

    #[test]
    fn message_header_packs_size_and_opcode() {
        // get_registry(new_id=2): one u32 arg → size 12, opcode 1 on object 1.
        let mut msg = Vec::new();
        msg.extend_from_slice(&WL_DISPLAY.to_le_bytes());
        let mut args = Vec::new();
        arg_u32(&mut args, 2);
        let size = (8 + args.len()) as u32;
        msg.extend_from_slice(&((size << 16) | WL_DISPLAY_GET_REGISTRY as u32).to_le_bytes());
        msg.extend_from_slice(&args);
        let (object, sz, opcode) = decode_header(&msg);
        assert_eq!((object, sz, opcode), (1, 12, 1));
        assert_eq!(msg.len(), 12);
    }

    #[test]
    fn string_arg_pads_to_four_bytes() {
        let mut buf = Vec::new();
        arg_str(&mut buf, "wl_shm"); // len 6 + NUL = 7 → padded to 8 bytes of text
        // 4 (length) + 8 (padded "wl_shm\0") = 12 bytes, length field = 7.
        assert_eq!(buf.len(), 12);
        assert_eq!(u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]), 7);
        assert!(buf.len().is_multiple_of(4));
        // Round-trips through read_str, leaving the offset at the padded end.
        let (s, next) = read_str(&buf, 0).unwrap();
        assert_eq!(s, "wl_shm");
        assert_eq!(next, 12);
    }

    #[test]
    fn read_str_parses_a_registry_global() {
        // name(uint) + interface(string) + version(uint), as wl_registry.global.
        let mut args = Vec::new();
        arg_u32(&mut args, 42);
        arg_str(&mut args, "xdg_wm_base");
        arg_u32(&mut args, 3);
        let name = u32::from_le_bytes([args[0], args[1], args[2], args[3]]);
        let (iface, next) = read_str(&args, 4).unwrap();
        let version =
            u32::from_le_bytes([args[next], args[next + 1], args[next + 2], args[next + 3]]);
        assert_eq!((name, iface.as_str(), version), (42, "xdg_wm_base", 3));
    }

    #[test]
    fn icon_is_square_premultiplied_argb() {
        let mut icon = Pixmap::new(PhysicalSize::new(2, 1));
        icon.as_bytes_mut()
            .copy_from_slice(&[255, 0, 0, 255, 0, 255, 0, 128]);
        let (side, bytes) = icon_argb(&icon);
        assert_eq!(side, 2);
        // The 2x1 icon fills row 0 of the 2x2 square (premultiplied BGRA);
        // row 1 is transparent padding.
        assert_eq!(&bytes[..8], &[0, 0, 255, 255, 0, 128, 0, 128]);
        assert_eq!(&bytes[8..], &[0; 8]);
    }

    #[test]
    fn cursor_shapes_and_size_args() {
        assert_eq!(cursor_shape(CursorIcon::Text), 9);
        assert_eq!(cursor_shape(CursorIcon::NwseResize), 29);
        assert_eq!(size_args(None), vec![0; 8]);
        assert_eq!(
            size_args(Some(Size::new(320.0, 240.0))),
            [320u32.to_le_bytes(), 240u32.to_le_bytes()].concat()
        );
    }

    #[test]
    fn xrgb_swizzle_drops_alpha() {
        let mut dst = [0u8; 8];
        rgba_to_xrgb(&[10, 20, 30, 255, 1, 2, 3, 128], &mut dst);
        assert_eq!(dst, [30, 20, 10, 0, 3, 2, 1, 0]);
    }

    #[test]
    fn evdev_maps_editing_keys_and_us_text() {
        let none = Modifiers::default();
        let evdev_to_event = |code, pressed| evdev_to_event(code, pressed, none);
        // Layout-independent editing/navigation keys.
        assert!(matches!(
            evdev_to_event(15, true),
            Some(Event::Key {
                code: KeyCode::Tab,
                state: ButtonState::Pressed,
                ..
            })
        ));
        assert!(matches!(
            evdev_to_event(105, true),
            Some(Event::Key {
                code: KeyCode::ArrowLeft,
                ..
            })
        ));
        assert!(matches!(
            evdev_to_event(28, false),
            Some(Event::Key {
                code: KeyCode::Enter,
                state: ButtonState::Released,
                ..
            })
        ));
        // US-QWERTY text on press; nothing on release.
        assert_eq!(evdev_to_event(30, true), Some(Event::Text("a".into()))); // KEY_A
        assert_eq!(evdev_to_event(57, true), Some(Event::Text(" ".into()))); // KEY_SPACE
        assert_eq!(evdev_to_event(30, false), None);
        assert_eq!(evdev_to_event(0, true), None);
    }

    #[test]
    fn evdev_maps_new_keys_and_modifiers() {
        let key = |code| match evdev_to_event(code, true, Modifiers::default()) {
            Some(Event::Key { code, .. }) => Some(code),
            _ => None,
        };
        assert_eq!(key(104), Some(KeyCode::PageUp));
        assert_eq!(key(109), Some(KeyCode::PageDown));
        assert_eq!(key(110), Some(KeyCode::Insert));
        assert_eq!(key(59), Some(KeyCode::F1));
        assert_eq!(key(68), Some(KeyCode::F10));
        assert_eq!(key(87), Some(KeyCode::F11));
        assert_eq!(key(88), Some(KeyCode::F12));
        let shift = Modifiers {
            shift: true,
            ..Modifiers::default()
        };
        assert_eq!(
            evdev_to_event(30, true, shift),
            Some(Event::Text("A".into()))
        );
        let ctrl = Modifiers {
            ctrl: true,
            ..Modifiers::default()
        };
        assert_eq!(
            evdev_to_event(46, true, ctrl), // KEY_C
            Some(Event::Key {
                code: KeyCode::Char('c'),
                state: ButtonState::Pressed,
                modifiers: ctrl,
            })
        );
        // Shift-selection needs the modifiers on named keys too.
        assert_eq!(
            evdev_to_event(105, true, shift),
            Some(Event::Key {
                code: KeyCode::ArrowLeft,
                state: ButtonState::Pressed,
                modifiers: shift,
            })
        );
    }

    #[test]
    fn keysyms_given_by_value_become_names() {
        assert_eq!(keysym_canonical_name("0xff09"), "Tab");
        assert_eq!(keysym_canonical_name("0x61"), "a");
        assert_eq!(keysym_canonical_name("0x20"), "space");
        assert_eq!(keysym_canonical_name("0xffbf"), "F2");
        assert_eq!(keysym_canonical_name("0x100263a"), "U263A");
        assert_eq!(keysym_canonical_name("Return"), "Return");
        let ev = keysym_name_to_event(
            &keysym_canonical_name("0x63"),
            true,
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
        );
        assert!(ev.is_some(), "Ctrl+c from a wtype keymap");
    }

    #[test]
    fn parse_xkb_maps_keycodes_to_keysyms() {
        let keymap = "\
xkb_keymap {
xkb_keycodes \"x\" {
    <AC01> = 38;
    <SPCE> = 65;
    <TAB>  = 23;
};
xkb_symbols \"x\" {
    key <AC01> { [ a, A ] };
    key <SPCE> { [ space ] };
    key <TAB>  { [ Tab ] };
};
};";
        let map = parse_xkb(keymap);
        assert_eq!(map.sym(38, 0), Some("a"));
        assert_eq!(map.sym(38, XKB_SHIFT), Some("A"));
        assert_eq!(map.sym(65, 0), Some("space"));
        assert_eq!(map.sym(23, 0), Some("Tab"));
        // No modifier_map: Alt and the logo key default to Mod1 and Mod4.
        assert_eq!((map.alt_mask, map.meta_mask), (XKB_MOD1, XKB_MOD4));
        let none = Modifiers::default();
        let keysym_name_to_event = |name, pressed| keysym_name_to_event(name, pressed, none);
        // keysym names decode to events.
        assert_eq!(
            keysym_name_to_event("a", true),
            Some(Event::Text("a".into()))
        );
        assert_eq!(
            keysym_name_to_event("space", true),
            Some(Event::Text(" ".into()))
        );
        assert!(matches!(
            keysym_name_to_event("Tab", true),
            Some(Event::Key {
                code: KeyCode::Tab,
                ..
            })
        ));
        assert_eq!(keysym_name_to_event("a", false), None); // text on press only
    }

    #[test]
    fn parse_xkb_reads_levels_blocks_and_modifier_maps() {
        // The shape xkbcommon serializes: multi-line blocks for keys with an
        // explicit type, and modifier_map lines naming keys.
        let keymap = "\
xkb_keymap {
xkb_keycodes \"x\" {
    <TAB>  = 23;
    <AC01> = 38;
    <AE01> = 10;
    <LALT> = 64;
    <LWIN> = 133;
    <PGUP> = 112;
    <FK05> = 71;
};
xkb_symbols \"x\" {
    key <TAB>  {
        type= \"TWO_LEVEL\",
        symbols[Group1]= [             Tab,    ISO_Left_Tab ]
    };
    key  <AC01> {	[               a,               A ] };
    key <AE01> {	[               1,          exclam ] };
    key <LALT> {	[           Alt_L,          Meta_L ] };
    key <LWIN> {
        actions[Group1]= [ SetMods(modifiers=Mod4) ],
        symbols[Group1]= [ Super_L ]
    };
    key <PGUP> {	[           Prior ] };
    key <FK05> {	[              F5,              F5 ] };
    modifier_map Mod1 { <LALT> };
    modifier_map Mod4 { <LWIN> };
};
};";
        let map = parse_xkb(keymap);
        // Shift picks level 2 for printable keys, but Tab stays Tab.
        assert_eq!(map.sym(23, XKB_SHIFT), Some("Tab"));
        assert_eq!(map.sym(10, XKB_SHIFT), Some("exclam"));
        assert_eq!(map.sym(10, XKB_LOCK), Some("1")); // Caps Lock: letters only
        assert_eq!(map.sym(38, XKB_LOCK), Some("A"));
        assert_eq!(map.sym(38, XKB_LOCK | XKB_SHIFT), Some("a"));
        assert_eq!(map.sym(133, 0), Some("Super_L")); // not the actions list
        assert_eq!(map.sym(112, 0), Some("Prior"));
        assert_eq!((map.alt_mask, map.meta_mask), (XKB_MOD1, XKB_MOD4));

        // A keymap that puts the logo key on Mod3.
        let moved = keymap.replace("modifier_map Mod4", "modifier_map Mod3");
        let moved = parse_xkb(&moved);
        assert_eq!(moved.meta_mask, 1 << 5);
        assert!(wl_modifiers(1 << 5, Some(&moved)).meta);
        assert!(!wl_modifiers(XKB_MOD4, Some(&moved)).meta);

        // wl_keyboard.modifiers bits → Modifiers.
        assert_eq!(
            wl_modifiers(XKB_SHIFT | XKB_CONTROL | XKB_MOD1 | XKB_MOD4, Some(&map)),
            Modifiers {
                shift: true,
                ctrl: true,
                alt: true,
                meta: true,
            }
        );
        assert_eq!(
            wl_modifiers(XKB_LOCK | (1 << 4), None),
            Modifiers::default()
        );

        // Named keys, and Ctrl+printable as a shortcut.
        let ctrl = Modifiers {
            ctrl: true,
            ..Modifiers::default()
        };
        assert!(matches!(
            keysym_name_to_event("Prior", true, ctrl),
            Some(Event::Key {
                code: KeyCode::PageUp,
                modifiers,
                ..
            }) if modifiers == ctrl
        ));
        assert!(matches!(
            keysym_name_to_event("F5", true, Modifiers::default()),
            Some(Event::Key {
                code: KeyCode::F5,
                ..
            })
        ));
        assert_eq!(
            keysym_name_to_event("v", true, ctrl),
            Some(Event::Key {
                code: KeyCode::Char('v'),
                state: ButtonState::Pressed,
                modifiers: ctrl,
            })
        );
        assert_eq!(
            keysym_name_to_event("exclam", true, Modifiers::default()),
            Some(Event::Text("!".into()))
        );
        assert_eq!(
            keysym_name_to_event("U20AC", true, Modifiers::default()),
            Some(Event::Text("\u{20ac}".into()))
        );
        // Named Latin-1 and other legacy keysyms type their character too.
        assert_eq!(
            keysym_name_to_event("eacute", true, Modifiers::default()),
            Some(Event::Text("é".into()))
        );
        assert_eq!(
            keysym_name_to_event("Cyrillic_a", true, Modifiers::default()),
            Some(Event::Text("а".into()))
        );
        // Dead keys type nothing by themselves: compose handles them.
        assert_eq!(
            keysym_name_to_event("dead_acute", true, Modifiers::default()),
            None
        );
        // The values the compose table matches on.
        assert_eq!(keysym_value("dead_acute"), Some(0xfe51));
        assert_eq!(keysym_value("é"), Some(0xe9));
        assert_eq!(keysym_value("€"), Some(0x0100_20ac));
        assert_eq!(keysym_value("Multi_key"), Some(0xff20));
    }

    #[test]
    fn pointer_axis_deltas() {
        // A touchpad: no discrete steps, the value is in pixels (+ = down).
        assert_eq!(
            axis_delta(0, (7 * 256) as u32, 0),
            Some(ScrollDelta { dx: 0.0, dy: 7.0 })
        );
        // A wheel notch up: one line, whatever distance the compositor sent.
        assert_eq!(
            axis_delta(0, (-15i32 * 256) as u32, -1),
            Some(ScrollDelta { dx: 0.0, dy: -40.0 })
        );
        // Horizontal.
        assert_eq!(
            axis_delta(1, (15 * 256) as u32, 1),
            Some(ScrollDelta { dx: 40.0, dy: 0.0 })
        );
        assert_eq!(axis_delta(2, 0, 0), None);
    }

    #[test]
    fn fixed_point_and_pointer_buttons() {
        use crate::platform::event::PointerButton;
        // wl_fixed is signed 24.8: 256 → 1.0, 128 → 0.5, negatives wrap.
        assert_eq!(fixed_to_f64(256), 1.0);
        assert_eq!(fixed_to_f64(128), 0.5);
        assert_eq!(fixed_to_f64((-256i32) as u32), -1.0);
        assert_eq!(pointer_button(0x110), Some(PointerButton::Left));
        assert_eq!(pointer_button(0x111), Some(PointerButton::Right));
        assert_eq!(pointer_button(0x999), None);
    }
}