stipple 0.0.2

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
//! A native X11 backend implemented directly against the wire protocol.
//!
//! No `xcb`/`x11` crate, no `libX11` FFI — just a `UnixStream` and the X11
//! byte protocol (the workspace policy in `ROADMAP.md` §1). It connects to
//! `$DISPLAY`, creates a top-level window, and presents the software [`Pixmap`].
//!
//! Scope: window creation, resize, close, pointer (move + buttons + wheel),
//! and keyboard — `GetKeyboardMapping` resolves keycodes to keysyms, which
//! become [`Event::Text`] (Latin-1 + Unicode) or editing [`Event::Key`]s.
//!
//! Presentation has two paths: when the server advertises the **MIT-SHM**
//! extension, frames are copied into a System V shared-memory segment the
//! server maps directly and blitted with `ShmPutImage` — limited to the
//! [`Surface::present`] damage rectangles, so a small change uploads no pixels
//! over the socket at all. Otherwise it falls back to plain `PutImage`. The shm
//! segment is the one place this otherwise-safe backend needs FFI (the SysV
//! `shm*` syscalls), hence the module-level `allow(unsafe_code)`.
//!
//! **Verification:** the pure codec (setup-reply / `$DISPLAY` / `.Xauthority`
//! parsing, RGBA→X11 conversion) is unit-tested below; the live socket path —
//! handshake, window mapping, present (both shm and `PutImage`), pointer +
//! keyboard input — is exercised by the `Visual` workflow's Xvfb jobs
//! (screenshot + `xdotool` click/type); Xvfb supports MIT-SHM, so CI covers the
//! shm path.

#![allow(unsafe_code)]

use std::cell::RefCell;
use std::io::{self, Read, Write};
use std::os::fd::RawFd;
use std::os::unix::net::UnixStream;
use std::rc::Rc;
use std::sync::{Arc, Mutex};

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

// ---- X11 protocol constants -------------------------------------------------

const OP_CREATE_WINDOW: u8 = 1;
const OP_DESTROY_WINDOW: u8 = 4;
const OP_MAP_WINDOW: u8 = 8;
const OP_INTERN_ATOM: u8 = 16;
const OP_CHANGE_PROPERTY: u8 = 18;
const OP_SET_SELECTION_OWNER: u8 = 22;
const OP_SEND_EVENT: u8 = 25;
const OP_GET_INPUT_FOCUS: u8 = 43;
const OP_QUERY_EXTENSION: u8 = 98;
const OP_SET_INPUT_FOCUS: u8 = 42;
const OP_CREATE_GC: u8 = 55;
const OP_PUT_IMAGE: u8 = 72;
const OP_GET_KEYBOARD_MAPPING: u8 = 101;

// MIT-SHM minor opcodes (within the extension's major opcode).
const SHM_ATTACH: u8 = 1;
const SHM_PUT_IMAGE: u8 = 3;

// System V IPC flags for the shared-memory segment.
const IPC_PRIVATE: i32 = 0;
const IPC_CREAT: i32 = 0o1000;
const IPC_RMID: i32 = 0;
const SHM_PERM: i32 = 0o600;

// Event masks.
const EV_EXPOSURE: u32 = 0x0000_8000;
const EV_KEY_PRESS: u32 = 0x0000_0001;
const EV_KEY_RELEASE: u32 = 0x0000_0002;
const EV_BUTTON_PRESS: u32 = 0x0000_0004;
const EV_BUTTON_RELEASE: u32 = 0x0000_0008;
const EV_POINTER_MOTION: u32 = 0x0000_0040;
const EV_STRUCTURE_NOTIFY: u32 = 0x0002_0000;

// Value-mask bits for CreateWindow.
const CW_BACK_PIXEL: u32 = 0x0000_0002;
const CW_EVENT_MASK: u32 = 0x0000_0800;

// Event codes (low 7 bits of the first byte).
const X_EXPOSE: u8 = 12;
const X_BUTTON_PRESS: u8 = 4;
const X_BUTTON_RELEASE: u8 = 5;
const X_MOTION_NOTIFY: u8 = 6;
const X_KEY_PRESS: u8 = 2;
const X_KEY_RELEASE: u8 = 3;
const X_CONFIGURE_NOTIFY: u8 = 22;
const X_SELECTION_CLEAR: u8 = 29;
const X_SELECTION_REQUEST: u8 = 30;
const X_CLIENT_MESSAGE: u8 = 33;

// Predefined atoms (X11 protocol appendix): STRING type and the ATOM type.
const ATOM_STRING: u32 = 31;
const ATOM_ATOM: u32 = 4;

/// Whether an X11 display is reachable (cheap check of `$DISPLAY`).
pub fn available() -> bool {
    std::env::var_os("DISPLAY").is_some()
}

/// Emit a diagnostic line to stderr when `STIPPLE_X11_DEBUG` is set. Used to
/// trace the live socket path (which CI exercises) without spamming normal use.
fn dbg(args: std::fmt::Arguments<'_>) {
    if std::env::var_os("STIPPLE_X11_DEBUG").is_some() {
        eprintln!("stipple x11: {args}");
    }
}

/// Parsed `$DISPLAY` (the local/unix-socket case).
#[derive(Debug, PartialEq, Eq)]
struct DisplayAddr {
    /// Display number (the `0` in `:0`).
    number: u32,
    /// Screen number (rarely non-zero); kept for completeness.
    screen: u32,
}

fn parse_display(display: &str) -> Option<DisplayAddr> {
    // Forms: ":0", ":0.1", "hostname:0". We support the local unix path, so we
    // only need the part after the last ':'.
    let after = display.rsplit(':').next()?;
    let mut parts = after.splitn(2, '.');
    let number: u32 = parts.next()?.parse().ok()?;
    let screen: u32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
    Some(DisplayAddr { number, screen })
}

/// The fields we need from the X11 connection-setup reply.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Setup {
    resource_id_base: u32,
    resource_id_mask: u32,
    root: u32,
    root_visual: u32,
    root_depth: u8,
    /// Server's max request length, in 4-byte units.
    max_request_len: u32,
    min_keycode: u8,
    max_keycode: u8,
}

/// Parse the additional-data portion of a successful setup reply (everything
/// after the first 8-byte header).
fn parse_setup(data: &[u8]) -> Option<Setup> {
    // Offsets within the additional data (see X11 protocol §Connection Setup).
    let resource_id_base = rd_u32(data, 4)?;
    let resource_id_mask = rd_u32(data, 8)?;
    let max_request_len = rd_u16(data, 18)? as u32;
    let vendor_len = rd_u16(data, 16)? as usize;
    let num_formats = *data.get(21)? as usize;

    // Skip the 32-byte fixed block, then vendor (padded to 4), then the
    // pixmap-formats list (8 bytes each), to reach the first SCREEN.
    let vendor_pad = (vendor_len + 3) & !3;
    let screens_off = 32 + vendor_pad + num_formats * 8;

    let min_keycode = *data.get(26)?;
    let max_keycode = *data.get(27)?;

    let root = rd_u32(data, screens_off)?;
    let root_visual = rd_u32(data, screens_off + 32)?;
    let root_depth = *data.get(screens_off + 38)?;

    Some(Setup {
        resource_id_base,
        resource_id_mask,
        root,
        root_visual,
        root_depth,
        max_request_len,
        min_keycode,
        max_keycode,
    })
}

fn rd_u16(b: &[u8], off: usize) -> Option<u16> {
    Some(u16::from_le_bytes([*b.get(off)?, *b.get(off + 1)?]))
}
fn rd_u32(b: &[u8], off: usize) -> Option<u32> {
    Some(u32::from_le_bytes([
        *b.get(off)?,
        *b.get(off + 1)?,
        *b.get(off + 2)?,
        *b.get(off + 3)?,
    ]))
}

/// Convert a straight-RGBA8 pixmap row into X11 ZPixmap bytes for a 24-depth
/// little-endian (LSBFirst) server: each pixel becomes `[B, G, R, 0]`.
fn rgba_to_bgrx(rgba: &[u8], out: &mut Vec<u8>) {
    out.clear();
    out.reserve(rgba.len());
    for px in rgba.as_chunks::<4>().0 {
        out.extend_from_slice(&[px[2], px[1], px[0], 0]);
    }
}

/// Swizzle a straight-RGBA8 row in place into a ZPixmap (`[B, G, R, 0]`) row of
/// equal pixel count. Used to fill the shared-memory image without allocating.
fn swizzle_row(src: &[u8], dst: &mut [u8]) {
    for (s, d) in src
        .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;
    }
}

// ---- MIT-SHM shared-memory presentation -------------------------------------

use core::ffi::c_void;

// System V shared-memory syscalls (libc, linked by default on Linux). Declared
// directly to keep the crate dependency-free; this is the only FFI in the X11
// backend.
unsafe extern "C" {
    fn shmget(key: i32, size: usize, shmflg: i32) -> i32;
    fn shmat(shmid: i32, shmaddr: *const c_void, shmflg: i32) -> *mut c_void;
    fn shmdt(shmaddr: *const c_void) -> i32;
    fn shmctl(shmid: i32, cmd: i32, buf: *mut c_void) -> i32;
}

/// A System V shared-memory segment attached to both this process and the X
/// server, used as the backing image for `ShmPutImage`.
#[derive(Debug)]
struct ShmState {
    /// MIT-SHM extension major opcode.
    major: u8,
    /// X resource id naming the attached segment (`ShmSeg`).
    seg: u32,
    /// Mapped address in this process.
    ptr: *mut u8,
    /// Bytes available at `ptr`.
    capacity: usize,
}

impl Drop for ShmState {
    fn drop(&mut self) {
        // Detach our mapping; the kernel frees the segment once the server
        // (which detaches on connection close) has also let go.
        unsafe {
            shmdt(self.ptr as *const c_void);
        }
    }
}

impl ShmState {
    /// The mapped segment as a mutable byte slice.
    fn buffer(&mut self) -> &mut [u8] {
        // Safe: we own this mapping for `capacity` bytes; access is single-
        // threaded (present runs on the event-loop thread).
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.capacity) }
    }

    /// Copy the damaged regions of `pixmap` into the segment and blit them with
    /// `ShmPutImage`. Returns `false` if the frame doesn't fit (caller should
    /// fall back to `PutImage`); `true` on a successful (queued) present.
    fn present(
        &mut self,
        conn: &mut Conn,
        window: u32,
        gc: u32,
        pixmap: &Pixmap,
        damage: &[crate::geometry::Rect],
    ) -> bool {
        let size = pixmap.size();
        let (w, h) = (size.width as usize, size.height as usize);
        let stride = w * 4;
        if stride * h > self.capacity {
            return false; // grew past our segment; let PutImage handle it
        }
        let (major, seg) = (self.major, self.seg);
        let src = pixmap.as_bytes();
        let dst = self.buffer();

        // Build the integer regions to upload: explicit damage, or the whole
        // frame when none is given (first frame / expose / resize).
        let mut regions: Vec<(usize, usize, usize, usize)> = Vec::new();
        if damage.is_empty() {
            regions.push((0, 0, w, h));
        } else {
            for r in damage {
                let x0 = (r.min_x().floor().max(0.0) as usize).min(w);
                let y0 = (r.min_y().floor().max(0.0) as usize).min(h);
                let x1 = (r.max_x().ceil().max(0.0) as usize).min(w);
                let y1 = (r.max_y().ceil().max(0.0) as usize).min(h);
                if x1 > x0 && y1 > y0 {
                    regions.push((x0, y0, x1 - x0, y1 - y0));
                }
            }
        }

        for &(x, y, rw, rh) in &regions {
            // Copy each row's sub-span into the shared image (matching strides).
            for row in y..y + rh {
                let off = row * stride + x * 4;
                let len = rw * 4;
                swizzle_row(&src[off..off + len], &mut dst[off..off + len]);
            }
            if conn
                .send(&finish(shm_put_image(
                    major, window, gc, seg, w, h, x, y, rw, rh,
                )))
                .is_err()
            {
                return false;
            }
        }
        true
    }
}

/// Encode a `ShmPutImage` request blitting the sub-rectangle `(x, y, rw, rh)` of
/// a `total_w × total_h` ZPixmap image (depth 24) from the attached segment to
/// the drawable at the same position.
#[allow(clippy::too_many_arguments)]
fn shm_put_image(
    major: u8,
    drawable: u32,
    gc: u32,
    seg: u32,
    total_w: usize,
    total_h: usize,
    x: usize,
    y: usize,
    rw: usize,
    rh: usize,
) -> Vec<u8> {
    let mut req = vec![major, SHM_PUT_IMAGE, 0, 0];
    req.extend_from_slice(&drawable.to_le_bytes());
    req.extend_from_slice(&gc.to_le_bytes());
    req.extend_from_slice(&(total_w as u16).to_le_bytes());
    req.extend_from_slice(&(total_h as u16).to_le_bytes());
    req.extend_from_slice(&(x as u16).to_le_bytes()); // src-x
    req.extend_from_slice(&(y as u16).to_le_bytes()); // src-y
    req.extend_from_slice(&(rw as u16).to_le_bytes()); // src-width
    req.extend_from_slice(&(rh as u16).to_le_bytes()); // src-height
    req.extend_from_slice(&(x as i16).to_le_bytes()); // dst-x
    req.extend_from_slice(&(y as i16).to_le_bytes()); // dst-y
    req.push(24); // depth
    req.push(2); // format: ZPixmap
    req.push(0); // send-event: false
    req.push(0); // unused
    req.extend_from_slice(&seg.to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes()); // offset into segment
    req
}

/// Query whether the server supports an extension, returning its major opcode.
/// Must be called before the window is mapped, so the reply doesn't interleave
/// with events.
fn query_extension(conn: &mut Conn, name: &[u8]) -> io::Result<Option<u8>> {
    let mut req = vec![OP_QUERY_EXTENSION, 0, 0, 0];
    req.extend_from_slice(&(name.len() as u16).to_le_bytes());
    req.extend_from_slice(&[0u8; 2]); // unused
    req.extend_from_slice(name);
    pad4(&mut req);
    conn.send(&finish(req))?;
    let mut pkt = [0u8; 32];
    conn.stream.read_exact(&mut pkt)?;
    // Reply: byte 8 = present (bool), byte 9 = major-opcode.
    if pkt[0] != 1 || pkt[8] == 0 {
        return Ok(None);
    }
    Ok(Some(pkt[9]))
}

// ---- DRI3: GPU buffer sharing with the X server -----------------------------
//
// DRI3 + Present is how a GPU frame reaches the window with no readback (the
// chosen Phase-B path): render to a dma-buf, wrap it as an X Pixmap via
// DRI3 `PixmapFromBuffers` (the fd sent over this socket with SCM_RIGHTS), then
// flip it to the window via the Present extension. `dri3_open` is the first step
// — it returns the server's DRM device fd, so our GPU context can render on the
// same device the server can import from. The fd arrives as ancillary data on
// the reply, received via `crate::platform::scm`.

const DRI3_QUERY_VERSION: u8 = 0;
const DRI3_OPEN: u8 = 1;

/// Build a `DRI3Open` request (minor opcode 1): drawable + provider (0 = pick).
fn dri3_open_request(major: u8, drawable: u32) -> Vec<u8> {
    let mut req = vec![major, DRI3_OPEN, 0, 0];
    req.extend_from_slice(&drawable.to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes()); // provider
    finish(req)
}

/// Negotiate DRI3 and open the server's DRM device, returning its fd. Returns
/// `Ok(None)` if the server has no DRI3 extension. The fd is owned by the caller.
fn dri3_open(conn: &mut Conn, drawable: u32) -> io::Result<Option<RawFd>> {
    let Some(major) = query_extension(conn, b"DRI3")? else {
        return Ok(None);
    };

    // DRI3QueryVersion — negotiate (we want >= 1.2 for PixmapFromBuffers later).
    let mut req = vec![major, DRI3_QUERY_VERSION, 0, 0];
    req.extend_from_slice(&1u32.to_le_bytes()); // client major
    req.extend_from_slice(&2u32.to_le_bytes()); // client minor
    conn.send(&finish(req))?;
    let mut reply = [0u8; 32];
    conn.stream.read_exact(&mut reply)?;
    if reply[0] != 1 {
        return Ok(None); // error reply
    }

    // DRI3Open — reply carries the DRM fd as ancillary data (nfd in byte 1).
    conn.send(&dri3_open_request(major, drawable))?;
    let mut reply = [0u8; 32];
    let mut fds = Vec::new();
    let n = crate::platform::scm::recv_with_fds(&conn.stream, &mut reply, &mut fds, 1)?;
    // The 32-byte reply may arrive split from the ancillary chunk; read the rest.
    if n < 32 {
        conn.stream.read_exact(&mut reply[n..])?;
    }
    if reply[0] != 1 {
        for fd in fds {
            unsafe { libc_close_fd(fd) };
        }
        return Ok(None);
    }
    Ok(fds.first().copied())
}

/// Connect to `$DISPLAY`, negotiate DRI3, and open the server's DRM device,
/// returning its fd (owned by the caller). `None` if the server lacks DRI3.
/// Maps no window (DRI3Open targets the root drawable), so it's a benign query.
/// The fd can be handed to `stipple::gpu` to bind EGL/GBM to the server's GPU.
pub fn dri3_open_drm_fd() -> Result<Option<RawFd>, PlatformError> {
    let mut conn = Conn::connect()?;
    let root = conn.setup.root;
    dri3_open(&mut conn, root).map_err(os)
}

/// As [`dri3_open_drm_fd`] but closes the fd and returns a human-readable result.
pub fn dri3_open_probe() -> Result<String, PlatformError> {
    match dri3_open_drm_fd()? {
        Some(fd) => {
            let msg = format!("DRI3Open ok: DRM device fd = {fd}");
            unsafe { libc_close_fd(fd) };
            Ok(msg)
        }
        None => Ok("DRI3 unavailable on this server".to_string()),
    }
}

unsafe extern "C" {
    #[link_name = "close"]
    fn libc_close_fd(fd: RawFd) -> i32;
}

// ---- DRI3 PixmapFromBuffers + Present: flip a GPU frame with no readback -----
//
// The last hop of the zero-copy path: wrap a rendered dma-buf as an X Pixmap via
// DRI3 `PixmapFromBuffers` (the plane fds sent over this socket with SCM_RIGHTS,
// echoing the format modifier so tiled buffers import correctly), then flip that
// Pixmap to the window with the Present extension's `PresentPixmap`. The
// `PixmapFromBuffers` step needs a real GPU (the server imports the dma-buf), so
// it's hardware-gated; the Present extension itself needs no GPU (it works under
// Xvfb), so its negotiation is CI-verifiable. The wire encoders below are
// unit-tested regardless.

const DRI3_PIXMAP_FROM_BUFFERS: u8 = 7;
const DRI3_FENCE_FROM_FD: u8 = 4;
const PRESENT_QUERY_VERSION: u8 = 0;
const PRESENT_PIXMAP: u8 = 1;

/// A rendered dma-buf to wrap as an X Pixmap via DRI3 `PixmapFromBuffers`. Holds
/// the geometry + format the server needs to interpret the (1..=4) planes; the
/// plane fds are passed separately as SCM_RIGHTS ancillary data.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DmabufImage {
    pub width: u16,
    pub height: u16,
    /// Pixmap depth (e.g. 24 for XRGB8888, 32 for ARGB8888).
    pub depth: u8,
    /// Bits per pixel (e.g. 32).
    pub bpp: u8,
    /// DRM format modifier — must echo the export's modifier (e.g. from
    /// `EGL_DMA_BUF_PLANE0_MODIFIER_*`) or a tiled buffer imports as garbage.
    pub modifier: u64,
    /// Per-plane `(stride, offset)` in bytes; 1..=4 planes, parallel to the fds.
    pub planes: Vec<(u32, u32)>,
}

/// Build a DRI3 `PixmapFromBuffers` request (minor 7): wrap the dma-buf planes
/// of `img` (whose fds are sent alongside as ancillary data via
/// [`crate::platform::scm::send_with_fds`]) as the X resource `pixmap`, in `window`'s
/// screen. Absent planes (of the 4 wire slots) are zero-filled.
pub fn pixmap_from_buffers_request(
    major: u8,
    pixmap: u32,
    window: u32,
    img: &DmabufImage,
) -> Vec<u8> {
    let mut req = vec![major, DRI3_PIXMAP_FROM_BUFFERS, 0, 0];
    req.extend_from_slice(&pixmap.to_le_bytes());
    req.extend_from_slice(&window.to_le_bytes());
    req.push(img.planes.len() as u8);
    req.extend_from_slice(&[0u8; 3]); // pad
    req.extend_from_slice(&img.width.to_le_bytes());
    req.extend_from_slice(&img.height.to_le_bytes());
    // stride0,offset0 .. stride3,offset3 (zero-filled for absent planes).
    for i in 0..4 {
        let (stride, offset) = img.planes.get(i).copied().unwrap_or((0, 0));
        req.extend_from_slice(&stride.to_le_bytes());
        req.extend_from_slice(&offset.to_le_bytes());
    }
    req.push(img.depth);
    req.push(img.bpp);
    req.extend_from_slice(&[0u8; 2]); // pad
    req.extend_from_slice(&img.modifier.to_le_bytes());
    finish(req)
}

/// Build a Present `PresentPixmap` request (minor 1): present `pixmap` to
/// `window`. `wait_fence` is an `XSyncFence` the server waits on before reading
/// the pixmap (`0` = none) — pass a fence the producer triggers when its GPU
/// render finishes (see [`dri3_fence_from_fd_request`]) for **frame sync**, so
/// the compositor never samples a half-rendered buffer. Regions, target CRTC,
/// the idle fence, and target MSC/divisor/remainder are left as 0 — a plain
/// immediate present; `serial` and `options` pass through. No notify list.
pub fn present_pixmap_request(
    major: u8,
    window: u32,
    pixmap: u32,
    wait_fence: u32,
    serial: u32,
    options: u32,
) -> Vec<u8> {
    let mut req = vec![major, PRESENT_PIXMAP, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&pixmap.to_le_bytes());
    req.extend_from_slice(&serial.to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes()); // valid region (None)
    req.extend_from_slice(&0u32.to_le_bytes()); // update region (None)
    req.extend_from_slice(&0i16.to_le_bytes()); // x-off
    req.extend_from_slice(&0i16.to_le_bytes()); // y-off
    req.extend_from_slice(&0u32.to_le_bytes()); // target CRTC (None)
    req.extend_from_slice(&wait_fence.to_le_bytes()); // wait fence (frame sync)
    req.extend_from_slice(&0u32.to_le_bytes()); // idle fence (None)
    req.extend_from_slice(&options.to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes()); // unused
    req.extend_from_slice(&0u64.to_le_bytes()); // target MSC
    req.extend_from_slice(&0u64.to_le_bytes()); // divisor
    req.extend_from_slice(&0u64.to_le_bytes()); // remainder
    finish(req)
}

/// Build a DRI3 `FenceFromFD` request (minor 4): wrap a kernel sync-file `fd`
/// (passed alongside as `SCM_RIGHTS` ancillary data) as the `XSyncFence`
/// resource `fence` on `drawable`'s screen. `initially_triggered` seeds the
/// fence state. The producer exports its render-completion fence as a sync-file
/// and the server waits on the resulting `XSyncFence` in
/// [`present_pixmap_request`] before sampling the pixmap — that is GPU frame
/// sync, no CPU stall.
pub fn dri3_fence_from_fd_request(
    major: u8,
    drawable: u32,
    fence: u32,
    initially_triggered: bool,
) -> Vec<u8> {
    let mut req = vec![major, DRI3_FENCE_FROM_FD, 0, 0];
    req.extend_from_slice(&drawable.to_le_bytes());
    req.extend_from_slice(&fence.to_le_bytes());
    req.push(initially_triggered as u8);
    req.extend_from_slice(&[0u8; 3]); // pad
    finish(req)
}

/// Negotiate the Present extension, returning the server's `(major, minor)`
/// version. `None` if the server lacks Present. Works without a GPU.
fn present_query_version(conn: &mut Conn) -> io::Result<Option<(u32, u32)>> {
    let Some(major) = query_extension(conn, b"Present")? else {
        return Ok(None);
    };
    let mut req = vec![major, PRESENT_QUERY_VERSION, 0, 0];
    req.extend_from_slice(&1u32.to_le_bytes()); // client major
    req.extend_from_slice(&2u32.to_le_bytes()); // client minor
    conn.send(&finish(req))?;
    let mut reply = [0u8; 32];
    conn.stream.read_exact(&mut reply)?;
    if reply[0] != 1 {
        return Ok(None);
    }
    let smajor = u32::from_le_bytes([reply[8], reply[9], reply[10], reply[11]]);
    let sminor = u32::from_le_bytes([reply[12], reply[13], reply[14], reply[15]]);
    Ok(Some((smajor, sminor)))
}

// The runtime composition that flips a GPU frame to a window with no readback —
// query DRI3 + Present, `conn.new_id()` for the pixmap,
// `scm::send_with_fds(pixmap_from_buffers_request(..), plane_fds)`, then
// `present_pixmap_request(..)` — lives in the windowed compositor once
// `stipple::gpu` exports a scene's dma-buf descriptor (fds + per-plane
// stride/offset + modifier). The wire encoders above are that path's tested
// building blocks; both DRI3 import and Present flip need real GPU hardware.

/// Connect and negotiate the Present extension, returning a one-line status.
/// Present needs no GPU (Xvfb supports it), so this is CI-verifiable — it proves
/// the half of the zero-copy present path that doesn't require DRM hardware.
pub fn present_probe() -> Result<String, PlatformError> {
    let mut conn = Conn::connect()?;
    match present_query_version(&mut conn).map_err(os)? {
        Some((maj, min)) => Ok(format!("Present {maj}.{min} available")),
        None => Ok("Present unavailable on this server".to_string()),
    }
}

/// Present a rendered dma-buf to a freshly created window with **no readback**,
/// composing the full zero-copy path end to end: connect, create + map a window
/// the size of `img`, then DRI3 `PixmapFromBuffers` (the plane `fds` passed over
/// the socket as `SCM_RIGHTS`) → Present `PresentPixmap` to flip it. A
/// `GetInputFocus` round-trip then surfaces any protocol error from those
/// requests. Returns a one-line status.
///
/// **Hardware-gated**: the server imports the dma-buf, so this needs a real GPU +
/// a DRM-capable X server — under Xvfb DRI3 is absent and it reports unavailable
/// (without touching `fds`). `fds.len()` must equal `img.planes.len()`; the fds
/// come from `stipple::gpu::export_dmabuf_on_device` bound to *this* server's DRM
/// device (its fd from [`dri3_open_drm_fd`]), so the server can import them.
pub fn dri3_present_dmabuf_self_test(
    img: &DmabufImage,
    fds: &[RawFd],
) -> Result<String, PlatformError> {
    let mut conn = Conn::connect()?;
    let Some(dri3_major) = query_extension(&mut conn, b"DRI3").map_err(os)? else {
        return Ok("DRI3 unavailable on this server (no GPU/DRM; e.g. Xvfb)".to_string());
    };
    let Some(present_major) = query_extension(&mut conn, b"Present").map_err(os)? else {
        return Ok("Present unavailable on this server".to_string());
    };

    // Create + map a window the size of the image (minimal: no GC/SHM needed —
    // the dma-buf pixmap is presented directly).
    let window = conn.new_id();
    let setup = conn.setup;
    let (w, h) = (img.width.max(1), img.height.max(1));
    let mut req = vec![OP_CREATE_WINDOW, setup.root_depth, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&setup.root.to_le_bytes());
    req.extend_from_slice(&0i16.to_le_bytes()); // x
    req.extend_from_slice(&0i16.to_le_bytes()); // y
    req.extend_from_slice(&w.to_le_bytes());
    req.extend_from_slice(&h.to_le_bytes());
    req.extend_from_slice(&0u16.to_le_bytes()); // border width
    req.extend_from_slice(&1u16.to_le_bytes()); // class: InputOutput
    req.extend_from_slice(&setup.root_visual.to_le_bytes());
    req.extend_from_slice(&CW_BACK_PIXEL.to_le_bytes()); // value-mask
    req.extend_from_slice(&0u32.to_le_bytes()); // back-pixel: black
    conn.send(&finish(req)).map_err(os)?;
    let mut req = vec![OP_MAP_WINDOW, 0, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    conn.send(&finish(req)).map_err(os)?;

    // Wrap the dma-buf as an X pixmap (its plane fds ride as ancillary data) and
    // flip that pixmap to the window — the zero-copy present.
    let pixmap = conn.new_id();
    let req = pixmap_from_buffers_request(dri3_major, pixmap, window, img);
    crate::platform::scm::send_with_fds(&conn.stream, &req, fds).map_err(os)?;
    // wait_fence 0: an immediate present. A real producer passes a fence wrapped
    // from its render-completion sync-file via `dri3_fence_from_fd_request`.
    conn.send(&present_pixmap_request(
        present_major,
        window,
        pixmap,
        0,
        0,
        0,
    ))
    .map_err(os)?;

    // Round-trip on GetInputFocus: if any request above errored, the error packet
    // arrives in place of the reply (first byte 0).
    conn.send(&finish(vec![OP_GET_INPUT_FOCUS, 0, 0, 0]))
        .map_err(os)?;
    let mut pkt = [0u8; 32];
    conn.stream.read_exact(&mut pkt).map_err(os)?;
    if pkt[0] == 0 {
        return Err(PlatformError::Os(format!(
            "X11 error during DRI3/Present (code {})",
            pkt[1]
        )));
    }
    Ok(format!(
        "presented {w}x{h} dma-buf pixmap to window {window:#x} (DRI3 {dri3_major} + Present {present_major})"
    ))
}

/// Set up MIT-SHM: create a shared segment of `capacity` bytes, attach it to the
/// server, and confirm the attach succeeded. Returns `None` (with everything
/// cleaned up) if the extension is absent or any step fails — the caller then
/// presents via `PutImage`. Must run before the window is mapped.
fn setup_shm(conn: &mut Conn, capacity: usize) -> Option<ShmState> {
    let major = query_extension(conn, b"MIT-SHM").ok()??;

    let shmid = unsafe { shmget(IPC_PRIVATE, capacity, IPC_CREAT | SHM_PERM) };
    if shmid < 0 {
        return None;
    }
    let addr = unsafe { shmat(shmid, core::ptr::null(), 0) };
    if addr as isize == -1 {
        unsafe {
            shmctl(shmid, IPC_RMID, core::ptr::null_mut());
        }
        return None;
    }
    let ptr = addr as *mut u8;

    // ShmAttach: hand the segment to the server.
    let seg = conn.new_id();
    let mut req = vec![major, SHM_ATTACH, 0, 0];
    req.extend_from_slice(&seg.to_le_bytes());
    req.extend_from_slice(&(shmid as u32).to_le_bytes());
    req.push(0); // read-only: false
    req.extend_from_slice(&[0u8; 3]);
    let cleanup = |ptr: *mut u8, shmid: i32| unsafe {
        shmdt(ptr as *const c_void);
        shmctl(shmid, IPC_RMID, core::ptr::null_mut());
    };
    if conn.send(&finish(req)).is_err() {
        cleanup(ptr, shmid);
        return None;
    }

    // Synchronize on GetInputFocus (which has a reply): if ShmAttach errored, the
    // error packet arrives first. No window is mapped yet, so nothing else can
    // interleave with the reply.
    if conn
        .send(&finish(vec![OP_GET_INPUT_FOCUS, 0, 0, 0]))
        .is_err()
    {
        cleanup(ptr, shmid);
        return None;
    }
    let mut pkt = [0u8; 32];
    if conn.stream.read_exact(&mut pkt).is_err() {
        cleanup(ptr, shmid);
        return None;
    }
    if pkt[0] == 0 {
        // ShmAttach failed; drain the GetInputFocus reply and bail.
        let mut reply = [0u8; 32];
        let _ = conn.stream.read_exact(&mut reply);
        cleanup(ptr, shmid);
        return None;
    }

    // Attach confirmed: mark the segment for deletion now (the server holds a
    // reference), so it's freed automatically once everyone detaches.
    unsafe {
        shmctl(shmid, IPC_RMID, core::ptr::null_mut());
    }
    Some(ShmState {
        major,
        seg,
        ptr,
        capacity,
    })
}

/// Read the first MIT-MAGIC-COOKIE-1 entry's cookie from `.Xauthority`, if any.
/// Best-effort: returns `None` when the file is absent or has no cookie (the
/// server may still accept an unauthenticated local connection).
fn read_auth_cookie() -> Option<Vec<u8>> {
    let path = std::env::var_os("XAUTHORITY")
        .map(std::path::PathBuf::from)
        .or_else(|| {
            std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".Xauthority"))
        })?;
    let data = std::fs::read(path).ok()?;
    parse_xauth_cookie(&data)
}

fn parse_xauth_cookie(data: &[u8]) -> Option<Vec<u8>> {
    // Each entry: family(2) addr_len(2) addr name_len(2) name data_len(2) data,
    // all big-endian lengths.
    let be16 = |b: &[u8], o: usize| -> Option<usize> {
        Some(u16::from_be_bytes([*b.get(o)?, *b.get(o + 1)?]) as usize)
    };
    let mut o = 0;
    while o + 2 <= data.len() {
        o += 2; // family
        let addr_len = be16(data, o)?;
        o += 2 + addr_len;
        let num_len = be16(data, o)?;
        o += 2 + num_len;
        let name_len = be16(data, o)?;
        let name = data.get(o + 2..o + 2 + name_len)?;
        o += 2 + name_len;
        let data_len = be16(data, o)?;
        let cookie = data.get(o + 2..o + 2 + data_len)?;
        o += 2 + data_len;
        if name == b"MIT-MAGIC-COOKIE-1" {
            return Some(cookie.to_vec());
        }
    }
    None
}

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

struct Conn {
    stream: UnixStream,
    setup: Setup,
    next_id: u32,
    id_step: u32,
    /// The text we currently own on the `CLIPBOARD` selection. Served to other
    /// clients in response to `SelectionRequest`; updated by `set_clipboard`.
    clipboard_text: String,
    /// Atoms interned once at startup for the clipboard protocol (0 until set).
    atom_clipboard: u32,
    atom_utf8: u32,
    atom_targets: u32,
    /// WM_PROTOCOLS / WM_DELETE_WINDOW, interned once so every window (including
    /// ones opened later) registers the close protocol the same way.
    atom_wm_protocols: u32,
    atom_wm_delete: u32,
}

impl Conn {
    fn connect() -> Result<Self, PlatformError> {
        let display =
            std::env::var("DISPLAY").map_err(|_| PlatformError::NoBackend("DISPLAY unset"))?;
        let addr =
            parse_display(&display).ok_or(PlatformError::NoBackend("could not parse DISPLAY"))?;
        let path = format!("/tmp/.X11-unix/X{}", addr.number);
        let mut stream = UnixStream::connect(&path)
            .map_err(|e| PlatformError::Os(format!("connect {path}: {e}")))?;

        // --- Setup request ---
        let cookie = read_auth_cookie().unwrap_or_default();
        let (auth_name, auth_data): (&[u8], &[u8]) = if cookie.is_empty() {
            (b"", b"")
        } else {
            (b"MIT-MAGIC-COOKIE-1", &cookie)
        };
        let mut req = Vec::new();
        req.push(b'l'); // little-endian
        req.push(0);
        req.extend_from_slice(&11u16.to_le_bytes()); // protocol major
        req.extend_from_slice(&0u16.to_le_bytes()); // protocol minor
        req.extend_from_slice(&(auth_name.len() as u16).to_le_bytes());
        req.extend_from_slice(&(auth_data.len() as u16).to_le_bytes());
        req.extend_from_slice(&0u16.to_le_bytes()); // pad
        req.extend_from_slice(auth_name);
        pad4(&mut req);
        req.extend_from_slice(auth_data);
        pad4(&mut req);
        stream.write_all(&req).map_err(os)?;
        stream.flush().map_err(os)?;

        // --- Setup reply ---
        let mut header = [0u8; 8];
        stream.read_exact(&mut header).map_err(os)?;
        if header[0] != 1 {
            // 0 = failed, 2 = authenticate.
            return Err(PlatformError::Os(format!(
                "X11 setup refused (status {})",
                header[0]
            )));
        }
        let extra_words = u16::from_le_bytes([header[6], header[7]]) as usize;
        let mut rest = vec![0u8; extra_words * 4];
        stream.read_exact(&mut rest).map_err(os)?;
        let setup = parse_setup(&rest).ok_or(PlatformError::Os("malformed setup reply".into()))?;

        dbg(format_args!(
            "connected: root={:#x} visual={:#x} depth={} max_req={}",
            setup.root, setup.root_visual, setup.root_depth, setup.max_request_len
        ));
        let id_step = setup.resource_id_mask & setup.resource_id_mask.wrapping_neg();
        Ok(Self {
            stream,
            setup,
            next_id: 0,
            id_step: id_step.max(1),
            clipboard_text: String::new(),
            atom_clipboard: 0,
            atom_utf8: 0,
            atom_targets: 0,
            atom_wm_protocols: 0,
            atom_wm_delete: 0,
        })
    }

    /// Allocate a fresh XID.
    fn new_id(&mut self) -> u32 {
        let id = self.setup.resource_id_base | (self.next_id * self.id_step);
        self.next_id += 1;
        id
    }

    fn send(&mut self, bytes: &[u8]) -> io::Result<()> {
        self.stream.write_all(bytes)?;
        self.stream.flush()
    }
}

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

fn pad4(buf: &mut Vec<u8>) {
    while !buf.len().is_multiple_of(4) {
        buf.push(0);
    }
}

/// Set the request-length field (offset 2, in 4-byte units) from the final
/// buffer length, then return the buffer.
fn finish(mut req: Vec<u8>) -> Vec<u8> {
    let words = (req.len() / 4) as u16;
    req[2..4].copy_from_slice(&words.to_le_bytes());
    req
}

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

/// Shared mutable connection so the window's surface and the event loop can
/// both talk to the server.
type SharedConn = Arc<Mutex<Conn>>;

/// Windows opened (or closed) from inside the event loop — e.g. by
/// [`Window::open_window`]. The loop drains these after each handler call and
/// merges them into its live set. Single-threaded (`Rc`/`RefCell`): every X11
/// window shares one connection and one loop, so there is no cross-thread use.
#[derive(Debug, Default)]
struct WindowReg {
    /// Newly created windows awaiting adoption into the loop's live set.
    opened: Vec<X11Window>,
    /// XIDs of windows the app asked to close.
    closed: Vec<u32>,
}

type Registry = Rc<RefCell<WindowReg>>;

#[derive(Debug)]
struct X11Window {
    conn: SharedConn,
    window: u32,
    gc: u32,
    size: PhysicalSize,
    // Set up once before mapping; moved into the surface on `create_surface`.
    shm: RefCell<Option<ShmState>>,
    // Shared with the event loop so opening/closing siblings reaches it. Held by
    // every window but normally points at empty queues (drained each iteration),
    // so there is no retained reference cycle through the loop's live set.
    reg: Registry,
}

impl std::fmt::Debug for Conn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Conn")
            .field("setup", &self.setup)
            .finish_non_exhaustive()
    }
}

impl Window for X11Window {
    fn id(&self) -> WindowId {
        WindowId(self.window as u64)
    }
    fn inner_size(&self) -> PhysicalSize {
        self.size
    }
    fn scale_factor(&self) -> ScaleFactor {
        // X11 DPI handling (Xft.dpi / RandR) is a follow-up; assume 1×.
        ScaleFactor::IDENTITY
    }
    fn request_redraw(&self) {
        // Driven by Expose; an explicit invalidate would need a SendEvent.
    }
    fn set_title(&self, _title: &str) {}
    fn set_clipboard(&self, text: &str) {
        // Become the owner of the CLIPBOARD selection and remember the text;
        // the event loop serves it to requestors via SelectionRequest.
        let mut conn = self.conn.lock().unwrap();
        conn.clipboard_text = text.to_string();
        let selection = conn.atom_clipboard;
        if selection == 0 {
            return;
        }
        let mut req = vec![OP_SET_SELECTION_OWNER, 0, 0, 0];
        req.extend_from_slice(&self.window.to_le_bytes()); // owner
        req.extend_from_slice(&selection.to_le_bytes()); // CLIPBOARD
        req.extend_from_slice(&0u32.to_le_bytes()); // time = CurrentTime
        let _ = conn.send(&finish(req));
    }
    fn create_surface(&self) -> Box<dyn Surface> {
        Box::new(X11Surface {
            conn: self.conn.clone(),
            window: self.window,
            gc: self.gc,
            size: self.size,
            shm: self.shm.borrow_mut().take(),
        })
    }
    fn open_window(&self, attrs: WindowAttributes) -> Option<WindowId> {
        // Create + map a sibling window on the same connection, then hand it to
        // the event loop (which shares `reg`) to adopt into its live set. Its
        // events arrive through the same handler, keyed by `id()`.
        let win = {
            let mut conn = self.conn.lock().unwrap();
            create_window(
                &mut conn,
                &attrs,
                self.conn.clone(),
                self.reg.clone(),
                false,
            )
            .ok()?
        };
        let id = win.id();
        self.reg.borrow_mut().opened.push(win);
        Some(id)
    }
    fn close_window(&self) {
        self.reg.borrow_mut().closed.push(self.window);
    }
}

struct X11Surface {
    conn: SharedConn,
    window: u32,
    gc: u32,
    size: PhysicalSize,
    /// Present via MIT-SHM when available; `None` falls back to `PutImage`.
    shm: Option<ShmState>,
}

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

impl Surface for X11Surface {
    fn resize(&mut self, size: PhysicalSize) {
        self.size = size;
    }
    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;
        }
        dbg(format_args!(
            "present {}x{} to window={:#x} (shm={})",
            size.width,
            size.height,
            self.window,
            self.shm.is_some()
        ));
        let mut conn = self.conn.lock().unwrap();

        // Fast path: copy only the damaged regions into shared memory and blit
        // them. On failure (frame grew past the segment), drop shm and fall
        // through to PutImage for this and subsequent frames.
        if let Some(shm) = self.shm.as_mut() {
            if shm.present(&mut conn, self.window, self.gc, pixmap, damage) {
                return;
            }
            self.shm = None;
        }
        // PutImage may exceed the server's max request length; send in row
        // bands that each fit. Header is 24 bytes; budget the rest for pixels.
        let max_bytes = (conn.setup.max_request_len as usize)
            .saturating_mul(4)
            .max(256 * 1024);
        let row_bytes = size.width as usize * 4;
        let rows_per = (max_bytes.saturating_sub(24) / row_bytes.max(1)).max(1);

        let src = pixmap.as_bytes();
        let mut bgrx = Vec::new();
        let mut y = 0u32;
        while y < size.height {
            let band = rows_per.min((size.height - y) as usize);
            let start = y as usize * row_bytes;
            let end = start + band * row_bytes;
            rgba_to_bgrx(&src[start..end], &mut bgrx);

            let mut req = vec![OP_PUT_IMAGE, 2 /* ZPixmap */, 0, 0];
            req.extend_from_slice(&self.window.to_le_bytes());
            req.extend_from_slice(&self.gc.to_le_bytes());
            req.extend_from_slice(&(size.width as u16).to_le_bytes());
            req.extend_from_slice(&(band as u16).to_le_bytes());
            req.extend_from_slice(&0i16.to_le_bytes()); // dst-x
            req.extend_from_slice(&(y as i16).to_le_bytes()); // dst-y
            req.push(0); // left-pad
            req.push(24); // depth
            req.extend_from_slice(&0u16.to_le_bytes()); // pad
            req.extend_from_slice(&bgrx);
            pad4(&mut req);
            if conn.send(&finish(req)).is_err() {
                break;
            }
            y += band as u32;
        }
    }
}

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

/// Create, configure, and map one top-level window on `conn`, returning a live
/// [`X11Window`]. Used both for the initial window and for siblings opened later
/// via [`Window::open_window`]. Requires the WM/clipboard atoms to be interned
/// on `conn` already (see [`run`]).
fn create_window(
    conn: &mut Conn,
    attrs: &WindowAttributes,
    shared: SharedConn,
    reg: Registry,
    use_shm: bool,
) -> Result<X11Window, PlatformError> {
    let size = ScaleFactor::IDENTITY.to_physical(attrs.logical_size);
    let (w, h) = (size.width.max(1) as u16, size.height.max(1) as u16);
    let window = conn.new_id();
    let gc = conn.new_id();
    let setup = conn.setup;

    // CreateWindow.
    let (x, y) = attrs.position.unwrap_or((0, 0));
    let mut req = vec![OP_CREATE_WINDOW, setup.root_depth, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&setup.root.to_le_bytes());
    req.extend_from_slice(&(x as i16).to_le_bytes()); // x
    req.extend_from_slice(&(y as i16).to_le_bytes()); // y
    req.extend_from_slice(&w.to_le_bytes());
    req.extend_from_slice(&h.to_le_bytes());
    req.extend_from_slice(&0u16.to_le_bytes()); // border width
    req.extend_from_slice(&1u16.to_le_bytes()); // class: InputOutput
    req.extend_from_slice(&setup.root_visual.to_le_bytes());
    req.extend_from_slice(&(CW_BACK_PIXEL | CW_EVENT_MASK).to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes()); // back-pixel: black
    let mask = EV_EXPOSURE
        | EV_KEY_PRESS
        | EV_KEY_RELEASE
        | EV_BUTTON_PRESS
        | EV_BUTTON_RELEASE
        | EV_POINTER_MOTION
        | EV_STRUCTURE_NOTIFY;
    req.extend_from_slice(&mask.to_le_bytes());
    conn.send(&finish(req)).map_err(os)?;

    // CreateGC.
    let mut req = vec![OP_CREATE_GC, 0, 0, 0];
    req.extend_from_slice(&gc.to_le_bytes());
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes()); // value-mask: none
    conn.send(&finish(req)).map_err(os)?;

    // Title via WM_NAME (atom 39 = WM_NAME, predefined; type STRING = 31).
    set_property_str(conn, window, 39, 31, attrs.title.as_bytes()).map_err(os)?;

    // WM_PROTOCOLS / WM_DELETE_WINDOW so the close button delivers an event.
    let (wm_protocols, wm_delete) = (conn.atom_wm_protocols, conn.atom_wm_delete);
    set_property_atoms(conn, window, wm_protocols, &[wm_delete]).map_err(os)?;

    // Set up MIT-SHM presentation before mapping (its handshake needs replies
    // that must not interleave with window events). Falls back to PutImage when
    // unavailable. Siblings opened mid-loop pass `use_shm = false`: the first
    // window is already emitting events, so reply-reads here would race the
    // event stream — those windows present via PutImage instead.
    let shm = if use_shm {
        setup_shm(conn, (w as usize) * (h as usize) * 4)
    } else {
        None
    };
    dbg(format_args!("shm present path: {}", shm.is_some()));

    // MapWindow.
    let mut req = vec![OP_MAP_WINDOW, 0, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    conn.send(&finish(req)).map_err(os)?;

    // Grab keyboard focus so key events arrive even with no window manager
    // (e.g. under Xvfb in CI). revert-to = PointerRoot (1), time = 0
    // (CurrentTime). Pointer events are delivered regardless of focus.
    let mut req = vec![OP_SET_INPUT_FOCUS, 1, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&0u32.to_le_bytes());
    conn.send(&finish(req)).map_err(os)?;

    dbg(format_args!(
        "mapped window={window:#x} gc={gc:#x} size={}x{}",
        w, h
    ));

    Ok(X11Window {
        conn: shared,
        window,
        gc,
        size,
        shm: RefCell::new(shm),
        reg,
    })
}

/// Connect to the X server, create a window, and drive `handler` over the event
/// stream until the handler returns [`ControlFlow::Exit`] or every window has
/// closed. Additional top-level windows opened via [`Window::open_window`] share
/// this one connection and loop; their events are dispatched to the same handler
/// against the [`Window`] they belong to.
pub fn run<H>(attrs: WindowAttributes, mut handler: H) -> Result<(), PlatformError>
where
    H: FnMut(Event, &dyn Window) -> ControlFlow,
{
    let mut conn = Conn::connect()?;

    // Fetch the keyboard mapping up front (no window yet, so the reply is the
    // next message and won't interleave with events).
    let keymap = fetch_keymap(&mut conn).map_err(os)?;
    dbg(format_args!(
        "keymap: {} keysyms, {}/keycode",
        keymap.syms.len(),
        keymap.per
    ));

    // Intern the WM + clipboard atoms once, up front, so `create_window` (used
    // for the first window and every later sibling) and the event loop can rely
    // on them.
    conn.atom_wm_protocols = intern_atom(&mut conn, b"WM_PROTOCOLS").map_err(os)?;
    conn.atom_wm_delete = intern_atom(&mut conn, b"WM_DELETE_WINDOW").map_err(os)?;
    conn.atom_clipboard = intern_atom(&mut conn, b"CLIPBOARD").map_err(os)?;
    conn.atom_utf8 = intern_atom(&mut conn, b"UTF8_STRING").map_err(os)?;
    conn.atom_targets = intern_atom(&mut conn, b"TARGETS").map_err(os)?;
    let wm_delete = conn.atom_wm_delete;

    // Wrap the connection for sharing, then create the first window against it
    // exactly as `open_window` creates later siblings.
    let reg: Registry = Rc::new(RefCell::new(WindowReg::default()));
    let shared: SharedConn = Arc::new(Mutex::new(conn));
    let initial = {
        let mut conn = shared.lock().unwrap();
        create_window(&mut conn, &attrs, shared.clone(), reg.clone(), true)?
    };

    // The live set of windows, keyed by XID via linear scan (tiny N).
    let mut windows: Vec<X11Window> = vec![initial];

    // Event loop. Events are 32 bytes each.
    let mut buf = [0u8; 32];
    loop {
        {
            let mut conn = shared.lock().unwrap();
            conn.stream.read_exact(&mut buf).map_err(os)?;
        }
        // An error reply (first byte 0) is not an event; log and skip it.
        if buf[0] == 0 {
            dbg(format_args!(
                "X error code={} major={} minor={} bad_resource={:#x}",
                buf[1],
                buf[10],
                u16::from_le_bytes([buf[8], buf[9]]),
                rd_u32(&buf, 4).unwrap_or(0)
            ));
            continue;
        }
        // Route the event to the window it names (falling back to the first).
        let xid = event_window(&buf);
        let idx = windows.iter().position(|w| w.window == xid).unwrap_or(0);
        let win = &windows[idx];
        let flow = match buf[0] & 0x7f {
            X_EXPOSE => {
                dbg(format_args!("expose"));
                handler(Event::RedrawRequested, win)
            }
            X_CONFIGURE_NOTIFY => {
                let nw = u16::from_le_bytes([buf[20], buf[21]]) as u32;
                let nh = u16::from_le_bytes([buf[22], buf[23]]) as u32;
                handler(Event::Resized(PhysicalSize::new(nw, nh)), win)
            }
            X_MOTION_NOTIFY => {
                let (x, y) = event_xy(&buf);
                handler(
                    Event::PointerMoved {
                        position: Point::new(x, y),
                    },
                    win,
                )
            }
            code @ (X_BUTTON_PRESS | X_BUTTON_RELEASE) => {
                let detail = buf[1];
                let (x, y) = event_xy(&buf);
                let state = if code == X_BUTTON_PRESS {
                    ButtonState::Pressed
                } else {
                    ButtonState::Released
                };
                // Buttons 4/5 are the scroll wheel.
                if detail == 4 || detail == 5 {
                    if code == X_BUTTON_PRESS {
                        let dy = if detail == 4 { -40.0 } else { 40.0 };
                        handler(
                            Event::Scroll {
                                delta: ScrollDelta { dx: 0.0, dy },
                            },
                            win,
                        )
                    } else {
                        ControlFlow::Wait
                    }
                } else {
                    let button = match detail {
                        1 => PointerButton::Left,
                        2 => PointerButton::Middle,
                        3 => PointerButton::Right,
                        n => PointerButton::Other(n as u16),
                    };
                    handler(
                        Event::PointerButton {
                            button,
                            state,
                            position: Point::new(x, y),
                        },
                        win,
                    )
                }
            }
            code @ (X_KEY_PRESS | X_KEY_RELEASE) => {
                let state = if code == X_KEY_PRESS {
                    ButtonState::Pressed
                } else {
                    ButtonState::Released
                };
                // buf[1] = keycode; buf[28..30] = modifier mask
                // (bit 0 = Shift, bit 2 = Control).
                let keycode = buf[1];
                let mask = rd_u16(&buf, 28).unwrap_or(0);
                // X core modifier mask: Shift=1, Control=4, Mod1/Alt=8,
                // Mod4/Super=0x40 (the common logo-key binding).
                let modifiers = Modifiers {
                    shift: mask & 0x0001 != 0,
                    ctrl: mask & 0x0004 != 0,
                    alt: mask & 0x0008 != 0,
                    meta: mask & 0x0040 != 0,
                };
                let ks = keymap.keysym(keycode, modifiers.shift);
                match keysym_to_event(ks, state, modifiers) {
                    Some(ev) => handler(ev, win),
                    None => ControlFlow::Wait,
                }
            }
            X_CLIENT_MESSAGE => {
                // data starts at byte 12; first 32-bit word is the protocol atom.
                let atom = rd_u32(&buf, 12).unwrap_or(0);
                if atom == wm_delete {
                    handler(Event::CloseRequested, win)
                } else {
                    ControlFlow::Wait
                }
            }
            X_SELECTION_REQUEST => {
                // Another client wants our CLIPBOARD text. Serve it, then notify.
                let mut conn = shared.lock().unwrap();
                let _ = serve_selection_request(&mut conn, &buf);
                ControlFlow::Wait
            }
            X_SELECTION_CLEAR => {
                // We lost ownership of the selection; drop our copy.
                let mut conn = shared.lock().unwrap();
                conn.clipboard_text.clear();
                ControlFlow::Wait
            }
            _ => ControlFlow::Wait, // errors, replies, unhandled events
        };
        if flow == ControlFlow::Exit {
            break;
        }
        // Adopt windows opened during this iteration, and destroy closed ones.
        {
            let mut r = reg.borrow_mut();
            windows.append(&mut r.opened);
            for xid in r.closed.drain(..) {
                if let Some(pos) = windows.iter().position(|w| w.window == xid) {
                    windows.remove(pos);
                    let mut conn = shared.lock().unwrap();
                    let mut req = vec![OP_DESTROY_WINDOW, 0, 0, 0];
                    req.extend_from_slice(&xid.to_le_bytes());
                    let _ = conn.send(&finish(req));
                }
            }
        }
        if windows.is_empty() {
            break; // every window closed
        }
    }
    Ok(())
}

/// The keyboard mapping (keycode → keysyms) fetched via `GetKeyboardMapping`,
/// used to turn key events into text + editing keys.
struct Keymap {
    syms: Vec<u32>,
    per: usize,
    min: u8,
}

impl Keymap {
    fn keysym(&self, keycode: u8, shift: bool) -> u32 {
        if keycode < self.min || self.per == 0 {
            return 0;
        }
        let base = (keycode - self.min) as usize * self.per;
        let i = base + if shift && self.per > 1 { 1 } else { 0 };
        let ks = self.syms.get(i).copied().unwrap_or(0);
        // Fall back to the unshifted keysym when the shifted slot is empty.
        if ks == 0 {
            self.syms.get(base).copied().unwrap_or(0)
        } else {
            ks
        }
    }
}

fn fetch_keymap(conn: &mut Conn) -> io::Result<Keymap> {
    let min = conn.setup.min_keycode;
    let max = conn.setup.max_keycode;
    let count = max.saturating_sub(min).saturating_add(1);
    let mut req = vec![OP_GET_KEYBOARD_MAPPING, 0, 0, 0, min, count, 0, 0];
    conn.send(&finish(std::mem::take(&mut req)))?;
    let mut reply = [0u8; 32];
    conn.stream.read_exact(&mut reply)?;
    let per = reply[1] as usize;
    let len_words = rd_u32(&reply, 4).unwrap_or(0) as usize; // = count * per
    let mut body = vec![0u8; len_words * 4];
    conn.stream.read_exact(&mut body)?;
    let syms = body
        .as_chunks::<4>()
        .0
        .iter()
        .map(|c| u32::from_le_bytes(*c))
        .collect();
    Ok(Keymap { syms, per, min })
}

/// Translate an X11 keysym into a Stipple event: editing/navigation keys become
/// [`Event::Key`] (carrying `modifiers`); printable Latin-1 / Unicode keysyms
/// become [`Event::Text`] (on press only).
fn keysym_to_event(ks: u32, state: ButtonState, modifiers: Modifiers) -> Option<Event> {
    let code = match ks {
        0xff08 => Some(KeyCode::Backspace),
        0xff09 => Some(KeyCode::Tab),
        0xff0d => Some(KeyCode::Enter),
        0xff1b => Some(KeyCode::Escape),
        0xff51 => Some(KeyCode::ArrowLeft),
        0xff52 => Some(KeyCode::ArrowUp),
        0xff53 => Some(KeyCode::ArrowRight),
        0xff54 => Some(KeyCode::ArrowDown),
        0xff50 => Some(KeyCode::Home),
        0xff57 => Some(KeyCode::End),
        0xffff => Some(KeyCode::Delete),
        _ => None,
    };
    if let Some(code) = code {
        return Some(Event::Key {
            code,
            state,
            modifiers,
        });
    }
    if state != ButtonState::Pressed {
        return None;
    }
    // Latin-1 keysyms map directly to codepoints; the Unicode plane is
    // 0x0100_0000 | codepoint.
    let cp = if (0x20..=0x7e).contains(&ks) || (0xa0..=0xff).contains(&ks) {
        ks
    } else if ks & 0xff00_0000 == 0x0100_0000 {
        ks & 0x00ff_ffff
    } else {
        return None;
    };
    let c = char::from_u32(cp)?;
    // With Ctrl/Meta held, a printable key is a shortcut (Ctrl+C, Ctrl+V, …),
    // not text input — deliver it as a `Key` so the app can map it.
    if modifiers.ctrl || modifiers.meta {
        return Some(Event::Key {
            code: KeyCode::Char(c),
            state,
            modifiers,
        });
    }
    Some(Event::Text(c.to_string()))
}

/// The XID of the window an event belongs to, read from the per-event-type
/// offset (Expose/ClientMessage at 4, ConfigureNotify's window at 8, input
/// events' event-window at 12). 0 for events that don't name a window.
fn event_window(buf: &[u8; 32]) -> u32 {
    match buf[0] & 0x7f {
        X_EXPOSE | X_CLIENT_MESSAGE => rd_u32(buf, 4).unwrap_or(0),
        X_CONFIGURE_NOTIFY => rd_u32(buf, 8).unwrap_or(0),
        X_MOTION_NOTIFY | X_BUTTON_PRESS | X_BUTTON_RELEASE | X_KEY_PRESS | X_KEY_RELEASE => {
            rd_u32(buf, 12).unwrap_or(0)
        }
        _ => 0,
    }
}

fn event_xy(buf: &[u8; 32]) -> (f64, f64) {
    // event-x / event-y are i16 at offsets 24 / 26 for pointer events.
    let x = i16::from_le_bytes([buf[24], buf[25]]) as f64;
    let y = i16::from_le_bytes([buf[26], buf[27]]) as f64;
    (x, y)
}

fn intern_atom(conn: &mut Conn, name: &[u8]) -> io::Result<u32> {
    let mut req = vec![OP_INTERN_ATOM, 0 /* only-if-exists = false */, 0, 0];
    req.extend_from_slice(&(name.len() as u16).to_le_bytes());
    req.extend_from_slice(&0u16.to_le_bytes()); // pad
    req.extend_from_slice(name);
    pad4(&mut req);
    conn.send(&finish(req))?;
    // InternAtom reply: 32-byte header; atom at offset 8.
    let mut reply = [0u8; 32];
    conn.stream.read_exact(&mut reply)?;
    Ok(rd_u32(&reply, 8).unwrap_or(0))
}

fn set_property_str(
    conn: &mut Conn,
    window: u32,
    prop: u32,
    ty: u32,
    val: &[u8],
) -> io::Result<()> {
    let mut req = vec![OP_CHANGE_PROPERTY, 0 /* Replace */, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&prop.to_le_bytes());
    req.extend_from_slice(&ty.to_le_bytes());
    req.push(8); // format
    req.extend_from_slice(&[0, 0, 0]); // pad
    req.extend_from_slice(&(val.len() as u32).to_le_bytes());
    req.extend_from_slice(val);
    pad4(&mut req);
    conn.send(&finish(req))
}

fn set_property_atoms(conn: &mut Conn, window: u32, prop: u32, atoms: &[u32]) -> io::Result<()> {
    let mut req = vec![OP_CHANGE_PROPERTY, 0, 0, 0];
    req.extend_from_slice(&window.to_le_bytes());
    req.extend_from_slice(&prop.to_le_bytes());
    req.extend_from_slice(&ATOM_ATOM.to_le_bytes()); // type ATOM
    req.push(32); // format
    req.extend_from_slice(&[0, 0, 0]);
    req.extend_from_slice(&(atoms.len() as u32).to_le_bytes());
    for a in atoms {
        req.extend_from_slice(&a.to_le_bytes());
    }
    conn.send(&finish(req))
}

/// Answer a `SelectionRequest`: fill the requestor's property with our clipboard
/// text (or the supported target list) and send back a `SelectionNotify`.
fn serve_selection_request(conn: &mut Conn, ev: &[u8; 32]) -> io::Result<()> {
    // SelectionRequest event fields: time@4, owner@8, requestor@12,
    // selection@16, target@20, property@24.
    let time = rd_u32(ev, 4).unwrap_or(0);
    let requestor = rd_u32(ev, 12).unwrap_or(0);
    let selection = rd_u32(ev, 16).unwrap_or(0);
    let target = rd_u32(ev, 20).unwrap_or(0);
    // An obsolete requestor may send property=None; reply into the target atom.
    let mut property = rd_u32(ev, 24).unwrap_or(0);
    if property == 0 {
        property = target;
    }

    // Only the CLIPBOARD selection is served. Decide whether we can satisfy the
    // requested target; on success the reply carries `property`, else `None`.
    let utf8 = conn.atom_utf8;
    let targets = conn.atom_targets;
    let satisfied = if selection != conn.atom_clipboard {
        false
    } else if target == targets {
        // Advertise the targets we support, as a list of ATOMs.
        let list = [targets, utf8, ATOM_STRING];
        set_property_atoms(conn, requestor, property, &list).is_ok()
    } else if target == utf8 || target == ATOM_STRING {
        let text = conn.clipboard_text.clone();
        set_property_str(conn, requestor, property, target, text.as_bytes()).is_ok()
    } else {
        false
    };
    let reply_prop = if satisfied { property } else { 0 };

    // Build a SelectionNotify event (type 31) and SendEvent it to the requestor.
    let mut notify = [0u8; 32];
    notify[0] = 31; // SelectionNotify
    notify[4..8].copy_from_slice(&time.to_le_bytes());
    notify[8..12].copy_from_slice(&requestor.to_le_bytes());
    notify[12..16].copy_from_slice(&selection.to_le_bytes());
    notify[16..20].copy_from_slice(&target.to_le_bytes());
    notify[20..24].copy_from_slice(&reply_prop.to_le_bytes());

    let mut req = vec![OP_SEND_EVENT, 0 /* propagate = false */, 0, 0];
    req.extend_from_slice(&requestor.to_le_bytes()); // destination
    req.extend_from_slice(&0u32.to_le_bytes()); // event-mask: deliver to creator
    req.extend_from_slice(&notify);
    conn.send(&finish(req))
}

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

    #[test]
    fn dri3_open_request_is_well_formed() {
        // DRI3Open: major opcode, minor 1, length 3 words, drawable, provider 0.
        let req = dri3_open_request(0x90, 0x0012_3456);
        assert_eq!(req[0], 0x90);
        assert_eq!(req[1], DRI3_OPEN);
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 3);
        assert_eq!(rd_u32(&req, 4).unwrap(), 0x0012_3456);
        assert_eq!(rd_u32(&req, 8).unwrap(), 0);
        assert_eq!(req.len(), 12);
    }

    #[test]
    fn pixmap_from_buffers_request_is_well_formed() {
        // A single-plane ARGB8888 4096×2160 buffer with a tiled modifier.
        let img = DmabufImage {
            width: 4096,
            height: 2160,
            depth: 24,
            bpp: 32,
            modifier: 0x0100_0000_0000_0001, // an arbitrary 64-bit DRM modifier
            planes: vec![(16384, 0)],
        };
        let req = pixmap_from_buffers_request(0x90, 0x0040_0000, 0x0020_0001, &img);
        assert_eq!(req[0], 0x90);
        assert_eq!(req[1], DRI3_PIXMAP_FROM_BUFFERS);
        // Fixed wire size: header(4) + pixmap(4) + window(4) + num/pad/w/h(8)
        // + 8 plane words(32) + depth/bpp/pad(4) + modifier(8) = 64 bytes / 16 words.
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 16);
        assert_eq!(req.len(), 64);
        assert_eq!(rd_u32(&req, 4).unwrap(), 0x0040_0000); // pixmap
        assert_eq!(rd_u32(&req, 8).unwrap(), 0x0020_0001); // window
        assert_eq!(req[12], 1); // num_buffers
        assert_eq!(u16::from_le_bytes([req[16], req[17]]), 4096); // width
        assert_eq!(u16::from_le_bytes([req[18], req[19]]), 2160); // height
        assert_eq!(rd_u32(&req, 20).unwrap(), 16384); // stride0
        assert_eq!(rd_u32(&req, 24).unwrap(), 0); // offset0
        // Planes 1..3 are zero-filled (stride1@28 .. offset3@48).
        assert_eq!(rd_u32(&req, 28).unwrap(), 0);
        assert_eq!(rd_u32(&req, 48).unwrap(), 0);
        assert_eq!(req[52], 24); // depth
        assert_eq!(req[53], 32); // bpp
        // Modifier is the last 8 bytes (little-endian u64).
        let modifier = u64::from_le_bytes(req[56..64].try_into().unwrap());
        assert_eq!(modifier, 0x0100_0000_0000_0001);
    }

    #[test]
    fn present_pixmap_request_is_well_formed() {
        // wait_fence 0x0060_0002 exercises the frame-sync slot.
        let req = present_pixmap_request(0x91, 0x0020_0001, 0x0040_0000, 0x0060_0002, 7, 0);
        assert_eq!(req[0], 0x91);
        assert_eq!(req[1], PRESENT_PIXMAP);
        // 4-byte header + window+pixmap+serial+valid+update (5 words) + off word
        // + crtc+wait+idle+options+unused (5 words) + msc/divisor/remainder
        // (6 words) = 18 words.
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 18);
        assert_eq!(req.len(), 72);
        assert_eq!(rd_u32(&req, 4).unwrap(), 0x0020_0001); // window
        assert_eq!(rd_u32(&req, 8).unwrap(), 0x0040_0000); // pixmap
        assert_eq!(rd_u32(&req, 12).unwrap(), 7); // serial
        assert_eq!(rd_u32(&req, 16).unwrap(), 0); // valid region (None)
        assert_eq!(rd_u32(&req, 20).unwrap(), 0); // update region (None)
        // crtc@28, wait-fence@32 (the frame-sync fence), idle-fence@36.
        assert_eq!(rd_u32(&req, 28).unwrap(), 0); // target CRTC (None)
        assert_eq!(rd_u32(&req, 32).unwrap(), 0x0060_0002); // wait fence
        assert_eq!(rd_u32(&req, 36).unwrap(), 0); // idle fence (None)
        // target-msc/divisor/remainder are the final three zero u64s.
        assert_eq!(u64::from_le_bytes(req[48..56].try_into().unwrap()), 0);
        assert_eq!(u64::from_le_bytes(req[64..72].try_into().unwrap()), 0);
    }

    #[test]
    fn dri3_fence_from_fd_request_is_well_formed() {
        let req = dri3_fence_from_fd_request(0x90, 0x0020_0001, 0x0060_0002, true);
        assert_eq!(req[0], 0x90);
        assert_eq!(req[1], DRI3_FENCE_FROM_FD);
        // header(4) + drawable(4) + fence(4) + triggered/pad(4) = 16 bytes / 4 words.
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 4);
        assert_eq!(req.len(), 16);
        assert_eq!(rd_u32(&req, 4).unwrap(), 0x0020_0001); // drawable
        assert_eq!(rd_u32(&req, 8).unwrap(), 0x0060_0002); // fence
        assert_eq!(req[12], 1); // initially_triggered
    }

    #[test]
    fn selection_notify_send_event_is_well_formed() {
        // A SendEvent carrying a SelectionNotify is 44 bytes (11 words): 12-byte
        // header (opcode, propagate, length, destination, mask) + 32-byte event.
        let mut conn_ev = [0u8; 32];
        conn_ev[0] = X_SELECTION_REQUEST;
        conn_ev[12..16].copy_from_slice(&0xCAFEu32.to_le_bytes()); // requestor@12
        // (No live socket here; just assert the encoder shape via a hand build.)
        let requestor = rd_u32(&conn_ev, 12).unwrap();
        let mut notify = [0u8; 32];
        notify[0] = 31;
        let mut req = vec![OP_SEND_EVENT, 0, 0, 0];
        req.extend_from_slice(&requestor.to_le_bytes());
        req.extend_from_slice(&0u32.to_le_bytes());
        req.extend_from_slice(&notify);
        let req = finish(req);
        assert_eq!(req[0], OP_SEND_EVENT);
        assert_eq!(req.len(), 44);
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 11); // length in words
        assert_eq!(rd_u32(&req, 4).unwrap(), 0xCAFE); // destination
    }

    #[test]
    fn parses_display_forms() {
        assert_eq!(
            parse_display(":0"),
            Some(DisplayAddr {
                number: 0,
                screen: 0
            })
        );
        assert_eq!(
            parse_display(":1.2"),
            Some(DisplayAddr {
                number: 1,
                screen: 2
            })
        );
        assert_eq!(
            parse_display("host:3"),
            Some(DisplayAddr {
                number: 3,
                screen: 0
            })
        );
        assert_eq!(parse_display("garbage"), None);
    }

    #[test]
    fn rgba_to_bgrx_swizzles() {
        let mut out = Vec::new();
        rgba_to_bgrx(&[10, 20, 30, 255, 1, 2, 3, 128], &mut out);
        assert_eq!(out, vec![30, 20, 10, 0, 3, 2, 1, 0]);
    }

    #[test]
    fn parse_setup_reads_screen_fields() {
        // Build a minimal additional-data buffer: 32-byte fixed block, no
        // vendor, one pixmap format (8 bytes), then a screen — matching the
        // X11 connection-setup reply layout.
        let mut d = vec![0u8; 32];
        d[4..8].copy_from_slice(&0x0040_0000u32.to_le_bytes()); // resource-id-base
        d[8..12].copy_from_slice(&0x001f_ffffu32.to_le_bytes()); // resource-id-mask
        d[16..18].copy_from_slice(&0u16.to_le_bytes()); // vendor-length
        d[18..20].copy_from_slice(&65535u16.to_le_bytes()); // max-request-length
        d[21] = 1; // number-of-formats
        d.extend_from_slice(&[0u8; 8]); // one pixmap format
        // Screen: root at +0, root-visual at +32, root-depth at +38.
        let mut screen = vec![0u8; 40];
        screen[0..4].copy_from_slice(&0x0000_0123u32.to_le_bytes()); // root
        screen[32..36].copy_from_slice(&0x0000_0021u32.to_le_bytes()); // root-visual
        screen[38] = 24; // root-depth
        d.extend_from_slice(&screen);

        let s = parse_setup(&d).expect("parse");
        assert_eq!(s.resource_id_base, 0x0040_0000);
        assert_eq!(s.resource_id_mask, 0x001f_ffff);
        assert_eq!(s.root, 0x0000_0123);
        assert_eq!(s.root_visual, 0x0000_0021);
        assert_eq!(s.root_depth, 24);
        assert_eq!(s.max_request_len, 65535);
    }

    #[test]
    fn parse_xauth_finds_cookie() {
        // family(2) addrlen(2)=1 addr("a") numlen(2)=1 num("0")
        // namelen(2)=18 name("MIT-MAGIC-COOKIE-1") datalen(2)=4 data(DE AD BE EF)
        let mut e = Vec::new();
        e.extend_from_slice(&0u16.to_be_bytes());
        e.extend_from_slice(&1u16.to_be_bytes());
        e.push(b'a');
        e.extend_from_slice(&1u16.to_be_bytes());
        e.push(b'0');
        e.extend_from_slice(&18u16.to_be_bytes());
        e.extend_from_slice(b"MIT-MAGIC-COOKIE-1");
        e.extend_from_slice(&4u16.to_be_bytes());
        e.extend_from_slice(&[0xDE, 0xAD, 0xBE, 0xEF]);
        assert_eq!(parse_xauth_cookie(&e), Some(vec![0xDE, 0xAD, 0xBE, 0xEF]));
        assert_eq!(parse_xauth_cookie(&[]), None);
    }

    #[test]
    fn finish_sets_length_in_words() {
        let req = finish(vec![1, 0, 0, 0, 0, 0, 0, 0]); // 8 bytes = 2 words
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 2);
    }

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

    #[test]
    fn shm_put_image_encodes_fields() {
        // major=130, draw=0xaa, gc=0xbb, seg=0xcc, total 200x100, rect (8,16,4,2).
        let req = finish(shm_put_image(130, 0xaa, 0xbb, 0xcc, 200, 100, 8, 16, 4, 2));
        assert_eq!(req[0], 130); // major opcode
        assert_eq!(req[1], SHM_PUT_IMAGE); // minor opcode
        assert_eq!(u16::from_le_bytes([req[2], req[3]]), 10); // length in words
        assert_eq!(rd_u32(&req, 4), Some(0xaa)); // drawable
        assert_eq!(rd_u32(&req, 8), Some(0xbb)); // gc
        assert_eq!(u16::from_le_bytes([req[12], req[13]]), 200); // total-width
        assert_eq!(u16::from_le_bytes([req[14], req[15]]), 100); // total-height
        assert_eq!(u16::from_le_bytes([req[16], req[17]]), 8); // src-x
        assert_eq!(u16::from_le_bytes([req[18], req[19]]), 16); // src-y
        assert_eq!(u16::from_le_bytes([req[20], req[21]]), 4); // src-width
        assert_eq!(u16::from_le_bytes([req[22], req[23]]), 2); // src-height
        assert_eq!(i16::from_le_bytes([req[24], req[25]]), 8); // dst-x
        assert_eq!(i16::from_le_bytes([req[26], req[27]]), 16); // dst-y
        assert_eq!(req[28], 24); // depth
        assert_eq!(req[29], 2); // ZPixmap
        assert_eq!(req[30], 0); // send-event
        assert_eq!(rd_u32(&req, 32), Some(0xcc)); // shmseg
        assert_eq!(rd_u32(&req, 36), Some(0)); // offset
    }
}