hjkl-clipboard 0.40.0

Cross-platform clipboard library with rich types, async support, and OSC 52 fallback for SSH
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
//! Wayland clipboard bg thread — data-control bind, set, clear, get, available,
//! and PRIMARY selection support.
//!
//! Phase 6c extends 6b with:
//!  - Read path: track data_control_offer events, issue offer.receive(mime, fd)
//!    and read from the pipe until EOF.
//!  - Available: inspect current offer's advertised MIME types.
//!  - PRIMARY: bind zwp_primary_selection_device_manager_v1 (optional; absent on
//!    compositors that don't support it, e.g. older sway).
//!
//! No libwayland-client — all wire protocol is hand-rolled via wayland_wire.rs
//! and wayland_socket.rs from phase 6a.
//!
//! Event loop: poll(2) on the socket fd (50 ms timeout) + non-blocking drain of
//! the mpsc inbox each iteration. Same latency trade-off as x11_thread.rs.

use std::collections::HashMap;
use std::ffi::c_int;
use std::sync::{Arc, Condvar, Mutex, OnceLock, mpsc};
use std::time::{Duration, Instant};

use crate::{ClipboardError, MimeType, Selection};

use super::wayland::WaylandConnection;
use super::wayland_socket::WaylandSocket;
use super::wayland_wire::{encode_message, encode_string, encode_u32, parse_string, parse_u32};

// ---------------------------------------------------------------------------
// Wayland object IDs — well-known (from open()) and client-allocated.
// ---------------------------------------------------------------------------

// Reserved by protocol / phase 6a connection open.
const WL_DISPLAY_ID: u32 = 1;
// const WL_REGISTRY_ID: u32 = 2;  // used during open()
// const WL_CALLBACK_ID: u32 = 3;  // used during open()

// Client allocations start at 4: 1 (display), 2 (registry), 3 (callback)
// are consumed during open(). Some compositors (sway/wlroots) reject bind
// requests with new_ids far above the contiguous client range with
// "invalid arguments" — libwayland-client itself allocates from 4
// monotonically, so we match that.
const FIRST_CLIENT_ID: u32 = 4;

// ---------------------------------------------------------------------------
// ext_data_control_v1 interface names
// ---------------------------------------------------------------------------

const EXT_DATA_CONTROL_MANAGER: &str = "ext_data_control_manager_v1";
const WL_SEAT: &str = "wl_seat";

// zwp_primary_selection_device_manager_v1 interface name (optional).
const ZWP_PRIMARY_SEL_MANAGER: &str = "zwp_primary_selection_device_manager_v1";

// ---------------------------------------------------------------------------
// Wayland opcodes (request side — what WE send)
// ---------------------------------------------------------------------------

// wl_display
const WL_DISPLAY_SYNC: u16 = 0;
// WL_DISPLAY_GET_REGISTRY sent during connection open (wayland.rs), not re-sent here.
#[allow(dead_code)]
const WL_DISPLAY_GET_REGISTRY: u16 = 1;

// wl_registry
const WL_REGISTRY_BIND: u16 = 0;

// ext_data_control_manager_v1 requests
const EXT_MANAGER_CREATE_DATA_SOURCE: u16 = 0;
const EXT_MANAGER_GET_DATA_DEVICE: u16 = 1;

// ext_data_control_device_v1 requests
const EXT_DEVICE_SET_SELECTION: u16 = 0;
// PRIMARY selection via ext_data_control uses the zwp protocol path instead.
#[allow(dead_code)]
const EXT_DEVICE_SET_PRIMARY_SELECTION: u16 = 2;

// ext_data_control_source_v1 requests
const EXT_SOURCE_OFFER: u16 = 0;
const EXT_SOURCE_DESTROY: u16 = 1;

// ext_data_control_offer_v1 requests
const EXT_OFFER_RECEIVE: u16 = 0;
const EXT_OFFER_DESTROY: u16 = 1;

// zwp_primary_selection_device_manager_v1 requests
const ZWP_PRIMARY_MANAGER_CREATE_SOURCE: u16 = 0;
const ZWP_PRIMARY_MANAGER_GET_DEVICE: u16 = 1;

// zwp_primary_selection_device_v1 requests
const ZWP_PRIMARY_DEVICE_SET_SELECTION: u16 = 0;

// zwp_primary_selection_source_v1 requests
const ZWP_PRIMARY_SOURCE_OFFER: u16 = 0;
const ZWP_PRIMARY_SOURCE_DESTROY: u16 = 1;

// zwp_primary_selection_offer_v1 requests
const ZWP_PRIMARY_OFFER_RECEIVE: u16 = 0;
const ZWP_PRIMARY_OFFER_DESTROY: u16 = 1;

// ---------------------------------------------------------------------------
// Wayland event opcodes (what WE receive)
// ---------------------------------------------------------------------------

// wl_display events
const WL_DISPLAY_ERROR: u16 = 0;
const WL_DISPLAY_DELETE_ID: u16 = 1;

// wl_registry events
// const WL_REGISTRY_GLOBAL: u16 = 0; // handled in open()

// wl_callback events
const WL_CALLBACK_DONE: u16 = 0;

// ext_data_control_source_v1 events
const EXT_SOURCE_SEND: u16 = 0;
const EXT_SOURCE_CANCELLED: u16 = 1;

// ext_data_control_offer_v1 events
const EXT_OFFER_OFFER: u16 = 0; // offer.offer(mime_type: string)

// ext_data_control_device_v1 events
const EXT_DEVICE_DATA_OFFER: u16 = 0; // new offer object introduced
const EXT_DEVICE_SELECTION: u16 = 1; // offer made current for CLIPBOARD
const EXT_DEVICE_FINISHED: u16 = 2;
const EXT_DEVICE_PRIMARY_SELECTION: u16 = 3; // offer made current for PRIMARY

// zwp_primary_selection_source_v1 events
const ZWP_PRIMARY_SOURCE_SEND: u16 = 0;
const ZWP_PRIMARY_SOURCE_CANCELLED: u16 = 1;

// zwp_primary_selection_offer_v1 events
// offer.offer events from zwp offers routed via EXT_OFFER_OFFER opcode (same value).
#[allow(dead_code)]
const ZWP_PRIMARY_OFFER_OFFER: u16 = 0;

// zwp_primary_selection_device_v1 events
const ZWP_PRIMARY_DEVICE_DATA_OFFER: u16 = 0;
const ZWP_PRIMARY_DEVICE_SELECTION: u16 = 1;

// ---------------------------------------------------------------------------
// MIME type strings for ext_data_control_source
// ---------------------------------------------------------------------------

/// MIME types we advertise for MimeType::Text.
const TEXT_MIME_TYPES: &[&str] = &[
    "text/plain;charset=utf-8",
    "text/plain",
    "UTF8_STRING",
    "STRING",
];

/// MIME types we advertise for MimeType::Html.
const HTML_MIME_TYPES: &[&str] = &["text/html"];

/// MIME types we advertise for MimeType::Rtf.
const RTF_MIME_TYPES: &[&str] = &["text/rtf", "application/rtf"];

/// MIME types we advertise for MimeType::UriList.
const URI_LIST_MIME_TYPES: &[&str] = &["text/uri-list"];

/// MIME types we advertise for MimeType::Png.
const PNG_MIME_TYPES: &[&str] = &["image/png"];

fn mimes_for(mime: &MimeType) -> &'static [&'static str] {
    match mime {
        MimeType::Text => TEXT_MIME_TYPES,
        MimeType::Html => HTML_MIME_TYPES,
        MimeType::Rtf => RTF_MIME_TYPES,
        MimeType::UriList => URI_LIST_MIME_TYPES,
        MimeType::Png => PNG_MIME_TYPES,
        MimeType::Custom(_) => &[], // handled separately
    }
}

// ---------------------------------------------------------------------------
// Op / Request types
// ---------------------------------------------------------------------------

pub enum WaylandOp {
    Set {
        sel: Selection,
        mime: MimeType,
        bytes: Vec<u8>,
    },
    Clear {
        sel: Selection,
    },
    Get {
        sel: Selection,
        mime: MimeType,
    },
    Available {
        sel: Selection,
    },
}

pub enum WaylandOpResult {
    Set(Result<(), ClipboardError>),
    Clear(Result<(), ClipboardError>),
    Get(Result<Vec<u8>, ClipboardError>),
    Available(Result<Vec<MimeType>, ClipboardError>),
}

pub struct WaylandRequest {
    pub op: WaylandOp,
    pub reply: crate::reply::Reply<WaylandOpResult>,
}

// ---------------------------------------------------------------------------
// WaylandFuture — wraps Oneshot<WaylandOpResult> as a Future
// ---------------------------------------------------------------------------

/// Future returned by [`WaylandThread::send_async`].
pub struct WaylandFuture {
    oneshot: Arc<crate::oneshot::Oneshot<WaylandOpResult>>,
}

impl std::future::Future for WaylandFuture {
    type Output = WaylandOpResult;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        self.oneshot.poll(cx)
    }
}

// ---------------------------------------------------------------------------
// WaylandThread public handle
// ---------------------------------------------------------------------------

pub struct WaylandThread {
    tx: mpsc::Sender<WaylandRequest>,
}

impl WaylandThread {
    fn new() -> Result<Self, ClipboardError> {
        // Open connection and probe globals on the calling thread so we can
        // return ClipboardError immediately on failure.
        let conn = WaylandConnection::open()?;

        // Check for required globals before handing off to the thread.
        if conn.find_global(EXT_DATA_CONTROL_MANAGER).is_none() {
            // GNOME case: no data-control protocol available.
            // 6c will wire OSC52 fallback here.
            return Err(ClipboardError::FocusRequired);
        }
        if conn.find_global(WL_SEAT).is_none() {
            return Err(ClipboardError::FocusRequired);
        }

        let (tx, rx) = mpsc::channel::<WaylandRequest>();

        std::thread::Builder::new()
            .name("hjkl-clipboard-wayland".into())
            .spawn(move || {
                let mut state = match WaylandState::init(conn) {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("hjkl-clipboard wayland thread: init failed: {e}");
                        // Keep serving the inbox with errors so callers that
                        // already enqueued (or will enqueue) requests get an
                        // error instead of hanging on a never-resolved reply.
                        serve_inbox_with_errors(rx);
                        return;
                    }
                };
                run_loop(&mut state, rx);
            })
            .expect("failed to spawn Wayland bg thread");

        Ok(Self { tx })
    }

    /// Enqueue an op and return a `Future` that resolves when the bg thread replies.
    pub(crate) fn send_async(&self, op: WaylandOp) -> WaylandFuture {
        let oneshot = crate::oneshot::Oneshot::new();
        let reply = crate::reply::Reply::Async(Arc::clone(&oneshot));

        if let Err(mpsc::SendError(req)) = self.tx.send(WaylandRequest { op, reply }) {
            // Bg thread is gone (compositor connection lost) — resolve the
            // future with an error instead of panicking the caller.
            fail_request(req);
        }

        WaylandFuture { oneshot }
    }

    /// Send an op and block until the bg thread replies.
    pub(crate) fn send_sync(&self, op: WaylandOp) -> Result<WaylandOpResult, ClipboardError> {
        let pair = Arc::new((Mutex::new(None::<WaylandOpResult>), Condvar::new()));
        let reply = crate::reply::Reply::Sync(Arc::clone(&pair));

        self.tx
            .send(WaylandRequest { op, reply })
            .map_err(|_| ClipboardError::io_other("wayland thread inbox closed"))?;

        let (lock, cvar) = &*pair;
        let mut guard = lock.lock().unwrap();
        while guard.is_none() {
            guard = cvar.wait(guard).unwrap();
        }
        Ok(guard.take().unwrap())
    }
}

// ---------------------------------------------------------------------------
// Singleton accessor
// ---------------------------------------------------------------------------

// ClipboardError is Clone so we can store the typed error directly.
// Preserves FocusRequired/LibNotFound/NoDisplay across calls so
// Clipboard::new() fallthrough logic sees the correct variant every time.
static WAYLAND_THREAD: OnceLock<Result<WaylandThread, ClipboardError>> = OnceLock::new();

/// Return the process-global Wayland thread, or an error if unavailable.
pub fn wayland_thread() -> Result<&'static WaylandThread, ClipboardError> {
    WAYLAND_THREAD
        .get_or_init(WaylandThread::new)
        .as_ref()
        .map_err(ClipboardError::clone)
}

// ---------------------------------------------------------------------------
// Per-source state tracked by the thread
// ---------------------------------------------------------------------------

struct OwnedSource {
    /// The client-side object id allocated for this source.
    id: u32,
    /// Payloads keyed by MIME type string.
    payloads: HashMap<String, Vec<u8>>,
    /// All advertised MIME type strings (including aliases). Recorded for
    /// future diagnostics; not read in v0.4.0 production paths.
    #[allow(dead_code)]
    offered_mimes: Vec<String>,
}

// ---------------------------------------------------------------------------
// Non-blocking write state — queued when O_NONBLOCK write returns EAGAIN
// ---------------------------------------------------------------------------

/// A pipe-write operation that could not complete in one shot because the
/// pipe buffer was full.  Kept in `WaylandState::pending_writes` and drained
/// on subsequent `poll(2)` iterations when the fd reports POLLOUT.
struct PendingWrite {
    /// Write end of the pipe received via SCM_RIGHTS.
    fd: c_int,
    /// Full payload to be written.
    payload: Vec<u8>,
    /// Bytes already written into the pipe.
    written: usize,
    /// Absolute time after which we give up and close the fd.
    deadline: Instant,
}

// ---------------------------------------------------------------------------
// Offer tracking for the read path
// ---------------------------------------------------------------------------

/// Data about a data_control_offer or primary_selection_offer we received.
struct OfferData {
    /// The compositor-assigned object id for this offer.
    id: u32,
    /// MIME types advertised by offer.offer(mime) events.
    mimes: Vec<String>,
}

// ---------------------------------------------------------------------------
// Thread-internal state
// ---------------------------------------------------------------------------

struct WaylandState {
    socket: WaylandSocket,
    /// Monotonically increasing id allocator (starts at FIRST_CLIENT_ID after
    /// startup objects were allocated).
    next_id: u32,
    /// Server-side global id (name) for the seat. Retained for reconnect in v0.5.
    #[allow(dead_code)]
    seat_name: u32,
    /// Our bound seat object id. Retained for reconnect in v0.5.
    #[allow(dead_code)]
    seat_id: u32,
    /// Server-side global id (name) for the data-control manager. Retained for reconnect.
    #[allow(dead_code)]
    manager_name: u32,
    /// Our bound manager object id.
    manager_id: u32,
    /// Our data-control device object id.
    device_id: u32,
    /// Sync callback object id — used during init; retained for protocol bookkeeping.
    #[allow(dead_code)]
    sync_id: u32,
    /// Currently owned clipboard source, if any.
    clipboard_source: Option<OwnedSource>,
    /// Currently owned PRIMARY source, if any.
    primary_source: Option<OwnedSource>,
    /// Offers introduced by device.data_offer() but not yet made current.
    /// Keyed by the compositor-assigned offer object id.
    pending_offers: HashMap<u32, OfferData>,
    /// Current clipboard offer (from device.selection()).
    current_clipboard_offer: Option<OfferData>,
    /// Current PRIMARY offer (from device.primary_selection()).
    current_primary_offer: Option<OfferData>,
    /// Object id of the PRIMARY selection device, or 0 if not bound.
    primary_device_id: u32,
    /// Object id of the PRIMARY selection manager, or 0 if not bound.
    primary_manager_id: u32,
    /// Set of object ids we know are data_control_offer objects (for routing
    /// offer.offer(mime) events).
    offer_ids: HashMap<u32, bool>, // id -> is_primary
    /// Pipe writes that could not be completed in one shot (EAGAIN on O_NONBLOCK
    /// fd).  Drained by the main event loop via POLLOUT on each fd.
    pending_writes: Vec<PendingWrite>,
    /// Set when the compositor sends `wl_display.error`. That error is fatal
    /// per the wayland protocol — the connection is unusable afterwards — so
    /// the main loop exits (and serves the inbox with errors) instead of
    /// spinning on a dead socket.
    fatal_error: bool,
}

impl WaylandState {
    fn alloc_id(&mut self) -> u32 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }
}

// ---------------------------------------------------------------------------
// State initialisation (bind globals, create device)
// ---------------------------------------------------------------------------

fn init_bind(
    socket: &mut WaylandSocket,
    next_id: &mut u32,
    seat_name: u32,
    seat_version: u32,
    manager_name: u32,
) -> Result<(u32, u32, u32, u32), ClipboardError> {
    // Allocate IDs for: registry, sync, seat, manager, device.
    // We re-do registry + sync to get a fresh view during bind.
    // Re-use the object ids allocated in open() for registry(2)/callback(3)
    // but we need NEW ids for seat/manager/device which are post-open.
    let registry_id: u32 = 2; // same as open()

    // Allocate IDs one at a time, sequentially, in send order — so the
    // sequence on the wire is monotonically increasing without gaps.
    let seat_id = *next_id;
    *next_id += 1;

    // Step 1: bind wl_seat, sync, drain — isolates seat-bind failures.
    let seat_ver = seat_version.min(7);
    send_registry_bind(socket, registry_id, seat_name, WL_SEAT, seat_ver, seat_id)?;
    sync_or_die(socket, next_id, "after wl_seat bind")?;

    // Step 2: bind ext_data_control_manager_v1, sync, drain.
    let manager_id = *next_id;
    *next_id += 1;
    send_registry_bind(
        socket,
        registry_id,
        manager_name,
        EXT_DATA_CONTROL_MANAGER,
        1,
        manager_id,
    )?;
    sync_or_die(socket, next_id, "after ext_data_control_manager_v1 bind")?;

    // Step 3: manager.get_data_device(new_id, seat), sync, drain.
    let device_id = *next_id;
    *next_id += 1;
    {
        let mut args = Vec::new();
        encode_u32(&mut args, device_id);
        encode_u32(&mut args, seat_id);
        let msg = encode_message(manager_id, EXT_MANAGER_GET_DATA_DEVICE, &args);
        socket.send(&msg, &[])?;
    }
    let sync_id = sync_or_die(socket, next_id, "after manager.get_data_device")?;

    Ok((seat_id, manager_id, device_id, sync_id))
}

/// Allocate a fresh sync id, send `wl_display.sync(sync_id)`, drain until the
/// callback fires. Returns the sync id (last one used). `phase` is appended to
/// any wl_display.error message so the caller can identify which step failed.
fn sync_or_die(
    socket: &mut WaylandSocket,
    next_id: &mut u32,
    phase: &str,
) -> Result<u32, ClipboardError> {
    let sync_id = *next_id;
    *next_id += 1;
    let mut args = Vec::new();
    encode_u32(&mut args, sync_id);
    let msg = encode_message(WL_DISPLAY_ID, WL_DISPLAY_SYNC, &args);
    socket.send(&msg, &[])?;
    drain_until_sync_phased(socket, sync_id, phase)?;
    Ok(sync_id)
}

/// Like `drain_until_sync` but appends `phase` to any wl_display.error message.
fn drain_until_sync_phased(
    socket: &mut WaylandSocket,
    sync_id: u32,
    phase: &str,
) -> Result<(), ClipboardError> {
    for _ in 0..4096 {
        socket.recv(true)?;
        while let Some((hdr, args)) = socket.next_message() {
            if hdr.object_id == sync_id && hdr.opcode == WL_CALLBACK_DONE {
                return Ok(());
            }
            if hdr.object_id == WL_DISPLAY_ID && hdr.opcode == WL_DISPLAY_ERROR {
                let msg = parse_display_error(&args);
                return Err(ClipboardError::io_other(&format!(
                    "wl_display.error {phase}: {msg}"
                )));
            }
        }
    }
    Err(ClipboardError::io_other(&format!(
        "timed out waiting for bind sync callback ({phase})"
    )))
}

/// Send wl_registry.bind for a global (typeless new_id form).
///
/// Wire format for bind with typeless new_id (libwayland convention):
///   name:u32 + interface:string + version:u32 + new_id:u32
fn send_registry_bind(
    socket: &mut WaylandSocket,
    registry_id: u32,
    name: u32,
    interface: &str,
    version: u32,
    new_id: u32,
) -> Result<(), ClipboardError> {
    let mut args = Vec::new();
    encode_u32(&mut args, name);
    encode_string(&mut args, interface);
    encode_u32(&mut args, version);
    encode_u32(&mut args, new_id);
    let msg = encode_message(registry_id, WL_REGISTRY_BIND, &args);
    socket.send(&msg, &[])
}

/// Extract a human-readable description from `wl_display.error` args.
/// Args layout: object_id(u32) + code(u32) + message(string).
fn parse_display_error(args: &[u8]) -> String {
    let Some((obj_id, rest)) = parse_u32(args) else {
        return "(malformed error event)".to_owned();
    };
    let Some((code, rest)) = parse_u32(rest) else {
        return format!("object={obj_id} (malformed code)");
    };
    let msg = if let Some((s, _)) = parse_string(rest) {
        s.to_owned()
    } else {
        "(no message)".to_owned()
    };
    format!("object={obj_id} code={code} msg={msg:?}")
}

impl WaylandState {
    fn init(conn: WaylandConnection) -> Result<Self, ClipboardError> {
        // Extract the globals we need before consuming conn.
        let seat_global = conn
            .find_global(WL_SEAT)
            .ok_or(ClipboardError::FocusRequired)?;
        let seat_name = seat_global.name;
        let seat_version = seat_global.version;

        let manager_global = conn
            .find_global(EXT_DATA_CONTROL_MANAGER)
            .ok_or(ClipboardError::FocusRequired)?;
        let manager_name = manager_global.name;

        // Snapshot primary manager global before consuming conn.
        let primary_global = conn.find_global(ZWP_PRIMARY_SEL_MANAGER).cloned();

        // Destructure conn to get the socket and next_id.
        let (mut socket, mut next_id) = conn.into_parts();

        // Start client IDs at FIRST_CLIENT_ID to leave room for protocol objects.
        if next_id < FIRST_CLIENT_ID {
            next_id = FIRST_CLIENT_ID;
        }

        let (seat_id, manager_id, device_id, sync_id) = init_bind(
            &mut socket,
            &mut next_id,
            seat_name,
            seat_version,
            manager_name,
        )?;

        // Optionally bind zwp_primary_selection_device_manager_v1.
        let (primary_manager_id, primary_device_id) =
            if let Some(pm_global) = primary_global.as_ref() {
                let pm_name = pm_global.name;
                let pm_id = next_id;
                next_id += 1;
                let pd_id = next_id;
                next_id += 1;
                send_registry_bind(&mut socket, 2, pm_name, ZWP_PRIMARY_SEL_MANAGER, 1, pm_id)?;
                {
                    // zwp_primary_selection_device_manager.get_device(new_id, seat)
                    let mut args = Vec::new();
                    encode_u32(&mut args, pd_id);
                    encode_u32(&mut args, seat_id);
                    let msg = encode_message(pm_id, ZWP_PRIMARY_MANAGER_GET_DEVICE, &args);
                    socket.send(&msg, &[])?;
                }
                (pm_id, pd_id)
            } else {
                (0, 0)
            };

        Ok(Self {
            socket,
            next_id,
            seat_name,
            seat_id,
            manager_name,
            manager_id,
            device_id,
            sync_id,
            clipboard_source: None,
            primary_source: None,
            pending_offers: HashMap::new(),
            current_clipboard_offer: None,
            current_primary_offer: None,
            primary_device_id,
            primary_manager_id,
            offer_ids: HashMap::new(),
            pending_writes: Vec::new(),
            fatal_error: false,
        })
    }
}

// ---------------------------------------------------------------------------
// Main event loop
// ---------------------------------------------------------------------------

fn run_loop(state: &mut WaylandState, rx: mpsc::Receiver<WaylandRequest>) {
    loop {
        // Build the poll set: Wayland socket (POLLIN) + all pending-write fds
        // (POLLOUT).
        let (socket_readable, writable_fds) = poll_fds(state, 50);

        // Expire any pending writes whose deadline has passed.
        let now = Instant::now();
        state.pending_writes.retain(|pw| {
            if now > pw.deadline {
                // SAFETY: fd is ours (via SCM_RIGHTS); close to avoid leak.
                unsafe { libc::close(pw.fd) };
                false
            } else {
                true
            }
        });

        // Drain writable pending writes.
        if !writable_fds.is_empty() {
            drain_pending_writes(state, &writable_fds);
        }

        if socket_readable {
            // Drain all available compositor events.
            if let Err(e) = state.socket.recv(false) {
                eprintln!("hjkl-clipboard wayland: recv error: {e}");
                break;
            }
            dispatch_events(state);
            // A `wl_display.error` during dispatch is fatal — the connection is
            // dead, so stop looping and fall through to serve the inbox with
            // errors instead of polling a broken socket forever.
            if state.fatal_error {
                break;
            }
        }

        // Drain the inbox (non-blocking).
        loop {
            match rx.recv_timeout(Duration::from_millis(0)) {
                Ok(req) => handle_op(state, req),
                Err(mpsc::RecvTimeoutError::Timeout) => break,
                Err(mpsc::RecvTimeoutError::Disconnected) => return,
            }
        }
    }

    // Compositor connection lost. Keep serving the inbox with errors so
    // callers blocked in send_sync (condvar) or awaiting a future never hang
    // on a request that would otherwise be silently dropped.
    serve_inbox_with_errors(rx);
}

/// Resolve a request with an "inbox closed" error — used when the bg thread
/// can no longer talk to the compositor.
fn fail_request(req: WaylandRequest) {
    let err = || ClipboardError::io_other("wayland thread unavailable");
    let result = match req.op {
        WaylandOp::Set { .. } => WaylandOpResult::Set(Err(err())),
        WaylandOp::Clear { .. } => WaylandOpResult::Clear(Err(err())),
        WaylandOp::Get { .. } => WaylandOpResult::Get(Err(err())),
        WaylandOp::Available { .. } => WaylandOpResult::Available(Err(err())),
    };
    req.reply.resolve(result);
}

/// Answer every remaining/future inbox request with an error. Returns when
/// all senders are gone (process teardown).
fn serve_inbox_with_errors(rx: mpsc::Receiver<WaylandRequest>) {
    while let Ok(req) = rx.recv() {
        fail_request(req);
    }
}

/// Call poll(2) on the Wayland socket plus any pending-write fds.
///
/// Returns `(socket_readable, Vec<fd>)` where `Vec<fd>` is the subset of
/// pending-write fds that are now writable (POLLOUT fired).
fn poll_fds(state: &WaylandState, timeout_ms: i32) -> (bool, Vec<c_int>) {
    // Slot 0 is always the Wayland socket (POLLIN).
    let mut pfds: Vec<libc::pollfd> = Vec::with_capacity(1 + state.pending_writes.len());
    pfds.push(libc::pollfd {
        fd: state.socket.raw_fd(),
        events: libc::POLLIN,
        revents: 0,
    });

    for pw in &state.pending_writes {
        pfds.push(libc::pollfd {
            fd: pw.fd,
            events: libc::POLLOUT,
            revents: 0,
        });
    }

    // SAFETY: pfds is a valid slice; nfds and timeout_ms are valid.
    let ret = unsafe { libc::poll(pfds.as_mut_ptr(), pfds.len() as libc::nfds_t, timeout_ms) };

    if ret <= 0 {
        return (false, vec![]);
    }

    let socket_readable = (pfds[0].revents & libc::POLLIN) != 0;
    let writable: Vec<c_int> = pfds[1..]
        .iter()
        .filter(|p| (p.revents & libc::POLLOUT) != 0)
        .map(|p| p.fd)
        .collect();

    (socket_readable, writable)
}

/// Continue writing for each fd in `writable_fds`, removing completed (or
/// errored) entries from `state.pending_writes`.
fn drain_pending_writes(state: &mut WaylandState, writable_fds: &[c_int]) {
    let mut i = 0;
    while i < state.pending_writes.len() {
        let pw = &state.pending_writes[i];
        if !writable_fds.contains(&pw.fd) {
            i += 1;
            continue;
        }

        // Try to write the remaining bytes.
        let fd = state.pending_writes[i].fd;
        let done = {
            let pw = &mut state.pending_writes[i];
            match try_write_nonblocking(fd, &pw.payload, pw.written) {
                WriteResult::Done => true,
                WriteResult::Partial(n) => {
                    pw.written += n;
                    false
                }
                WriteResult::WouldBlock => false,
                WriteResult::Error => true, // close + drop on error
            }
        };

        if done {
            let fd = state.pending_writes[i].fd;
            // SAFETY: fd is ours (received via SCM_RIGHTS).
            unsafe { libc::close(fd) };
            state.pending_writes.swap_remove(i);
            // Don't advance i — swap_remove puts the last element at i.
        } else {
            i += 1;
        }
    }
}

enum WriteResult {
    /// All bytes written; fd should be closed.
    Done,
    /// Partial write of `n` additional bytes; more to go.
    Partial(usize),
    /// EAGAIN / EWOULDBLOCK; try again later.
    WouldBlock,
    /// Unrecoverable error (EPIPE, etc); fd should be closed.
    Error,
}

/// Attempt a single non-blocking write of `data[written..]` into `fd`.
fn try_write_nonblocking(fd: c_int, data: &[u8], written: usize) -> WriteResult {
    if written >= data.len() {
        return WriteResult::Done;
    }
    let remaining = &data[written..];
    // SAFETY: fd is valid; remaining is valid memory.
    let n = unsafe {
        libc::write(
            fd,
            remaining.as_ptr() as *const libc::c_void,
            remaining.len(),
        )
    };
    if n > 0 {
        let n = n as usize;
        if written + n >= data.len() {
            WriteResult::Done
        } else {
            WriteResult::Partial(n)
        }
    } else if n == 0 {
        WriteResult::Done
    } else {
        let err = std::io::Error::last_os_error();
        // EAGAIN and EWOULDBLOCK have the same value on Linux; allow_unused
        // avoids an unreachable-pattern warning on that platform.
        #[allow(unreachable_patterns)]
        match err.raw_os_error() {
            Some(libc::EAGAIN) | Some(libc::EWOULDBLOCK) => WriteResult::WouldBlock,
            _ => WriteResult::Error,
        }
    }
}

// ---------------------------------------------------------------------------
// Event dispatch
// ---------------------------------------------------------------------------

fn dispatch_events(state: &mut WaylandState) {
    // Collect messages to avoid borrow issues — socket.next_message() borrows
    // socket mutably. We snapshot all pending messages first.
    let mut messages: Vec<(super::wayland_wire::MessageHeader, Vec<u8>, Option<c_int>)> =
        Vec::new();

    while let Some((hdr, args)) = state.socket.next_message() {
        // Only `data_source.send` events carry an fd (via SCM_RIGHTS). Pop the
        // fd queue exclusively for those messages: popping an fd for every
        // message would misattribute (and close) an fd that belongs to a later
        // send event whenever unrelated messages arrive in the same batch,
        // breaking the paste. Unmatched fds stay queued for the message they
        // belong to (and are closed by WaylandSocket::drop as a last resort).
        let expects_fd = (hdr.opcode == EXT_SOURCE_SEND
            && state.clipboard_source.as_ref().map(|s| s.id) == Some(hdr.object_id))
            || (hdr.opcode == ZWP_PRIMARY_SOURCE_SEND
                && state.primary_source.as_ref().map(|s| s.id) == Some(hdr.object_id));
        let opt_fd = if expects_fd {
            state.socket.next_fd()
        } else {
            None
        };
        messages.push((hdr, args, opt_fd));
    }

    for (hdr, args, opt_fd) in messages {
        handle_event(state, hdr.object_id, hdr.opcode, &args, opt_fd);
    }
}

fn handle_event(
    state: &mut WaylandState,
    object_id: u32,
    opcode: u16,
    args: &[u8],
    opt_fd: Option<c_int>,
) {
    if object_id == WL_DISPLAY_ID {
        match opcode {
            WL_DISPLAY_ERROR => {
                let detail = parse_display_error(args);
                eprintln!(
                    "hjkl-clipboard wayland: wl_display.error ({detail}) — terminating bg thread"
                );
                // Fatal per protocol: the connection is unusable. Signal the
                // main loop to stop rather than spin on a dead socket.
                state.fatal_error = true;
            }
            WL_DISPLAY_DELETE_ID => {
                // Compositor deleted one of our object ids; clean up offer tracking.
                if let Some((id, _)) = parse_u32(args) {
                    state.pending_offers.remove(&id);
                    state.offer_ids.remove(&id);
                }
            }
            _ => {}
        }
        if let Some(fd) = opt_fd {
            // SAFETY: fd is valid and unclaimed.
            unsafe { libc::close(fd) };
        }
        return;
    }

    // Data-control device events (offers + selection notification).
    if object_id == state.device_id {
        match opcode {
            EXT_DEVICE_DATA_OFFER => {
                // New offer object introduced. Args: new_id(u32).
                if let Some((offer_id, _)) = parse_u32(args) {
                    state.pending_offers.insert(
                        offer_id,
                        OfferData {
                            id: offer_id,
                            mimes: Vec::new(),
                        },
                    );
                    state.offer_ids.insert(offer_id, false); // not primary
                }
            }
            EXT_DEVICE_SELECTION => {
                // Args: offer_id(u32). 0 = clipboard cleared by another client.
                if let Some((offer_id, _)) = parse_u32(args) {
                    // Destroy old offer if present.
                    if let Some(old) = state.current_clipboard_offer.take() {
                        let msg = encode_message(old.id, EXT_OFFER_DESTROY, &[]);
                        let _ = state.socket.send(&msg, &[]);
                        state.offer_ids.remove(&old.id);
                    }
                    if offer_id == 0 {
                        state.current_clipboard_offer = None;
                    } else {
                        let offer = state.pending_offers.remove(&offer_id).unwrap_or(OfferData {
                            id: offer_id,
                            mimes: Vec::new(),
                        });
                        state.current_clipboard_offer = Some(offer);
                    }
                }
            }
            EXT_DEVICE_PRIMARY_SELECTION => {
                // Same as SELECTION but for the PRIMARY slot via ext_data_control.
                if let Some((offer_id, _)) = parse_u32(args) {
                    if let Some(old) = state.current_primary_offer.take() {
                        let msg = encode_message(old.id, EXT_OFFER_DESTROY, &[]);
                        let _ = state.socket.send(&msg, &[]);
                        state.offer_ids.remove(&old.id);
                    }
                    if offer_id == 0 {
                        state.current_primary_offer = None;
                    } else {
                        let offer = state.pending_offers.remove(&offer_id).unwrap_or(OfferData {
                            id: offer_id,
                            mimes: Vec::new(),
                        });
                        state.current_primary_offer = Some(offer);
                    }
                }
            }
            EXT_DEVICE_FINISHED => {
                // Device finished — device is no longer valid.
            }
            _ => {}
        }
        if let Some(fd) = opt_fd {
            // SAFETY: fd is valid and unclaimed.
            unsafe { libc::close(fd) };
        }
        return;
    }

    // Primary selection device events (zwp protocol).
    if state.primary_device_id != 0 && object_id == state.primary_device_id {
        match opcode {
            ZWP_PRIMARY_DEVICE_DATA_OFFER => {
                if let Some((offer_id, _)) = parse_u32(args) {
                    state.pending_offers.insert(
                        offer_id,
                        OfferData {
                            id: offer_id,
                            mimes: Vec::new(),
                        },
                    );
                    state.offer_ids.insert(offer_id, true); // is primary
                }
            }
            ZWP_PRIMARY_DEVICE_SELECTION => {
                if let Some((offer_id, _)) = parse_u32(args) {
                    if let Some(old) = state.current_primary_offer.take() {
                        let msg = encode_message(old.id, ZWP_PRIMARY_OFFER_DESTROY, &[]);
                        let _ = state.socket.send(&msg, &[]);
                        state.offer_ids.remove(&old.id);
                    }
                    if offer_id == 0 {
                        state.current_primary_offer = None;
                    } else {
                        let offer = state.pending_offers.remove(&offer_id).unwrap_or(OfferData {
                            id: offer_id,
                            mimes: Vec::new(),
                        });
                        state.current_primary_offer = Some(offer);
                    }
                }
            }
            _ => {}
        }
        if let Some(fd) = opt_fd {
            // SAFETY: fd is valid and unclaimed.
            unsafe { libc::close(fd) };
        }
        return;
    }

    // Offer events: offer.offer(mime_type: string) populates pending_offers.
    // Both ext and zwp offer interfaces use opcode 0 for the offer event.
    if state.offer_ids.contains_key(&object_id) {
        if opcode == EXT_OFFER_OFFER
            && let Some((mime, _)) = parse_string(args)
        {
            if let Some(offer) = state.pending_offers.get_mut(&object_id) {
                offer.mimes.push(mime.to_owned());
            }
            // Propagate to current offer if id matches (edge case: late offer event).
            if state.current_clipboard_offer.as_ref().map(|o| o.id) == Some(object_id) {
                if let Some(ref mut o) = state.current_clipboard_offer
                    && !o.mimes.contains(&mime.to_owned())
                {
                    o.mimes.push(mime.to_owned());
                }
            } else if state.current_primary_offer.as_ref().map(|o| o.id) == Some(object_id)
                && let Some(ref mut o) = state.current_primary_offer
                && !o.mimes.contains(&mime.to_owned())
            {
                o.mimes.push(mime.to_owned());
            }
        }
        if let Some(fd) = opt_fd {
            // SAFETY: fd is valid and unclaimed.
            unsafe { libc::close(fd) };
        }
        return;
    }

    // Check if this is from our current clipboard source.
    let is_our_clipboard_source = state
        .clipboard_source
        .as_ref()
        .is_some_and(|s| s.id == object_id);

    if is_our_clipboard_source {
        match opcode {
            EXT_SOURCE_SEND => handle_source_send(state, args, opt_fd),
            EXT_SOURCE_CANCELLED => handle_source_cancelled(state, opt_fd),
            _ => {
                if let Some(fd) = opt_fd {
                    // SAFETY: fd is valid and unclaimed.
                    unsafe { libc::close(fd) };
                }
            }
        }
        return;
    }

    // Check if this is from our primary source.
    let is_our_primary_source = state
        .primary_source
        .as_ref()
        .is_some_and(|s| s.id == object_id);

    if is_our_primary_source {
        match opcode {
            ZWP_PRIMARY_SOURCE_SEND => handle_primary_source_send(state, args, opt_fd),
            ZWP_PRIMARY_SOURCE_CANCELLED => handle_primary_source_cancelled(state, opt_fd),
            _ => {
                if let Some(fd) = opt_fd {
                    // SAFETY: fd is valid and unclaimed.
                    unsafe { libc::close(fd) };
                }
            }
        }
        return;
    }

    // Unknown object — ignore.
    if let Some(fd) = opt_fd {
        // SAFETY: fd is valid and unclaimed.
        unsafe { libc::close(fd) };
    }
}

// ---------------------------------------------------------------------------
// data_source.send event handler
// ---------------------------------------------------------------------------

fn handle_source_send(state: &mut WaylandState, args: &[u8], opt_fd: Option<c_int>) {
    // Event args: mime(string) + fd(out-of-band via SCM_RIGHTS).
    let Some((mime, _rest)) = parse_string(args) else {
        if let Some(fd) = opt_fd {
            // SAFETY: fd is valid; we close it to avoid leaking.
            unsafe { libc::close(fd) };
        }
        return;
    };

    let Some(write_fd) = opt_fd else {
        // No fd means this event is malformed.
        return;
    };

    // Look up payload for this mime type.
    let payload = state
        .clipboard_source
        .as_ref()
        .and_then(|s| s.payloads.get(mime))
        .cloned()
        .unwrap_or_default();

    begin_nonblocking_write(state, write_fd, payload);
}

/// Write all bytes to fd, handling partial writes (blocking — for test/mock use only).
#[cfg(test)]
fn write_to_fd(fd: c_int, data: &[u8]) {
    let mut written = 0;
    while written < data.len() {
        // SAFETY: fd is valid; slice is valid memory.
        let n = unsafe {
            libc::write(
                fd,
                data[written..].as_ptr() as *const libc::c_void,
                data.len() - written,
            )
        };
        if n <= 0 {
            // Write error or EOF; abort.
            break;
        }
        written += n as usize;
    }
}

/// Set O_NONBLOCK on `write_fd`, attempt an immediate write, then either close
/// the fd (all bytes sent) or stash a `PendingWrite` for deferred draining.
///
/// This prevents `handle_source_send` from blocking the bg thread when the
/// paste receiver hasn't drained the pipe yet (the root cause of issue #4,
/// downstream symptom kryptic-sh/buffr#34).
fn begin_nonblocking_write(state: &mut WaylandState, write_fd: c_int, payload: Vec<u8>) {
    // Set O_NONBLOCK so subsequent writes don't block.
    // SAFETY: fcntl with F_GETFL / F_SETFL on a valid fd is safe.
    let flags = unsafe { libc::fcntl(write_fd, libc::F_GETFL) };
    if flags >= 0 {
        unsafe { libc::fcntl(write_fd, libc::F_SETFL, flags | libc::O_NONBLOCK) };
    }

    if payload.is_empty() {
        // Nothing to write — close immediately.
        // SAFETY: write_fd is ours (received via SCM_RIGHTS).
        unsafe { libc::close(write_fd) };
        return;
    }

    // Attempt immediate write.
    match try_write_nonblocking(write_fd, &payload, 0) {
        WriteResult::Done => {
            // SAFETY: write_fd is ours.
            unsafe { libc::close(write_fd) };
        }
        WriteResult::Partial(n) => {
            // Queue remainder for draining via POLLOUT in the main loop.
            state.pending_writes.push(PendingWrite {
                fd: write_fd,
                payload,
                written: n,
                deadline: Instant::now() + Duration::from_secs(5),
            });
        }
        WriteResult::WouldBlock => {
            // Pipe buffer is already full — queue the whole payload.
            state.pending_writes.push(PendingWrite {
                fd: write_fd,
                payload,
                written: 0,
                deadline: Instant::now() + Duration::from_secs(5),
            });
        }
        WriteResult::Error => {
            // SAFETY: write_fd is ours.
            unsafe { libc::close(write_fd) };
        }
    }
}

// ---------------------------------------------------------------------------
// data_source.cancelled event handler
// ---------------------------------------------------------------------------

fn handle_source_cancelled(state: &mut WaylandState, opt_fd: Option<c_int>) {
    // Compositor revoked our selection. Drop the source.
    if let Some(source) = state.clipboard_source.take() {
        // Send source.destroy so the compositor can clean up.
        let msg = encode_message(source.id, EXT_SOURCE_DESTROY, &[]);
        let _ = state.socket.send(&msg, &[]);
    }
    if let Some(fd) = opt_fd {
        // SAFETY: fd is valid and unclaimed.
        unsafe { libc::close(fd) };
    }
}

// ---------------------------------------------------------------------------
// PRIMARY source send/cancelled handlers
// ---------------------------------------------------------------------------

fn handle_primary_source_send(state: &mut WaylandState, args: &[u8], opt_fd: Option<c_int>) {
    let Some((mime, _)) = parse_string(args) else {
        if let Some(fd) = opt_fd {
            // SAFETY: fd is valid; close to avoid leak.
            unsafe { libc::close(fd) };
        }
        return;
    };

    let Some(write_fd) = opt_fd else {
        return;
    };

    let payload = state
        .primary_source
        .as_ref()
        .and_then(|s| s.payloads.get(mime))
        .cloned()
        .unwrap_or_default();

    begin_nonblocking_write(state, write_fd, payload);
}

fn handle_primary_source_cancelled(state: &mut WaylandState, opt_fd: Option<c_int>) {
    if let Some(source) = state.primary_source.take() {
        let msg = encode_message(source.id, ZWP_PRIMARY_SOURCE_DESTROY, &[]);
        let _ = state.socket.send(&msg, &[]);
    }
    if let Some(fd) = opt_fd {
        // SAFETY: fd is valid and unclaimed.
        unsafe { libc::close(fd) };
    }
}

// ---------------------------------------------------------------------------
// Op handlers
// ---------------------------------------------------------------------------

fn handle_op(state: &mut WaylandState, req: WaylandRequest) {
    let result = match req.op {
        WaylandOp::Set { sel, mime, bytes } => {
            WaylandOpResult::Set(do_set(state, sel, mime, bytes))
        }
        WaylandOp::Clear { sel } => WaylandOpResult::Clear(do_clear(state, sel)),
        WaylandOp::Get { sel, mime } => WaylandOpResult::Get(do_get(state, sel, &mime)),
        WaylandOp::Available { sel } => WaylandOpResult::Available(do_available(state, sel)),
    };
    req.reply.resolve(result);
}

fn do_set(
    state: &mut WaylandState,
    sel: Selection,
    mime: MimeType,
    bytes: Vec<u8>,
) -> Result<(), ClipboardError> {
    if sel == Selection::Primary {
        return do_set_primary(state, mime, bytes);
    }

    // Destroy existing source if any, then create a fresh one.
    if let Some(old) = state.clipboard_source.take() {
        let msg = encode_message(old.id, EXT_SOURCE_DESTROY, &[]);
        let _ = state.socket.send(&msg, &[]);
    }

    let source_id = state.alloc_id();

    // manager.create_data_source(new_id)
    {
        let mut args = Vec::new();
        encode_u32(&mut args, source_id);
        let msg = encode_message(state.manager_id, EXT_MANAGER_CREATE_DATA_SOURCE, &args);
        state.socket.send(&msg, &[])?;
    }

    // Build the set of MIME types to offer.
    let mimes: Vec<String> = if let MimeType::Custom(ref s) = mime {
        vec![s.clone()]
    } else {
        mimes_for(&mime).iter().map(|s| s.to_string()).collect()
    };

    // Build payloads: all aliases serve the same bytes.
    let mut payloads: HashMap<String, Vec<u8>> = HashMap::new();
    for m in &mimes {
        payloads.insert(m.clone(), bytes.clone());
    }

    // source.offer(mime) for each offered mime type.
    for m in &mimes {
        let mut args = Vec::new();
        encode_string(&mut args, m);
        let msg = encode_message(source_id, EXT_SOURCE_OFFER, &args);
        state.socket.send(&msg, &[])?;
    }

    // device.set_selection(source)
    {
        let mut args = Vec::new();
        encode_u32(&mut args, source_id);
        let msg = encode_message(state.device_id, EXT_DEVICE_SET_SELECTION, &args);
        state.socket.send(&msg, &[])?;
    }

    state.clipboard_source = Some(OwnedSource {
        id: source_id,
        payloads,
        offered_mimes: mimes,
    });

    Ok(())
}

fn do_set_primary(
    state: &mut WaylandState,
    mime: MimeType,
    bytes: Vec<u8>,
) -> Result<(), ClipboardError> {
    if state.primary_device_id == 0 {
        return Err(ClipboardError::UnsupportedMime);
    }

    if let Some(old) = state.primary_source.take() {
        let msg = encode_message(old.id, ZWP_PRIMARY_SOURCE_DESTROY, &[]);
        let _ = state.socket.send(&msg, &[]);
    }

    let source_id = state.alloc_id();

    // primary_manager.create_source(new_id)
    {
        let mut args = Vec::new();
        encode_u32(&mut args, source_id);
        let msg = encode_message(
            state.primary_manager_id,
            ZWP_PRIMARY_MANAGER_CREATE_SOURCE,
            &args,
        );
        state.socket.send(&msg, &[])?;
    }

    let mimes: Vec<String> = if let MimeType::Custom(ref s) = mime {
        vec![s.clone()]
    } else {
        mimes_for(&mime).iter().map(|s| s.to_string()).collect()
    };

    let mut payloads: HashMap<String, Vec<u8>> = HashMap::new();
    for m in &mimes {
        payloads.insert(m.clone(), bytes.clone());
    }

    for m in &mimes {
        let mut args = Vec::new();
        encode_string(&mut args, m);
        let msg = encode_message(source_id, ZWP_PRIMARY_SOURCE_OFFER, &args);
        state.socket.send(&msg, &[])?;
    }

    // primary_device.set_selection(source, serial=0)
    {
        let mut args = Vec::new();
        encode_u32(&mut args, source_id);
        encode_u32(&mut args, 0); // serial; 0 accepted in headless/data-control context
        let msg = encode_message(
            state.primary_device_id,
            ZWP_PRIMARY_DEVICE_SET_SELECTION,
            &args,
        );
        state.socket.send(&msg, &[])?;
    }

    state.primary_source = Some(OwnedSource {
        id: source_id,
        payloads,
        offered_mimes: mimes,
    });

    Ok(())
}

fn do_clear(state: &mut WaylandState, sel: Selection) -> Result<(), ClipboardError> {
    if sel == Selection::Primary {
        return do_clear_primary(state);
    }

    // Destroy existing source.
    if let Some(source) = state.clipboard_source.take() {
        let msg = encode_message(source.id, EXT_SOURCE_DESTROY, &[]);
        let _ = state.socket.send(&msg, &[]);
    }

    // device.set_selection(0) — null source = NONE (clear).
    {
        let mut args = Vec::new();
        encode_u32(&mut args, 0);
        let msg = encode_message(state.device_id, EXT_DEVICE_SET_SELECTION, &args);
        state.socket.send(&msg, &[])?;
    }

    Ok(())
}

fn do_clear_primary(state: &mut WaylandState) -> Result<(), ClipboardError> {
    if state.primary_device_id == 0 {
        return Err(ClipboardError::UnsupportedMime);
    }

    if let Some(source) = state.primary_source.take() {
        let msg = encode_message(source.id, ZWP_PRIMARY_SOURCE_DESTROY, &[]);
        let _ = state.socket.send(&msg, &[]);
    }

    // primary_device.set_selection(0, serial=0) — null source = clear.
    {
        let mut args = Vec::new();
        encode_u32(&mut args, 0);
        encode_u32(&mut args, 0);
        let msg = encode_message(
            state.primary_device_id,
            ZWP_PRIMARY_DEVICE_SET_SELECTION,
            &args,
        );
        state.socket.send(&msg, &[])?;
    }

    Ok(())
}

/// Map a MIME type string to a MimeType variant.
///
/// Returns None for unknown MIME types (they are not surfaced in available()).
fn mime_str_to_type(s: &str) -> Option<MimeType> {
    match s {
        "text/plain;charset=utf-8" | "UTF8_STRING" | "text/plain" | "STRING" => {
            Some(MimeType::Text)
        }
        "text/html" => Some(MimeType::Html),
        "text/rtf" | "application/rtf" => Some(MimeType::Rtf),
        "text/uri-list" => Some(MimeType::UriList),
        "image/png" => Some(MimeType::Png),
        _ => None,
    }
}

/// Read bytes from the current offer for the given MIME type.
///
/// Protocol flow:
///  1. Create a pipe (read_fd, write_fd) with O_CLOEXEC.
///  2. Send offer.receive(mime, write_fd) — compositor forwards the fd to the
///     selection owner who writes the data and closes write_fd.
///  3. Close our copy of write_fd.
///  4. Read from read_fd until EOF.
fn do_get(
    state: &mut WaylandState,
    sel: Selection,
    mime: &MimeType,
) -> Result<Vec<u8>, ClipboardError> {
    // Self-paste short-circuit: when we own the data_source for this
    // selection, return the cached payload directly. Going through
    // offer.receive + read_fd_to_end would deadlock — the bg thread
    // cannot dispatch the matching `data_source.send` event while it's
    // blocked reading from the pipe.
    if let Some(own) = match sel {
        Selection::Clipboard => state.clipboard_source.as_ref(),
        Selection::Primary => state.primary_source.as_ref(),
    } {
        let candidates: &[&str] = match mime {
            MimeType::Text => &[
                "text/plain;charset=utf-8",
                "UTF8_STRING",
                "text/plain",
                "STRING",
            ],
            MimeType::Html => &["text/html"],
            MimeType::Rtf => &["text/rtf", "application/rtf"],
            MimeType::UriList => &["text/uri-list"],
            MimeType::Png => &["image/png"],
            MimeType::Custom(s) => &[s.as_str()],
        };
        for c in candidates {
            if let Some(bytes) = own.payloads.get(*c) {
                return Ok(bytes.clone());
            }
        }
        return Err(ClipboardError::UnsupportedMime);
    }

    let offer = match sel {
        Selection::Clipboard => state.current_clipboard_offer.as_ref(),
        Selection::Primary => state.current_primary_offer.as_ref(),
    };

    let offer = offer.ok_or(ClipboardError::UnsupportedMime)?;

    // Find the best matching MIME string the offer actually advertises.
    let candidates: &[&str] = match mime {
        MimeType::Text => &[
            "text/plain;charset=utf-8",
            "UTF8_STRING",
            "text/plain",
            "STRING",
        ],
        MimeType::Html => &["text/html"],
        MimeType::Rtf => &["text/rtf", "application/rtf"],
        MimeType::UriList => &["text/uri-list"],
        MimeType::Png => &["image/png"],
        MimeType::Custom(s) => {
            // For custom, try exact match.
            let found = offer.mimes.iter().any(|m| m == s.as_str());
            if !found {
                return Err(ClipboardError::UnsupportedMime);
            }
            let offer_id = offer.id;
            let is_primary = sel == Selection::Primary;
            return receive_from_offer(state, offer_id, s, is_primary);
        }
    };

    let mime_str = candidates
        .iter()
        .find(|c| offer.mimes.iter().any(|m| m == **c))
        .copied()
        .ok_or(ClipboardError::UnsupportedMime)?;

    let offer_id = offer.id;
    let is_primary = sel == Selection::Primary;
    receive_from_offer(state, offer_id, mime_str, is_primary)
}

/// Issue offer.receive(mime, write_fd) and read the response.
fn receive_from_offer(
    state: &mut WaylandState,
    offer_id: u32,
    mime_str: &str,
    is_primary: bool,
) -> Result<Vec<u8>, ClipboardError> {
    // Create a pipe with O_CLOEXEC so fds don't leak into child processes.
    let mut fds = [0i32; 2];
    // SAFETY: pipe2 is safe to call with a valid [i32;2] and valid flags.
    let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
    if rc != 0 {
        return Err(ClipboardError::io(std::io::Error::last_os_error()));
    }
    let read_fd = fds[0];
    let write_fd = fds[1];

    // Send offer.receive(mime_type: string, fd: fd) — fd is out-of-band.
    let receive_opcode = if is_primary {
        ZWP_PRIMARY_OFFER_RECEIVE
    } else {
        EXT_OFFER_RECEIVE
    };
    let mut args = Vec::new();
    encode_string(&mut args, mime_str);
    let msg = encode_message(offer_id, receive_opcode, &args);
    let send_result = state.socket.send(&msg, &[write_fd]);

    // Close our copy of write_fd — the compositor dups it via SCM_RIGHTS.
    // SAFETY: write_fd was created by us; close exactly once.
    unsafe { libc::close(write_fd) };

    if let Err(e) = send_result {
        // SAFETY: read_fd was created by us; close to avoid a leak.
        unsafe { libc::close(read_fd) };
        return Err(e);
    }

    // Read from read_fd until EOF (the owner closed write_fd after writing).
    let data = read_fd_to_end(read_fd);

    // SAFETY: read_fd was created by us; close after reading (on both the
    // success and the error path).
    unsafe { libc::close(read_fd) };

    data
}

/// Cap on a single paste read so a hostile or buggy selection owner cannot
/// stream unbounded data into memory. Generous — large images legitimately
/// reach tens of MiB.
const MAX_PASTE_BYTES: usize = 256 * 1024 * 1024;

/// Give up on a paste if the selection owner sends no data (and doesn't close
/// the pipe) for this long. This is an **idle** timeout — it resets every time
/// bytes arrive — so a legitimately large-but-streaming paste still completes,
/// while a hostile owner that opens the pipe and then stalls forever can't hang
/// the clipboard thread.
const PASTE_IDLE_TIMEOUT_MS: c_int = 2000;

/// Read all available bytes from `fd` until EOF, capped at [`MAX_PASTE_BYTES`]
/// and bounded by an idle timeout ([`PASTE_IDLE_TIMEOUT_MS`]).
fn read_fd_to_end(fd: c_int) -> Result<Vec<u8>, ClipboardError> {
    let mut result = Vec::new();
    let mut buf = [0u8; 4096];
    loop {
        // Wait for the fd to become readable (or hang up) before reading, so a
        // stalled owner that never writes and never closes can't block us in
        // `read` indefinitely.
        let mut pfd = libc::pollfd {
            fd,
            events: libc::POLLIN,
            revents: 0,
        };
        // SAFETY: single valid pollfd, count 1.
        let pr = unsafe { libc::poll(&mut pfd, 1, PASTE_IDLE_TIMEOUT_MS) };
        if pr < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            return Err(ClipboardError::io(err));
        }
        if pr == 0 {
            return Err(ClipboardError::io(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "clipboard paste stalled (no data from selection owner)",
            )));
        }

        // SAFETY: fd is valid; buf is valid memory.
        let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len()) };
        if n < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted
                || err.kind() == std::io::ErrorKind::WouldBlock
            {
                continue;
            }
            return Err(ClipboardError::io(err));
        }
        if n == 0 {
            break; // EOF (owner closed the write end)
        }
        result.extend_from_slice(&buf[..n as usize]);
        if result.len() > MAX_PASTE_BYTES {
            return Err(ClipboardError::io(std::io::Error::other(
                "clipboard paste exceeds size limit",
            )));
        }
    }
    Ok(result)
}

fn do_available(state: &mut WaylandState, sel: Selection) -> Result<Vec<MimeType>, ClipboardError> {
    let offer = match sel {
        Selection::Clipboard => state.current_clipboard_offer.as_ref(),
        Selection::Primary => state.current_primary_offer.as_ref(),
    };

    let Some(offer) = offer else {
        return Ok(vec![]);
    };

    // Deduplicate by MimeType variant (first hit wins).
    let mut seen = std::collections::HashSet::new();
    let mut result = Vec::new();
    for mime_str in &offer.mimes {
        if let Some(mt) = mime_str_to_type(mime_str) {
            // Use discriminant as dedup key since MimeType isn't Hash.
            let key = match &mt {
                MimeType::Text => 0u8,
                MimeType::Html => 1,
                MimeType::Rtf => 2,
                MimeType::UriList => 3,
                MimeType::Png => 4,
                MimeType::Custom(_) => 5,
            };
            if seen.insert(key) {
                result.push(mt);
            }
        }
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Public helpers for lib.rs wiring
// ---------------------------------------------------------------------------

pub fn set_clipboard(
    thread: &WaylandThread,
    sel: Selection,
    mime: &MimeType,
    bytes: &[u8],
) -> Result<(), ClipboardError> {
    let result = thread.send_sync(WaylandOp::Set {
        sel,
        mime: mime.clone(),
        bytes: bytes.to_vec(),
    })?;
    match result {
        WaylandOpResult::Set(r) => r,
        _ => unreachable!(),
    }
}

pub fn clear_clipboard(thread: &WaylandThread, sel: Selection) -> Result<(), ClipboardError> {
    let result = thread.send_sync(WaylandOp::Clear { sel })?;
    match result {
        WaylandOpResult::Clear(r) => r,
        _ => unreachable!(),
    }
}

pub fn get_clipboard(
    thread: &WaylandThread,
    sel: Selection,
    mime: &MimeType,
) -> Result<Vec<u8>, ClipboardError> {
    let result = thread.send_sync(WaylandOp::Get {
        sel,
        mime: mime.clone(),
    })?;
    match result {
        WaylandOpResult::Get(r) => r,
        _ => unreachable!(),
    }
}

pub fn available_clipboard(
    thread: &WaylandThread,
    sel: Selection,
) -> Result<Vec<MimeType>, ClipboardError> {
    let result = thread.send_sync(WaylandOp::Available { sel })?;
    match result {
        WaylandOpResult::Available(r) => r,
        _ => unreachable!(),
    }
}

// ---------------------------------------------------------------------------
// WaylandConnection::into_parts()
// (Defined in wayland.rs via a helper; we add it here as a method extension
//  in wayland.rs — we need socket + next_id from the connection.)
// ---------------------------------------------------------------------------
// NOTE: `into_parts()` is implemented in wayland.rs (added in this phase).

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

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

    use std::collections::HashMap;
    use std::ffi::c_int;
    use std::os::unix::net::UnixListener;
    use std::path::{Path, PathBuf};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex, OnceLock};

    use super::super::wayland_socket::WaylandSocket;
    use super::super::wayland_wire::{
        encode_message, encode_string, encode_u32, parse_string, parse_u32,
    };

    // One mock compositor for all Wayland thread tests (approach a — shared
    // singleton matching XVFB_SESSION pattern in x11_thread tests).
    static MOCK_SESSION: OnceLock<Option<Arc<MockCompositor>>> = OnceLock::new();
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    // ---------------------------------------------------------------------------
    // Mock compositor
    // ---------------------------------------------------------------------------

    /// State the mock compositor tracks (accessible from test assertions).
    pub struct MockState {
        /// bound globals: new_id -> (global_name, interface, version)
        pub bound: HashMap<u32, (u32, String, u32)>,
        /// For each created data source: offered mimes.
        pub source_mimes: HashMap<u32, Vec<String>>,
        /// The source id of the most recent set_selection call (0 = cleared).
        pub current_selection: Option<u32>,
        /// Paste results: mime -> bytes the client wrote when we sent send events.
        pub paste_results: HashMap<String, Vec<u8>>,
        /// Object id counter for server-side allocations.
        #[allow(dead_code)]
        next_server_id: u32,
        /// Pipe write ends we use to trigger send events, keyed by source id.
        /// The mock server thread reads these to send events to the client.
        pending_sends: Vec<PendingSend>,
        /// Whether a cancelled event was triggered.
        pub cancelled_triggered: bool,
        /// Pending clipboard offer to advertise to the client.
        /// Set by advertise_clipboard_offer(); cleared once sent.
        pending_clipboard_offer: Option<PendingOffer>,
        /// Pending primary offer to advertise.
        pending_primary_offer: Option<PendingOffer>,
        /// Server-side payloads for offers, keyed by offer object id then mime.
        offer_payloads: HashMap<u32, HashMap<String, Vec<u8>>>,
        /// Pending receive requests: (offer_id, mime, write_fd).
        pending_receives: Vec<(u32, String, c_int)>,
    }

    struct PendingOffer {
        mimes: Vec<String>,
        payloads: HashMap<String, Vec<u8>>,
        #[allow(dead_code)]
        is_primary: bool,
    }

    struct PendingSend {
        mime: String,
        #[allow(dead_code)]
        read_fd: c_int,
        write_fd: c_int,
        source_id: u32,
        complete: bool,
    }

    impl Default for MockState {
        fn default() -> Self {
            Self {
                bound: HashMap::new(),
                source_mimes: HashMap::new(),
                current_selection: None,
                paste_results: HashMap::new(),
                next_server_id: 200,
                pending_sends: Vec::new(),
                cancelled_triggered: false,
                pending_clipboard_offer: None,
                pending_primary_offer: None,
                offer_payloads: HashMap::new(),
                pending_receives: Vec::new(),
            }
        }
    }

    impl MockState {
        #[allow(dead_code)]
        fn alloc_server_id(&mut self) -> u32 {
            let id = self.next_server_id;
            self.next_server_id += 1;
            id
        }

        /// Reset between test runs (except bound/device state).
        fn reset(&mut self) {
            self.source_mimes.clear();
            self.current_selection = None;
            self.paste_results.clear();
            self.pending_sends.clear();
            self.cancelled_triggered = false;
            self.pending_clipboard_offer = None;
            self.pending_primary_offer = None;
            self.offer_payloads.clear();
            self.pending_receives.clear();
        }
    }

    /// Handle for the mock Wayland compositor.
    pub struct MockCompositor {
        pub socket_path: PathBuf,
        pub state: Arc<Mutex<MockState>>,
        #[allow(dead_code)]
        shutdown: Arc<AtomicBool>,
    }

    impl MockCompositor {
        pub(crate) fn socket_path(&self) -> &Path {
            &self.socket_path
        }

        pub(crate) fn state(&self) -> std::sync::MutexGuard<'_, MockState> {
            self.state.lock().unwrap()
        }

        /// Trigger a paste: send data_source.send(mime, write_fd) to the client
        /// via the server thread, then collect bytes from the read_fd.
        ///
        /// This creates a pipe, enqueues a PendingSend in the mock state (the
        /// server thread will detect it and send the event), then reads from
        /// the read_fd until EOF to collect what the client wrote.
        pub(crate) fn trigger_paste(&self, mime: &str) -> Result<Vec<u8>, std::io::Error> {
            // Create a pipe.
            let mut fds = [0i32; 2];
            // SAFETY: pipe2 with O_CLOEXEC is safe to call with a valid [i32;2].
            let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
            if rc != 0 {
                return Err(std::io::Error::last_os_error());
            }
            let read_fd = fds[0];
            let write_fd = fds[1];

            // Enqueue the send event.
            {
                let mut st = self.state.lock().unwrap();
                let source_id = st.current_selection.unwrap_or(0);
                st.pending_sends.push(PendingSend {
                    mime: mime.to_owned(),
                    read_fd,
                    write_fd,
                    source_id,
                    complete: false,
                });
            }

            // Wait for the server thread to process the send and the client to
            // write its response. We poll the complete flag.
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
            loop {
                {
                    let st = self.state.lock().unwrap();
                    if st.pending_sends.iter().all(|p| p.complete) {
                        break;
                    }
                }
                if std::time::Instant::now() > deadline {
                    return Err(std::io::Error::other("trigger_paste timed out"));
                }
                std::thread::sleep(std::time::Duration::from_millis(10));
            }

            // Read from the read_fd until EOF.
            let mut result = Vec::new();
            let mut buf = [0u8; 4096];
            loop {
                // SAFETY: read_fd is valid; buf is valid memory.
                let n = unsafe {
                    libc::read(read_fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len())
                };
                if n <= 0 {
                    break;
                }
                result.extend_from_slice(&buf[..n as usize]);
            }
            // SAFETY: read_fd is valid; we close it after reading.
            unsafe { libc::close(read_fd) };

            // Store in paste_results.
            {
                let mut st = self.state.lock().unwrap();
                st.paste_results.insert(mime.to_owned(), result.clone());
            }

            Ok(result)
        }

        /// Advertise a clipboard offer to the client.
        ///
        /// The mock server thread will pick up this pending offer on its next
        /// iteration and send device.data_offer + offer.offer(mime) * N +
        /// device.selection events to the client. Once the client calls
        /// offer.receive(mime, fd), the server writes the payload to fd.
        pub(crate) fn advertise_clipboard_offer(
            &self,
            mimes: Vec<String>,
            payloads: HashMap<String, Vec<u8>>,
        ) {
            let mut st = self.state.lock().unwrap();
            st.pending_clipboard_offer = Some(PendingOffer {
                mimes,
                payloads,
                is_primary: false,
            });
        }

        /// Advertise a PRIMARY selection offer to the client.
        pub(crate) fn advertise_primary_offer(
            &self,
            mimes: Vec<String>,
            payloads: HashMap<String, Vec<u8>>,
        ) {
            let mut st = self.state.lock().unwrap();
            st.pending_primary_offer = Some(PendingOffer {
                mimes,
                payloads,
                is_primary: true,
            });
        }

        /// Wait until the client's bg thread has processed the current offer.
        #[allow(dead_code)]
        pub(crate) fn wait_for_clipboard_offer(&self, timeout_ms: u64) {
            let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
            loop {
                std::thread::sleep(std::time::Duration::from_millis(10));
                if std::time::Instant::now() > deadline {
                    break;
                }
            }
        }

        #[allow(dead_code)]
        pub(crate) fn shutdown(self) {
            self.shutdown.store(true, Ordering::Relaxed);
        }
    }

    /// Spawn a mock Wayland compositor on a temporary socket path.
    pub fn spawn_mock_compositor(advertise_data_control: bool) -> Arc<MockCompositor> {
        spawn_mock_compositor_with_primary(advertise_data_control, true)
    }

    /// Spawn with explicit primary selection support toggle.
    pub fn spawn_mock_compositor_with_primary(
        advertise_data_control: bool,
        advertise_primary: bool,
    ) -> Arc<MockCompositor> {
        // Use a unique socket path in /tmp.
        let socket_path = PathBuf::from(format!("/tmp/hjkl-clipboard-mock-{}.sock", unsafe {
            libc::getpid()
        }));

        // Remove stale socket if any.
        let _ = std::fs::remove_file(&socket_path);

        let listener = UnixListener::bind(&socket_path).expect("failed to bind mock socket");

        let state = Arc::new(Mutex::new(MockState::default()));
        let shutdown = Arc::new(AtomicBool::new(false));

        let state_clone = Arc::clone(&state);
        let shutdown_clone = Arc::clone(&shutdown);
        let socket_path_clone = socket_path.clone();

        std::thread::Builder::new()
            .name("hjkl-mock-compositor".into())
            .spawn(move || {
                run_mock_compositor(
                    listener,
                    state_clone,
                    shutdown_clone,
                    advertise_data_control,
                    advertise_primary,
                    socket_path_clone,
                );
            })
            .expect("failed to spawn mock compositor thread");

        Arc::new(MockCompositor {
            socket_path,
            state,
            shutdown,
        })
    }

    // ---------------------------------------------------------------------------
    // Mock compositor server thread
    // ---------------------------------------------------------------------------

    /// Object type tags for the mock server's object table.
    #[derive(Debug, Clone, PartialEq)]
    enum MockObjectType {
        Display,
        Registry,
        Callback,
        Seat,
        DataControlManager,
        DataControlDevice,
        DataControlSource,
        DataControlOffer,
        PrimaryManager,
        PrimaryDevice,
        PrimarySource,
        PrimaryOffer,
    }

    struct MockServer {
        socket: WaylandSocket,
        objects: HashMap<u32, MockObjectType>,
        next_id: u32,
        state: Arc<Mutex<MockState>>,
        #[allow(dead_code)]
        advertise_data_control: bool,
        #[allow(dead_code)]
        advertise_primary: bool,
        /// Globals we advertise: (name, interface, version).
        globals: Vec<(u32, &'static str, u32)>,
        /// Device object id (client-allocated) so we can send events to it.
        device_obj_id: u32,
        /// Primary device object id (client-allocated), 0 if not bound.
        primary_device_obj_id: u32,
    }

    impl MockServer {
        #[allow(dead_code)]
        fn alloc_id(&mut self) -> u32 {
            let id = self.next_id;
            self.next_id += 1;
            id
        }

        fn send(&self, object_id: u32, opcode: u16, args: &[u8]) {
            let msg = encode_message(object_id, opcode, args);
            let _ = self.socket.send(&msg, &[]);
        }

        #[allow(dead_code)]
        fn send_with_fd(&self, object_id: u32, opcode: u16, args: &[u8], fd: c_int) {
            let msg = encode_message(object_id, opcode, args);
            let _ = self.socket.send(&msg, &[fd]);
        }
    }

    fn run_mock_compositor(
        listener: UnixListener,
        state: Arc<Mutex<MockState>>,
        shutdown: Arc<AtomicBool>,
        advertise_data_control: bool,
        advertise_primary: bool,
        _socket_path: PathBuf,
    ) {
        // Accept exactly one connection (our client).
        listener.set_nonblocking(true).ok();

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        let (stream, _) = loop {
            match listener.accept() {
                Ok(pair) => break pair,
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    if shutdown.load(Ordering::Relaxed) || std::time::Instant::now() > deadline {
                        return;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(5));
                    continue;
                }
                Err(_) => return,
            }
        };

        // Wrap the accepted stream in a WaylandSocket-compatible fd.
        use std::os::unix::io::IntoRawFd;
        let raw_fd = stream.into_raw_fd();

        let socket = unsafe { WaylandSocket::from_raw_fd(raw_fd) };

        let mut globals: Vec<(u32, &'static str, u32)> = vec![(1, WL_SEAT, 7)];
        if advertise_data_control {
            globals.push((2, EXT_DATA_CONTROL_MANAGER, 1));
        }
        if advertise_primary {
            globals.push((3, ZWP_PRIMARY_SEL_MANAGER, 1));
        }

        let mut server = MockServer {
            socket,
            objects: HashMap::new(),
            next_id: 300,
            state,
            advertise_data_control,
            advertise_primary,
            globals,
            device_obj_id: 0,
            primary_device_obj_id: 0,
        };

        // Register well-known objects.
        server.objects.insert(1, MockObjectType::Display);
        server.objects.insert(2, MockObjectType::Registry);

        run_mock_server_loop(&mut server, shutdown);
    }

    fn run_mock_server_loop(server: &mut MockServer, shutdown: Arc<AtomicBool>) {
        loop {
            if shutdown.load(Ordering::Relaxed) {
                return;
            }

            // Dispatch pending offer advertisements (from test thread).
            dispatch_pending_offers(server);

            // Dispatch pending receive requests (client wants to read an offer).
            dispatch_pending_receives(server);

            // Check for pending send events to dispatch.
            dispatch_pending_sends(server);

            // Non-blocking receive.
            if let Err(e) = server.socket.recv(false) {
                let err_str = e.to_string();
                if err_str.contains("closed") || err_str.contains("reset") {
                    return;
                }
                break;
            }

            // Drain messages.
            while let Some((hdr, args)) = server.socket.next_message() {
                // Check for fd alongside each message.
                let opt_fd = server.socket.next_fd();
                handle_mock_message(server, hdr.object_id, hdr.opcode, &args, opt_fd);
            }

            std::thread::sleep(std::time::Duration::from_millis(1));
        }
    }

    /// Send a pending offer to the client (device.data_offer + offer.offer*N + device.selection).
    fn dispatch_pending_offers(server: &mut MockServer) {
        let (clipboard_offer, primary_offer) = {
            let mut st = server.state.lock().unwrap();
            (
                st.pending_clipboard_offer.take(),
                st.pending_primary_offer.take(),
            )
        };

        if let Some(offer) = clipboard_offer {
            if server.device_obj_id == 0 {
                // Device not yet bound; re-enqueue.
                server.state.lock().unwrap().pending_clipboard_offer = Some(offer);
                return;
            }
            let offer_id = server.next_id;
            server.next_id += 1;
            server
                .objects
                .insert(offer_id, MockObjectType::DataControlOffer);

            // Save payloads server-side.
            {
                let mut st = server.state.lock().unwrap();
                st.offer_payloads.insert(offer_id, offer.payloads);
            }

            // Send device.data_offer(new_id) to client.
            {
                let mut args = Vec::new();
                encode_u32(&mut args, offer_id);
                server.send(server.device_obj_id, EXT_DEVICE_DATA_OFFER, &args);
            }

            // Send offer.offer(mime) for each mime.
            for mime in &offer.mimes {
                let mut args = Vec::new();
                encode_string(&mut args, mime);
                server.send(offer_id, EXT_OFFER_OFFER, &args);
            }

            // Send device.selection(offer_id).
            {
                let mut args = Vec::new();
                encode_u32(&mut args, offer_id);
                server.send(server.device_obj_id, EXT_DEVICE_SELECTION, &args);
            }
        }

        if let Some(offer) = primary_offer {
            let dev_id = server.primary_device_obj_id;
            if dev_id == 0 {
                server.state.lock().unwrap().pending_primary_offer = Some(offer);
                return;
            }
            let offer_id = server.next_id;
            server.next_id += 1;
            server
                .objects
                .insert(offer_id, MockObjectType::PrimaryOffer);

            {
                let mut st = server.state.lock().unwrap();
                st.offer_payloads.insert(offer_id, offer.payloads);
            }

            // Send primary_device.data_offer(new_id).
            {
                let mut args = Vec::new();
                encode_u32(&mut args, offer_id);
                server.send(dev_id, ZWP_PRIMARY_DEVICE_DATA_OFFER, &args);
            }

            for mime in &offer.mimes {
                let mut args = Vec::new();
                encode_string(&mut args, mime);
                server.send(offer_id, ZWP_PRIMARY_OFFER_OFFER, &args);
            }

            // Send primary_device.selection(offer_id).
            {
                let mut args = Vec::new();
                encode_u32(&mut args, offer_id);
                server.send(dev_id, ZWP_PRIMARY_DEVICE_SELECTION, &args);
            }
        }
    }

    /// Service pending offer.receive requests: write payload to the fd.
    fn dispatch_pending_receives(server: &mut MockServer) {
        let work: Vec<(u32, String, c_int)> = {
            let mut st = server.state.lock().unwrap();
            st.pending_receives.drain(..).collect()
        };

        for (offer_id, mime, write_fd) in work {
            let payload = {
                let st = server.state.lock().unwrap();
                st.offer_payloads
                    .get(&offer_id)
                    .and_then(|m| m.get(&mime))
                    .cloned()
                    .unwrap_or_default()
            };

            // Write payload to the fd the client gave us.
            write_to_fd(write_fd, &payload);
            // SAFETY: write_fd was received via SCM_RIGHTS; close after write.
            unsafe { libc::close(write_fd) };
        }
    }

    fn dispatch_pending_sends(server: &mut MockServer) {
        // Collect work items without holding the lock across the send.
        // Each item: (source_id, mime, write_fd).
        let work: Vec<(u32, String, c_int)> = {
            let mut st = server.state.lock().unwrap();
            let mut items = Vec::new();
            for pending in st.pending_sends.iter_mut() {
                if !pending.complete {
                    items.push((pending.source_id, pending.mime.clone(), pending.write_fd));
                    pending.complete = true;
                    pending.write_fd = -1; // prevent double-close
                }
            }
            items
        };
        // Lock is released here. Now send events without holding state lock.

        for (source_id, mime, write_fd) in work {
            let mut args = Vec::new();
            encode_string(&mut args, &mime);

            // Send data_source.send(mime, write_fd) to the client.
            let msg = encode_message(source_id, EXT_SOURCE_SEND, &args);
            let _ = server.socket.send(&msg, &[write_fd]);

            // Close our copy of the write fd (kernel dups it during SCM_RIGHTS).
            // SAFETY: write_fd is valid and was created by pipe2; we own this copy.
            unsafe { libc::close(write_fd) };
        }
    }

    fn handle_mock_message(
        server: &mut MockServer,
        object_id: u32,
        opcode: u16,
        args: &[u8],
        opt_fd: Option<c_int>,
    ) {
        let obj_type = server.objects.get(&object_id).cloned();

        match obj_type {
            Some(MockObjectType::Display) => handle_mock_display(server, opcode, args),
            Some(MockObjectType::Registry) => handle_mock_registry(server, opcode, args),
            Some(MockObjectType::Callback) => {
                // Callbacks have no requests from the client; ignore.
            }
            Some(MockObjectType::Seat) => {
                // Seat capabilities etc — ignore in 6b.
            }
            Some(MockObjectType::DataControlManager) => handle_mock_manager(server, opcode, args),
            Some(MockObjectType::DataControlDevice) => {
                handle_mock_device(server, object_id, opcode, args)
            }
            Some(MockObjectType::DataControlSource) => {
                handle_mock_source(server, object_id, opcode, args)
            }
            Some(MockObjectType::DataControlOffer) => {
                handle_mock_offer(server, object_id, opcode, args, opt_fd, false)
            }
            Some(MockObjectType::PrimaryManager) => {
                handle_mock_primary_manager(server, opcode, args)
            }
            Some(MockObjectType::PrimaryDevice) => {
                handle_mock_primary_device(server, object_id, opcode, args)
            }
            Some(MockObjectType::PrimarySource) => {
                handle_mock_primary_source(server, object_id, opcode, args)
            }
            Some(MockObjectType::PrimaryOffer) => {
                handle_mock_offer(server, object_id, opcode, args, opt_fd, true)
            }
            None => {
                if let Some(fd) = opt_fd {
                    // SAFETY: fd is valid and unclaimed.
                    unsafe { libc::close(fd) };
                }
            }
        }
    }

    // wl_display request handling (server side).
    fn handle_mock_display(server: &mut MockServer, opcode: u16, args: &[u8]) {
        match opcode {
            0 => {
                // wl_display.sync(new_id) — send wl_callback.done(serial=0).
                if let Some((callback_id, _)) = parse_u32(args) {
                    server.objects.insert(callback_id, MockObjectType::Callback);
                    // wl_callback.done: opcode 0, args: callback_data(u32)
                    let mut done_args = Vec::new();
                    encode_u32(&mut done_args, 0u32); // serial
                    server.send(callback_id, 0, &done_args);
                }
            }
            1 => {
                // wl_display.get_registry(new_id)
                if let Some((registry_id, _)) = parse_u32(args) {
                    server.objects.insert(registry_id, MockObjectType::Registry);
                    // Send wl_registry.global for each advertised global.
                    for (name, interface, version) in &server.globals.clone() {
                        let mut ga = Vec::new();
                        encode_u32(&mut ga, *name);
                        encode_string(&mut ga, interface);
                        encode_u32(&mut ga, *version);
                        // wl_registry.global opcode = 0
                        server.send(registry_id, 0, &ga);
                    }
                }
            }
            _ => {}
        }
    }

    // wl_registry.bind handling.
    fn handle_mock_registry(server: &mut MockServer, opcode: u16, args: &[u8]) {
        if opcode != 0 {
            return; // only bind
        }
        // bind args: name(u32) + interface(string) + version(u32) + new_id(u32)
        let Some((name, rest)) = parse_u32(args) else {
            return;
        };
        let Some((interface, rest)) = parse_string(rest) else {
            return;
        };
        let Some((version, rest)) = parse_u32(rest) else {
            return;
        };
        let Some((new_id, _)) = parse_u32(rest) else {
            return;
        };

        let obj_type = match interface {
            "wl_seat" => MockObjectType::Seat,
            "ext_data_control_manager_v1" => MockObjectType::DataControlManager,
            "zwp_primary_selection_device_manager_v1" => MockObjectType::PrimaryManager,
            _ => return,
        };

        server.objects.insert(new_id, obj_type);

        let mut st = server.state.lock().unwrap();
        st.bound
            .insert(new_id, (name, interface.to_owned(), version));
    }

    // ext_data_control_manager_v1 request handling.
    fn handle_mock_manager(server: &mut MockServer, opcode: u16, args: &[u8]) {
        match opcode {
            0 => {
                // create_data_source(new_id)
                if let Some((new_id, _)) = parse_u32(args) {
                    server
                        .objects
                        .insert(new_id, MockObjectType::DataControlSource);
                    let mut st = server.state.lock().unwrap();
                    st.source_mimes.insert(new_id, Vec::new());
                }
            }
            1 => {
                // get_data_device(new_id, seat)
                if let Some((new_id, _)) = parse_u32(args) {
                    server
                        .objects
                        .insert(new_id, MockObjectType::DataControlDevice);
                    server.device_obj_id = new_id;
                }
            }
            2 => {
                // destroy — no-op for mock
            }
            _ => {}
        }
    }

    // ext_data_control_device_v1 request handling.
    fn handle_mock_device(server: &mut MockServer, _object_id: u32, opcode: u16, args: &[u8]) {
        match opcode {
            0 => {
                // set_selection(source_id)
                if let Some((source_id, _)) = parse_u32(args) {
                    let mut st = server.state.lock().unwrap();
                    if source_id == 0 {
                        st.current_selection = None;
                    } else {
                        st.current_selection = Some(source_id);
                    }
                }
            }
            1 => {
                // destroy — no-op
            }
            2 => {
                // set_primary_selection — not tested; ignore.
                let _ = args;
            }
            _ => {}
        }
    }

    // ext_data_control_offer_v1 request handling (receive / destroy).
    fn handle_mock_offer(
        server: &mut MockServer,
        object_id: u32,
        opcode: u16,
        args: &[u8],
        opt_fd: Option<c_int>,
        _is_primary: bool,
    ) {
        match opcode {
            0 => {
                // receive(mime_type: string, fd: fd)
                if let Some((mime, _)) = parse_string(args) {
                    if let Some(fd) = opt_fd {
                        let mut st = server.state.lock().unwrap();
                        st.pending_receives.push((object_id, mime.to_owned(), fd));
                    }
                } else if let Some(fd) = opt_fd {
                    // SAFETY: fd is valid and unclaimed.
                    unsafe { libc::close(fd) };
                }
            }
            1 => {
                // destroy
                server.objects.remove(&object_id);
                server
                    .state
                    .lock()
                    .unwrap()
                    .offer_payloads
                    .remove(&object_id);
            }
            _ => {
                if let Some(fd) = opt_fd {
                    // SAFETY: fd is valid and unclaimed.
                    unsafe { libc::close(fd) };
                }
            }
        }
    }

    // zwp_primary_selection_device_manager_v1 request handling.
    fn handle_mock_primary_manager(server: &mut MockServer, opcode: u16, args: &[u8]) {
        match opcode {
            0 => {
                // create_source(new_id)
                if let Some((new_id, _)) = parse_u32(args) {
                    server.objects.insert(new_id, MockObjectType::PrimarySource);
                    let mut st = server.state.lock().unwrap();
                    st.source_mimes.insert(new_id, Vec::new());
                }
            }
            1 => {
                // get_device(new_id, seat)
                if let Some((new_id, _)) = parse_u32(args) {
                    server.objects.insert(new_id, MockObjectType::PrimaryDevice);
                    server.primary_device_obj_id = new_id;
                }
            }
            2 => {
                // destroy — no-op
            }
            _ => {}
        }
    }

    // zwp_primary_selection_device_v1 request handling.
    fn handle_mock_primary_device(
        server: &mut MockServer,
        _object_id: u32,
        opcode: u16,
        args: &[u8],
    ) {
        match opcode {
            0 => {
                // set_selection(source, serial)
                if let Some((source_id, _)) = parse_u32(args) {
                    let mut st = server.state.lock().unwrap();
                    if source_id == 0 {
                        st.current_selection = None;
                    } else {
                        st.current_selection = Some(source_id);
                    }
                }
            }
            1 => {
                // destroy — no-op
            }
            _ => {}
        }
    }

    // zwp_primary_selection_source_v1 request handling.
    fn handle_mock_primary_source(
        server: &mut MockServer,
        object_id: u32,
        opcode: u16,
        args: &[u8],
    ) {
        match opcode {
            0 => {
                // offer(mime_type: string)
                if let Some((mime, _)) = parse_string(args) {
                    let mut st = server.state.lock().unwrap();
                    st.source_mimes
                        .entry(object_id)
                        .or_default()
                        .push(mime.to_owned());
                }
            }
            1 => {
                // destroy
                server.objects.remove(&object_id);
            }
            _ => {}
        }
    }

    // ext_data_control_source_v1 request handling.
    fn handle_mock_source(server: &mut MockServer, object_id: u32, opcode: u16, args: &[u8]) {
        match opcode {
            0 => {
                // offer(mime_type: string)
                if let Some((mime, _)) = parse_string(args) {
                    let mut st = server.state.lock().unwrap();
                    st.source_mimes
                        .entry(object_id)
                        .or_default()
                        .push(mime.to_owned());
                }
            }
            1 => {
                // destroy — remove from object table
                server.objects.remove(&object_id);
            }
            _ => {}
        }
    }

    // ---------------------------------------------------------------------------
    // Test infrastructure — shared mock session
    // ---------------------------------------------------------------------------

    /// Ensure the shared mock compositor is running and return it.
    ///
    /// The mock is started once for the whole test process. Tests reset the
    /// MockState between runs via reset() inside TEST_LOCK.
    fn ensure_mock() -> Option<Arc<MockCompositor>> {
        MOCK_SESSION
            .get_or_init(|| {
                let mock = spawn_mock_compositor(true);

                // Set WAYLAND_DISPLAY to the mock socket path before initialising
                // WAYLAND_THREAD so it connects to our mock, not a real compositor.
                //
                // SAFETY: test-only; single-threaded at this point (OnceLock callback).
                let path = mock.socket_path().to_str().unwrap().to_owned();
                unsafe { std::env::set_var("WAYLAND_DISPLAY", &path) };

                // The socket file is created by UnixListener::bind BEFORE the
                // mock thread is spawned, so we only need to verify the file
                // exists. We do NOT probe with a real connection here — that
                // would consume the mock's single accept slot, leaving the
                // real WaylandThread::new() connection unhandled.
                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
                while std::time::Instant::now() < deadline {
                    if mock.socket_path().exists() {
                        break;
                    }
                    std::thread::sleep(std::time::Duration::from_millis(5));
                }

                // Brief sleep so the mock thread's accept loop is spinning
                // before we connect.
                std::thread::sleep(std::time::Duration::from_millis(20));

                // Eagerly initialise WAYLAND_THREAD inside the OnceLock callback to
                // avoid races between "WAYLAND_DISPLAY is set" and "thread is init".
                let _ = wayland_thread();

                Some(mock)
            })
            .as_ref()
            .cloned()
    }

    fn get_thread_for_test() -> Option<&'static WaylandThread> {
        ensure_mock()?;
        match wayland_thread() {
            Ok(t) => Some(t),
            Err(e) => {
                eprintln!("SKIP: wayland_thread failed: {e}");
                None
            }
        }
    }

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

    /// Set text then trigger a paste via the mock and assert the bytes match.
    #[test]
    fn mock_compositor_set_then_paste_text() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        let payload = b"hello wayland 6b";
        set_clipboard(thread, Selection::Clipboard, &MimeType::Text, payload)
            .expect("set_clipboard failed");

        // Give the bg thread time to send the protocol messages and the mock
        // to process them.
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Verify mock recorded the selection.
        assert!(
            mock.state().current_selection.is_some(),
            "mock should have a current_selection after set"
        );

        // Trigger a paste for the primary text MIME type.
        let received = mock
            .trigger_paste("text/plain;charset=utf-8")
            .expect("trigger_paste failed");

        assert_eq!(received, payload, "pasted bytes should match what was set");
    }

    /// Set then clear — mock should report no current selection.
    #[test]
    fn mock_compositor_clear_unsets_selection() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        set_clipboard(
            thread,
            Selection::Clipboard,
            &MimeType::Text,
            b"to-be-cleared",
        )
        .expect("set failed");
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert!(
            mock.state().current_selection.is_some(),
            "selection should be set"
        );

        clear_clipboard(thread, Selection::Clipboard).expect("clear failed");
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert!(
            mock.state().current_selection.is_none(),
            "selection should be cleared"
        );
    }

    /// Set HTML payload and verify paste returns the correct bytes.
    #[test]
    fn mock_compositor_offer_html() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        let html = b"<b>bold</b>";
        set_clipboard(thread, Selection::Clipboard, &MimeType::Html, html)
            .expect("set html failed");
        std::thread::sleep(std::time::Duration::from_millis(50));

        let received = mock
            .trigger_paste("text/html")
            .expect("trigger_paste html failed");
        assert_eq!(received, html, "html paste mismatch");
    }

    /// Set "hello", then set "world" — paste should return "world".
    #[test]
    fn mock_compositor_replace_selection() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        set_clipboard(thread, Selection::Clipboard, &MimeType::Text, b"hello")
            .expect("set hello failed");
        std::thread::sleep(std::time::Duration::from_millis(50));

        set_clipboard(thread, Selection::Clipboard, &MimeType::Text, b"world")
            .expect("set world failed");
        std::thread::sleep(std::time::Duration::from_millis(50));

        let received = mock
            .trigger_paste("text/plain;charset=utf-8")
            .expect("trigger_paste failed");
        assert_eq!(received, b"world", "expected replaced selection");
    }

    // -------------------------------------------------------------------------
    // Phase 6c tests
    // -------------------------------------------------------------------------

    /// Mock advertises a clipboard offer with text/plain;charset=utf-8.
    /// Our backend get(Clipboard, Text) should return the bytes.
    #[test]
    fn mock_get_clipboard_text() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();
        // Clear any owned source left over from a prior test in this
        // process — otherwise do_get short-circuits to our own payload
        // instead of fetching the mock's advertised offer.
        let _ = clear_clipboard(thread, Selection::Clipboard);

        let mut payloads = HashMap::new();
        payloads.insert("text/plain;charset=utf-8".to_owned(), b"hello".to_vec());

        mock.advertise_clipboard_offer(vec!["text/plain;charset=utf-8".to_owned()], payloads);

        // Give the bg thread time to receive and process the offer events.
        std::thread::sleep(std::time::Duration::from_millis(200));

        let result = get_clipboard(thread, Selection::Clipboard, &MimeType::Text);
        let bytes = result.expect("get should succeed");
        assert_eq!(bytes, b"hello", "get returned wrong bytes");
    }

    /// Mock advertises a clipboard offer with text/html.
    /// Our backend get(Clipboard, Html) should return the HTML bytes.
    #[test]
    fn mock_get_clipboard_html() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();
        let _ = clear_clipboard(thread, Selection::Clipboard);

        let html = b"<b>x</b>";
        let mut payloads = HashMap::new();
        payloads.insert("text/html".to_owned(), html.to_vec());

        mock.advertise_clipboard_offer(vec!["text/html".to_owned()], payloads);

        std::thread::sleep(std::time::Duration::from_millis(200));

        let bytes = get_clipboard(thread, Selection::Clipboard, &MimeType::Html)
            .expect("get html should succeed");
        assert_eq!(bytes, html, "html content mismatch");
    }

    /// Advertise text + html; available() should return [Text, Html].
    #[test]
    fn mock_available_lists_mimes() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        let mut payloads = HashMap::new();
        payloads.insert("text/plain;charset=utf-8".to_owned(), b"text".to_vec());
        payloads.insert("text/html".to_owned(), b"<b>html</b>".to_vec());

        mock.advertise_clipboard_offer(
            vec![
                "text/plain;charset=utf-8".to_owned(),
                "text/html".to_owned(),
            ],
            payloads,
        );

        std::thread::sleep(std::time::Duration::from_millis(200));

        let mimes =
            available_clipboard(thread, Selection::Clipboard).expect("available should succeed");

        assert!(mimes.contains(&MimeType::Text), "should have Text");
        assert!(mimes.contains(&MimeType::Html), "should have Html");
    }

    /// No current offer; get() should return UnsupportedMime.
    #[test]
    fn mock_get_unowned_returns_unsupported() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        // Advertise null selection (clear). Send selection(0) by advertising
        // an empty offer vector — actually easier: just don't advertise and
        // reset state to ensure no current offer.
        // The bg thread's current_clipboard_offer may still be set from a
        // prior test. Send a null selection event by advertising an offer
        // with offer_id=0 — but the protocol uses separate events.
        // Simplest: use a short sleep after reset to let any prior state settle,
        // but the offer is only cleared when the compositor sends selection(0).
        // For isolation we rely on advertise_clipboard_offer with a fresh offer
        // and then immediately test the reset path.
        //
        // Just verify that if we ask for a mime not in the current offer,
        // we get UnsupportedMime.
        let _ = clear_clipboard(thread, Selection::Clipboard);
        let mut payloads = HashMap::new();
        payloads.insert("text/html".to_owned(), b"html".to_vec());
        mock.advertise_clipboard_offer(vec!["text/html".to_owned()], payloads);
        std::thread::sleep(std::time::Duration::from_millis(200));

        // Text is not in the offer, so get(Text) should fail.
        let result = get_clipboard(thread, Selection::Clipboard, &MimeType::Text);
        assert!(
            matches!(result, Err(ClipboardError::UnsupportedMime)),
            "expected UnsupportedMime, got: {result:?}"
        );
    }

    /// Regression: self-paste must not deadlock.
    ///
    /// When we own the clipboard data_source, calling `get` previously
    /// went through `offer.receive(write_fd) → read_fd_to_end(read_fd)`,
    /// which deadlocked because the matching `data_source.send` event
    /// could not be dispatched while the bg thread was blocked in
    /// `read`. The fix short-circuits `do_get` when
    /// `state.clipboard_source.is_some()` and returns the cached
    /// payload directly.
    #[test]
    fn self_paste_after_set_does_not_deadlock() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();
        let _ = clear_clipboard(thread, Selection::Clipboard);

        set_clipboard(thread, Selection::Clipboard, &MimeType::Text, b"self-paste")
            .expect("set should succeed");

        // Without the short-circuit this call would block forever on a
        // pipe that only this same bg thread can write to. With the
        // short-circuit it returns the cached payload immediately.
        let bytes = get_clipboard(thread, Selection::Clipboard, &MimeType::Text)
            .expect("self-paste get should succeed");
        assert_eq!(bytes, b"self-paste");
    }

    /// No current offer; available() should return Ok(vec![]).
    #[test]
    fn mock_available_no_offer_returns_empty() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        // Advertise a null selection by sending selection(0).
        // We don't have a direct API for that, but we can check PRIMARY which
        // starts at None after reset. However the shared singleton means we
        // can't guarantee clipboard offer is None either.
        //
        // Test PRIMARY available instead — primary offer is None after reset
        // when no primary offer has been advertised.
        let result = available_clipboard(thread, Selection::Primary)
            .expect("available primary should succeed");
        // May or may not be empty depending on prior test; just verify no panic.
        let _ = result;

        // For a stricter test: check that available for a Selection that has
        // no pending offer returns an empty list. We'll rely on the fact that
        // we do not advertise a PRIMARY offer in most tests, so it should be None.
        // The important thing is no error is returned.
        let mimes = available_clipboard(thread, Selection::Clipboard)
            .expect("available clipboard should succeed");
        // After the previous test advertised an html-only offer, this returns [Html].
        // The key invariant is no panic and Ok is returned.
        assert!(mimes.len() <= 5, "sanity: not too many mimes");
    }

    /// Mock advertises a PRIMARY offer; get(Primary, Text) returns the bytes.
    ///
    /// This test exercises the zwp_primary_selection path end-to-end.
    #[test]
    fn mock_primary_advertise_then_get() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let Some(mock) = ensure_mock() else { return };
        let Some(thread) = get_thread_for_test() else {
            return;
        };

        mock.state().reset();

        let mut payloads = HashMap::new();
        payloads.insert(
            "text/plain;charset=utf-8".to_owned(),
            b"primary-text".to_vec(),
        );

        mock.advertise_primary_offer(vec!["text/plain;charset=utf-8".to_owned()], payloads);

        // Wait for the offer events to be delivered and processed.
        std::thread::sleep(std::time::Duration::from_millis(300));

        let result = get_clipboard(thread, Selection::Primary, &MimeType::Text);
        match result {
            Ok(bytes) => {
                assert_eq!(bytes, b"primary-text", "primary text mismatch");
            }
            Err(ClipboardError::UnsupportedMime) => {
                // Primary device not bound (compositor doesn't support it).
                // Acceptable: the mock advertises the global but if the
                // primary device binding races with the test, this can happen.
                eprintln!("SKIP: primary selection not bound (UnsupportedMime)");
            }
            Err(e) => panic!("unexpected error: {e}"),
        }
    }

    // Self-loop (set then get via own offer): SKIPPED for Wayland.
    //
    // Wayland data-control protocol: the client that sets the selection does
    // NOT receive device.selection() events for its own selection — the
    // compositor suppresses self-notifications (the setter IS the owner, so
    // there's no point advertising it back). Attempting a self-loop would
    // require the mock to fabricate a reflection event which diverges from
    // real compositor behaviour and would only test the mock, not the protocol.
    // Covered by the set path tests (6b) + get path tests above (6c) separately.

    // -------------------------------------------------------------------------
    // Non-blocking send path — issue #4 / buffr#34 regression test
    // -------------------------------------------------------------------------

    /// Simulate the deadlock scenario from issue #4:
    ///
    /// - Create a pipe whose read end is intentionally NOT drained.
    /// - Build a payload larger than the Linux pipe buffer (default 64 KB;
    ///   we use 256 KB) so a blocking write would stall indefinitely.
    /// - Call `begin_nonblocking_write` directly (production helper, not the
    ///   mock layer) and assert it returns immediately, queueing a PendingWrite
    ///   rather than blocking.
    ///
    /// This test does not require a Wayland session.
    #[test]
    fn nonblocking_send_queues_on_full_pipe_instead_of_blocking() {
        use super::super::wayland_socket::WaylandSocket;
        use super::super::wayland_wire;

        // Construct a minimal WaylandState using a socketpair so we have a
        // valid WaylandSocket without a real compositor.
        let mut sv = [0i32; 2];
        // SAFETY: socketpair is safe with valid args.
        let rc = unsafe {
            libc::socketpair(
                libc::AF_UNIX,
                libc::SOCK_STREAM | libc::SOCK_CLOEXEC,
                0,
                sv.as_mut_ptr(),
            )
        };
        assert_eq!(rc, 0, "socketpair failed");

        // We own sv[0] as our "socket"; close sv[1] immediately (we don't
        // need the peer for this test).
        // SAFETY: sv[1] is valid.
        unsafe { libc::close(sv[1]) };

        let socket = unsafe { WaylandSocket::from_raw_fd(sv[0]) };

        let mut state = WaylandState {
            socket,
            next_id: 100,
            seat_name: 0,
            seat_id: 0,
            manager_name: 0,
            manager_id: 0,
            device_id: 0,
            sync_id: 0,
            clipboard_source: None,
            primary_source: None,
            pending_offers: HashMap::new(),
            current_clipboard_offer: None,
            current_primary_offer: None,
            primary_device_id: 0,
            primary_manager_id: 0,
            offer_ids: HashMap::new(),
            pending_writes: Vec::new(),
            fatal_error: false,
        };

        // Create a pipe.  Hold the read end open but never read from it so
        // the pipe buffer fills up.
        let mut fds = [0i32; 2];
        // SAFETY: pipe2 with O_CLOEXEC is safe.
        let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
        assert_eq!(rc, 0, "pipe2 failed");
        let read_fd = fds[0];
        let write_fd = fds[1];

        // 256 KB payload — larger than the 64 KB default Linux pipe buffer.
        let payload = vec![0xABu8; 256 * 1024];

        // This must return immediately without blocking, even though the pipe
        // is unread (issue #4: previously this called write_to_fd which would
        // block here until the pipe drained or the peer closed).
        let start = std::time::Instant::now();
        begin_nonblocking_write(&mut state, write_fd, payload.clone());
        let elapsed = start.elapsed();

        // SAFETY: read_fd is ours; close it now that we've proven the write
        // side did not block.
        unsafe { libc::close(read_fd) };

        // The call must have returned in well under 1 second.
        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "begin_nonblocking_write blocked for {elapsed:?} — deadlock regression"
        );

        // The payload was not fully writable (pipe was never read), so a
        // PendingWrite must have been queued.
        assert!(
            !state.pending_writes.is_empty(),
            "expected a PendingWrite queued for the blocked pipe write"
        );

        // Clean up: close any pending fd.
        for pw in state.pending_writes.drain(..) {
            // SAFETY: fd is ours.
            unsafe { libc::close(pw.fd) };
        }

        // The _ suppresses unused-import warning on wayland_wire (it is used
        // transitively but the compiler can't see it here).
        let _ = wayland_wire::encode_u32;
    }

    /// A `wl_display.error` event must flip `fatal_error` so the main loop
    /// exits instead of spinning on a now-dead connection.
    #[test]
    fn wl_display_error_marks_state_fatal() {
        let mut sv = [0i32; 2];
        // SAFETY: standard socketpair call with a valid out-array.
        let rc = unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, sv.as_mut_ptr()) };
        assert_eq!(rc, 0, "socketpair failed");
        // SAFETY: sv[1] is a valid fd we don't need.
        unsafe { libc::close(sv[1]) };
        // SAFETY: sv[0] is a valid, owned fd.
        let socket = unsafe { WaylandSocket::from_raw_fd(sv[0]) };

        let mut state = WaylandState {
            socket,
            next_id: 100,
            seat_name: 0,
            seat_id: 0,
            manager_name: 0,
            manager_id: 0,
            device_id: 0,
            sync_id: 0,
            clipboard_source: None,
            primary_source: None,
            pending_offers: HashMap::new(),
            current_clipboard_offer: None,
            current_primary_offer: None,
            primary_device_id: 0,
            primary_manager_id: 0,
            offer_ids: HashMap::new(),
            pending_writes: Vec::new(),
            fatal_error: false,
        };

        assert!(!state.fatal_error);
        handle_event(&mut state, WL_DISPLAY_ID, WL_DISPLAY_ERROR, &[], None);
        assert!(
            state.fatal_error,
            "wl_display.error must mark the state as fatal"
        );
    }
}