euv-core 0.48.3

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

unsafe extern "C" {
    /// Dynamically opens a POSIX shared object.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Shared library name.
    /// - `i32` - `RTLD_*` resolution flags.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Shared library handle or null.
    fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
    /// Resolves a dynamic symbol from an open shared library handle.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Shared library handle.
    /// - `*const c_char` - Null-terminated symbol name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Symbol address or null.
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
    /// Opens or creates a POSIX file descriptor (used for `/dev/shm` fallback when `memfd_create` is unavailable).
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated filesystem path.
    /// - `i32` - Open flags bitmask.
    /// - `...` - Optional POSIX file creation mode when `O_CREAT` is set.
    ///
    /// # Returns
    ///
    /// - `i32` - File descriptor or `-1` on error.
    fn open(pathname: *const c_char, flags: i32, ...) -> i32;
    /// Removes a filesystem directory entry immediately after opening anonymous shared memory.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated filesystem path.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success, `-1` on error.
    fn unlink(pathname: *const c_char) -> i32;
    /// Resizes an open POSIX shared-memory file descriptor to `length` bytes.
    ///
    /// # Arguments
    ///
    /// - `i32` - Open file descriptor.
    /// - `i64` - New file size in bytes.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success, `-1` on error.
    fn ftruncate(fd: i32, length: i64) -> i32;
    /// Maps a POSIX file descriptor into the process address space.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Optional hint address (`null_mut()`).
    /// - `usize` - Mapping length in bytes.
    /// - `i32` - Protection flags (`PROT_READ | PROT_WRITE`).
    /// - `i32` - Mapping flags (`MAP_SHARED`).
    /// - `i32` - Open file descriptor.
    /// - `isize` - Byte offset into the file (`0`).
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Mapped base address or `MAP_FAILED` (`-1`).
    fn mmap(
        addr: *mut c_void,
        length: usize,
        prot: i32,
        flags: i32,
        fd: i32,
        offset: isize,
    ) -> *mut c_void;
    /// Unmaps a previously mapped shared-memory address range.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Base address returned by `mmap`.
    /// - `usize` - Mapping length in bytes.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success, `-1` on error.
    fn munmap(addr: *mut c_void, length: usize) -> i32;
    /// Closes an open POSIX file descriptor.
    ///
    /// # Arguments
    ///
    /// - `i32` - Open file descriptor.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success, `-1` on error.
    fn close(fd: i32) -> i32;
    /// Returns the current Linux process identifier for unique `/dev/shm` filenames.
    ///
    /// # Returns
    ///
    /// - `i32` - Current POSIX PID.
    fn getpid() -> i32;
}

/// Loads a symbol pointer from a `dlopen` handle.
///
/// # Arguments
///
/// - `*mut c_void` - Shared library handle.
/// - `&'static str` - Null-terminated symbol name.
///
/// # Returns
///
/// - `*mut c_void` - Resolved symbol pointer, or null.
pub(crate) fn linux_dlsym(handle: *mut c_void, sym: &'static str) -> *mut c_void {
    if handle.is_null() {
        return null_mut();
    }
    // SAFETY: `sym` is a static null-terminated ASCII symbol name.
    unsafe { dlsym(handle, sym.as_ptr().cast::<c_char>()) }
}

/// Resolves and caches all `libX11.so.6` function pointers once per process (zero per-frame `dlsym`).
///
/// # Returns
///
/// - `&'static LinuxX11Syms` - Cached X11 symbol table.
pub(crate) fn linux_x11_syms() -> &'static LinuxX11Syms {
    LINUX_X11_SYMS.get_or_init(|| -> LinuxX11Syms {
        // SAFETY: Opens `libX11.so.6` once for the process lifetime and resolves static symbol names.
        unsafe {
            let x11: *mut c_void = dlopen(LINUX_LIB_X11.as_ptr().cast::<c_char>(), RTLD_LAZY);
            if x11.is_null() {
                return LinuxX11Syms::default();
            }
            LinuxX11Syms {
                lib: x11 as usize,
                open_display: linux_dlsym(x11, SYM_X_OPEN_DISPLAY) as usize,
                default_screen: linux_dlsym(x11, SYM_X_DEFAULT_SCREEN) as usize,
                root_window: linux_dlsym(x11, SYM_X_ROOT_WINDOW) as usize,
                create_simple_window: linux_dlsym(x11, SYM_X_CREATE_SIMPLE_WINDOW) as usize,
                store_name: linux_dlsym(x11, SYM_X_STORE_NAME) as usize,
                map_window: linux_dlsym(x11, SYM_X_MAP_WINDOW) as usize,
                resize_window: linux_dlsym(x11, SYM_X_RESIZE_WINDOW) as usize,
                destroy_window: linux_dlsym(x11, SYM_X_DESTROY_WINDOW) as usize,
                flush: linux_dlsym(x11, SYM_X_FLUSH) as usize,
                default_gc: linux_dlsym(x11, SYM_X_DEFAULT_GC) as usize,
                default_visual: linux_dlsym(x11, SYM_X_DEFAULT_VISUAL) as usize,
                default_depth: linux_dlsym(x11, SYM_X_DEFAULT_DEPTH) as usize,
                create_image: linux_dlsym(x11, SYM_X_CREATE_IMAGE) as usize,
                put_image: linux_dlsym(x11, SYM_X_PUT_IMAGE) as usize,
                free: linux_dlsym(x11, SYM_X_FREE) as usize,
                select_input: linux_dlsym(x11, SYM_X_SELECT_INPUT) as usize,
                intern_atom: linux_dlsym(x11, SYM_X_INTERN_ATOM) as usize,
                set_wm_protocols: linux_dlsym(x11, SYM_X_SET_WM_PROTOCOLS) as usize,
                pending: linux_dlsym(x11, SYM_X_PENDING) as usize,
                next_event: linux_dlsym(x11, SYM_X_NEXT_EVENT) as usize,
                lookup_string: linux_dlsym(x11, SYM_X_LOOKUP_STRING) as usize,
                resource_manager_string: linux_dlsym(x11, SYM_X_RESOURCE_MANAGER_STRING) as usize,
            }
        }
    })
}

/// Resolves and caches `libXrandr.so.2` function pointers once per process (eliminates `dlopen` handle leak).
///
/// # Returns
///
/// - `&'static LinuxXRandrSyms` - Cached XRandR symbol table.
pub(crate) fn linux_xrandr_syms() -> &'static LinuxXRandrSyms {
    LINUX_XRANDR_SYMS.get_or_init(|| -> LinuxXRandrSyms {
        // SAFETY: Opens `libXrandr.so.2` once for the process lifetime and resolves static symbol names.
        unsafe {
            let xrandr: *mut c_void = dlopen(LINUX_LIB_XRANDR.as_ptr().cast::<c_char>(), RTLD_LAZY);
            if xrandr.is_null() {
                return LinuxXRandrSyms::default();
            }
            LinuxXRandrSyms {
                get_screen_info: linux_dlsym(xrandr, SYM_XRR_GET_SCREEN_INFO) as usize,
                config_current_rate: linux_dlsym(xrandr, SYM_XRR_CONFIG_CURRENT_RATE) as usize,
                free_screen_config_info: linux_dlsym(xrandr, SYM_XRR_FREE_SCREEN_CONFIG_INFO)
                    as usize,
            }
        }
    })
}

/// Resolves and caches `libXext.so.6` MIT-SHM function pointers once per process.
///
/// # Returns
///
/// - `&'static LinuxXShmSyms` - Cached MIT-SHM symbol table.
pub(crate) fn linux_xshm_syms() -> &'static LinuxXShmSyms {
    LINUX_XSHM_SYMS.get_or_init(|| -> LinuxXShmSyms {
        // SAFETY: Opens `libXext.so.6` once for the process lifetime and resolves MIT-SHM symbols.
        unsafe {
            let xext: *mut c_void = dlopen(LINUX_LIB_XEXT.as_ptr().cast::<c_char>(), RTLD_LAZY);
            if xext.is_null() {
                return LinuxXShmSyms::default();
            }
            LinuxXShmSyms {
                query_extension: linux_dlsym(xext, SYM_XSHM_QUERY_EXTENSION) as usize,
                create_image: linux_dlsym(xext, SYM_XSHM_CREATE_IMAGE) as usize,
                attach: linux_dlsym(xext, SYM_XSHM_ATTACH) as usize,
                detach: linux_dlsym(xext, SYM_XSHM_DETACH) as usize,
                put_image: linux_dlsym(xext, SYM_XSHM_PUT_IMAGE) as usize,
            }
        }
    })
}

/// Resolves and caches `libwayland-client.so.0` + Vulkan Wayland WSI symbols once per process.
///
/// # Returns
///
/// - `&'static LinuxWaylandSyms` - Cached Wayland symbol table.
pub(crate) fn linux_wayland_syms() -> &'static LinuxWaylandSyms {
    LINUX_WAYLAND_SYMS.get_or_init(|| -> LinuxWaylandSyms {
        // SAFETY: Opens `libwayland-client.so.0` and optional `libvulkan.so.1` once for the process lifetime.
        unsafe {
            let vk: *mut c_void = dlopen(LINUX_LIB_VULKAN.as_ptr().cast::<c_char>(), RTLD_LAZY);
            let vulkan_wsi_available: bool =
                !vk.is_null() && !linux_dlsym(vk, SYM_VK_CREATE_WAYLAND_SURFACE).is_null();
            let xlib_vulkan_wsi_available: bool =
                !vk.is_null() && !linux_dlsym(vk, SYM_VK_CREATE_XLIB_SURFACE).is_null();
            let wl: *mut c_void = dlopen(LINUX_LIB_WAYLAND.as_ptr().cast::<c_char>(), RTLD_LAZY);
            if wl.is_null() {
                return LinuxWaylandSyms {
                    vulkan_wsi_available,
                    xlib_vulkan_wsi_available,
                    ..LinuxWaylandSyms::default()
                };
            }
            LinuxWaylandSyms {
                lib: wl as usize,
                display_connect: linux_dlsym(wl, SYM_WL_DISPLAY_CONNECT) as usize,
                display_disconnect: linux_dlsym(wl, SYM_WL_DISPLAY_DISCONNECT) as usize,
                display_dispatch_pending: linux_dlsym(wl, SYM_WL_DISPLAY_DISPATCH_PENDING) as usize,
                display_dispatch: linux_dlsym(wl, SYM_WL_DISPLAY_DISPATCH) as usize,
                display_flush: linux_dlsym(wl, SYM_WL_DISPLAY_FLUSH) as usize,
                display_roundtrip: linux_dlsym(wl, SYM_WL_DISPLAY_ROUNDTRIP) as usize,
                display_get_error: linux_dlsym(wl, SYM_WL_DISPLAY_GET_ERROR) as usize,
                proxy_marshal_flags: linux_dlsym(wl, SYM_WL_PROXY_MARSHAL_FLAGS) as usize,
                proxy_add_listener: linux_dlsym(wl, SYM_WL_PROXY_ADD_LISTENER) as usize,
                proxy_destroy: linux_dlsym(wl, SYM_WL_PROXY_DESTROY) as usize,
                proxy_get_version: linux_dlsym(wl, SYM_WL_PROXY_GET_VERSION) as usize,
                registry_interface: linux_dlsym(wl, SYM_WL_REGISTRY_INTERFACE) as usize,
                compositor_interface: linux_dlsym(wl, SYM_WL_COMPOSITOR_INTERFACE) as usize,
                surface_interface: linux_dlsym(wl, SYM_WL_SURFACE_INTERFACE) as usize,
                shm_interface: linux_dlsym(wl, SYM_WL_SHM_INTERFACE) as usize,
                shm_pool_interface: linux_dlsym(wl, SYM_WL_SHM_POOL_INTERFACE) as usize,
                buffer_interface: linux_dlsym(wl, SYM_WL_BUFFER_INTERFACE) as usize,
                vulkan_wsi_available,
                xlib_vulkan_wsi_available,
            }
        }
    })
}

/// Allocates an anonymous shared-memory file descriptor (`memfd_create` with `/dev/shm` fallback) and `mmap`s `size` bytes.
///
/// # Arguments
///
/// - `usize` - Requested mapping size in bytes (`1..=i32::MAX`).
///
/// # Returns
///
/// - `Result<(i32, usize, usize), PlatformError>` - `(fd, mapped_ptr, mapped_len)` on success.
pub(crate) fn linux_alloc_shm_file(size: usize) -> Result<(i32, usize, usize), PlatformError> {
    if size == 0 || size > (i32::MAX as usize) {
        return Err(PlatformError::SurfaceError(
            ERR_LINUX_WL_SHM_ALLOC.to_string(),
        ));
    }
    // SAFETY: Uses standard Linux `memfd_create` / `/dev/shm` + `ftruncate` + `mmap` with validated sizes.
    unsafe {
        let mut fd: i32 = -1;
        let memfd_sym: *mut c_void = dlsym(null_mut(), SYM_MEMFD_CREATE.as_ptr().cast::<c_char>());
        if !memfd_sym.is_null() {
            let memfd_create: unsafe extern "C" fn(*const c_char, u32) -> i32 =
                transmute(memfd_sym as *const c_void);
            fd = memfd_create(WL_MEMFD_NAME.as_ptr().cast::<c_char>(), LINUX_MFD_CLOEXEC);
        }
        if fd < 0 {
            let pid: i32 = getpid();
            let seq: u64 = LINUX_SHM_SEQ.fetch_add(1, Ordering::Relaxed);
            let path_str: String = format!("{LINUX_DEV_SHM_PREFIX}-{pid}-{seq}");
            if let Ok(c_path) = CString::new(path_str) {
                fd = open(c_path.as_ptr(), LINUX_SHM_OPEN_FLAGS, LINUX_SHM_FILE_MODE);
                if fd >= 0 {
                    let _: i32 = unlink(c_path.as_ptr());
                }
            }
        }
        if fd < 0 {
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SHM_ALLOC.to_string(),
            ));
        }
        if ftruncate(fd, size as i64) != 0 {
            let _: i32 = close(fd);
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SHM_ALLOC.to_string(),
            ));
        }
        let ptr: *mut c_void = mmap(
            null_mut(),
            size,
            LINUX_MMAP_PROT_RW,
            LINUX_MMAP_SHARED,
            fd,
            0,
        );
        if ptr.is_null() || (ptr as isize) == -1 {
            let _: i32 = close(fd);
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SHM_ALLOC.to_string(),
            ));
        }
        Ok((fd, ptr as usize, size))
    }
}

/// Releases a previously `mmap`ped shared-memory region and closes its POSIX file descriptor.
///
/// # Arguments
///
/// - `i32` - Open shared-memory file descriptor (`-1` is ignored).
/// - `usize` - Mapped base pointer (`0` is ignored).
/// - `usize` - Mapped byte length (`0` is ignored).
pub(crate) fn linux_free_shm_file(fd: i32, ptr: usize, len: usize) {
    // SAFETY: Unmaps and closes only handles previously returned by `linux_alloc_shm_file`.
    unsafe {
        if ptr != 0 && len > 0 {
            let _: i32 = munmap(ptr as *mut c_void, len);
        }
        if fd >= 0 {
            let _: i32 = close(fd);
        }
    }
}

/// Wayland `wl_registry.global` callback binding `wl_compositor` and `wl_shm` into `WlRegistryBindState`.
///
/// # Arguments
///
/// - `*mut c_void` - Pointer to `WlRegistryBindState`.
/// - `*mut c_void` - Active `wl_registry*` proxy.
/// - `u32` - Numeric global name announced by the compositor.
/// - `*const c_char` - Null-terminated Wayland interface name.
/// - `u32` - Compositor-advertised interface version.
pub(crate) unsafe extern "C" fn linux_wl_registry_global(
    data: *mut c_void,
    registry: *mut c_void,
    name: u32,
    interface: *const c_char,
    version: u32,
) {
    if data.is_null() || registry.is_null() || interface.is_null() {
        return;
    }
    let wl: &LinuxWaylandSyms = linux_wayland_syms();
    if wl.proxy_marshal_flags == 0 {
        return;
    }
    // SAFETY: `interface` is a valid C string supplied by `libwayland-client`; `data` points to `WlRegistryBindState`.
    unsafe {
        let Ok(iface_str) = CStr::from_ptr(interface).to_str() else {
            return;
        };
        let state: &mut WlRegistryBindState = &mut *data.cast::<WlRegistryBindState>();
        let marshal_bind: unsafe extern "C" fn(
            *mut c_void,
            u32,
            *const c_void,
            u32,
            u32,
            u32,
            *const c_char,
            u32,
            *mut c_void,
        ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
        if iface_str == WL_IFACE_COMPOSITOR && state.compositor == 0 && wl.compositor_interface != 0
        {
            let bind_ver: u32 = version.clamp(1, WL_COMPOSITOR_MAX_VERSION);
            let proxy: *mut c_void = marshal_bind(
                registry,
                WL_OPCODE_REGISTRY_BIND,
                wl.compositor_interface as *const c_void,
                bind_ver,
                0,
                name,
                interface,
                bind_ver,
                null_mut(),
            );
            state.compositor = proxy as usize;
            state.compositor_version = bind_ver;
        } else if iface_str == WL_IFACE_SHM && state.shm == 0 && wl.shm_interface != 0 {
            let bind_ver: u32 = version.clamp(1, WL_SHM_MAX_VERSION);
            let proxy: *mut c_void = marshal_bind(
                registry,
                WL_OPCODE_REGISTRY_BIND,
                wl.shm_interface as *const c_void,
                bind_ver,
                0,
                name,
                interface,
                bind_ver,
                null_mut(),
            );
            state.shm = proxy as usize;
        }
    }
}

/// Wayland `wl_registry.global_remove` callback (no-op for static globals).
///
/// # Arguments
///
/// - `*mut c_void` - Opaque listener userdata.
/// - `*mut c_void` - Active `wl_registry*` proxy.
/// - `u32` - Removed numeric global name.
pub(crate) unsafe extern "C" fn linux_wl_registry_global_remove(
    _data: *mut c_void,
    _registry: *mut c_void,
    _name: u32,
) {
}

/// Wayland `wl_buffer.release` callback clearing the double-buffer slot's atomic busy flag.
///
/// # Arguments
///
/// - `*mut c_void` - Pointer to the slot's pinned `AtomicBool` busy flag.
/// - `*mut c_void` - Released `wl_buffer*` proxy.
pub(crate) unsafe extern "C" fn linux_wl_buffer_release(data: *mut c_void, _buffer: *mut c_void) {
    if data.is_null() {
        return;
    }
    // SAFETY: `data` points to the heap-boxed `AtomicBool` owned by the live `WaylandShmBufferSlot`.
    unsafe {
        let busy_flag: &AtomicBool = &*data.cast::<AtomicBool>();
        busy_flag.store(false, Ordering::Release);
    }
}

/// Binds `wl_compositor` and `wl_shm` via `wl_display.get_registry` and creates a live `wl_surface`.
///
/// # Arguments
///
/// - `*mut c_void` - Live `wl_display*` connection pointer.
///
/// # Returns
///
/// - `(usize, usize, u64, u32)` - `(wl_compositor*, wl_shm*, wl_surface*, surface_version)`.
fn linux_wayland_bind_globals(wl_display: *mut c_void) -> (usize, usize, u64, u32) {
    let wl: &LinuxWaylandSyms = linux_wayland_syms();
    if wl_display.is_null()
        || wl.proxy_marshal_flags == 0
        || wl.proxy_add_listener == 0
        || wl.display_roundtrip == 0
        || wl.registry_interface == 0
    {
        return (0, 0, 0, 0);
    }
    // SAFETY: Invokes standard Wayland `wl_display.get_registry`, attaches `WL_REGISTRY_LISTENER`, roundtrips, and creates a `wl_surface`.
    unsafe {
        let marshal_get_reg: unsafe extern "C" fn(
            *mut c_void,
            u32,
            *const c_void,
            u32,
            u32,
            *mut c_void,
        ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
        let add_listener: unsafe extern "C" fn(*mut c_void, *const c_void, *mut c_void) -> i32 =
            transmute(wl.proxy_add_listener as *const c_void);
        let roundtrip: unsafe extern "C" fn(*mut c_void) -> i32 =
            transmute(wl.display_roundtrip as *const c_void);
        let registry: *mut c_void = marshal_get_reg(
            wl_display,
            WL_OPCODE_DISPLAY_GET_REGISTRY,
            wl.registry_interface as *const c_void,
            1,
            0,
            null_mut(),
        );
        if registry.is_null() {
            return (0, 0, 0, 0);
        }
        let mut bind_state: WlRegistryBindState = WlRegistryBindState::default();
        let _: i32 = add_listener(
            registry,
            (&raw const WL_REGISTRY_LISTENER).cast::<c_void>(),
            (&raw mut bind_state).cast::<c_void>(),
        );
        let _: i32 = roundtrip(wl_display);
        if wl.proxy_destroy != 0 {
            let proxy_destroy: unsafe extern "C" fn(*mut c_void) =
                transmute(wl.proxy_destroy as *const c_void);
            proxy_destroy(registry);
        }
        let mut surface: u64 = 0;
        let mut surface_version: u32 = bind_state.compositor_version;
        if bind_state.compositor != 0 && wl.surface_interface != 0 {
            let marshal_create_surface: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
                *mut c_void,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            let wl_surface: *mut c_void = marshal_create_surface(
                bind_state.compositor as *mut c_void,
                WL_OPCODE_COMPOSITOR_CREATE_SURFACE,
                wl.surface_interface as *const c_void,
                bind_state.compositor_version.max(1),
                0,
                null_mut(),
            );
            surface = wl_surface as u64;
            if !wl_surface.is_null() && wl.proxy_get_version != 0 {
                let get_ver: unsafe extern "C" fn(*mut c_void) -> u32 =
                    transmute(wl.proxy_get_version as *const c_void);
                surface_version = get_ver(wl_surface);
            }
        }
        (
            bind_state.compositor,
            bind_state.shm,
            surface,
            surface_version,
        )
    }
}

/// Queries the native Linux display refresh rate via `EUV_REFRESH_RATE_HZ` or cached `libXrandr.so.2`.
///
/// # Arguments
///
/// - `*mut c_void` - Active X11 `Display*` pointer (or null when unavailable).
/// - `usize` - Target X11 window handle (`0` when unavailable).
///
/// # Returns
///
/// - `f32` - Active display refresh rate in Hertz (`60.0` fallback).
#[must_use]
pub(crate) fn linux_display_refresh_rate_hz(display: *mut c_void, window: usize) -> f32 {
    if let Ok(val) = env::var(LINUX_REFRESH_ENV_VAR)
        && let Ok(parsed) = val.trim().parse::<f32>()
        && parsed.is_finite()
        && parsed >= MIN_REFRESH_RATE_HZ
    {
        return parsed.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
    }
    if display.is_null() || window == 0 {
        return FALLBACK_REFRESH_RATE_HZ;
    }
    let syms: &LinuxXRandrSyms = linux_xrandr_syms();
    if syms.get_screen_info == 0
        || syms.config_current_rate == 0
        || syms.free_screen_config_info == 0
    {
        return FALLBACK_REFRESH_RATE_HZ;
    }
    // SAFETY: Invokes cached `libXrandr.so.2` function pointers with exact C ABI.
    unsafe {
        let get_info: unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void =
            transmute(syms.get_screen_info as *const c_void);
        let cur_rate: unsafe extern "C" fn(*mut c_void) -> i16 =
            transmute(syms.config_current_rate as *const c_void);
        let free_info: unsafe extern "C" fn(*mut c_void) =
            transmute(syms.free_screen_config_info as *const c_void);
        let config: *mut c_void = get_info(display, window);
        if config.is_null() {
            return FALLBACK_REFRESH_RATE_HZ;
        }
        let rate: i16 = cur_rate(config);
        free_info(config);
        if rate >= 24 {
            (rate as f32).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ)
        } else {
            FALLBACK_REFRESH_RATE_HZ
        }
    }
}

/// Queries the Linux display DPI scale factor from environment variables or cached `XResourceManagerString` (`Xft.dpi`).
///
/// # Arguments
///
/// - `*mut c_void` - Active X11 `Display*` (or null on Wayland).
///
/// # Returns
///
/// - `f32` - Clamped DPI scale factor in `[1.0, 4.0]`.
pub(crate) fn linux_x11_query_scale_factor(display: *mut c_void) -> f32 {
    for var_name in LINUX_DPI_ENV_VARS.iter() {
        if let Ok(val) = env::var(var_name)
            && let Ok(parsed) = val.trim().parse::<f32>()
            && parsed.is_finite()
            && parsed >= 1.0
        {
            return parsed.clamp(1.0, 4.0);
        }
    }
    let syms: &LinuxX11Syms = linux_x11_syms();
    if syms.resource_manager_string != 0 && !display.is_null() {
        // SAFETY: Valid `XResourceManagerString` ABI call returning an owned Xlib string.
        unsafe {
            let x_rm: unsafe extern "C" fn(*mut c_void) -> *const c_char =
                transmute(syms.resource_manager_string as *const c_void);
            let raw_ptr: *const c_char = x_rm(display);
            if !raw_ptr.is_null()
                && let Ok(text) = CStr::from_ptr(raw_ptr).to_str()
            {
                for line in text.lines() {
                    let trimmed: &str = line.trim();
                    if let Some(rest) = trimmed.strip_prefix(XFT_DPI_PREFIX)
                        && let Ok(dpi) = rest.trim().parse::<f32>()
                        && dpi.is_finite()
                        && dpi > 48.0
                    {
                        return (dpi / X11_DEFAULT_DPI).clamp(1.0, 4.0);
                    }
                }
            }
        }
    }
    1.0
}

/// Checks whether the X11 server supports MIT-SHM shared-memory image blitting via cached `XShmQueryExtension`.
///
/// # Arguments
///
/// - `*mut c_void` - Active X11 `Display*`.
///
/// # Returns
///
/// - `bool` - `true` when MIT-SHM is supported on `display`.
fn linux_x11_probe_mit_shm(display: *mut c_void) -> bool {
    let shm: &LinuxXShmSyms = linux_xshm_syms();
    if display.is_null()
        || shm.query_extension == 0
        || shm.create_image == 0
        || shm.attach == 0
        || shm.detach == 0
        || shm.put_image == 0
    {
        return false;
    }
    // SAFETY: Standard `XShmQueryExtension(Display*) -> Bool` ABI call.
    unsafe {
        let query_fn: unsafe extern "C" fn(*mut c_void) -> i32 =
            transmute(shm.query_extension as *const c_void);
        query_fn(display) != 0
    }
}

/// Returns whether native Wayland should be attempted ahead of X11 (`WAYLAND_DISPLAY` set and `EUV_LINUX_FORCE_X11 != "1"`).
///
/// # Returns
///
/// - `bool` - `true` when Wayland is preferred.
#[must_use]
fn linux_should_prefer_wayland() -> bool {
    if let Ok(force_x11) = env::var(LINUX_FORCE_X11_ENV)
        && force_x11.trim() == "1"
    {
        return false;
    }
    env::var(LINUX_WAYLAND_DISPLAY_ENV)
        .map(|val: String| !val.trim().is_empty())
        .unwrap_or(false)
}

/// Attempts to open a native Linux display connection, preferring Wayland (with Vulkan WSI) before falling back to X11.
///
/// # Arguments
///
/// - `&WindowConfig` - Declarative window config.
///
/// # Returns
///
/// - `Result<LinuxNativeWindowHandle, PlatformError>` - Resolved display, window, GC, visual, depth, and DPI scale.
pub(crate) fn linux_create_native_window(
    config: &WindowConfig,
) -> Result<LinuxNativeWindowHandle, PlatformError> {
    // SAFETY: Invokes cached dynamic Linux Wayland and X11 symbols with verified C ABI.
    unsafe {
        if linux_should_prefer_wayland() {
            let wl: &LinuxWaylandSyms = linux_wayland_syms();
            if wl.lib != 0 && wl.display_connect != 0 {
                let wl_connect: unsafe extern "C" fn(*const c_char) -> *mut c_void =
                    transmute(wl.display_connect as *const c_void);
                let wl_display: *mut c_void = wl_connect(null());
                if !wl_display.is_null() {
                    let (wl_compositor, wl_shm, wl_surface, wl_surface_version): (
                        usize,
                        usize,
                        u64,
                        u32,
                    ) = linux_wayland_bind_globals(wl_display);
                    let scale_factor: f32 = linux_x11_query_scale_factor(null_mut());
                    return Ok(LinuxNativeWindowHandle {
                        lib: wl.lib,
                        is_wayland: true,
                        display: wl_display as usize,
                        window: wl_surface,
                        gc: 0,
                        visual: 0,
                        depth: 32,
                        wm_delete_atom: 0,
                        scale_factor,
                        mit_shm_available: false,
                        wayland_vulkan_wsi: wl.vulkan_wsi_available,
                        xlib_vulkan_wsi: false,
                        wl_compositor,
                        wl_shm,
                        wl_surface_version,
                    });
                }
            }
        }
        let x11: &LinuxX11Syms = linux_x11_syms();
        if x11.lib != 0
            && x11.open_display != 0
            && x11.default_screen != 0
            && x11.root_window != 0
            && x11.create_simple_window != 0
        {
            let x_open: unsafe extern "C" fn(*const c_char) -> *mut c_void =
                transmute(x11.open_display as *const c_void);
            let display: *mut c_void = x_open(null());
            if !display.is_null() {
                let x_screen: unsafe extern "C" fn(*mut c_void) -> i32 =
                    transmute(x11.default_screen as *const c_void);
                let x_root: unsafe extern "C" fn(*mut c_void, i32) -> u64 =
                    transmute(x11.root_window as *const c_void);
                let x_create: unsafe extern "C" fn(
                    *mut c_void,
                    u64,
                    i32,
                    i32,
                    u32,
                    u32,
                    u32,
                    u64,
                    u64,
                ) -> u64 = transmute(x11.create_simple_window as *const c_void);
                let screen: i32 = x_screen(display);
                let root: u64 = x_root(display, screen);
                let scale_factor: f32 = linux_x11_query_scale_factor(display);
                let phys_w: u32 = ((config.get_width() as f32) * scale_factor)
                    .round()
                    .max(1.0) as u32;
                let phys_h: u32 = ((config.get_height() as f32) * scale_factor)
                    .round()
                    .max(1.0) as u32;
                let (pos_x, pos_y): (i32, i32) = config.position_value().unwrap_or((0, 0));
                let win: u64 = x_create(display, root, pos_x, pos_y, phys_w, phys_h, 0, 0, 0);
                let gc: usize = if x11.default_gc != 0 {
                    let x_gc: unsafe extern "C" fn(*mut c_void, i32) -> *mut c_void =
                        transmute(x11.default_gc as *const c_void);
                    x_gc(display, screen) as usize
                } else {
                    0
                };
                let visual: usize = if x11.default_visual != 0 {
                    let x_vis: unsafe extern "C" fn(*mut c_void, i32) -> *mut c_void =
                        transmute(x11.default_visual as *const c_void);
                    x_vis(display, screen) as usize
                } else {
                    0
                };
                let depth: u32 = if x11.default_depth != 0 {
                    let x_dep: unsafe extern "C" fn(*mut c_void, i32) -> i32 =
                        transmute(x11.default_depth as *const c_void);
                    x_dep(display, screen).max(24) as u32
                } else {
                    24
                };
                if x11.select_input != 0 {
                    let x_select: unsafe extern "C" fn(*mut c_void, u64, isize) -> i32 =
                        transmute(x11.select_input as *const c_void);
                    let _: i32 = x_select(display, win, X11_EVENT_MASK);
                }
                let mut wm_delete_atom: u64 = 0;
                if x11.intern_atom != 0 && x11.set_wm_protocols != 0 {
                    let x_intern: unsafe extern "C" fn(*mut c_void, *const c_char, i32) -> u64 =
                        transmute(x11.intern_atom as *const c_void);
                    let x_proto: unsafe extern "C" fn(*mut c_void, u64, *mut u64, i32) -> i32 =
                        transmute(x11.set_wm_protocols as *const c_void);
                    wm_delete_atom =
                        x_intern(display, ATOM_WM_DELETE_WINDOW.as_ptr().cast::<c_char>(), 0);
                    if wm_delete_atom != 0 {
                        let _: i32 = x_proto(display, win, &mut wm_delete_atom, 1);
                    }
                }
                if x11.store_name != 0
                    && let Ok(c_title) = CString::new(config.get_title().as_str())
                {
                    let x_store: unsafe extern "C" fn(*mut c_void, u64, *const c_char) -> i32 =
                        transmute(x11.store_name as *const c_void);
                    let _: i32 = x_store(display, win, c_title.as_ptr());
                }
                if x11.flush != 0 {
                    let x_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
                        transmute(x11.flush as *const c_void);
                    let _: i32 = x_flush(display);
                }
                let mit_shm_available: bool = linux_x11_probe_mit_shm(display);
                let wl_probe: &LinuxWaylandSyms = linux_wayland_syms();
                return Ok(LinuxNativeWindowHandle {
                    lib: x11.lib,
                    is_wayland: false,
                    display: display as usize,
                    window: win,
                    gc,
                    visual,
                    depth,
                    wm_delete_atom,
                    scale_factor,
                    mit_shm_available,
                    wayland_vulkan_wsi: false,
                    xlib_vulkan_wsi: wl_probe.xlib_vulkan_wsi_available,
                    wl_compositor: 0,
                    wl_shm: 0,
                    wl_surface_version: 0,
                });
            }
        }
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if wl.lib != 0 && wl.display_connect != 0 {
            let wl_connect: unsafe extern "C" fn(*const c_char) -> *mut c_void =
                transmute(wl.display_connect as *const c_void);
            let wl_display: *mut c_void = wl_connect(null());
            if !wl_display.is_null() {
                let (wl_compositor, wl_shm, wl_surface, wl_surface_version): (
                    usize,
                    usize,
                    u64,
                    u32,
                ) = linux_wayland_bind_globals(wl_display);
                return Ok(LinuxNativeWindowHandle {
                    lib: wl.lib,
                    is_wayland: true,
                    display: wl_display as usize,
                    window: wl_surface,
                    gc: 0,
                    visual: 0,
                    depth: 32,
                    wm_delete_atom: 0,
                    scale_factor: linux_x11_query_scale_factor(null_mut()),
                    mit_shm_available: false,
                    wayland_vulkan_wsi: wl.vulkan_wsi_available,
                    xlib_vulkan_wsi: false,
                    wl_compositor,
                    wl_shm,
                    wl_surface_version,
                });
            }
        }
    }
    Err(PlatformError::InitializationFailed(
        ERR_LINUX_NO_DISPLAY.to_string(),
    ))
}

/// Maps an X11 window via cached `XMapWindow` + `XFlush` after Frame 1 has been presented.
///
/// # Arguments
///
/// - `usize` - Active X11 `Display*`.
/// - `u64` - Target X11 `Window`.
pub(crate) fn linux_x11_map_window(display: usize, window: u64) {
    if display == 0 || window == 0 {
        return;
    }
    let syms: &LinuxX11Syms = linux_x11_syms();
    if syms.map_window == 0 {
        return;
    }
    // SAFETY: Invokes cached `XMapWindow` and optional `XFlush` on a live X11 connection.
    unsafe {
        let x_map: unsafe extern "C" fn(*mut c_void, u64) -> i32 =
            transmute(syms.map_window as *const c_void);
        let _: i32 = x_map(display as *mut c_void, window);
        if syms.flush != 0 {
            let x_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
                transmute(syms.flush as *const c_void);
            let _: i32 = x_flush(display as *mut c_void);
        }
    }
}

/// Packs a dirty sub-rectangle of an RGBA8 `Framebuffer` into contiguous BGRA8 pixels for X11 sub-rect `XPutImage`.
///
/// # Arguments
///
/// - `&Framebuffer` - Source RGBA8 framebuffer.
/// - `u32` - Inclusive left pixel coordinate.
/// - `u32` - Inclusive top pixel coordinate.
/// - `u32` - Sub-rectangle width in pixels.
/// - `u32` - Sub-rectangle height in pixels.
///
/// # Returns
///
/// - `Vec<u8>` - Packed BGRA8 sub-rectangle bytes.
fn linux_pack_bgra_subrect(
    framebuffer: &Framebuffer,
    x0: u32,
    y0: u32,
    width: u32,
    height: u32,
) -> Vec<u8> {
    let fb_w: usize = framebuffer.get_width() as usize;
    let src: &[u8] = framebuffer.get_pixels().as_slice();
    let mut bgra: Vec<u8> = Vec::with_capacity((width as usize) * (height as usize) * 4);
    for row in y0..(y0 + height) {
        let row_start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
        let row_end: usize = row_start + (width as usize) * 4;
        if row_end <= src.len() {
            for px in src[row_start..row_end].as_chunks::<4>().0 {
                bgra.push(px[2]);
                bgra.push(px[1]);
                bgra.push(px[0]);
                bgra.push(px[3]);
            }
        }
    }
    bgra
}

/// Normalizes a `DamageRegion` into clamped non-empty physical pixel rectangles `(x, y, width, height)` for Wayland/X11 submission.
///
/// # Arguments
///
/// - `&Framebuffer` - Source RGBA8 framebuffer providing physical bounds.
/// - `DamageRegion` - Frame damage region (empty, partial multi-rect, or full-frame).
///
/// # Returns
///
/// - `Vec<(u32, u32, u32, u32)>` - Empty when unchanged (`SkippedUnchanged`); otherwise non-empty clamped damage rectangles.
#[must_use]
pub(crate) fn linux_normalize_damage_rects(
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Vec<(u32, u32, u32, u32)> {
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    if fb_w == 0 || fb_h == 0 {
        return Vec::new();
    }
    if damage.get_full_damage() {
        return vec![(0, 0, fb_w, fb_h)];
    }
    let DamageRegion {
        rects: raw_rects,
        rect_count,
        ..
    } = damage;
    let count: usize = (rect_count as usize).min(raw_rects.len());
    let mut rects: Vec<(u32, u32, u32, u32)> = Vec::new();
    for rect in raw_rects[..count].iter() {
        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
        let x1: u32 = ((rect.get_x() + rect.get_width()).ceil().max(0.0) as u32).min(fb_w);
        let y1: u32 = ((rect.get_y() + rect.get_height()).ceil().max(0.0) as u32).min(fb_h);
        if x1 > x0 && y1 > y0 {
            rects.push((x0, y0, x1 - x0, y1 - y0));
        }
    }
    if rects.is_empty()
        && let Some(bounds) = damage.bounds_rect()
    {
        let x0: u32 = (bounds.get_x().floor().max(0.0) as u32).min(fb_w);
        let y0: u32 = (bounds.get_y().floor().max(0.0) as u32).min(fb_h);
        let x1: u32 = ((bounds.get_x() + bounds.get_width()).ceil().max(0.0) as u32).min(fb_w);
        let y1: u32 = ((bounds.get_y() + bounds.get_height()).ceil().max(0.0) as u32).min(fb_h);
        if x1 > x0 && y1 > y0 {
            rects.push((x0, y0, x1 - x0, y1 - y0));
        }
    }
    rects
}

/// Copies RGBA8 dirty rectangles from `framebuffer` into an `mmap`ped Wayland `wl_shm` slice as little-endian `XRGB8888` or `ARGB8888`.
///
/// # Arguments
///
/// - `&Framebuffer` - Source RGBA8 pixel framebuffer.
/// - `&mut [u8]` - Destination mapped Wayland `wl_shm` byte slice.
/// - `usize` - Destination row stride in bytes (`fb_w * 4`).
/// - `&[(u32, u32, u32, u32)]` - Clamped `(x, y, width, height)` rectangles to copy.
/// - `u32` - Target Wayland shm format (`WL_SHM_FORMAT_ARGB8888` or `WL_SHM_FORMAT_XRGB8888`).
///
/// # Returns
///
/// - `u64` - Total pixel bytes written into the mapped shared-memory buffer.
pub(crate) fn linux_copy_rgba_to_wayland_shm(
    framebuffer: &Framebuffer,
    dst: &mut [u8],
    stride: usize,
    rects: &[(u32, u32, u32, u32)],
    format: u32,
) -> u64 {
    let fb_w: usize = framebuffer.get_width() as usize;
    let src: &[u8] = framebuffer.get_pixels().as_slice();
    let opaque_alpha: bool = format == WL_SHM_FORMAT_XRGB8888;
    let mut copied_bytes: u64 = 0;
    for &(x0, y0, rw, rh) in rects.iter() {
        let row_pixels: usize = rw as usize;
        let row_bytes: usize = row_pixels.saturating_mul(4);
        for row in y0..(y0 + rh) {
            let src_start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
            let src_end: usize = src_start + row_bytes;
            let dst_start: usize = (row as usize) * stride + (x0 as usize) * 4;
            let dst_end: usize = dst_start + row_bytes;
            if src_end <= src.len() && dst_end <= dst.len() {
                let src_row: &[u8] = &src[src_start..src_end];
                let dst_row: &mut [u8] = &mut dst[dst_start..dst_end];
                for (src_px, dst_px) in src_row
                    .as_chunks::<4>()
                    .0
                    .iter()
                    .zip(dst_row.as_chunks_mut::<4>().0.iter_mut())
                {
                    dst_px[0] = src_px[2];
                    dst_px[1] = src_px[1];
                    dst_px[2] = src_px[0];
                    dst_px[3] = if opaque_alpha { 0xFF } else { src_px[3] };
                }
                copied_bytes = copied_bytes.saturating_add(row_bytes as u64);
            }
        }
    }
    copied_bytes
}

/// Presents an RGBA8 `Framebuffer` onto a Linux Wayland (`wl_shm`) or X11 (`XPutImage` multi-rect) window and returns explicit presentation telemetry.
///
/// # Arguments
///
/// - `&mut LinuxWindowRecord` - Active Linux window record tracking Wayland shm swapchain and telemetry.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `DamageRegion` - Frame damage region distinguishing unchanged skips from partial or full updates.
///
/// # Returns
///
/// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on `Submitted`/`SkippedUnchanged`, or `Err` on failure.
pub(crate) fn linux_present_window_region(
    rec: &mut LinuxWindowRecord,
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Result<LinuxPresentTelemetry, PlatformError> {
    if rec.get_is_wayland() {
        let display: usize = rec.get_display();
        let surface: usize = rec.get_window() as usize;
        let wl_shm: usize = rec.get_wl_shm();
        let surface_version: u32 = rec.get_wl_surface_version();
        let mut transport: NativeWaylandShmTransport =
            NativeWaylandShmTransport::new(display, surface, wl_shm, surface_version);
        let shm_arc: Arc<Mutex<WaylandShmSwapchain>> = rec.wayland_shm_handle();
        let result: Result<LinuxPresentTelemetry, PlatformError> = match shm_arc.lock() {
            Ok(mut guard) => guard.present_framebuffer(framebuffer, damage, &mut transport),
            Err(_) => Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
            )),
        };
        match result {
            Ok(telemetry) => {
                rec.set_presentation_mode(LinuxPresentationMode::WaylandShmSoftware);
                rec.set_cpu_mirror_active(telemetry.get_cpu_mirror_active());
                rec.set_last_telemetry(telemetry);
                Ok(telemetry)
            }
            Err(err) => {
                let mut failed: LinuxPresentTelemetry = rec.get_last_telemetry();
                failed.set_mode(LinuxPresentationMode::WaylandShmSoftware);
                failed.set_outcome(LinuxPresentOutcome::Failed);
                failed.set_cpu_mirror_active(true);
                failed.set_upload_bytes(0);
                failed.set_dirty_rect_count(0);
                failed.set_failed_frames(failed.get_failed_frames().saturating_add(1));
                rec.set_presentation_mode(LinuxPresentationMode::WaylandShmSoftware);
                rec.set_cpu_mirror_active(true);
                rec.set_last_telemetry(failed);
                Err(err)
            }
        }
    } else {
        linux_x11_present_framebuffer_region(rec, framebuffer, damage)
    }
}

/// Blits an RGBA8 `Framebuffer` (multi-rect dirty or full-frame) onto an X11 `Window` using cached symbols and explicit outcome telemetry.
///
/// # Arguments
///
/// - `&mut LinuxWindowRecord` - Active X11 window metadata.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `DamageRegion` - Frame damage region.
///
/// # Returns
///
/// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on `Submitted`/`SkippedUnchanged`, or `Err` on failure.
fn linux_x11_present_framebuffer_region(
    rec: &mut LinuxWindowRecord,
    framebuffer: &Framebuffer,
    damage: DamageRegion,
) -> Result<LinuxPresentTelemetry, PlatformError> {
    let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
    telemetry.set_mode(LinuxPresentationMode::X11Software);
    telemetry.set_cpu_mirror_active(true);
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    let required_bytes: usize = (fb_w as usize)
        .saturating_mul(fb_h as usize)
        .saturating_mul(4);
    if fb_w == 0 || fb_h == 0 || framebuffer.get_pixels().len() < required_bytes {
        telemetry.set_outcome(LinuxPresentOutcome::Failed);
        telemetry.set_upload_bytes(0);
        telemetry.set_dirty_rect_count(0);
        telemetry.set_failed_frames(telemetry.get_failed_frames().saturating_add(1));
        rec.set_presentation_mode(LinuxPresentationMode::X11Software);
        rec.set_cpu_mirror_active(true);
        rec.set_last_telemetry(telemetry);
        return Err(PlatformError::SurfaceError(
            ERR_LINUX_INVALID_FRAMEBUFFER.to_string(),
        ));
    }
    let rects: Vec<(u32, u32, u32, u32)> = linux_normalize_damage_rects(framebuffer, damage);
    if rects.is_empty() {
        telemetry.set_outcome(LinuxPresentOutcome::SkippedUnchanged);
        telemetry.set_upload_bytes(0);
        telemetry.set_dirty_rect_count(0);
        telemetry.set_skipped_unchanged_frames(
            telemetry.get_skipped_unchanged_frames().saturating_add(1),
        );
        rec.set_presentation_mode(LinuxPresentationMode::X11Software);
        rec.set_cpu_mirror_active(true);
        rec.set_last_telemetry(telemetry);
        return Ok(telemetry);
    }
    let syms: &LinuxX11Syms = linux_x11_syms();
    if rec.get_display() == 0
        || rec.get_window() == 0
        || rec.get_gc() == 0
        || rec.get_visual() == 0
        || syms.create_image == 0
        || syms.put_image == 0
    {
        telemetry.set_outcome(LinuxPresentOutcome::Failed);
        telemetry.set_upload_bytes(0);
        telemetry.set_dirty_rect_count(0);
        telemetry.set_failed_frames(telemetry.get_failed_frames().saturating_add(1));
        rec.set_presentation_mode(LinuxPresentationMode::X11Software);
        rec.set_cpu_mirror_active(true);
        rec.set_last_telemetry(telemetry);
        return Err(PlatformError::SurfaceError(
            ERR_LINUX_X11_SURFACE_MISSING.to_string(),
        ));
    }
    let mut upload_bytes: u64 = 0;
    // SAFETY: `bgra` remains alive across each `XPutImage`; `XFree` frees only the XImage header without touching `bgra`.
    unsafe {
        let x_create_img: unsafe extern "C" fn(
            *mut c_void,
            *mut c_void,
            u32,
            i32,
            i32,
            *mut c_char,
            u32,
            u32,
            i32,
            i32,
        ) -> *mut c_void = transmute(syms.create_image as *const c_void);
        let x_put_img: unsafe extern "C" fn(
            *mut c_void,
            u64,
            *mut c_void,
            *mut c_void,
            i32,
            i32,
            i32,
            i32,
            u32,
            u32,
        ) -> i32 = transmute(syms.put_image as *const c_void);
        let display: *mut c_void = rec.get_display() as *mut c_void;
        let visual: *mut c_void = rec.get_visual() as *mut c_void;
        let gc: *mut c_void = rec.get_gc() as *mut c_void;
        for &(x0, y0, rw, rh) in rects.iter() {
            let mut bgra: Vec<u8> = if x0 == 0 && y0 == 0 && rw == fb_w && rh == fb_h {
                framebuffer.to_bgra_bytes()
            } else {
                linux_pack_bgra_subrect(framebuffer, x0, y0, rw, rh)
            };
            let stride: i32 = (rw as i32) * 4;
            let img: *mut c_void = x_create_img(
                display,
                visual,
                rec.get_depth(),
                X11_Z_PIXMAP,
                0,
                bgra.as_mut_ptr().cast::<c_char>(),
                rw,
                rh,
                32,
                stride,
            );
            if img.is_null() {
                telemetry.set_outcome(LinuxPresentOutcome::Failed);
                telemetry.set_upload_bytes(upload_bytes);
                telemetry.set_dirty_rect_count(rects.len() as u32);
                telemetry.set_failed_frames(telemetry.get_failed_frames().saturating_add(1));
                rec.set_presentation_mode(LinuxPresentationMode::X11Software);
                rec.set_cpu_mirror_active(true);
                rec.set_last_telemetry(telemetry);
                return Err(PlatformError::SurfaceError(
                    ERR_LINUX_X11_SURFACE_MISSING.to_string(),
                ));
            }
            let _: i32 = x_put_img(
                display,
                rec.get_window(),
                gc,
                img,
                0,
                0,
                x0 as i32,
                y0 as i32,
                rw,
                rh,
            );
            upload_bytes = upload_bytes.saturating_add(bgra.len() as u64);
            if syms.free != 0 {
                let x_free: unsafe extern "C" fn(*mut c_void) -> i32 =
                    transmute(syms.free as *const c_void);
                let _: i32 = x_free(img);
            }
        }
        if syms.flush != 0 {
            let x_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
                transmute(syms.flush as *const c_void);
            let _: i32 = x_flush(display);
        }
    }
    telemetry.set_outcome(LinuxPresentOutcome::Submitted);
    telemetry.set_upload_bytes(upload_bytes);
    telemetry.set_dirty_rect_count(rects.len() as u32);
    telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
    rec.set_presentation_mode(LinuxPresentationMode::X11Software);
    rec.set_cpu_mirror_active(true);
    rec.set_last_telemetry(telemetry);
    Ok(telemetry)
}

/// Converts an X11 modifier state bitmask into platform-neutral `Modifiers`.
///
/// # Arguments
///
/// - `u32` - X11 `state` bitmask.
///
/// # Returns
///
/// - `Modifiers` - Decoded keyboard modifiers.
#[must_use]
fn linux_x11_modifiers(state: u32) -> Modifiers {
    Modifiers::new(
        (state & X11_SHIFT_MASK) != 0,
        (state & X11_CTRL_MASK) != 0,
        (state & X11_ALT_MASK) != 0,
        (state & X11_META_MASK) != 0,
    )
}

/// Maps an X11 KeySym into a unified `KeyCode`.
///
/// # Arguments
///
/// - `u64` - X11 KeySym value returned by `XLookupString`.
/// - `Option<char>` - Printable character decoded by `XLookupString`.
///
/// # Returns
///
/// - `KeyCode` - Normalized key code.
#[must_use]
fn linux_x11_keysym_to_keycode(keysym: u64, ch: Option<char>) -> KeyCode {
    match keysym {
        0xFF08 => KeyCode::Backspace,
        0xFF09 => KeyCode::Tab,
        0xFF0D | 0xFF8D => KeyCode::Enter,
        0xFF1B => KeyCode::Escape,
        0xFF50 => KeyCode::Home,
        0xFF51 => KeyCode::ArrowLeft,
        0xFF52 => KeyCode::ArrowUp,
        0xFF53 => KeyCode::ArrowRight,
        0xFF54 => KeyCode::ArrowDown,
        0xFF55 => KeyCode::PageUp,
        0xFF56 => KeyCode::PageDown,
        0xFF57 => KeyCode::End,
        0xFFFF => KeyCode::Delete,
        0x0020 => KeyCode::Space,
        0x0021..=0x007E => KeyCode::Character((keysym as u8 as char).to_ascii_lowercase()),
        _ => match ch {
            Some(c) if !c.is_control() => KeyCode::Character(c),
            _ => KeyCode::Unknown,
        },
    }
}

/// Looks up the active `WindowId`, scale factor, and `WM_DELETE_WINDOW` atom matching an X11 window XID.
///
/// # Arguments
///
/// - `u64` - Native X11 window XID.
/// - `&HashMap<WindowId, LinuxWindowRecord>` - Active Linux window table.
///
/// # Returns
///
/// - `Option<(WindowId, f32, u64)>` - Matching window id, DPI scale, and delete atom.
#[must_use]
fn linux_find_window(
    xid: u64,
    map: &HashMap<WindowId, LinuxWindowRecord>,
) -> Option<(WindowId, f32, u64)> {
    for (wid, rec) in map.iter() {
        if !rec.get_is_wayland() && rec.get_window() == xid {
            return Some((
                *wid,
                rec.get_state().get_scale_factor(),
                rec.get_wm_delete_atom(),
            ));
        }
    }
    None
}

/// Translates a single dequeued raw X11 event union into `WindowEvent`s.
///
/// # Arguments
///
/// - `&X11EventRaw` - Raw X11 event read from `XNextEvent`.
/// - `*mut c_void` - Optional dynamically resolved `XLookupString` symbol pointer.
/// - `&mut HashMap<WindowId, LinuxWindowRecord>` - Active Linux windows map.
/// - `&mut Vec<WindowEvent>` - Event sink receiving translated window events.
unsafe fn linux_x11_handle_raw_event(
    raw: &X11EventRaw,
    lookup_sym: *mut c_void,
    windows: &mut HashMap<WindowId, LinuxWindowRecord>,
    out_events: &mut Vec<WindowEvent>,
) {
    let ev_type: i32 = (raw.pad[0] & 0xFFFF_FFFF) as i32;
    // SAFETY: Caller guarantees `raw` was initialized by Xlib `XNextEvent` with LP64 union alignment.
    unsafe {
        match ev_type {
            X11_CONFIGURE_NOTIFY => {
                let cfg_ev: X11ConfigureEvent =
                    *(raw as *const X11EventRaw).cast::<X11ConfigureEvent>();
                if let Some((wid, scale, _)) = linux_find_window(cfg_ev.window, windows) {
                    let phys_w: u32 = cfg_ev.width.max(1) as u32;
                    let phys_h: u32 = cfg_ev.height.max(1) as u32;
                    let exact_lw: f32 = ((phys_w as f32) / scale).max(1.0);
                    let exact_lh: f32 = ((phys_h as f32) / scale).max(1.0);
                    let log_w: u32 = exact_lw.round().max(1.0) as u32;
                    let log_h: u32 = exact_lh.round().max(1.0) as u32;
                    if let Some(rec) = windows.get_mut(&wid) {
                        let prev_w: u32 = rec.get_state().get_physical_width();
                        let prev_h: u32 = rec.get_state().get_physical_height();
                        if prev_w != phys_w || prev_h != phys_h {
                            rec.get_mut_config().set_width(log_w);
                            rec.get_mut_config().set_height(log_h);
                            rec.get_mut_state().set_logical_width(exact_lw);
                            rec.get_mut_state().set_logical_height(exact_lh);
                            rec.get_mut_state().set_physical_width(phys_w);
                            rec.get_mut_state().set_physical_height(phys_h);
                            out_events.push(WindowEvent::Resized(wid, log_w, log_h, scale));
                        }
                    }
                }
            }
            X11_EXPOSE => {
                let kb: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if let Some((wid, _, _)) = linux_find_window(kb.window, windows) {
                    out_events.push(WindowEvent::RedrawRequested(wid));
                }
            }
            X11_CLIENT_MESSAGE => {
                let cm: X11ClientMessageEvent =
                    *(raw as *const X11EventRaw).cast::<X11ClientMessageEvent>();
                if let Some((wid, _, wm_del)) = linux_find_window(cm.window, windows)
                    && wm_del != 0
                    && cm.data[0] == wm_del
                {
                    out_events.push(WindowEvent::CloseRequested(wid));
                }
            }
            X11_FOCUS_IN | X11_FOCUS_OUT => {
                let kb: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if let Some((wid, _, _)) = linux_find_window(kb.window, windows) {
                    let focused: bool = ev_type == X11_FOCUS_IN;
                    if let Some(rec) = windows.get_mut(&wid) {
                        rec.get_mut_state().set_focused(focused);
                    }
                    if !focused {
                        out_events.push(WindowEvent::PointerCancel(wid, 0));
                    }
                    out_events.push(WindowEvent::Focused(wid, focused));
                    let lc_ev: SystemEvent = if focused {
                        SystemEvent::Foreground
                    } else {
                        SystemEvent::Inactive
                    };
                    out_events.push(WindowEvent::System(lc_ev));
                }
            }
            X11_UNMAP_NOTIFY => {
                let kb: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if let Some((wid, _, _)) = linux_find_window(kb.window, windows) {
                    out_events.push(WindowEvent::PointerCancel(wid, 0));
                    out_events.push(WindowEvent::System(SystemEvent::Background));
                }
            }
            X11_MAP_NOTIFY => {
                let kb: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if linux_find_window(kb.window, windows).is_some() {
                    out_events.push(WindowEvent::System(SystemEvent::Foreground));
                }
            }
            X11_DESTROY_NOTIFY => {
                let kb: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if linux_find_window(kb.window, windows).is_some() {
                    out_events.push(WindowEvent::System(SystemEvent::Terminate));
                }
            }
            X11_MOTION_NOTIFY => {
                let mot: X11MotionEvent = *(raw as *const X11EventRaw).cast::<X11MotionEvent>();
                if let Some((wid, scale, _)) = linux_find_window(mot.window, windows) {
                    let pos: Point = Point::new((mot.x as f32) / scale, (mot.y as f32) / scale);
                    let pressed_btn: f32 = if (mot.state & 0x0100) != 0 { 1.0 } else { 0.0 };
                    let ev: PointerEvent = PointerEvent::new(
                        1,
                        PointerDevice::Mouse,
                        pos,
                        PointerButton::Primary,
                        pressed_btn,
                        linux_x11_modifiers(mot.state),
                    );
                    out_events.push(WindowEvent::PointerMove(wid, ev));
                }
            }
            X11_BUTTON_PRESS | X11_BUTTON_RELEASE => {
                let btn: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if let Some((wid, scale, _)) = linux_find_window(btn.window, windows) {
                    if ev_type == X11_BUTTON_PRESS && (btn.detail == 4 || btn.detail == 5) {
                        let step: f32 = if btn.detail == 4 { -40.0 } else { 40.0 };
                        let delta: Point = if (btn.state & X11_SHIFT_MASK) != 0 {
                            Point::new(step, 0.0)
                        } else {
                            Point::new(0.0, step)
                        };
                        out_events.push(WindowEvent::Scroll(wid, delta));
                    } else if ev_type == X11_BUTTON_PRESS && (btn.detail == 6 || btn.detail == 7) {
                        let dx: f32 = if btn.detail == 6 { -40.0 } else { 40.0 };
                        out_events.push(WindowEvent::Scroll(wid, Point::new(dx, 0.0)));
                    } else if btn.detail <= 3 {
                        let button: PointerButton = match btn.detail {
                            2 => PointerButton::Auxiliary,
                            3 => PointerButton::Secondary,
                            _ => PointerButton::Primary,
                        };
                        let pos: Point = Point::new((btn.x as f32) / scale, (btn.y as f32) / scale);
                        let pressed: bool = ev_type == X11_BUTTON_PRESS;
                        let pev: PointerEvent = PointerEvent::new(
                            1,
                            PointerDevice::Mouse,
                            pos,
                            button,
                            if pressed { 1.0 } else { 0.0 },
                            linux_x11_modifiers(btn.state),
                        );
                        if pressed {
                            out_events.push(WindowEvent::PointerDown(wid, pev));
                        } else {
                            out_events.push(WindowEvent::PointerUp(wid, pev));
                        }
                    }
                }
            }
            X11_KEY_PRESS | X11_KEY_RELEASE => {
                let mut key_ev: X11KeyOrButtonEvent =
                    *(raw as *const X11EventRaw).cast::<X11KeyOrButtonEvent>();
                if let Some((wid, _, _)) = linux_find_window(key_ev.window, windows) {
                    let mut buf: [u8; 16] = [0; 16];
                    let mut keysym: u64 = 0;
                    let mut len: i32 = 0;
                    if !lookup_sym.is_null() {
                        let lookup_fn: unsafe extern "C" fn(
                            *mut X11KeyOrButtonEvent,
                            *mut c_char,
                            i32,
                            *mut u64,
                            *mut c_void,
                        ) -> i32 = transmute(lookup_sym);
                        len = lookup_fn(
                            &mut key_ev,
                            buf.as_mut_ptr().cast::<c_char>(),
                            16,
                            &mut keysym,
                            null_mut(),
                        );
                    }
                    let decoded_str: Option<&str> = if len > 0 {
                        from_utf8(&buf[..(len as usize).min(16)]).ok()
                    } else {
                        None
                    };
                    let first_ch: Option<char> = decoded_str.and_then(|s: &str| s.chars().next());
                    let code: KeyCode = linux_x11_keysym_to_keycode(keysym, first_ch);
                    let mods: Modifiers = linux_x11_modifiers(key_ev.state);
                    let kev: KeyEvent = KeyEvent::new(code, mods, false);
                    if ev_type == X11_KEY_PRESS {
                        out_events.push(WindowEvent::KeyDown(wid, kev));
                        if !mods.get_ctrl()
                            && !mods.get_meta()
                            && let Some(text) = decoded_str
                            && text.chars().all(|c: char| !c.is_control())
                            && !text.is_empty()
                        {
                            out_events.push(WindowEvent::TextInput(wid, text.to_string()));
                        }
                    } else {
                        out_events.push(WindowEvent::KeyUp(wid, kev));
                    }
                }
            }
            _ => {}
        }
    }
}

/// Pumps all queued X11 and Wayland events non-blockingly using cached symbols (zero per-frame `dlsym`).
///
/// # Arguments
///
/// - `&mut HashMap<WindowId, LinuxWindowRecord>` - Active Linux windows map.
/// - `&mut Vec<WindowEvent>` - Event sink receiving translated window events.
pub(crate) fn linux_x11_pump_events(
    windows: &mut HashMap<WindowId, LinuxWindowRecord>,
    out_events: &mut Vec<WindowEvent>,
) {
    if windows.is_empty() {
        return;
    }
    let wl: &LinuxWaylandSyms = linux_wayland_syms();
    if wl.display_dispatch_pending != 0 {
        let mut wl_displays: Vec<usize> = Vec::new();
        for rec in windows.values() {
            if rec.get_is_wayland()
                && rec.get_display() != 0
                && !wl_displays.contains(&rec.get_display())
            {
                wl_displays.push(rec.get_display());
            }
        }
        // SAFETY: Non-blocking `wl_display_dispatch_pending` on live Wayland displays.
        unsafe {
            let wl_dispatch_pending: unsafe extern "C" fn(*mut c_void) -> i32 =
                transmute(wl.display_dispatch_pending as *const c_void);
            for disp in wl_displays.into_iter() {
                let _: i32 = wl_dispatch_pending(disp as *mut c_void);
            }
        }
    }
    let syms: &LinuxX11Syms = linux_x11_syms();
    if syms.pending == 0 || syms.next_event == 0 {
        return;
    }
    let displays: Vec<usize> = {
        let mut seen: Vec<usize> = Vec::new();
        for rec in windows.values() {
            if !rec.get_is_wayland() && rec.get_display() != 0 && !seen.contains(&rec.get_display())
            {
                seen.push(rec.get_display());
            }
        }
        seen
    };
    let lookup_sym: *mut c_void = syms.lookup_string as *mut c_void;
    // SAFETY: Standard Xlib non-blocking event loop using cached function pointers.
    unsafe {
        let x_pending: unsafe extern "C" fn(*mut c_void) -> i32 =
            transmute(syms.pending as *const c_void);
        let x_next: unsafe extern "C" fn(*mut c_void, *mut X11EventRaw) -> i32 =
            transmute(syms.next_event as *const c_void);
        for disp_addr in displays.into_iter() {
            let disp: *mut c_void = disp_addr as *mut c_void;
            let mut raw: X11EventRaw = X11EventRaw { pad: [0; 24] };
            while x_pending(disp) > 0 {
                let _: i32 = x_next(disp, &mut raw);
                linux_x11_handle_raw_event(&raw, lookup_sym, windows, out_events);
            }
        }
    }
}

/// Blocks on Wayland `wl_display_dispatch` or X11 `XNextEvent` with zero CPU usage until an OS event wakes the connection.
///
/// # Arguments
///
/// - `&mut HashMap<WindowId, LinuxWindowRecord>` - Active Linux windows map.
/// - `&mut Vec<WindowEvent>` - Event sink receiving translated window events.
pub(crate) fn linux_x11_wait_events(
    windows: &mut HashMap<WindowId, LinuxWindowRecord>,
    out_events: &mut Vec<WindowEvent>,
) {
    if windows.is_empty() {
        return;
    }
    if let Some(wl_disp) = windows
        .values()
        .find(|rec: &&LinuxWindowRecord| rec.get_is_wayland() && rec.get_display() != 0)
        .map(LinuxWindowRecord::get_display)
    {
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if wl.display_dispatch != 0 {
            // SAFETY: Standard blocking Wayland `wl_display_dispatch` on live `wl_display*`.
            unsafe {
                let wl_dispatch: unsafe extern "C" fn(*mut c_void) -> i32 =
                    transmute(wl.display_dispatch as *const c_void);
                let _: i32 = wl_dispatch(wl_disp as *mut c_void);
            }
        }
        return;
    }
    let first_disp: usize = windows
        .values()
        .find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland() && rec.get_display() != 0)
        .map(LinuxWindowRecord::get_display)
        .unwrap_or(0);
    if first_disp == 0 {
        return;
    }
    let syms: &LinuxX11Syms = linux_x11_syms();
    if syms.next_event == 0 {
        return;
    }
    let lookup_sym: *mut c_void = syms.lookup_string as *mut c_void;
    // SAFETY: Standard blocking Xlib `XNextEvent` wait on active `Display*`.
    unsafe {
        let x_next: unsafe extern "C" fn(*mut c_void, *mut X11EventRaw) -> i32 =
            transmute(syms.next_event as *const c_void);
        let mut raw: X11EventRaw = X11EventRaw { pad: [0; 24] };
        let _: i32 = x_next(first_disp as *mut c_void, &mut raw);
        linux_x11_handle_raw_event(&raw, lookup_sym, windows, out_events);
    }
    linux_x11_pump_events(windows, out_events);
}

/// Disconnects a Wayland display handle cleanly via cached `wl_display_disconnect`.
///
/// # Arguments
///
/// - `usize` - Active `wl_display*`.
pub(crate) fn linux_wayland_disconnect(display: usize) {
    if display == 0 {
        return;
    }
    let wl: &LinuxWaylandSyms = linux_wayland_syms();
    if wl.display_disconnect == 0 {
        return;
    }
    // SAFETY: Disconnects a live `wl_display*` returned by `wl_display_connect`.
    unsafe {
        let disconnect: unsafe extern "C" fn(*mut c_void) =
            transmute(wl.display_disconnect as *const c_void);
        disconnect(display as *mut c_void);
    }
}

/// Updates an X11 window title via cached `XStoreName`.
///
/// # Arguments
///
/// - `usize` - X11 `Display*`.
/// - `u64` - X11 `Window`.
/// - `&str` - New title.
pub(crate) fn linux_x11_set_title(display: usize, window: u64, title: &str) {
    let syms: &LinuxX11Syms = linux_x11_syms();
    if display == 0 || window == 0 || syms.store_name == 0 {
        return;
    }
    if let Ok(c_title) = CString::new(title) {
        // SAFETY: Valid `XStoreName` ABI call with live `CString`.
        unsafe {
            let func: unsafe extern "C" fn(*mut c_void, u64, *const c_char) -> i32 =
                transmute(syms.store_name as *const c_void);
            let _: i32 = func(display as *mut c_void, window, c_title.as_ptr());
        }
    }
}

/// Resizes an X11 window via cached `XResizeWindow`.
///
/// # Arguments
///
/// - `usize` - X11 `Display*`.
/// - `u64` - X11 `Window`.
/// - `u32` - Width.
/// - `u32` - Height.
pub(crate) fn linux_x11_resize(display: usize, window: u64, width: u32, height: u32) {
    let syms: &LinuxX11Syms = linux_x11_syms();
    if display == 0 || window == 0 || syms.resize_window == 0 {
        return;
    }
    // SAFETY: Valid `XResizeWindow` ABI call.
    unsafe {
        let func: unsafe extern "C" fn(*mut c_void, u64, u32, u32) -> i32 =
            transmute(syms.resize_window as *const c_void);
        let _: i32 = func(display as *mut c_void, window, width.max(1), height.max(1));
    }
}

/// Destroys an X11 window via cached `XDestroyWindow`.
///
/// # Arguments
///
/// - `usize` - X11 `Display*`.
/// - `u64` - X11 `Window`.
pub(crate) fn linux_x11_destroy(display: usize, window: u64) {
    let syms: &LinuxX11Syms = linux_x11_syms();
    if display == 0 || window == 0 || syms.destroy_window == 0 {
        return;
    }
    // SAFETY: Valid `XDestroyWindow` ABI call.
    unsafe {
        let func: unsafe extern "C" fn(*mut c_void, u64) -> i32 =
            transmute(syms.destroy_window as *const c_void);
        let _: i32 = func(display as *mut c_void, window);
    }
}