euv-core 0.47.0

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
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;
}

/// 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 wl: *mut c_void = dlopen(LINUX_LIB_WAYLAND.as_ptr().cast::<c_char>(), RTLD_LAZY);
            if wl.is_null() {
                return LinuxWaylandSyms::default();
            }
            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();
            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,
                vulkan_wsi_available,
            }
        }
    })
}

/// 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() {
                    if wl.display_roundtrip != 0 {
                        let wl_roundtrip: unsafe extern "C" fn(*mut c_void) -> i32 =
                            transmute(wl.display_roundtrip as *const c_void);
                        let _: i32 = wl_roundtrip(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: 0,
                        gc: 0,
                        visual: 0,
                        depth: 32,
                        wm_delete_atom: 0,
                        scale_factor,
                        mit_shm_available: false,
                        wayland_vulkan_wsi: wl.vulkan_wsi_available,
                    });
                }
            }
        }
        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);
                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,
                });
            }
        }
        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() {
                return Ok(LinuxNativeWindowHandle {
                    lib: wl.lib,
                    is_wayland: true,
                    display: wl_display as usize,
                    window: 0,
                    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,
                });
            }
        }
    }
    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
}

/// Blits an RGBA8 `Framebuffer` (or only `dirty_rect`) onto an X11 `Window` using cached symbols (zero per-frame `dlsym`).
///
/// # Arguments
///
/// - `&LinuxWindowRecord` - Active X11 or Wayland window metadata.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `Option<Rect>` - Optional dirty pixel sub-rectangle avoiding full-frame socket transfers.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn linux_x11_present_framebuffer(
    rec: &LinuxWindowRecord,
    framebuffer: &Framebuffer,
    dirty_rect: Option<Rect>,
) -> Result<(), PlatformError> {
    if rec.get_is_wayland() {
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if rec.get_display() != 0 && wl.display_flush != 0 {
            // SAFETY: Flushes outgoing Wayland protocol requests on the live `wl_display*`.
            unsafe {
                let wl_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
                    transmute(wl.display_flush as *const c_void);
                let _: i32 = wl_flush(rec.get_display() as *mut c_void);
            }
        }
        return Ok(());
    }
    if rec.get_display() == 0 || rec.get_window() == 0 || rec.get_gc() == 0 || rec.get_visual() == 0
    {
        return Ok(());
    }
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    if fb_w == 0 || fb_h == 0 {
        return Ok(());
    }
    let syms: &LinuxX11Syms = linux_x11_syms();
    if syms.create_image == 0 || syms.put_image == 0 {
        return Ok(());
    }
    let (dst_x, dst_y, blit_w, blit_h, mut bgra): (i32, i32, u32, u32, Vec<u8>) = match dirty_rect {
        Some(r) => {
            let x0: u32 = (r.get_x().floor().max(0.0) as u32).min(fb_w);
            let y0: u32 = (r.get_y().floor().max(0.0) as u32).min(fb_h);
            let x1: u32 = ((r.get_x() + r.get_width()).ceil().max(0.0) as u32).min(fb_w);
            let y1: u32 = ((r.get_y() + r.get_height()).ceil().max(0.0) as u32).min(fb_h);
            if x1 > x0 && y1 > y0 && (x1 - x0 < fb_w || y1 - y0 < fb_h) {
                let rw: u32 = x1 - x0;
                let rh: u32 = y1 - y0;
                (
                    x0 as i32,
                    y0 as i32,
                    rw,
                    rh,
                    linux_pack_bgra_subrect(framebuffer, x0, y0, rw, rh),
                )
            } else {
                (0, 0, fb_w, fb_h, framebuffer.to_bgra_bytes())
            }
        }
        None => (0, 0, fb_w, fb_h, framebuffer.to_bgra_bytes()),
    };
    let stride: i32 = (blit_w as i32) * 4;
    // SAFETY: `bgra` remains alive across `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;
        let img: *mut c_void = x_create_img(
            display,
            visual,
            rec.get_depth(),
            X11_Z_PIXMAP,
            0,
            bgra.as_mut_ptr().cast::<c_char>(),
            blit_w,
            blit_h,
            32,
            stride,
        );
        if !img.is_null() {
            let _: i32 = x_put_img(
                display,
                rec.get_window(),
                gc,
                img,
                0,
                0,
                dst_x,
                dst_y,
                blit_w,
                blit_h,
            );
            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);
        }
    }
    Ok(())
}

/// 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,
        _ => 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);
                    }
                    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 linux_find_window(kb.window, windows).is_some() {
                    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 kev: KeyEvent =
                        KeyEvent::new(code, linux_x11_modifiers(key_ev.state), false);
                    if ev_type == X11_KEY_PRESS {
                        out_events.push(WindowEvent::KeyDown(wid, kev));
                        if 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);
    }
}