taut 0.3.0

A Rust GUI library for Windows, Linux, macOS, iOS and the web that aims to be small, fast and accessible, with zero dependencies and nothing compiled in that your program doesn't use.
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
//! Wayland windows shown through Vulkan, with the feature `gpu`, where a window asks for a GPU
//! path (`Renderer::Vulkan`, `Gpu`, or another named): `Auto` keeps shared memory. The CPU
//! draws every pixel as without it, into a buffer the GPU reads; what changed is copied from
//! there into one of three images, with what that image missed since it was last shown, and the
//! image is handed to the compositor as a dmabuf (`zwp_linux_dmabuf_v1`). No shader touches a
//! pixel: the compositor gets the CPU's pixels, byte for byte.
//!
//! - **Layout:** a DRM format modifier both sides take (`VK_EXT_image_drm_format_modifier`),
//!   of one plane the device copies into and exports. The compositor's are from its default
//!   feedback (v4: format table and tranches), else its `modifier` events (v3). A device that
//!   drives the compositor's main device comes first.
//! - **Buffers:** made with `create`, answered later by `created` or `failed`; never
//!   `create_immed`, whose failure ends the connection.
//! - **Frames:** the copy's fence is waited for before the commit. An image is drawn into again
//!   only once the compositor releases it; one of an old size goes when released.
//! - **Failures:** each falls back to shared memory (`wl_shm`) for good, and the surface is
//!   drawn whole there: no Vulkan 1.2, no device exporting dmabufs, a compositor without the
//!   protocol or a common layout, an image or buffer refused, a lost device.
use super::{Host, Link, Sheet, on_pixels};
use crate::canvas::Canvas;
use crate::geom::{Rect, rect};
use crate::platform::Renderer;
use crate::vk::*;
use crate::wayland_wire::{Arg, Interface, Message, Wire, read_file};
use std::ffi::{CStr, c_char, c_int, c_void};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::ptr::{null, null_mut};

/// DRM's codes of the formats handed over: XRGB8888 and ARGB8888, as `wl_shm`'s.
const SOLID: u32 = u32::from_le_bytes(*b"XR24");
const SEE_THROUGH: u32 = u32::from_le_bytes(*b"AR24");
/// A window's images: the one shown, one the compositor may still hold, one to draw into.
const IMAGES: usize = 3;
/// Most places copied one by one; beyond, the area around them all.
const MOST: usize = 16;
/// How long a copy may take before the device is taken for lost: a second, in nanoseconds.
const WAITED: u64 = 1_000_000_000;
/// Vulkan 1.2, as `VK_MAKE_API_VERSION` makes it.
const VULKAN_1_2: u32 = (1 << 22) | (2 << 12);
/// Memory as a dmabuf; exportable so.
const DMA_BUF: u32 = 0x200;
const EXPORTABLE: u32 = 0x2;
/// Images laid out by a DRM format modifier; the memory of their first plane.
const BY_MODIFIER: u32 = 1_000_158_000;
const PLANE_0: u32 = 0x80;
/// A layout's feature: copied into (`VK_FORMAT_FEATURE_TRANSFER_DST_BIT`).
const COPIED_INTO: u32 = 0x8000;
/// The image layout outside this program, and the queue families there: another API's, another
/// device's (`VK_QUEUE_FAMILY_FOREIGN_EXT`), else another instance's (`VK_QUEUE_FAMILY_EXTERNAL`).
const LAYOUT_GENERAL: u32 = 1;
const FOREIGN: u32 = !2;
const EXTERNAL: u32 = !1;
/// Device extensions: needed, then wanted.
const NEEDED: [&CStr; 3] = [c"VK_KHR_external_memory_fd", c"VK_EXT_external_memory_dma_buf", c"VK_EXT_image_drm_format_modifier"];
const TO_OTHERS: &CStr = c"VK_EXT_queue_family_foreign";
const NUMBERED: &CStr = c"VK_EXT_physical_device_drm";

functions!(Global {
    vkCreateInstance: fn(*const VkInstanceCreateInfo, *const c_void, *mut Object) -> i32;
});

functions!(Instance {
    vkDestroyInstance: fn(Object, *const c_void);
    vkEnumeratePhysicalDevices: fn(Object, *mut u32, *mut Object) -> i32;
    vkGetPhysicalDeviceProperties: fn(Object, *mut VkPhysicalDeviceProperties);
    vkGetPhysicalDeviceProperties2: fn(Object, *mut VkPhysicalDeviceProperties2);
    vkGetPhysicalDeviceQueueFamilyProperties: fn(Object, *mut u32, *mut VkQueueFamilyProperties);
    vkGetPhysicalDeviceMemoryProperties: fn(Object, *mut VkPhysicalDeviceMemoryProperties);
    vkGetPhysicalDeviceFormatProperties2: fn(Object, u32, *mut VkFormatProperties2);
    vkGetPhysicalDeviceImageFormatProperties2: fn(Object, *const VkPhysicalDeviceImageFormatInfo2, *mut VkImageFormatProperties2) -> i32;
    vkEnumerateDeviceExtensionProperties: fn(Object, *const c_char, *mut u32, *mut VkExtensionProperties) -> i32;
    vkCreateDevice: fn(Object, *const VkDeviceCreateInfo, *const c_void, *mut Object) -> i32;
    vkGetDeviceProcAddr: fn(Object, *const c_char) -> *const c_void;
});

functions!(Device {
    vkDestroyDevice: fn(Object, *const c_void);
    vkGetDeviceQueue: fn(Object, u32, u32, *mut Object);
    vkDeviceWaitIdle: fn(Object) -> i32;
    vkQueueSubmit: fn(Object, u32, *const VkSubmitInfo, Handle) -> i32;
    vkCreateBuffer: fn(Object, *const VkBufferCreateInfo, *const c_void, *mut Handle) -> i32;
    vkDestroyBuffer: fn(Object, Handle, *const c_void);
    vkGetBufferMemoryRequirements: fn(Object, Handle, *mut VkMemoryRequirements);
    vkCreateImage: fn(Object, *const VkImageCreateInfo, *const c_void, *mut Handle) -> i32;
    vkDestroyImage: fn(Object, Handle, *const c_void);
    vkGetImageMemoryRequirements: fn(Object, Handle, *mut VkMemoryRequirements);
    vkGetImageSubresourceLayout: fn(Object, Handle, *const VkImageSubresource, *mut VkSubresourceLayout);
    vkGetImageDrmFormatModifierPropertiesEXT: fn(Object, Handle, *mut VkImageDrmFormatModifierPropertiesEXT) -> i32;
    vkAllocateMemory: fn(Object, *const VkMemoryAllocateInfo, *const c_void, *mut Handle) -> i32;
    vkFreeMemory: fn(Object, Handle, *const c_void);
    vkBindBufferMemory: fn(Object, Handle, Handle, u64) -> i32;
    vkBindImageMemory: fn(Object, Handle, Handle, u64) -> i32;
    vkMapMemory: fn(Object, Handle, u64, u64, u32, *mut *mut c_void) -> i32;
    vkGetMemoryFdKHR: fn(Object, *const VkMemoryGetFdInfoKHR, *mut c_int) -> i32;
    vkCreateCommandPool: fn(Object, *const VkCommandPoolCreateInfo, *const c_void, *mut Handle) -> i32;
    vkDestroyCommandPool: fn(Object, Handle, *const c_void);
    vkAllocateCommandBuffers: fn(Object, *const VkCommandBufferAllocateInfo, *mut Object) -> i32;
    vkFreeCommandBuffers: fn(Object, Handle, u32, *const Object);
    vkBeginCommandBuffer: fn(Object, *const VkCommandBufferBeginInfo) -> i32;
    vkEndCommandBuffer: fn(Object) -> i32;
    vkCmdPipelineBarrier: fn(Object, u32, u32, u32, u32, *const c_void, u32, *const c_void, u32, *const VkImageMemoryBarrier);
    vkCmdCopyBufferToImage: fn(Object, Handle, Handle, u32, u32, *const VkBufferImageCopy);
    vkCreateFence: fn(Object, *const VkFenceCreateInfo, *const c_void, *mut Handle) -> i32;
    vkDestroyFence: fn(Object, Handle, *const c_void);
    vkWaitForFences: fn(Object, u32, *const Handle, u32, u64) -> i32;
    vkResetFences: fn(Object, u32, *const Handle) -> i32;
});

/// What a program's windows have of dmabufs: the compositor's side, and the device, once asked
/// for.
pub(super) struct Gpu {
    /// `zwp_linux_dmabuf_v1`.
    dmabuf: u32,
    /// The formats and modifiers the compositor takes; and with v4, its format table, the
    /// tranches told since its last `done`, and its main device.
    offered: Vec<(u32, u64)>,
    table: Vec<(u32, u64)>,
    told: Vec<(u32, u64)>,
    main: Option<u64>,
    /// The device (none: none would do), once asked for.
    vulkan: Option<Vulkan>,
    tried: bool,
    /// The compositor's answers: each request's object, and the buffer made (0: refused).
    answers: Vec<(u32, u32)>,
    /// Requests whose images are gone: their buffers go as soon as made.
    orphans: Vec<u32>,
    /// The buffers the compositor holds; and images of an old size it holds, let go once
    /// released.
    held: Vec<u32>,
    retired: Vec<Image>,
}

/// The device, its queue and the layouts both it and the compositor take.
struct Vulkan {
    instance: Object,
    calls: Instance,
    device: Object,
    on: Device,
    queue: Object,
    pool: Handle,
    family: u32,
    /// The queue family images are handed to, and taken back from.
    outside: u32,
    /// Kinds of memory, one bit each: the CPU writes and the GPU reads; the GPU's own.
    writable: u32,
    local: u32,
    /// The modifiers both take, for solid pixels and for see-through ones.
    solid: Vec<u64>,
    clear: Vec<u64>,
    /// The device failed, or was lost: every window goes back to shared memory.
    lost: bool,
    /// Where the GPU draws surfaces too, what it records to, and what it draws with (see
    /// `gpu_draw`).
    #[cfg(feature = "gpu-draw")]
    drawing: crate::gpu_draw::Drawing,
    #[cfg(feature = "gpu-draw")]
    list: Box<crate::gpu_draw::DrawList>,
    #[cfg(feature = "gpu-draw")]
    pipeline: Option<Box<crate::gpu_draw_vulkan::Pipeline>>,
    /// Tests: every copy from now on says the device was lost.
    #[cfg(test)]
    faked: bool,
}

/// A device that could do: its queue family, its layouts, whether it hands images over to
/// another device, and how good it is (0: it drives the compositor's main device; 1: a GPU; 2:
/// the CPU at work).
struct Candidate {
    physical: Object,
    family: u32,
    solid: Vec<u64>,
    clear: Vec<u64>,
    foreign: bool,
    rank: u8,
}

/// How a surface is shown: not yet asked, through the GPU, or by shared memory.
#[derive(Default)]
pub(super) enum Way {
    #[default]
    Unasked,
    Gpu(Shows),
    Shm,
}

/// A surface shown through the GPU: its pixels in a buffer the CPU writes, its images, and the
/// commands copying from one to the other.
pub(super) struct Shows {
    size: [i32; 2],
    clear: bool,
    buffer: Handle,
    memory: Handle,
    pixels: *mut u32,
    images: Vec<Image>,
    commands: Object,
    fence: Handle,
    /// Where the GPU draws the surface (`gpu-draw`): an image of its pixels it draws in, and
    /// its memory (none until it first draws), and the places painted into the buffer since
    /// they were copied into it.
    #[cfg(feature = "gpu-draw")]
    picture: (Handle, Handle),
    #[cfg(feature = "gpu-draw")]
    pending: Vec<[i32; 4]>,
    /// Tests: the places the last frame copied.
    #[cfg(test)]
    copied: Vec<[i32; 4]>,
}

/// An image handed over: its memory, the request for its buffer and the buffer (0: not yet
/// made), whether it was ever copied into, and the places it lacks (left, top, right, bottom in
/// pixels).
struct Image {
    image: Handle,
    memory: Handle,
    params: u32,
    buffer: u32,
    shown: bool,
    missing: Vec<[i32; 4]>,
    /// Tests: its first plane's offset and row pitch in its memory.
    #[cfg(test)]
    layout: (u64, u64),
}

/// What a frame paints: `areas` (in units), at `places` (left, top, right, bottom in pixels), at
/// `scale`, by `paint`.
#[cfg(feature = "gpu-draw")]
struct Painting<'a> {
    areas: &'a [Rect],
    places: &'a [[i32; 4]],
    scale: f32,
    paint: &'a mut dyn FnMut(&mut Canvas),
}

/// What a surface's draw came to.
enum Drawn {
    /// Shared memory shows it.
    Shm,
    /// The GPU failed: shared memory shows it from now on, all of it to be drawn there.
    Fell,
    /// No image is free yet.
    Waits,
    /// This buffer is to be handed over.
    Buffer(u32),
}

impl<App> Host<App> {
    /// Asks the compositor what it takes as dmabufs, where windows ask for a GPU path.
    pub(super) fn ask_gpu(&mut self, renderer: Renderer) {
        ask(&self.link, renderer);
    }

    /// A message to `zwp_linux_dmabuf_v1` or what it made.
    pub(super) fn heard_by_gpu(&mut self, message: Message) {
        if let Some(gpu) = self.link.gpu.borrow_mut().as_mut() {
            gpu.heard(&self.link.wire, message);
        }
    }

    /// Tells the interface which path shows the first window (`Ui::renderer`); it runs again
    /// where that changed.
    pub(super) fn tell_renderer(&mut self) {
        let renderer = if matches!(self.windows[0].sheet.way, Way::Gpu(_)) { Renderer::Vulkan } else { Renderer::Cpu };
        self.rerun |= std::mem::replace(&mut self.ui.renderer, renderer) != renderer;
    }

    /// Whether buffer `id`, released, was an image's (which may be drawn into again).
    pub(super) fn released_by_gpu(&mut self, id: u32) -> bool {
        self.link.gpu.borrow_mut().as_mut().is_some_and(|gpu| gpu.released(&self.link.wire, id))
    }
}

/// Binds `zwp_linux_dmabuf_v1` where windows ask for a GPU path (`renderer`, or
/// `TAUT_RENDERER`) and the compositor offers it, and asks for its default feedback (v4).
fn ask(link: &Link, renderer: Renderer) {
    let ((name, version), wire) = (link.has.dmabuf, &link.wire);
    if name == 0 || crate::platform::wants_gpu(renderer) != Some(true) {
        return;
    }
    let version = version.min(4);
    let dmabuf = wire.bind(link.has.registry, name, "zwp_linux_dmabuf_v1", version, Interface::Dmabuf);
    let feedback = if version >= 4 { wire.make(Interface::DmabufFeedback) } else { 0 };
    if feedback != 0 {
        wire.send(dmabuf, 2, &[Arg::Uint(feedback)]);
    }
    let gpu = Gpu {
        dmabuf,
        offered: Vec::new(),
        table: Vec::new(),
        told: Vec::new(),
        main: None,
        vulkan: None,
        tried: false,
        answers: Vec::new(),
        orphans: Vec::new(),
        held: Vec::new(),
        retired: Vec::new(),
    };
    *link.gpu.borrow_mut() = Some(gpu);
}

impl Sheet {
    /// Draws what changed through the GPU where it shows this surface: painted into its
    /// pixels, copied into a free image, handed over. Says whether it committed; nothing where
    /// shared memory shows it (all of it, where the GPU just failed).
    pub(super) fn draw_by_gpu(&mut self, link: &Link, scale: f32, paint: &mut dyn FnMut(&mut Canvas)) -> Option<bool> {
        if matches!(self.way, Way::Shm) {
            return None;
        }
        let (units, size, clear) = (rect(0.0, 0.0, self.units[0] as f32, self.units[1] as f32), self.pixels, self.clear);
        let areas: Vec<Rect> = self.changed.iter().map(|area| area.intersect(units)).filter(|area| !area.is_empty()).collect();
        let places: Vec<[i32; 4]> = areas.iter().map(|area| on_pixels(*area, scale, size)).collect();
        #[cfg(not(feature = "gpu-draw"))]
        let mut painted = |pixels: &mut [u32]| areas.iter().for_each(|area| paint_pixels(pixels, size, *area, scale, clear, paint));
        #[cfg(feature = "gpu-draw")]
        let painting = Painting { areas: &areas, places: &places, scale, paint };
        let drawn = match link.gpu.borrow_mut().as_mut() {
            #[cfg(not(feature = "gpu-draw"))]
            Some(gpu) => gpu.draw(&link.wire, &mut self.way, size, clear, &places, &mut painted),
            #[cfg(feature = "gpu-draw")]
            Some(gpu) => gpu.draw(&link.wire, &mut self.way, size, clear, &places, painting),
            None => Drawn::Shm,
        };
        match drawn {
            Drawn::Shm => self.way = Way::Shm,
            Drawn::Fell => (self.way, self.changed) = (Way::Shm, vec![units]),
            Drawn::Waits => return Some(self.pay(link)),
            Drawn::Buffer(buffer) => return Some(self.hand_over(link, buffer, scale)),
        }
        None
    }

    /// Hands buffer `id` over, naming what changed as damage, and asks for a frame callback (as
    /// `draw` does for a buffer of shared memory). Says it committed.
    fn hand_over(&mut self, link: &Link, id: u32, scale: f32) -> bool {
        let (wire, units) = (&link.wire, rect(0.0, 0.0, self.units[0] as f32, self.units[1] as f32));
        wire.send(self.surface, 1, &[Arg::Object(id), Arg::Int(0), Arg::Int(0)]);
        for area in std::mem::take(&mut self.changed) {
            let [left, top, right, bottom] = on_pixels(area.intersect(units), scale, self.pixels);
            wire.send(self.surface, 9, &[Arg::Int(left), Arg::Int(top), Arg::Int(right - left), Arg::Int(bottom - top)]);
        }
        self.waiting = wire.make(Interface::Callback);
        wire.send(self.surface, 3, &[Arg::Uint(self.waiting)]);
        wire.send(self.surface, 6, &[]);
        (self.hurry, self.owed) = (false, false);
        true
    }

    /// Lets go of what the GPU has of a surface.
    pub(super) fn forget_gpu(link: &Link, way: Way) {
        if let (Way::Gpu(shows), Some(gpu)) = (way, link.gpu.borrow_mut().as_mut()) {
            gpu.forget(&link.wire, shows);
        }
    }
}

impl Gpu {
    /// Takes a message to `zwp_linux_dmabuf_v1` (v3: a format's modifier), its feedback (v4:
    /// the format table, the main device, a tranche's formats, the end of a tranche and of all),
    /// or a buffer request (made, or refused).
    fn heard(&mut self, wire: &Wire, mut message: Message) {
        match (message.of, message.opcode) {
            (Interface::Dmabuf, 1) => {
                let (format, high, low) = (message.uint(), message.uint(), message.uint());
                self.offered.push((format, (high as u64) << 32 | low as u64));
            }
            (Interface::DmabufFeedback, 0) => self.offered = std::mem::take(&mut self.told),
            (Interface::DmabufFeedback, 1) => {
                let (size, file) = (message.uint() as usize, message.file.take());
                self.table = file.and_then(|file| read_file(&file, size.min(1 << 20))).map(|bytes| table(&bytes)).unwrap_or_default();
            }
            (Interface::DmabufFeedback, 2) => self.main = message.bytes().first_chunk::<8>().map(|number| u64::from_ne_bytes(*number)),
            (Interface::DmabufFeedback, 5) => {
                let table = &self.table;
                let found = message.bytes().as_chunks::<2>().0.iter().filter_map(|index| table.get(u16::from_ne_bytes(*index) as usize));
                self.told.extend(found);
            }
            (Interface::DmabufParams, 0) => {
                let buffer = message.uint();
                wire.note(buffer, Interface::Buffer);
                self.made(wire, message.object, buffer);
            }
            (Interface::DmabufParams, 1) => self.made(wire, message.object, 0),
            _ => {}
        }
    }

    /// The compositor answered request `params`: `buffer` made (0: refused). The answer waits
    /// for its image (the request lives until then: its number is not used again meanwhile);
    /// where the image is gone, the request and the buffer go.
    fn made(&mut self, wire: &Wire, params: u32, buffer: u32) {
        let Some(at) = self.orphans.iter().position(|orphan| *orphan == params) else { return self.answers.push((params, buffer)) };
        self.orphans.swap_remove(at);
        wire.send(params, 0, &[]);
        unbuffer(wire, buffer);
    }

    /// The answer to an image's request, if there is one yet: the request goes.
    fn answer(&mut self, wire: &Wire, image: &mut Image) -> bool {
        let Some(at) = self.answers.iter().position(|(params, _)| *params == image.params) else { return false };
        wire.send(image.params, 0, &[]);
        (image.params, image.buffer) = (0, self.answers.swap_remove(at).1);
        true
    }

    /// Buffer `id` was released. Says whether it was an image's: one of an old size goes.
    fn released(&mut self, wire: &Wire, id: u32) -> bool {
        let Some(at) = self.held.iter().position(|held| *held == id) else { return false };
        self.held.swap_remove(at);
        if let Some(at) = self.retired.iter().position(|image| image.buffer == id) {
            let image = self.retired.swap_remove(at);
            self.unmake(wire, image);
        }
        true
    }

    /// Draws a surface `size` pixels big through the GPU, if it shows it: `paint` paints `places`
    /// into its pixels (or, with `gpu-draw`, the GPU draws some), which are copied into a free
    /// image.
    #[rustfmt::skip]
    fn draw(&mut self, wire: &Wire, way: &mut Way, size: [i32; 2], clear: bool, places: &[[i32; 4]],
        #[cfg(not(feature = "gpu-draw"))] paint: &mut dyn FnMut(&mut [u32]), #[cfg(feature = "gpu-draw")] paint: Painting) -> Drawn {
        if matches!(way, Way::Unasked) {
            *way = self.shows(clear).map_or(Way::Shm, Way::Gpu);
        }
        let Way::Gpu(shows) = way else { return Drawn::Shm };
        match self.frame(wire, shows, size, places, paint) {
            Ok(Some(buffer)) => Drawn::Buffer(buffer),
            Ok(None) => Drawn::Waits,
            Err(()) => self.fall(wire, way),
        }
    }

    /// The GPU failed a surface: shared memory shows it from now on.
    fn fall(&mut self, wire: &Wire, way: &mut Way) -> Drawn {
        if let Way::Gpu(shows) = std::mem::replace(way, Way::Shm) {
            self.forget(wire, shows);
        }
        Drawn::Fell
    }

    /// A surface's part on the GPU, its images not yet made. Nothing where the device can't
    /// show it (opened first, if it was not yet).
    fn shows(&mut self, clear: bool) -> Option<Shows> {
        if !std::mem::replace(&mut self.tried, true) {
            self.vulkan = Vulkan::open(&self.offered, self.main);
        }
        let vulkan = self.vulkan.as_mut().filter(|vulkan| !vulkan.lost)?;
        if (if clear { &vulkan.clear } else { &vulkan.solid }).is_empty() {
            return None;
        }
        let (commands, fence) = vulkan.parts()?;
        Some(Shows {
            size: [0; 2],
            clear,
            buffer: 0,
            memory: 0,
            pixels: null_mut(),
            images: Vec::new(),
            commands,
            fence,
            #[cfg(feature = "gpu-draw")]
            picture: (0, 0),
            #[cfg(feature = "gpu-draw")]
            pending: Vec::new(),
            #[cfg(test)]
            copied: Vec::new(),
        })
    }

    /// One frame of a surface: its places painted into its pixels (or drawn by the GPU) and
    /// copied, with what the image lacks, into the first image made and free. The buffer to
    /// hand over; nothing where none is free yet. An error where the device or the compositor
    /// failed.
    #[rustfmt::skip]
    fn frame(&mut self, wire: &Wire, shows: &mut Shows, size: [i32; 2], places: &[[i32; 4]],
        #[cfg(not(feature = "gpu-draw"))] paint: &mut dyn FnMut(&mut [u32]), #[cfg(feature = "gpu-draw")] paint: Painting) -> Result<Option<u32>, ()> {
        if self.vulkan.as_ref().is_none_or(|vulkan| vulkan.lost) {
            return Err(());
        }
        if shows.size != size {
            self.fit(wire, shows, size)?;
        }
        self.answered(wire, shows)?;
        let held = &self.held;
        let Some(at) = shows.images.iter().position(|image| image.buffer != 0 && !held.contains(&image.buffer)) else { return Ok(None) };
        #[cfg(feature = "gpu-draw")]
        if !self.vulkan.as_mut().is_some_and(|vulkan| vulkan.painted(shows, paint)) {
            return Err(());
        }
        // SAFETY: the pixels are mapped, `size` big, and the GPU is done with them (every copy
        // is waited for).
        #[cfg(not(feature = "gpu-draw"))]
        paint(unsafe { std::slice::from_raw_parts_mut(shows.pixels, size[0] as usize * size[1] as usize) });
        let mut wanted = std::mem::take(&mut shows.images[at].missing);
        wanted.extend_from_slice(places);
        let wanted = bounded(wanted);
        if !self.vulkan.as_mut().is_some_and(|vulkan| vulkan.copy(shows, at, &wanted)) {
            return Err(());
        }
        for (_, image) in shows.images.iter_mut().enumerate().filter(|(other, _)| *other != at) {
            image.missing.extend_from_slice(places);
            image.missing = bounded(std::mem::take(&mut image.missing));
        }
        #[cfg(test)]
        {
            shows.copied = wanted;
        }
        shows.images[at].shown = true;
        self.held.push(shows.images[at].buffer);
        Ok(Some(shows.images[at].buffer))
    }

    /// Takes the compositor's answers for a surface's images. An error where it refused one.
    fn answered(&mut self, wire: &Wire, shows: &mut Shows) -> Result<(), ()> {
        for image in shows.images.iter_mut().filter(|image| image.buffer == 0) {
            if self.answer(wire, image) && image.buffer == 0 {
                return Err(());
            }
        }
        Ok(())
    }

    /// Gives a surface pixels and images `size` big; those of the old size go (as the
    /// compositor releases them). An error where any can't be made.
    fn fit(&mut self, wire: &Wire, shows: &mut Shows, size: [i32; 2]) -> Result<(), ()> {
        std::mem::take(&mut shows.images).into_iter().for_each(|image| self.let_go(wire, image));
        let (vulkan, dmabuf) = (self.vulkan.as_mut().ok_or(())?, self.dmabuf);
        vulkan.unbuffer(shows);
        shows.size = size;
        if !vulkan.buffer(shows) {
            return Err(());
        }
        for _ in 0..IMAGES {
            let image = vulkan.image(wire, dmabuf, size, shows.clear).ok_or(())?;
            shows.images.push(image);
        }
        Ok(())
    }

    /// Lets go of an image: at once, or once the compositor releases its buffer.
    fn let_go(&mut self, wire: &Wire, mut image: Image) {
        if image.buffer != 0 && self.held.contains(&image.buffer) {
            return self.retired.push(image);
        }
        if image.buffer == 0 && image.params != 0 && !self.answer(wire, &mut image) {
            self.orphans.push(image.params);
        }
        self.unmake(wire, image);
    }

    /// Destroys an image and its buffer.
    fn unmake(&mut self, wire: &Wire, image: Image) {
        unbuffer(wire, image.buffer);
        if let Some(vulkan) = &self.vulkan {
            vulkan.unmake(&image);
        }
    }

    /// Lets go of a surface's part on the GPU.
    fn forget(&mut self, wire: &Wire, mut shows: Shows) {
        std::mem::take(&mut shows.images).into_iter().for_each(|image| self.let_go(wire, image));
        if let Some(vulkan) = &mut self.vulkan {
            vulkan.unbuffer(&mut shows);
            vulkan.unpart(&shows);
        }
    }

    /// Tests: the device is lost, as when it is removed: the next copy says so.
    #[cfg(test)]
    fn lose(&mut self) {
        if let Some(vulkan) = &mut self.vulkan {
            vulkan.faked = true;
        }
    }
}

impl Drop for Gpu {
    /// Lets go of the images still held. (The device goes after.)
    fn drop(&mut self) {
        if let Some(vulkan) = &self.vulkan {
            self.retired.iter().for_each(|image| vulkan.unmake(image));
        }
    }
}

/// Draws one area into pixels `size` big: a canvas over the rows it covers (as `paint_area`
/// does into a buffer of shared memory).
fn paint_pixels(pixels: &mut [u32], [width, height]: [i32; 2], area: Rect, scale: f32, clear: bool, paint: &mut dyn FnMut(&mut Canvas)) {
    let [_, top, _, bottom] = on_pixels(area, scale, [width, height]);
    if top >= bottom {
        return;
    }
    let rows = &mut pixels[(top * width) as usize..(bottom * width) as usize];
    let mut canvas = Canvas::new(rows, width as usize, (bottom - top) as usize, (0, top), scale);
    canvas.clip(area.snap_to_pixels(scale));
    if clear {
        canvas.erase();
    }
    paint(&mut canvas);
}

/// Destroys a buffer the compositor made (0: none).
fn unbuffer(wire: &Wire, buffer: u32) {
    if buffer != 0 {
        wire.send(buffer, 0, &[]);
        wire.note(buffer, Interface::Free);
    }
}

/// Places (left, top, right, bottom), none inside another, up to `MOST`; else the area around
/// them all.
fn bounded(places: Vec<[i32; 4]>) -> Vec<[i32; 4]> {
    let inside = |inner: &[i32; 4], outer: &[i32; 4]| outer[0] <= inner[0] && outer[1] <= inner[1] && inner[2] <= outer[2] && inner[3] <= outer[3];
    let mut kept: Vec<[i32; 4]> = Vec::new();
    for place in places {
        if !kept.iter().any(|other| inside(&place, other)) {
            kept.retain(|other| !inside(other, &place));
            kept.push(place);
        }
    }
    if kept.len() <= MOST {
        return kept;
    }
    vec![kept.iter().fold([i32::MAX, i32::MAX, 0, 0], |all, place| [all[0].min(place[0]), all[1].min(place[1]), all[2].max(place[2]), all[3].max(place[3])])]
}

/// The compositor's format table: a format and a modifier each 16 bytes.
fn table(bytes: &[u8]) -> Vec<(u32, u64)> {
    let entries = bytes.as_chunks::<16>().0.iter().filter_map(|entry| Some((u32::from_ne_bytes(*entry.first_chunk()?), u64::from_ne_bytes(*entry.last_chunk()?))));
    entries.collect()
}

/// A device number (`dev_t`) from its major and minor numbers, as glibc's `makedev` makes it.
fn device_number(major: u64, minor: u64) -> u64 {
    (major & 0xffff_f000) << 32 | (major & 0xfff) << 8 | (minor & 0xffff_ff00) << 12 | (minor & 0xff)
}

impl Vulkan {
    /// Opens the loader, makes an instance of Vulkan 1.2, and a device on the best that hands
    /// over images the compositor takes (`offered`; driving its `main` device first). Nothing
    /// where none does.
    fn open(offered: &[(u32, u64)], main: Option<u64>) -> Option<Vulkan> {
        let get = loader()?;
        // SAFETY: the instance is null or Vulkan's.
        let find = move |instance: Object, name: &CStr| unsafe { get(instance, name.as_ptr()) };
        let global = Global::load(&mut |name| find(null_mut(), name)).ok()?;
        let application = VkApplicationInfo { kind: 0, api_version: VULKAN_1_2, ..Default::default() };
        let asked = VkInstanceCreateInfo { kind: 1, application: &application, ..Default::default() };
        let mut instance = null_mut();
        // SAFETY: Vulkan's documented call.
        if unsafe { (global.vkCreateInstance)(&asked, null(), &mut instance) } != 0 {
            return None;
        }
        let Ok(calls) = Instance::load(&mut |name| find(instance, name)) else { return unmade(find(instance, c"vkDestroyInstance"), instance) };
        // SAFETY: Vulkan's documented enumeration.
        let devices = listed(null_mut(), |count, list| unsafe { (calls.vkEnumeratePhysicalDevices)(instance, count, list) });
        let best = devices.into_iter().filter_map(|physical| Candidate::of(&calls, physical, offered, main)).min_by_key(|candidate| candidate.rank);
        match best {
            Some(best) => Vulkan::make(instance, calls, best),
            None => unmade(calls.vkDestroyInstance as *const c_void, instance),
        }
    }

    /// A device on `chosen`, with its queue and a pool of commands. Nothing (and the instance
    /// gone) where any of it can't be made.
    fn make(instance: Object, calls: Instance, chosen: Candidate) -> Option<Vulkan> {
        let mut names: Vec<*const c_char> = NEEDED.iter().map(|name| name.as_ptr()).collect();
        if chosen.foreign {
            names.push(TO_OTHERS.as_ptr());
        }
        let (physical, family, priority) = (chosen.physical, chosen.family, 1.0f32);
        let queue = VkDeviceQueueCreateInfo { kind: 2, family, count: 1, priorities: &priority, ..Default::default() };
        let asked = VkDeviceCreateInfo { kind: 3, queue_count: 1, queues: &queue, extension_count: names.len() as u32, extensions: names.as_ptr(), ..Default::default() };
        let (mut device, mut memory) = (null_mut(), VkPhysicalDeviceMemoryProperties::default());
        // SAFETY: Vulkan's documented calls; the names end in zeros.
        let made = unsafe {
            (calls.vkGetPhysicalDeviceMemoryProperties)(physical, &mut memory);
            (calls.vkCreateDevice)(physical, &asked, null(), &mut device)
        };
        let find = calls.vkGetDeviceProcAddr;
        // SAFETY: the device was just made.
        let on = (made == 0).then(|| Device::load(&mut |name| unsafe { find(device, name.as_ptr()) }).ok()).flatten();
        let Some(on) = on else {
            if made == 0 {
                // SAFETY: the device was just made.
                unmade(unsafe { find(device, c"vkDestroyDevice".as_ptr()) }, device);
            }
            return unmade(calls.vkDestroyInstance as *const c_void, instance);
        };
        let kinds = |wanted: u32| memory.types.iter().take(memory.type_count as usize).enumerate().filter(|(_, kind)| kind.flags & wanted == wanted).fold(0, |all, (at, _)| all | 1 << at);
        let outside = if chosen.foreign { FOREIGN } else { EXTERNAL };
        let (writable, local) = (kinds(HOST_VISIBLE_AND_COHERENT), kinds(DEVICE_LOCAL));
        let mut vulkan = Vulkan {
            instance,
            calls,
            device,
            on,
            queue: null_mut(),
            pool: 0,
            family,
            outside,
            writable,
            local,
            solid: chosen.solid,
            clear: chosen.clear,
            lost: false,
            #[cfg(feature = "gpu-draw")]
            drawing: crate::gpu_draw::Drawing::chosen(false, chosen.rank < 2, std::env::var("TAUT_DRAW").ok().as_deref()),
            #[cfg(feature = "gpu-draw")]
            list: Box::default(),
            #[cfg(feature = "gpu-draw")]
            pipeline: None,
            #[cfg(test)]
            faked: false,
        };
        // What it draws with, where it draws: its shaders are made here.
        #[cfg(feature = "gpu-draw")]
        if vulkan.drawing != crate::gpu_draw::Drawing::Never {
            // SAFETY: the device was just made; the names end in zeros.
            vulkan.pipeline = crate::gpu_draw_vulkan::Pipeline::new(&mut |name| unsafe { find(device, name.as_ptr()) }, device, &memory, false);
        }
        let pool = VkCommandPoolCreateInfo { kind: 39, flags: 0x2, family, ..Default::default() };
        // SAFETY: the device's queue 0 of the family it was made with; and a pool for it.
        let made = unsafe {
            (vulkan.on.vkGetDeviceQueue)(device, family, 0, &mut vulkan.queue);
            (vulkan.on.vkCreateCommandPool)(device, &pool, null(), &mut vulkan.pool)
        };
        (made == 0).then_some(vulkan)
    }

    /// A surface's commands and their fence. Nothing where either can't be made.
    fn parts(&mut self) -> Option<(Object, Handle)> {
        let commands = VkCommandBufferAllocateInfo { kind: 40, pool: self.pool, count: 1, ..Default::default() };
        let fence = VkFenceCreateInfo { kind: 8, ..Default::default() };
        let (mut made, mut fenced) = (null_mut(), 0);
        // SAFETY: Vulkan's documented calls on the device, filling in one handle each.
        let results = unsafe { [(self.on.vkAllocateCommandBuffers)(self.device, &commands, &mut made), (self.on.vkCreateFence)(self.device, &fence, null(), &mut fenced)] };
        if results == [0; 2] {
            return Some((made, fenced));
        }
        // SAFETY: what was made is not used after; null handles are let be.
        unsafe { (self.on.vkDestroyFence)(self.device, fenced, null()) };
        if !made.is_null() {
            unsafe { (self.on.vkFreeCommandBuffers)(self.device, self.pool, 1, &made) };
        }
        None
    }

    /// Lets go of a surface's commands and fence.
    fn unpart(&self, shows: &Shows) {
        // SAFETY: neither is in use (every copy is waited for).
        unsafe {
            (self.on.vkDestroyFence)(self.device, shows.fence, null());
            (self.on.vkFreeCommandBuffers)(self.device, self.pool, 1, &shows.commands);
        }
    }

    /// Makes a surface's pixels: a buffer its size, in memory the CPU writes and the GPU reads,
    /// mapped. Says whether it could.
    fn buffer(&mut self, shows: &mut Shows) -> bool {
        let (on, device, [width, height]) = (&self.on, self.device, shows.size);
        let asked = VkBufferCreateInfo { kind: 12, size: width as u64 * height as u64 * 4, usage: USAGE_TRANSFER_SOURCE, ..Default::default() };
        let mut needs = VkMemoryRequirements::default();
        // SAFETY: Vulkan's documented calls on the device.
        unsafe {
            if (on.vkCreateBuffer)(device, &asked, null(), &mut shows.buffer) != 0 {
                return false;
            }
            (on.vkGetBufferMemoryRequirements)(device, shows.buffer, &mut needs);
        }
        let fitting = needs.type_bits & self.writable;
        let asked = VkMemoryAllocateInfo { kind: 5, size: needs.size, type_index: fitting.trailing_zeros(), ..Default::default() };
        let mut pixels = null_mut();
        // SAFETY: as above; the memory is bound whole and mapped whole.
        let made = unsafe {
            fitting != 0
                && (on.vkAllocateMemory)(device, &asked, null(), &mut shows.memory) == 0
                && (on.vkBindBufferMemory)(device, shows.buffer, shows.memory, 0) == 0
                && (on.vkMapMemory)(device, shows.memory, 0, needs.size, 0, &mut pixels) == 0
        };
        shows.pixels = pixels.cast();
        made && !pixels.is_null()
    }

    /// Lets go of a surface's pixels, and the image the GPU draws them in.
    fn unbuffer(&self, shows: &mut Shows) {
        #[cfg(feature = "gpu-draw")]
        if let Some(pipeline) = &self.pipeline {
            pipeline.unpicture(std::mem::take(&mut shows.picture));
            shows.pending.clear();
        }
        // SAFETY: the GPU is done with them (every copy is waited for); null handles are let be.
        unsafe {
            (self.on.vkDestroyBuffer)(self.device, shows.buffer, null());
            (self.on.vkFreeMemory)(self.device, shows.memory, null());
        }
        (shows.buffer, shows.memory, shows.pixels) = (0, 0, null_mut());
    }

    /// An image `size` big, exported, and the compositor asked to make a buffer of it (through
    /// `dmabuf`). Nothing where any of it can't be had.
    fn image(&self, wire: &Wire, dmabuf: u32, [width, height]: [i32; 2], clear: bool) -> Option<Image> {
        let modifiers = if clear { &self.clear } else { &self.solid };
        let list = VkImageDrmFormatModifierListCreateInfoEXT { kind: 1_000_158_003, count: modifiers.len() as u32, modifiers: modifiers.as_ptr(), ..Default::default() };
        let external = VkExternalMemoryImageCreateInfo { kind: 1_000_072_001, next: (&raw const list).cast(), handles: DMA_BUF };
        let asked = VkImageCreateInfo {
            kind: 14,
            next: (&raw const external).cast(),
            image_type: 1,
            format: B8G8R8A8_UNORM,
            extent: [width as u32, height as u32, 1],
            mip_levels: 1,
            array_layers: 1,
            samples: 1,
            tiling: BY_MODIFIER,
            usage: USAGE_TRANSFER_DESTINATION,
            ..Default::default()
        };
        let mut image = Image {
            image: 0,
            memory: 0,
            params: 0,
            buffer: 0,
            shown: false,
            missing: vec![[0, 0, width, height]],
            #[cfg(test)]
            layout: (0, 0),
        };
        // SAFETY: Vulkan's documented call; everything chained lives until it returns.
        if unsafe { (self.on.vkCreateImage)(self.device, &asked, null(), &mut image.image) } != 0 {
            return None;
        }
        let Some((file, offset, pitch, modifier)) = self.backed(&mut image).then(|| self.exported(&image)).flatten() else {
            self.unmake(&image);
            return None;
        };
        #[cfg(test)]
        {
            image.layout = (offset as u64, pitch as u64);
        }
        let format = if clear { SEE_THROUGH } else { SOLID };
        image.params = wire.make(Interface::DmabufParams);
        wire.send(dmabuf, 1, &[Arg::Uint(image.params)]);
        wire.send(image.params, 1, &[Arg::File(file.as_raw_fd()), Arg::Uint(0), Arg::Uint(offset), Arg::Uint(pitch), Arg::Uint((modifier >> 32) as u32), Arg::Uint(modifier as u32)]);
        wire.send(image.params, 2, &[Arg::Int(width), Arg::Int(height), Arg::Uint(format), Arg::Uint(0)]);
        Some(image)
    }

    /// Gives an image memory of its own, the GPU's where it can, exportable as a dmabuf. Says
    /// whether it could.
    fn backed(&self, image: &mut Image) -> bool {
        let mut needs = VkMemoryRequirements::default();
        // SAFETY: Vulkan's documented call on the device's image.
        unsafe { (self.on.vkGetImageMemoryRequirements)(self.device, image.image, &mut needs) };
        let kinds = if needs.type_bits & self.local != 0 { needs.type_bits & self.local } else { needs.type_bits };
        let own = VkMemoryDedicatedAllocateInfo { kind: 1_000_127_001, image: image.image, ..Default::default() };
        let export = VkExportMemoryAllocateInfo { kind: 1_000_072_002, next: (&raw const own).cast(), handles: DMA_BUF };
        let asked = VkMemoryAllocateInfo { kind: 5, next: (&raw const export).cast(), size: needs.size, type_index: kinds.trailing_zeros() };
        // SAFETY: as above; everything chained lives until it returns.
        kinds != 0 && unsafe { (self.on.vkAllocateMemory)(self.device, &asked, null(), &mut image.memory) == 0 && (self.on.vkBindImageMemory)(self.device, image.image, image.memory, 0) == 0 }
    }

    /// An image's memory as a dmabuf, with its first plane's offset and row pitch, and the
    /// modifier the device chose. Nothing where it can't be had.
    fn exported(&self, image: &Image) -> Option<(OwnedFd, u32, u32, u64)> {
        let mut chosen = VkImageDrmFormatModifierPropertiesEXT { kind: 1_000_158_005, ..Default::default() };
        let (plane, mut layout, mut fd) = (VkImageSubresource { aspect: PLANE_0, level: 0, layer: 0 }, VkSubresourceLayout::default(), -1);
        let asked = VkMemoryGetFdInfoKHR { kind: 1_000_074_002, memory: image.memory, handle: DMA_BUF, ..Default::default() };
        // SAFETY: Vulkan's documented calls on the device's image and its memory.
        let said = unsafe {
            (self.on.vkGetImageSubresourceLayout)(self.device, image.image, &plane, &mut layout);
            [(self.on.vkGetImageDrmFormatModifierPropertiesEXT)(self.device, image.image, &mut chosen), (self.on.vkGetMemoryFdKHR)(self.device, &asked, &mut fd)]
        };
        // SAFETY: an fd Vulkan just gave this program.
        let file = (fd >= 0).then(|| unsafe { OwnedFd::from_raw_fd(fd) })?;
        let (offset, pitch) = (u32::try_from(layout.offset).ok()?, u32::try_from(layout.row_pitch).ok()?);
        (said == [0; 2]).then_some((file, offset, pitch, chosen.modifier))
    }

    /// Destroys an image and its memory.
    fn unmake(&self, image: &Image) {
        // SAFETY: the GPU is done with it (every copy is waited for); null handles are let be.
        unsafe {
            (self.on.vkDestroyImage)(self.device, image.image, null());
            (self.on.vkFreeMemory)(self.device, image.memory, null());
        }
    }

    /// Paints a frame's places into a surface's pixels, each but those the GPU draws into the
    /// image it draws the surface in. Says whether all went well; if not, the device is lost.
    #[cfg(feature = "gpu-draw")]
    fn painted(&mut self, shows: &mut Shows, painting: Painting) -> bool {
        let [width, height] = shows.size;
        for (area, place) in painting.areas.iter().zip(painting.places) {
            if self.drawn_by_gpu(shows, *area, *place, painting.scale, &mut *painting.paint) {
                continue;
            }
            // SAFETY: the pixels are mapped, `size` big, and the GPU is done with them (every
            // copy is waited for).
            let pixels = unsafe { std::slice::from_raw_parts_mut(shows.pixels, width as usize * height as usize) };
            paint_pixels(pixels, shows.size, *area, painting.scale, shows.clear, &mut *painting.paint);
            if shows.picture.0 != 0 {
                crate::gpu_x11::note(&mut shows.pending, *place);
            }
        }
        !self.lost
    }

    /// Draws `area` of a solid surface (`place` in pixels) into the image the GPU draws it in
    /// (made the first time, from the pixels), where it draws a part that big (see `gpu_draw`).
    /// Says whether it did: if not, the CPU is to.
    #[cfg(feature = "gpu-draw")]
    fn drawn_by_gpu(&mut self, shows: &mut Shows, area: Rect, place: [i32; 4], scale: f32, paint: &mut dyn FnMut(&mut Canvas)) -> bool {
        if shows.clear || !self.drawing.takes(place) {
            return false;
        }
        let (Some(mut pipeline), mut list) = (self.pipeline.take(), std::mem::take(&mut *self.list)) else { return false };
        list.begin(shows.size);
        let mut canvas = Canvas::recording(&mut list, shows.size[0] as usize, shows.size[1] as usize, (0, 0), scale);
        canvas.clip(area.snap_to_pixels(scale));
        paint(&mut canvas);
        drop(canvas);
        let drawn = !list.failed && self.draw_with(shows, &mut pipeline, &list, place);
        list.finish(drawn);
        (*self.list, self.pipeline) = (list, Some(pipeline));
        drawn
    }

    /// Records and runs a paint drawn by `pipeline` into the image the GPU draws a surface in,
    /// inside `place`, and waits for it. A failure loses the device: the image and the pixels
    /// no longer agree.
    #[cfg(feature = "gpu-draw")]
    fn draw_with(&mut self, shows: &mut Shows, pipeline: &mut crate::gpu_draw_vulkan::Pipeline, list: &crate::gpu_draw::DrawList, place: [i32; 4]) -> bool {
        let fresh = shows.picture.0 == 0;
        if fresh {
            let Some(made) = pipeline.picture(shows.size) else { return false };
            shows.picture = made;
        }
        let (commands, begin) = (shows.commands, VkCommandBufferBeginInfo { kind: 42, flags: 0x1, ..Default::default() });
        // SAFETY: Vulkan's documented calls; the commands are not in use (their last run was
        // waited for).
        unsafe {
            (self.on.vkResetFences)(self.device, 1, &shows.fence);
            (self.on.vkBeginCommandBuffer)(commands, &begin);
        }
        self.fill_picture(shows, fresh);
        let was = crate::gpu_draw_vulkan::Was { layout: LAYOUT_TRANSFER_SOURCE, access: ACCESS_TRANSFER_READ, stage: STAGE_TRANSFER };
        let recorded = pipeline.record(commands, shows.picture.0, shows.size, list, place, was, LAYOUT_TRANSFER_SOURCE);
        let (on, submit) = (&self.on, VkSubmitInfo { kind: 4, buffer_count: 1, buffers: &commands, ..Default::default() });
        // SAFETY: as above; the fence is the surface's.
        let done = unsafe {
            (on.vkEndCommandBuffer)(commands) == 0 && recorded && (on.vkQueueSubmit)(self.queue, 1, &submit, shows.fence) == 0 && (on.vkWaitForFences)(self.device, 1, &shows.fence, 1, WAITED) == 0
        };
        pipeline.forget_target();
        self.lost |= !done;
        done
    }

    /// Records the places painted since copied into the image the GPU draws a surface in (all
    /// of it, if `fresh`: just made), which is then ready to be copied from.
    #[cfg(feature = "gpu-draw")]
    fn fill_picture(&self, shows: &mut Shows, fresh: bool) {
        if shows.pending.is_empty() && !fresh {
            return;
        }
        let (picture, width) = (shows.picture.0, shows.size[0]);
        let places = if fresh { vec![[0, 0, shows.size[0], shows.size[1]]] } else { std::mem::take(&mut shows.pending) };
        let regions: Vec<VkBufferImageCopy> = places.into_iter().map(|place| region(place, width)).collect();
        let (old, access) = if fresh { (LAYOUT_UNDEFINED, 0) } else { (LAYOUT_TRANSFER_SOURCE, ACCESS_TRANSFER_READ) };
        let to_copy = barrier(picture, old, LAYOUT_TRANSFER_DESTINATION, access, ACCESS_TRANSFER_WRITE);
        let to_read = barrier(picture, LAYOUT_TRANSFER_DESTINATION, LAYOUT_TRANSFER_SOURCE, ACCESS_TRANSFER_WRITE, ACCESS_TRANSFER_READ);
        let (on, commands) = (&self.on, shows.commands);
        // SAFETY: the commands are being recorded; the places lie in the buffer and the image.
        unsafe {
            (on.vkCmdPipelineBarrier)(commands, STAGE_TRANSFER, STAGE_TRANSFER, 0, 0, null(), 0, null(), 1, &to_copy);
            (on.vkCmdCopyBufferToImage)(commands, shows.buffer, picture, LAYOUT_TRANSFER_DESTINATION, regions.len() as u32, regions.as_ptr());
            (on.vkCmdPipelineBarrier)(commands, STAGE_TRANSFER, STAGE_TRANSFER, 0, 0, null(), 0, null(), 1, &to_read);
        }
        shows.pending.clear();
    }

    /// Records `wanted` places copied into image `image` from the image the GPU draws the
    /// surface in, where it has one (what was painted since going into it first). Says whether
    /// it did; if not, they are copied from the pixels.
    #[cfg(feature = "gpu-draw")]
    fn copied_from_picture(&self, shows: &mut Shows, image: Handle, wanted: &[[i32; 4]]) -> bool {
        let Some(pipeline) = self.pipeline.as_deref().filter(|_| shows.picture.0 != 0) else { return false };
        self.fill_picture(shows, false);
        pipeline.copy_places(shows.commands, shows.picture.0, image, wanted);
        true
    }

    /// Copies `wanted` places of a surface's pixels into image `at`, taken back from the
    /// compositor and handed to it again, and waits until done. Says whether it was; if not,
    /// the device is lost.
    #[cfg(not(feature = "gpu-draw"))]
    fn copy(&mut self, shows: &Shows, at: usize, wanted: &[[i32; 4]]) -> bool {
        #[cfg(test)]
        if self.faked {
            self.lost = true;
            return false;
        }
        let (on, commands, image) = (&self.on, shows.commands, &shows.images[at]);
        let regions: Vec<VkBufferImageCopy> = wanted.iter().filter(|place| place[0] < place[2] && place[1] < place[3]).map(|place| region(*place, shows.size[0])).collect();
        let (old, from, to) = if image.shown { (LAYOUT_GENERAL, self.outside, self.family) } else { (LAYOUT_UNDEFINED, !0, !0) };
        let taken = VkImageMemoryBarrier {
            kind: 45,
            destination_access: ACCESS_TRANSFER_WRITE,
            old_layout: old,
            new_layout: LAYOUT_TRANSFER_DESTINATION,
            source_family: from,
            destination_family: to,
            image: image.image,
            range: WHOLE,
            ..Default::default()
        };
        let given = VkImageMemoryBarrier {
            kind: 45,
            source_access: ACCESS_TRANSFER_WRITE,
            old_layout: LAYOUT_TRANSFER_DESTINATION,
            new_layout: LAYOUT_GENERAL,
            source_family: self.family,
            destination_family: self.outside,
            image: image.image,
            range: WHOLE,
            ..Default::default()
        };
        let begin = VkCommandBufferBeginInfo { kind: 42, flags: 0x1, ..Default::default() };
        // SAFETY: Vulkan's documented calls; the commands are not in use (their last run was
        // waited for), the buffer and image are the surface's.
        let recorded = unsafe {
            (on.vkResetFences)(self.device, 1, &shows.fence);
            (on.vkBeginCommandBuffer)(commands, &begin);
            (on.vkCmdPipelineBarrier)(commands, STAGE_TOP, STAGE_TRANSFER, 0, 0, null(), 0, null(), 1, &taken);
            if !regions.is_empty() {
                (on.vkCmdCopyBufferToImage)(commands, shows.buffer, image.image, LAYOUT_TRANSFER_DESTINATION, regions.len() as u32, regions.as_ptr());
            }
            (on.vkCmdPipelineBarrier)(commands, STAGE_TRANSFER, STAGE_BOTTOM, 0, 0, null(), 0, null(), 1, &given);
            (on.vkEndCommandBuffer)(commands)
        };
        let submit = VkSubmitInfo { kind: 4, buffer_count: 1, buffers: &commands, ..Default::default() };
        // SAFETY: as above; the fence is the surface's.
        let done = recorded == 0 && unsafe { (on.vkQueueSubmit)(self.queue, 1, &submit, shows.fence) == 0 && (on.vkWaitForFences)(self.device, 1, &shows.fence, 1, WAITED) == 0 };
        self.lost |= !done;
        done
    }

    /// Copies `wanted` places of a surface's pixels into image `at`, taken back from the
    /// compositor and handed to it again, and waits until done. Says whether it was; if not,
    /// the device is lost.
    #[cfg(feature = "gpu-draw")]
    fn copy(&mut self, shows: &mut Shows, at: usize, wanted: &[[i32; 4]]) -> bool {
        #[cfg(test)]
        if self.faked {
            self.lost = true;
            return false;
        }
        let (commands, image) = (shows.commands, shows.images[at].image);
        let shown = shows.images[at].shown;
        let regions: Vec<VkBufferImageCopy> = wanted.iter().filter(|place| place[0] < place[2] && place[1] < place[3]).map(|place| region(*place, shows.size[0])).collect();
        let (old, from, to) = if shown { (LAYOUT_GENERAL, self.outside, self.family) } else { (LAYOUT_UNDEFINED, !0, !0) };
        let taken = VkImageMemoryBarrier {
            kind: 45,
            destination_access: ACCESS_TRANSFER_WRITE,
            old_layout: old,
            new_layout: LAYOUT_TRANSFER_DESTINATION,
            source_family: from,
            destination_family: to,
            image,
            range: WHOLE,
            ..Default::default()
        };
        let given = VkImageMemoryBarrier {
            kind: 45,
            source_access: ACCESS_TRANSFER_WRITE,
            old_layout: LAYOUT_TRANSFER_DESTINATION,
            new_layout: LAYOUT_GENERAL,
            source_family: self.family,
            destination_family: self.outside,
            image,
            range: WHOLE,
            ..Default::default()
        };
        let begin = VkCommandBufferBeginInfo { kind: 42, flags: 0x1, ..Default::default() };
        // SAFETY: Vulkan's documented calls; the commands are not in use (their last run was
        // waited for), the buffer and image are the surface's.
        unsafe {
            (self.on.vkResetFences)(self.device, 1, &shows.fence);
            (self.on.vkBeginCommandBuffer)(commands, &begin);
            (self.on.vkCmdPipelineBarrier)(commands, STAGE_TOP, STAGE_TRANSFER, 0, 0, null(), 0, null(), 1, &taken);
        }
        if !self.copied_from_picture(shows, image, wanted) && !regions.is_empty() {
            // SAFETY: as above; the places lie in the buffer and the image.
            unsafe { (self.on.vkCmdCopyBufferToImage)(commands, shows.buffer, image, LAYOUT_TRANSFER_DESTINATION, regions.len() as u32, regions.as_ptr()) };
        }
        let on = &self.on;
        // SAFETY: as above.
        let recorded = unsafe {
            (on.vkCmdPipelineBarrier)(commands, STAGE_TRANSFER, STAGE_BOTTOM, 0, 0, null(), 0, null(), 1, &given);
            (on.vkEndCommandBuffer)(commands)
        };
        let submit = VkSubmitInfo { kind: 4, buffer_count: 1, buffers: &commands, ..Default::default() };
        // SAFETY: as above; the fence is the surface's.
        let done = recorded == 0 && unsafe { (on.vkQueueSubmit)(self.queue, 1, &submit, shows.fence) == 0 && (on.vkWaitForFences)(self.device, 1, &shows.fence, 1, WAITED) == 0 };
        self.lost |= !done;
        done
    }
}

impl Drop for Vulkan {
    /// Lets go of the pool, the device and the instance. (Surfaces went first.)
    fn drop(&mut self) {
        // SAFETY: Vulkan's documented calls; nothing of either is used after.
        unsafe {
            (self.on.vkDeviceWaitIdle)(self.device);
            #[cfg(feature = "gpu-draw")]
            drop(self.pipeline.take());
            (self.on.vkDestroyCommandPool)(self.device, self.pool, null());
            (self.on.vkDestroyDevice)(self.device, null());
            (self.calls.vkDestroyInstance)(self.instance, null());
        }
    }
}

/// Destroys an instance or a device nothing came of, through its function `destroy` (if
/// found): nothing.
fn unmade(destroy: *const c_void, made: Object) -> Option<Vulkan> {
    // SAFETY: the function is Vulkan's, as vulkan_core.h declares it; what was made is not used
    // after.
    if !destroy.is_null() {
        unsafe { std::mem::transmute::<*const c_void, unsafe extern "system" fn(Object, *const c_void)>(destroy)(made, null()) };
    }
    None
}

impl Candidate {
    /// Device `physical`, where it can: Vulkan 1.2, the extensions needed, a queue that
    /// copies, and a layout for solid pixels both it and the compositor take (`takes`).
    fn of(calls: &Instance, physical: Object, takes: &[(u32, u64)], main: Option<u64>) -> Option<Candidate> {
        let mut properties = VkPhysicalDeviceProperties::default();
        // SAFETY: Vulkan's documented calls and enumerations, of the instance's device.
        unsafe { (calls.vkGetPhysicalDeviceProperties)(physical, &mut properties) };
        let extensions = |count: *mut u32, list: *mut VkExtensionProperties| unsafe { (calls.vkEnumerateDeviceExtensionProperties)(physical, null(), count, list) };
        let has = |name: &CStr| offered(extensions, name);
        if properties.api_version < VULKAN_1_2 || !NEEDED.iter().all(|name| has(name)) {
            return None;
        }
        let families = listed(VkQueueFamilyProperties::default(), |count, list| {
            unsafe { (calls.vkGetPhysicalDeviceQueueFamilyProperties)(physical, count, list) };
            0
        });
        // (Graphics 0x1, compute 0x2, transfer 0x4: any copies.)
        let family = families.iter().position(|family| family.count > 0 && family.flags & 0x7 != 0)? as u32;
        let ours = layouts(calls, physical);
        let both = |format: u32| takes.iter().filter(|(taken, modifier)| *taken == format && ours.contains(modifier)).map(|(_, modifier)| *modifier).collect::<Vec<u64>>();
        let (solid, clear) = (both(SOLID), both(SEE_THROUGH));
        let serves = has(NUMBERED) && main.is_some_and(|main| drives(calls, physical, main));
        let rank = if serves {
            0
        } else if properties.device_type == 4 {
            2
        } else {
            1
        };
        (!solid.is_empty()).then_some(Candidate { physical, family, solid, clear, foreign: has(TO_OTHERS), rank })
    }
}

/// The modifiers of one plane device `physical` copies 8-bit blue, green, red and alpha into
/// and exports as dmabufs.
fn layouts(calls: &Instance, physical: Object) -> Vec<u64> {
    let mut list = VkDrmFormatModifierPropertiesListEXT { kind: 1_000_158_000, ..Default::default() };
    let mut asked = VkFormatProperties2 { kind: 1_000_059_002, next: (&raw mut list).cast(), ..Default::default() };
    // SAFETY: Vulkan's documented call, asked twice: for the count, then for that many.
    unsafe { (calls.vkGetPhysicalDeviceFormatProperties2)(physical, B8G8R8A8_UNORM, &mut asked) };
    let mut all = vec![VkDrmFormatModifierPropertiesEXT::default(); list.count.min(64) as usize];
    (list.count, list.properties) = (all.len() as u32, all.as_mut_ptr());
    asked.next = (&raw mut list).cast();
    unsafe { (calls.vkGetPhysicalDeviceFormatProperties2)(physical, B8G8R8A8_UNORM, &mut asked) };
    all.truncate(list.count as usize);
    let usable = all.into_iter().filter(|layout| layout.planes == 1 && layout.features & COPIED_INTO != 0);
    usable.map(|layout| layout.modifier).filter(|modifier| exportable(calls, physical, *modifier)).collect()
}

/// Whether device `physical` exports images of 8-bit blue, green, red and alpha laid out by
/// `modifier`, copied into, as dmabufs.
fn exportable(calls: &Instance, physical: Object, modifier: u64) -> bool {
    let layout = VkPhysicalDeviceImageDrmFormatModifierInfoEXT { kind: 1_000_158_002, modifier, ..Default::default() };
    let external = VkPhysicalDeviceExternalImageFormatInfo { kind: 1_000_071_000, next: (&raw const layout).cast(), handle: DMA_BUF };
    let asked = VkPhysicalDeviceImageFormatInfo2 {
        kind: 1_000_059_004,
        next: (&raw const external).cast(),
        format: B8G8R8A8_UNORM,
        image_type: 1,
        tiling: BY_MODIFIER,
        usage: USAGE_TRANSFER_DESTINATION,
        flags: 0,
    };
    let mut outside = VkExternalImageFormatProperties { kind: 1_000_071_001, ..Default::default() };
    let mut said = VkImageFormatProperties2 { kind: 1_000_059_003, next: (&raw mut outside).cast(), ..Default::default() };
    // SAFETY: Vulkan's documented call; everything chained lives until it returns.
    unsafe { (calls.vkGetPhysicalDeviceImageFormatProperties2)(physical, &asked, &mut said) == 0 && outside.features & EXPORTABLE != 0 }
}

/// Whether device `physical` drives device number `main` (its primary or render node).
fn drives(calls: &Instance, physical: Object, main: u64) -> bool {
    let mut numbers = VkPhysicalDeviceDrmPropertiesEXT { kind: 1_000_353_000, ..Default::default() };
    let mut asked = VkPhysicalDeviceProperties2 { kind: 1_000_059_001, next: (&raw mut numbers).cast(), ..Default::default() };
    // SAFETY: Vulkan's documented call; it fills in both.
    unsafe { (calls.vkGetPhysicalDeviceProperties2)(physical, &mut asked) };
    let nodes = [(numbers.has_primary, numbers.primary), (numbers.has_render, numbers.render)];
    nodes.iter().any(|(has, [major, minor])| *has != 0 && device_number(*major as u64, *minor as u64) == main)
}

#[cfg(test)]
mod tests {
    use super::super::readable;
    use super::*;
    use crate::compositors::tests::{Desk, found};
    use crate::geom::Size;
    use crate::platform::{LocalClipboard, Window};
    use crate::surface::Surface;
    use crate::text::BuiltInFont;
    use crate::ui::Ui;
    use crate::x11::{Session, SystemText};
    use std::cell::RefCell;
    use std::os::unix::net::UnixStream;
    use std::rc::Rc;
    use std::time::{Duration, Instant};

    unsafe extern "C" {
        fn mmap(at: *mut c_void, length: usize, protection: c_int, flags: c_int, fd: c_int, offset: i64) -> *mut c_void;
        fn munmap(at: *mut c_void, length: usize) -> c_int;
    }

    /// The modifier of no layout said (the buffer's own), which taut never takes; and linear.
    const UNSAID: u64 = 0x00ff_ffff_ffff_ffff;
    const LINEAR: u64 = 0;
    /// The first buffer number a compositor gives.
    const THEIRS: u32 = 0xff00_0000;

    /// A test compositor at the other end of a socket, offering what shows windows, and
    /// `zwp_linux_dmabuf_v1` at a version (if any). With the program's link to it.
    fn offering(dmabuf: Option<u32>) -> (Wire, Link) {
        let (ours, theirs) = UnixStream::pair().unwrap();
        let compositor = Wire::over(theirs);
        let mut offers = vec![("wl_compositor", 6), ("wl_shm", 1), ("xdg_wm_base", 6)];
        offers.extend(dmabuf.map(|version| ("zwp_linux_dmabuf_v1", version)));
        // The program's registry is object 2, its first callback 3.
        for (name, (interface, version)) in offers.iter().enumerate() {
            compositor.send(2, 0, &[Arg::Uint(name as u32 + 1), Arg::Text(interface), Arg::Uint(*version)]);
        }
        compositor.send(3, 0, &[Arg::Uint(0)]);
        compositor.flush();
        (compositor, Link::over(Wire::over(ours)).unwrap().0)
    }

    /// What the program said to the compositor since last asked: object, opcode, arguments.
    fn said(compositor: &Wire, link: &Link) -> Vec<(u32, u16, Vec<i32>)> {
        link.wire.flush();
        compositor.read();
        std::iter::from_fn(|| compositor.next()).map(|message| (message.object, message.opcode, message.words())).collect()
    }

    /// The program takes in what the compositor said, as its windows would.
    fn hears(compositor: &Wire, link: &Link) {
        compositor.flush();
        link.wire.read();
        while let Some(message) = link.wire.next() {
            let mut gpu = link.gpu.borrow_mut();
            let gpu = gpu.as_mut().unwrap();
            match message.of {
                Interface::Buffer => _ = gpu.released(&link.wire, message.object),
                Interface::Dmabuf | Interface::DmabufFeedback | Interface::DmabufParams => gpu.heard(&link.wire, message),
                _ => {}
            }
        }
    }

    /// The compositor takes these formats and modifiers (v3).
    fn takes(compositor: &Wire, link: &Link, layouts: &[(u32, u64)]) {
        let dmabuf = link.gpu.borrow().as_ref().unwrap().dmabuf;
        for (format, modifier) in layouts {
            compositor.send(dmabuf, 0, &[Arg::Uint(*format)]);
            compositor.send(dmabuf, 1, &[Arg::Uint(*format), Arg::Uint((modifier >> 32) as u32), Arg::Uint(*modifier as u32)]);
        }
        hears(compositor, link);
    }

    /// Whether a device here exports dmabufs, laid out linearly. Where the machine is to have
    /// one (`TAUT_DMABUF_EXPORTS`, set on the test bed with `/dev/udmabuf`), it must.
    fn exports() -> bool {
        let exports = Vulkan::open(&[(SOLID, LINEAR)], None).is_some();
        assert!(exports || std::env::var_os("TAUT_DMABUF_EXPORTS").is_none(), "a device exporting dmabufs, as this machine is to have");
        exports
    }

    /// A label with a count and a button.
    fn counted(count: &u32, ui: &mut Ui) {
        ui.column().pad(10.0).gap(8.0).open();
        ui.label(&format!("{count} pressed"));
        ui.button("Press");
        ui.close();
    }

    /// An interface with the built-in font, this big, run once with a count. (Its first
    /// changes are taken: a new surface draws all of it anyway.)
    fn interface(size: Size, count: u32) -> Ui {
        let mut ui = Ui::new(Box::new(BuiltInFont), Box::new(LocalClipboard::default()));
        ui.resize(size, 1.0);
        ui.run(&mut |ui| counted(&count, ui));
        ui.changes();
        ui
    }

    /// The count changes, and the surface hears what changed.
    fn recount(ui: &mut Ui, sheet: &mut Sheet, count: u32) {
        ui.run(&mut |ui| counted(&count, ui));
        sheet.changed.extend(ui.changes());
        sheet.waiting = 0;
    }

    /// The surface's part on the GPU.
    fn shows(sheet: &Sheet) -> &Shows {
        let Way::Gpu(shows) = &sheet.way else { panic!("not shown through the GPU") };
        shows
    }

    /// The pixels of the image last handed over, read from its dmabuf.
    fn handed(link: &Link, sheet: &Sheet) -> Vec<u32> {
        let shows = shows(sheet);
        let image = shows.images.iter().find(|image| image.shown && image.missing.is_empty()).expect("an image holding all of it");
        let gpu = link.gpu.borrow();
        let vulkan = gpu.as_ref().unwrap().vulkan.as_ref().unwrap();
        let asked = VkMemoryGetFdInfoKHR { kind: 1_000_074_002, memory: image.memory, handle: DMA_BUF, ..Default::default() };
        let mut fd = -1;
        assert_eq!(unsafe { (vulkan.on.vkGetMemoryFdKHR)(vulkan.device, &asked, &mut fd) }, 0);
        let file = unsafe { OwnedFd::from_raw_fd(fd) };
        let ((offset, pitch), [width, height]) = (image.layout, shows.size.map(|side| side as usize));
        let len = offset as usize + pitch as usize * height;
        // (1, 1: readable, shared.)
        let at = unsafe { mmap(null_mut(), len, 1, 1, file.as_raw_fd(), 0) };
        assert_ne!(at as isize, -1, "the dmabuf maps");
        let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) };
        let rows = (0..height).map(|row| &bytes[offset as usize + row * pitch as usize..][..width * 4]);
        let pixels = rows.flat_map(|row| row.as_chunks::<4>().0.iter().map(|pixel| u32::from_ne_bytes(*pixel))).collect();
        unsafe { munmap(at, len) };
        pixels
    }

    /// The buffer requests the program made: their objects, each added a plane (fd, offset,
    /// stride, modifier) and asked to be made with `create` (never `create_immed`).
    fn requests(told: &[(u32, u16, Vec<i32>)], dmabuf: u32, size: [i32; 2], format: u32) -> Vec<u32> {
        let params: Vec<u32> = told.iter().filter(|(object, opcode, _)| (*object, *opcode) == (dmabuf, 1)).map(|(_, _, words)| words[0] as u32).collect();
        for params in &params {
            let of = |opcode: u16| told.iter().filter(move |(object, said, _)| (*object, *said) == (*params, opcode));
            let added: Vec<_> = of(1).collect();
            assert_eq!(added.len(), 1, "one plane");
            let [plane, offset, stride, high, low] = added[0].2[..] else { panic!("a plane's numbers") };
            assert_eq!((plane, (high as u64) << 32 | low as u32 as u64), (0, LINEAR), "the first plane, laid out linearly (all both take)");
            assert!(offset >= 0 && stride >= size[0] * 4, "its offset and stride: {offset}, {stride}");
            assert_eq!(of(2).map(|(_, _, words)| words.clone()).collect::<Vec<_>>(), [vec![size[0], size[1], format as i32, 0]]);
            assert_eq!(of(3).count(), 0, "never create_immed");
        }
        params
    }

    /// Each request made: answered with buffers from `first` on.
    fn made(compositor: &Wire, link: &Link, params: &[u32], first: u32) {
        params.iter().enumerate().for_each(|(at, params)| compositor.send(*params, 0, &[Arg::Uint(first + at as u32)]));
        hears(compositor, link);
    }

    /// The surface's damage, in pixels: left, top, right, bottom.
    fn damaged(told: &[(u32, u16, Vec<i32>)], surface: u32) -> Vec<[i32; 4]> {
        let damage = told.iter().filter(|(object, opcode, _)| (*object, *opcode) == (surface, 9));
        damage.map(|(_, _, words)| [words[0], words[1], words[0] + words[2], words[1] + words[3]]).collect()
    }

    /// The buffer handed over (attached).
    fn attached(told: &[(u32, u16, Vec<i32>)], surface: u32) -> Option<u32> {
        told.iter().find(|(object, opcode, _)| (*object, *opcode) == (surface, 1)).map(|(_, _, words)| words[0] as u32)
    }

    #[test]
    fn device_numbers_are_made_as_the_system_makes_them() {
        // (As glibc's makedev gives them. /dev/dri/renderD128 is 226, 128.)
        assert_eq!(device_number(226, 128), 0xe280);
        assert_eq!(device_number(226, 0x1234), 0x120_e234);
        assert_eq!(device_number(0x1_2345, 1), 0x1_2000_0003_4501);
        let entries = [(SOLID, LINEAR), (SEE_THROUGH, 0x0100_0000_0000_0001)];
        let bytes: Vec<u8> = entries.iter().flat_map(|(format, modifier)| [&format.to_ne_bytes()[..], &[0; 4], &modifier.to_ne_bytes()].concat()).collect();
        assert_eq!(table(&bytes), entries);
        assert_eq!(bounded(vec![[1, 2, 3, 4], [0, 0, 9, 9], [1, 2, 3, 4], [10, 0, 12, 2]]), [[0, 0, 9, 9], [10, 0, 12, 2]], "none inside another");
        assert_eq!(bounded((0..20).map(|at| [at, at, at + 2, at + 3]).collect()), [[0, 0, 21, 22]]);
    }

    /// v4: the default feedback is asked for; its format table, read (never mapped), and its
    /// tranches give what the compositor takes; its main device is kept.
    #[test]
    fn the_compositors_feedback_says_what_it_takes() {
        let (compositor, link) = offering(Some(5));
        ask(&link, Renderer::Vulkan);
        let told = said(&compositor, &link);
        let dmabuf = link.gpu.borrow().as_ref().unwrap().dmabuf;
        let bound = told.iter().find(|(object, opcode, words)| (*object, *opcode) == (2, 0) && words[0] == 4).expect("bound");
        assert_eq!(bound.2[bound.2.len() - 2..], [4, dmabuf as i32], "at version 4 at most");
        let feedback = told.iter().find(|(object, opcode, _)| (*object, *opcode) == (dmabuf, 2)).expect("its default feedback asked for").2[0] as u32;
        let entries = [(SOLID, UNSAID), (SOLID, LINEAR), (SEE_THROUGH, LINEAR), (u32::from_le_bytes(*b"NV12"), LINEAR)];
        let bytes: Vec<u8> = entries.iter().flat_map(|(format, modifier)| [&format.to_ne_bytes()[..], &[0; 4], &modifier.to_ne_bytes()].concat()).collect();
        let file = crate::wayland_wire::Shared::new(bytes.len()).unwrap();
        std::os::unix::fs::FileExt::write_all_at(&std::fs::File::from(file.file.try_clone().unwrap()), &bytes, 0).unwrap();
        compositor.send(feedback, 1, &[Arg::File(file.file.as_raw_fd()), Arg::Uint(bytes.len() as u32)]);
        compositor.send(feedback, 2, &[Arg::Bytes(&0xe280u64.to_ne_bytes())]);
        // Two tranches: the first the main device's (with a flag for scanout), the second
        // another's; each names entries of the table.
        let indices = |at: &[u16]| at.iter().flat_map(|index| index.to_ne_bytes()).collect::<Vec<u8>>();
        compositor.send(feedback, 4, &[Arg::Bytes(&0xe280u64.to_ne_bytes())]);
        compositor.send(feedback, 5, &[Arg::Bytes(&indices(&[1, 0]))]);
        compositor.send(feedback, 6, &[Arg::Uint(1)]);
        compositor.send(feedback, 3, &[]);
        compositor.send(feedback, 5, &[Arg::Bytes(&indices(&[2, 3, 9]))]);
        compositor.send(feedback, 3, &[]);
        hears(&compositor, &link);
        assert!(link.gpu.borrow().as_ref().unwrap().offered.is_empty(), "nothing taken before it is done");
        compositor.send(feedback, 0, &[]);
        hears(&compositor, &link);
        let gpu = link.gpu.borrow();
        let gpu = gpu.as_ref().unwrap();
        assert_eq!(gpu.offered, [entries[1], entries[0], entries[2], entries[3]], "the tranches' entries, in order (an index past the table is none)");
        assert_eq!(gpu.main, Some(0xe280));
    }

    /// Only a window asking for a GPU path binds the protocol; `Auto` and `Cpu` never do. A
    /// compositor without it, or without a layout both take, leaves shared memory.
    #[test]
    fn without_the_protocol_or_a_common_layout_shared_memory_shows_the_surface() {
        for renderer in [Renderer::Auto, Renderer::Cpu] {
            let (compositor, link) = offering(Some(3));
            ask(&link, renderer);
            assert!(link.gpu.borrow().is_none() && !said(&compositor, &link).iter().any(|(object, _, words)| *object == 2 && words[0] == 4), "{renderer:?}: not bound");
        }
        let mut ui = interface(Size { w: 120.0, h: 80.0 }, 0);
        for (offered, layouts) in [(None, vec![]), (Some(3), vec![(u32::from_le_bytes(*b"NV12"), LINEAR), (SOLID, UNSAID)])] {
            let (compositor, link) = offering(offered);
            ask(&link, Renderer::Vulkan);
            if offered.is_some() {
                takes(&compositor, &link, &layouts);
            }
            let mut sheet = Sheet::new(&link, false);
            sheet.size(&link, [120, 80], 1.0);
            assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)), "drawn at once");
            assert!(matches!(sheet.way, Way::Shm) && sheet.buffers[0].memory.pixels() == Surface::draw(&mut ui, 64).pixels, "by shared memory");
            let told = said(&compositor, &link);
            assert_eq!(attached(&told, sheet.surface), Some(sheet.buffers[0].id));
            sheet.destroy(&link);
        }
    }

    /// The surface's pixels go into three images, each a dmabuf the compositor is asked to make
    /// a buffer of; each frame is copied into one it does not hold, with what that one lacks:
    /// the compositor gets the CPU's pixels byte for byte, and is told only what changed. Where
    /// no device here exports dmabufs (WSL has no `/dev/udmabuf`), shared memory shows it.
    #[test]
    fn a_surface_is_handed_over_as_dmabufs_and_only_what_changed_is_copied() {
        let (compositor, link) = offering(Some(3));
        ask(&link, Renderer::Vulkan);
        takes(&compositor, &link, &[(SOLID, UNSAID), (SOLID, LINEAR), (SEE_THROUGH, LINEAR)]);
        let (exports, dmabuf, size) = (exports(), link.gpu.borrow().as_ref().unwrap().dmabuf, [200, 120]);
        let mut ui = interface(Size { w: 200.0, h: 120.0 }, 0);
        let mut sheet = Sheet::new(&link, false);
        sheet.size(&link, size, 1.0);
        let first = sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas));
        if !exports {
            assert!(first && matches!(sheet.way, Way::Shm) && sheet.buffers[0].memory.pixels() == Surface::draw(&mut ui, 64).pixels);
            sheet.destroy(&link);
            return eprintln!("no device here exports dmabufs: shared memory shows the surface");
        }
        // Nothing is handed over before the compositor has made a buffer.
        assert!(!first && sheet.buffers.is_empty(), "nothing yet, nor by shared memory");
        let told = said(&compositor, &link);
        let params = requests(&told, dmabuf, size, SOLID);
        assert_eq!(params.len(), IMAGES);
        made(&compositor, &link, &params, THEIRS);
        // (Its number is not used again before: another surface's request would get its answer.)
        assert!(!said(&compositor, &link).iter().any(|(object, opcode, _)| params.contains(object) && *opcode == 0), "a request lives until its image takes the answer");
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        let told = said(&compositor, &link);
        assert!(told.iter().filter(|(object, opcode, _)| params.contains(object) && *opcode == 0).count() == IMAGES, "each request let go once its answer is taken");
        assert_eq!(attached(&told, sheet.surface), Some(THEIRS));
        assert_eq!(damaged(&told, sheet.surface), [[0, 0, 200, 120]], "all of it is new");
        assert_eq!(shows(&sheet).copied, [[0, 0, 200, 120]]);
        assert!(handed(&link, &sheet) == Surface::draw(&mut ui, 64).pixels, "the dmabuf holds the interface as drawn afresh");
        // The compositor holds the first: the next frame goes into the second, which lacks
        // everything; the compositor is told only what changed.
        recount(&mut ui, &mut sheet, 5);
        let changed: Vec<[i32; 4]> = sheet.changed.iter().map(|area| on_pixels(*area, 1.0, size)).collect();
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        let told = said(&compositor, &link);
        assert_eq!((attached(&told, sheet.surface), damaged(&told, sheet.surface)), (Some(THEIRS + 1), changed.clone()));
        assert_eq!(shows(&sheet).copied, [[0, 0, 200, 120]], "an image not yet shown gets all of it");
        assert!(handed(&link, &sheet) == Surface::draw(&mut ui, 64).pixels);
        // Released, the first is drawn into again: only what it missed and what changed now.
        compositor.send(THEIRS, 0, &[]);
        hears(&compositor, &link);
        recount(&mut ui, &mut sheet, 7);
        let now: Vec<[i32; 4]> = sheet.changed.iter().map(|area| on_pixels(*area, 1.0, size)).collect();
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        assert_eq!(attached(&said(&compositor, &link), sheet.surface), Some(THEIRS));
        assert_eq!(shows(&sheet).copied, bounded([changed, now].concat()), "what it missed, and what changed now");
        let copied: i32 = shows(&sheet).copied.iter().map(|[left, top, right, bottom]| (right - left) * (bottom - top)).sum();
        assert!(copied < 200 * 120 / 2, "a part, not all of it: {:?}", shows(&sheet).copied);
        assert!(handed(&link, &sheet) == Surface::draw(&mut ui, 64).pixels);
        // Held: the third. All held: nothing until one is released.
        recount(&mut ui, &mut sheet, 8);
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        assert_eq!(attached(&said(&compositor, &link), sheet.surface), Some(THEIRS + 2));
        recount(&mut ui, &mut sheet, 9);
        assert!(!sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)), "every image held");
        assert!(!sheet.changed.is_empty() && attached(&said(&compositor, &link), sheet.surface).is_none());
        compositor.send(THEIRS + 1, 0, &[]);
        hears(&compositor, &link);
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        assert_eq!(attached(&said(&compositor, &link), sheet.surface), Some(THEIRS + 1));
        assert!(handed(&link, &sheet) == Surface::draw(&mut ui, 64).pixels);
        // The surface goes while the compositor holds all three: each buffer goes once released.
        sheet.destroy(&link);
        assert!(!said(&compositor, &link).iter().any(|(object, opcode, _)| *object >= THEIRS && *opcode == 0), "none while held");
        (0..3).for_each(|at| compositor.send(THEIRS + at, 0, &[]));
        hears(&compositor, &link);
        let gone = said(&compositor, &link);
        assert!((0..3).all(|at| gone.iter().any(|(object, opcode, _)| (*object, *opcode) == (THEIRS + at, 0))), "every buffer goes once released");
        assert!(link.gpu.borrow().as_ref().unwrap().retired.is_empty());
    }

    /// A surface of another size gets new pixels and images; the old images go, those the
    /// compositor holds once it releases them.
    #[test]
    fn a_resized_surface_gets_new_images_and_the_old_go_once_released() {
        let (compositor, link) = offering(Some(3));
        ask(&link, Renderer::Vulkan);
        takes(&compositor, &link, &[(SOLID, LINEAR)]);
        if !exports() {
            return eprintln!("no device here exports dmabufs: not tested");
        }
        let dmabuf = link.gpu.borrow().as_ref().unwrap().dmabuf;
        let mut ui = interface(Size { w: 100.0, h: 80.0 }, 0);
        let mut sheet = Sheet::new(&link, false);
        sheet.size(&link, [100, 80], 1.0);
        sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas));
        made(&compositor, &link, &requests(&said(&compositor, &link), dmabuf, [100, 80], SOLID), THEIRS);
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        said(&compositor, &link);
        // Larger while the compositor holds the first buffer.
        ui.resize(Size { w: 160.0, h: 90.0 }, 1.0);
        ui.run(&mut |ui| counted(&3, ui));
        sheet.size(&link, [160, 90], 1.0);
        sheet.waiting = 0;
        assert!(!sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)), "new buffers asked for first");
        let told = said(&compositor, &link);
        let unheld: Vec<u32> = [THEIRS + 1, THEIRS + 2].into();
        assert!(unheld.iter().all(|buffer| told.iter().any(|(object, opcode, _)| (*object, *opcode) == (*buffer, 0))), "those not held go at once");
        assert!(!told.iter().any(|(object, opcode, _)| (*object, *opcode) == (THEIRS, 0)), "the held one stays");
        let params = requests(&told, dmabuf, [160, 90], SOLID);
        assert_eq!((params.len(), shows(&sheet).size), (IMAGES, [160, 90]));
        made(&compositor, &link, &params, THEIRS + 10);
        assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)));
        assert_eq!(attached(&said(&compositor, &link), sheet.surface), Some(THEIRS + 10));
        assert!(handed(&link, &sheet) == Surface::draw(&mut ui, 64).pixels, "all of it, at its new size");
        compositor.send(THEIRS, 0, &[]);
        hears(&compositor, &link);
        assert!(said(&compositor, &link).iter().any(|(object, opcode, _)| (*object, *opcode) == (THEIRS, 0)), "released, the old one goes");
        assert!(link.gpu.borrow().as_ref().unwrap().retired.is_empty());
        sheet.destroy(&link);
    }

    /// A buffer the compositor refuses, and a device lost, each put the surface on shared
    /// memory for good, drawn whole there.
    #[test]
    fn a_refused_buffer_or_a_lost_device_puts_the_surface_on_shared_memory() {
        if !exports() {
            return eprintln!("no device here exports dmabufs: not tested");
        }
        for refused in [true, false] {
            let (compositor, link) = offering(Some(3));
            ask(&link, Renderer::Vulkan);
            takes(&compositor, &link, &[(SOLID, LINEAR)]);
            let dmabuf = link.gpu.borrow().as_ref().unwrap().dmabuf;
            let mut ui = interface(Size { w: 100.0, h: 80.0 }, 0);
            let mut sheet = Sheet::new(&link, false);
            sheet.size(&link, [100, 80], 1.0);
            sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas));
            let params = requests(&said(&compositor, &link), dmabuf, [100, 80], SOLID);
            if refused {
                made(&compositor, &link, &params[..2], THEIRS);
                compositor.send(params[2], 1, &[]);
                hears(&compositor, &link);
            } else {
                made(&compositor, &link, &params, THEIRS);
                assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)) && matches!(sheet.way, Way::Gpu(_)));
                said(&compositor, &link);
                link.gpu.borrow_mut().as_mut().unwrap().lose();
                recount(&mut ui, &mut sheet, 1);
            }
            assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)), "drawn");
            assert!(matches!(sheet.way, Way::Shm), "by shared memory");
            let told = said(&compositor, &link);
            assert_eq!(attached(&told, sheet.surface), Some(sheet.buffers[0].id));
            assert_eq!(damaged(&told, sheet.surface), [[0, 0, 100, 80]], "all of it");
            assert!(sheet.buffers[0].memory.pixels() == Surface::draw(&mut ui, 64).pixels);
            // (Lost, the buffer the compositor holds goes once it releases it.)
            let gone = if refused { [THEIRS, THEIRS + 1] } else { [THEIRS + 1, THEIRS + 2] };
            assert!(gone.iter().all(|buffer| told.iter().any(|(object, opcode, _)| (*object, *opcode) == (*buffer, 0))), "the buffers made go");
            recount(&mut ui, &mut sheet, 2);
            assert!(sheet.draw(&link, 1.0, &mut |canvas| ui.paint(canvas)) && matches!(sheet.way, Way::Shm), "for good");
            sheet.destroy(&link);
        }
    }

    /// A test app: a count and a button, in a window asking for Vulkan.
    type Windows = Host<Box<dyn FnMut(&mut Ui)>>;

    /// Opens the app's window on the compositor the environment names. Nothing where none
    /// answers.
    fn opened(count: Rc<RefCell<u32>>, renderer: Renderer, [width, height]: [f32; 2]) -> Option<Windows> {
        let (link, outputs) = Link::new()?;
        let window = Window { title: "taut through dmabufs", width, height, renderer, ..Default::default() };
        let app = Box::new(move |ui: &mut Ui| counted(&count.borrow(), ui)) as Box<dyn FnMut(&mut Ui)>;
        Host::open(link, outputs, SystemText::new()?, Session::on(None), window, app)
    }

    /// Whether a window's surface is drawn as it is now: nothing changed since, and an image
    /// (or buffer) holds all of it.
    fn drawn(host: &Windows) -> bool {
        let sheet = &host.windows[0].sheet;
        let held = match &sheet.way {
            Way::Gpu(shows) => shows.images.iter().any(|image| image.shown && image.missing.is_empty()),
            _ => sheet.buffers.iter().any(|buffer| buffer.missing.is_empty()),
        };
        host.windows[0].configured && sheet.changed.is_empty() && held
    }

    /// Takes turns until something holds, up to five seconds. Says whether it came to hold.
    fn waits(host: &mut Windows, so: impl Fn(&Windows) -> bool) -> bool {
        let until = Instant::now() + Duration::from_secs(5);
        while !so(host) && Instant::now() < until {
            readable(host.link.wire.fd(), 10);
            host.turn();
        }
        so(host)
    }

    /// Where the window's surface is on the screen, if the tests can see it and point.
    fn corner(host: &mut Windows, desk: &mut Desk) -> Option<crate::geom::Point> {
        let surface = host.windows[0].sheet.surface;
        found(desk, &mut |_| {
            readable(host.link.wire.fd(), 10);
            host.turn();
            (host.pointer.over == surface).then_some(host.pointer.at)
        })
    }

    /// Whether the screen shows the window's surface as the interface is drawn afresh, pixel
    /// for pixel (retaken for up to three seconds: a compositor shows a frame at its next
    /// composite). Nothing where the tests can't see the screen.
    fn on_screen(host: &mut Windows, desk: &mut Desk, corner: crate::geom::Point) -> Option<usize> {
        let afresh = Surface::draw(&mut host.ui, 64);
        let until = Instant::now() + Duration::from_secs(3);
        loop {
            let (width, pixels) = desk.picture()?;
            let (left, top) = (corner.x.round() as usize, corner.y.round() as usize);
            let inside = (0..afresh.height).flat_map(|row| (0..afresh.width).map(move |column| (row, column)));
            let differ =
                inside.filter(|(row, column)| pixels.get((top + row) * width + left + column).is_none_or(|shown| shown & 0xff_ffff != afresh.pixels[row * afresh.width + column] & 0xff_ffff)).count();
            if differ == 0 || Instant::now() > until {
                return Some(differ);
            }
            readable(host.link.wire.fd(), 100);
            host.turn();
        }
    }

    /// On a real compositor: a window asking for Vulkan is shown through dmabufs where the
    /// compositor takes them and a device exports them, else by shared memory; either way
    /// byte for byte what the CPU draws, on the screen too where the tests see it. A change
    /// copies only what changed. A lost device puts it back on shared memory, still exact.
    #[test]
    #[ignore]
    fn a_window_asking_for_vulkan_is_shown_byte_for_byte_on_the_compositor() {
        let _alone = crate::x11::tests::alone();
        let count = Rc::new(RefCell::new(0));
        let Some(mut host) = opened(count.clone(), Renderer::Vulkan, [320.0, 240.0]) else { return eprintln!("no compositor: not tested") };
        assert!(waits(&mut host, drawn), "the window is drawn");
        let takes_dmabufs = host.link.has.dmabuf.0 != 0;
        let mut desk = Desk::new();
        let corner = desk.as_mut().filter(|desk| desk.has_hands()).and_then(|desk| corner(&mut host, desk));
        // The pointer goes to the screen's corner farthest from the window: the compositor
        // draws it over what it shows.
        if let (Some(desk), Some(at)) = (desk.as_mut(), corner) {
            let [wide, high] = desk.units();
            desk.point(crate::geom::pt(if at.x > wide / 2.0 { 2.0 } else { wide - 3.0 }, if at.y > high / 2.0 { 2.0 } else { high - 3.0 }));
        }
        let afresh = Surface::draw(&mut host.ui, 64);
        if !takes_dmabufs || !exports() {
            assert!(matches!(host.windows[0].sheet.way, Way::Shm), "by shared memory");
            assert_eq!(host.ui.renderer(), Renderer::Cpu);
            let buffer = host.windows[0].sheet.buffers.iter_mut().find(|buffer| buffer.missing.is_empty()).unwrap();
            assert!(buffer.memory.pixels() == afresh.pixels);
            if let (Some(desk), Some(corner)) = (desk.as_mut(), corner) {
                assert_eq!(on_screen(&mut host, desk, corner), Some(0), "the screen shows it");
            }
            return eprintln!("the compositor takes no dmabufs ({takes_dmabufs}) or no device exports them: shared memory shows the window");
        }
        assert!(matches!(host.windows[0].sheet.way, Way::Gpu(_)), "through the GPU");
        assert_eq!(host.ui.renderer(), Renderer::Vulkan, "and the interface is told so");
        assert!(handed(&host.link, &host.windows[0].sheet) == afresh.pixels, "the dmabuf holds what the CPU draws");
        match (desk.as_mut(), corner) {
            (Some(desk), Some(corner)) => assert_eq!(on_screen(&mut host, desk, corner), Some(0), "the screen shows it, pixel for pixel"),
            _ => eprintln!("the tests can't see this compositor's screen: the dmabuf's pixels compared only"),
        }
        // Changes: once an image was shown, only what it lacks is copied into it.
        let [wide, high] = host.windows[0].sheet.pixels;
        let mut small = 0;
        for at in 1..=5 {
            *count.borrow_mut() = at;
            host.rerun = true;
            assert!(waits(&mut host, |host| !host.rerun && drawn(host)), "change {at} drawn");
            let Way::Gpu(shows) = &host.windows[0].sheet.way else { panic!("still through the GPU") };
            small += shows.copied.iter().all(|[left, top, right, bottom]| (right - left) * (bottom - top) < wide * high / 4) as u32;
        }
        assert!(small >= 2, "only what changed was copied, once each image was shown ({small} of 5)");
        assert!(handed(&host.link, &host.windows[0].sheet) == Surface::draw(&mut host.ui, 64).pixels);
        if let (Some(desk), Some(corner)) = (desk.as_mut(), corner) {
            assert_eq!(on_screen(&mut host, desk, corner), Some(0));
        }
        // The device is lost: shared memory shows the window from then on, exactly.
        host.link.gpu.borrow_mut().as_mut().unwrap().lose();
        *count.borrow_mut() = 6;
        host.rerun = true;
        assert!(waits(&mut host, |host| !host.rerun && matches!(host.windows[0].sheet.way, Way::Shm) && drawn(host)), "shared memory shows it");
        let afresh = Surface::draw(&mut host.ui, 64);
        let buffer = host.windows[0].sheet.buffers.iter_mut().find(|buffer| buffer.missing.is_empty()).unwrap();
        assert!(buffer.memory.pixels() == afresh.pixels);
        assert_eq!(host.ui.renderer(), Renderer::Cpu, "the interface is told");
        if let (Some(desk), Some(corner)) = (desk.as_mut(), corner) {
            assert_eq!(on_screen(&mut host, desk, corner), Some(0), "the screen shows it after the fall");
        }
    }

    /// What a window's surface waits for, for a test that failed.
    fn state(host: &Windows) -> String {
        let sheet = &host.windows[0].sheet;
        let gpu = host.link.gpu.borrow();
        let held = gpu.as_ref().map(|gpu| gpu.held.clone()).unwrap_or_default();
        let images: Vec<u32> = match &sheet.way {
            Way::Gpu(shows) => shows.images.iter().map(|image| image.buffer).collect(),
            _ => sheet.buffers.iter().map(|buffer| buffer.id | (buffer.busy as u32) << 31).collect(),
        };
        format!("waiting {}, changed {:?}, images or buffers {images:x?}, held {held:x?}", sheet.waiting, sheet.changed)
    }

    /// Whether a window may draw at once: the compositor showed its last frame, and holds not
    /// every image (or buffer). (An image whose buffer was made but not yet taken is free.)
    fn ready(host: &Windows) -> bool {
        let sheet = &host.windows[0].sheet;
        let gpu = host.link.gpu.borrow();
        let free = match (&sheet.way, gpu.as_ref()) {
            (Way::Gpu(shows), Some(gpu)) => shows.images.iter().any(|image| {
                let made = gpu.answers.iter().any(|(params, buffer)| *params == image.params && *buffer != 0);
                (image.buffer != 0 && !gpu.held.contains(&image.buffer)) || made
            }),
            _ => sheet.buffers.len() < 2 || sheet.buffers.iter().any(|buffer| !buffer.busy),
        };
        sheet.waiting == 0 && free
    }

    /// On a real compositor: how long drawing a frame takes the program (painting, and through
    /// the GPU the copy and its wait) and how long until the compositor has shown it, through
    /// dmabufs and through shared memory: for a small change (a label) and for all of an 800
    /// by 500 window. Prints the medians of 60 frames.
    #[test]
    #[ignore]
    fn how_long_frames_take_through_dmabufs_and_shared_memory() {
        let _alone = crate::x11::tests::alone();
        for renderer in [Renderer::Vulkan, Renderer::Cpu] {
            let count = Rc::new(RefCell::new(0));
            let Some(mut host) = opened(count.clone(), renderer, [800.0, 500.0]) else { return eprintln!("no compositor: not tested") };
            assert!(waits(&mut host, drawn), "the window is drawn");
            let way = if matches!(host.windows[0].sheet.way, Way::Gpu(_)) { "dmabufs" } else { "shared memory" };
            let pixels = host.windows[0].sheet.pixels;
            for whole in [false, true] {
                let (mut drawing, mut shown) = (Vec::new(), Vec::new());
                for at in 1..=60 {
                    assert!(waits(&mut host, ready), "ready to draw: frame {at}, {}", state(&host));
                    *count.borrow_mut() = at;
                    host.rerun = true;
                    host.describe();
                    if whole {
                        let units = host.windows[0].sheet.units;
                        host.windows[0].sheet.changed = vec![rect(0.0, 0.0, units[0] as f32, units[1] as f32)];
                    }
                    let start = Instant::now();
                    host.draw(0);
                    drawing.push(start.elapsed());
                    assert!(host.windows[0].sheet.changed.is_empty(), "drawn at once");
                    assert!(waits(&mut host, |host| host.windows[0].sheet.waiting == 0), "shown");
                    shown.push(start.elapsed());
                }
                drawing.sort();
                shown.sort();
                let what = if whole { "all of it" } else { "a label" };
                eprintln!(
                    "TIMES {way}, {what}, {}x{} pixels: drawing {:.3} ms, shown after {:.3} ms (medians of 60)",
                    pixels[0],
                    pixels[1],
                    drawing[30].as_secs_f64() * 1e3,
                    shown[30].as_secs_f64() * 1e3
                );
            }
        }
    }
}