euv-core 0.48.2

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
use super::*;

/// Default initialization for an unallocated `WaylandShmBufferSlot`.
impl Default for WaylandShmBufferSlot {
    /// Creates an empty Wayland shared-memory slot with no backing FD or mapping.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty unallocated buffer slot.
    fn default() -> Self {
        Self {
            fd: -1,
            mapped_ptr: 0,
            mapped_len: 0,
            width: 0,
            height: 0,
            stride: 0,
            format: WL_SHM_FORMAT_XRGB8888,
            wl_pool: 0,
            wl_buffer: 0,
            busy: Box::new(AtomicBool::new(false)),
            has_full_copy: false,
        }
    }
}

/// Automatically unmaps POSIX shared memory and closes its FD when a `WaylandShmBufferSlot` is dropped.
impl Drop for WaylandShmBufferSlot {
    /// Releases the slot's POSIX `mmap` mapping and file descriptor.
    fn drop(&mut self) {
        let Self {
            fd,
            mapped_ptr,
            mapped_len,
            ..
        } = self;
        linux_free_shm_file(*fd, *mapped_ptr, *mapped_len);
        *fd = -1;
        *mapped_ptr = 0;
        *mapped_len = 0;
    }
}

/// Shared-memory lifecycle and busy-tracking helpers for `WaylandShmBufferSlot`.
impl WaylandShmBufferSlot {
    /// Returns whether the compositor still holds this buffer awaiting `wl_buffer.release`.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when busy.
    #[must_use]
    pub fn is_busy(&self) -> bool {
        let Self { busy, .. } = self;
        busy.load(Ordering::Acquire)
    }

    /// Marks this buffer slot as busy after `wl_surface.attach` + `wl_surface.commit`.
    pub fn mark_busy(&mut self) {
        let Self { busy, .. } = self;
        busy.store(true, Ordering::Release);
    }

    /// Clears the busy flag when `wl_buffer.release` arrives from the compositor.
    pub fn release(&mut self) {
        let Self { busy, .. } = self;
        busy.store(false, Ordering::Release);
    }

    /// Returns the pinned raw pointer to the slot's `AtomicBool` release flag for `wl_buffer_listener`.
    ///
    /// # Returns
    ///
    /// - `usize` - Stable heap pointer to `AtomicBool`.
    #[must_use]
    pub fn release_flag_ptr(&self) -> usize {
        let Self { busy, .. } = self;
        (&raw const **busy) as usize
    }

    /// Returns an immutable slice over the slot's `mmap`ped shared-memory bytes, if allocated.
    ///
    /// # Returns
    ///
    /// - `Option<&[u8]>` - Mapped pixel buffer slice.
    #[must_use]
    pub fn mapped_bytes(&self) -> Option<&[u8]> {
        let Self {
            mapped_ptr,
            mapped_len,
            ..
        } = self;
        if *mapped_ptr == 0 || *mapped_len == 0 {
            return None;
        }
        // SAFETY: `mapped_ptr` points to a valid `mmap`ped region of `*mapped_len` bytes owned by `self`.
        Some(unsafe { from_raw_parts(*mapped_ptr as *const u8, *mapped_len) })
    }

    /// Returns a mutable slice over the slot's `mmap`ped shared-memory bytes, if allocated.
    ///
    /// # Returns
    ///
    /// - `Option<&mut [u8]>` - Mutable mapped pixel buffer slice.
    fn mapped_bytes_mut(&mut self) -> Option<&mut [u8]> {
        let Self {
            mapped_ptr,
            mapped_len,
            ..
        } = self;
        if *mapped_ptr == 0 || *mapped_len == 0 {
            return None;
        }
        // SAFETY: `mapped_ptr` points to an exclusively borrowed `mmap`ped region of `*mapped_len` bytes.
        Some(unsafe { from_raw_parts_mut(*mapped_ptr as *mut u8, *mapped_len) })
    }

    /// Ensures this slot holds an `mmap`ped POSIX shared-memory buffer and Wayland `wl_buffer` matching `(req_width, req_height, req_format)`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Required physical pixel width.
    /// - `u32` - Required physical pixel height.
    /// - `u32` - Required Wayland shm pixel format.
    /// - `&mut T` - Wayland pool/buffer transport.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - `Ok(())` when mapped and ready to write.
    fn ensure_allocated<T>(
        &mut self,
        req_width: u32,
        req_height: u32,
        req_format: u32,
        ops: &mut T,
    ) -> Result<(), PlatformError>
    where
        T: WaylandShmCommitOps,
    {
        let Self {
            fd,
            mapped_ptr,
            mapped_len,
            width,
            height,
            stride,
            format,
            wl_pool,
            wl_buffer,
            busy,
            has_full_copy,
        } = self;
        let needed_stride: u32 = req_width.saturating_mul(4);
        let needed_bytes: usize = (needed_stride as usize).saturating_mul(req_height as usize);
        if *fd >= 0
            && *mapped_ptr != 0
            && *mapped_len == needed_bytes
            && *width == req_width
            && *height == req_height
            && *format == req_format
            && *wl_buffer != 0
        {
            return Ok(());
        }
        if *wl_pool != 0 || *wl_buffer != 0 {
            ops.destroy_pool_and_buffer(*wl_pool, *wl_buffer);
            *wl_pool = 0;
            *wl_buffer = 0;
        }
        linux_free_shm_file(*fd, *mapped_ptr, *mapped_len);
        *fd = -1;
        *mapped_ptr = 0;
        *mapped_len = 0;
        *has_full_copy = false;
        let (new_fd, new_ptr, new_len): (i32, usize, usize) = linux_alloc_shm_file(needed_bytes)?;
        let flag_ptr: usize = (&raw const **busy) as usize;
        let desc: WaylandShmBufferDescriptor = WaylandShmBufferDescriptor::new(
            new_fd,
            new_len as i32,
            req_width as i32,
            req_height as i32,
            needed_stride as i32,
            req_format,
            flag_ptr,
        );
        match ops.create_pool_and_buffer(desc) {
            Ok((pool, buffer)) => {
                if buffer == 0 {
                    linux_free_shm_file(new_fd, new_ptr, new_len);
                    return Err(PlatformError::SurfaceError(
                        ERR_LINUX_WL_BUFFER_CREATE.to_string(),
                    ));
                }
                *fd = new_fd;
                *mapped_ptr = new_ptr;
                *mapped_len = new_len;
                *width = req_width;
                *height = req_height;
                *stride = needed_stride;
                *format = req_format;
                *wl_pool = pool;
                *wl_buffer = buffer;
                busy.store(false, Ordering::Release);
                Ok(())
            }
            Err(err) => {
                linux_free_shm_file(new_fd, new_ptr, new_len);
                Err(err)
            }
        }
    }
}

/// Default initialization for `WaylandShmSwapchain` using opaque `WL_SHM_FORMAT_XRGB8888`.
impl Default for WaylandShmSwapchain {
    /// Creates an unallocated double-buffered Wayland shm swapchain.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized swapchain.
    fn default() -> Self {
        Self::with_format(WL_SHM_FORMAT_XRGB8888)
    }
}

/// Double-buffered Wayland `wl_shm` software presentation, dirty-rect copying, and release tracking.
impl WaylandShmSwapchain {
    /// Creates a double-buffered Wayland `wl_shm` swapchain targeting `pixel_format` (`XRGB8888` or `ARGB8888`).
    ///
    /// # Arguments
    ///
    /// - `u32` - Wayland shm pixel format code.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized double-buffered swapchain.
    #[must_use]
    pub fn with_format(pixel_format: u32) -> Self {
        Self {
            slots: [
                WaylandShmBufferSlot::default(),
                WaylandShmBufferSlot::default(),
            ],
            pixel_format,
            previous_dirty_rects: Vec::new(),
            last_committed_slot: 1,
            submitted_frames: 0,
            skipped_unchanged_frames: 0,
            failed_frames: 0,
        }
    }

    /// Marks buffer slot `slot` (`0` or `1`) as released by the compositor.
    ///
    /// # Arguments
    ///
    /// - `usize` - Slot index (`0` or `1`).
    pub fn release_slot(&mut self, slot: usize) {
        let Self { slots, .. } = self;
        if let Some(target) = slots.get_mut(slot) {
            target.release();
        }
    }

    /// Returns whether buffer slot `slot` (`0` or `1`) is currently held busy by the compositor.
    ///
    /// # Arguments
    ///
    /// - `usize` - Slot index (`0` or `1`).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the slot is busy.
    #[must_use]
    pub fn is_slot_busy(&self, slot: usize) -> bool {
        let Self { slots, .. } = self;
        slots
            .get(slot)
            .map(WaylandShmBufferSlot::is_busy)
            .unwrap_or(false)
    }

    /// Returns an immutable slice over the `mmap`ped pixel bytes of slot `slot` (`0` or `1`), if allocated.
    ///
    /// # Arguments
    ///
    /// - `usize` - Slot index (`0` or `1`).
    ///
    /// # Returns
    ///
    /// - `Option<&[u8]>` - Mapped XRGB8888/ARGB8888 shared-memory bytes.
    #[must_use]
    pub fn slot_bytes(&self, slot: usize) -> Option<&[u8]> {
        let Self { slots, .. } = self;
        slots.get(slot).and_then(WaylandShmBufferSlot::mapped_bytes)
    }

    /// Presents `framebuffer` over Wayland `wl_shm` with double-buffering, dirty-rect copying, and explicit `Submitted`/`SkippedUnchanged`/`Failed` outcomes.
    ///
    /// # Arguments
    ///
    /// - `&Framebuffer` - Source RGBA8 framebuffer.
    /// - `DamageRegion` - Frame damage region.
    /// - `&mut T` - Wayland shm/surface commit transport.
    ///
    /// # Returns
    ///
    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on `Submitted` or `SkippedUnchanged`, or `Err` on `Failed`.
    pub fn present_framebuffer<T>(
        &mut self,
        framebuffer: &Framebuffer,
        damage: DamageRegion,
        ops: &mut T,
    ) -> Result<LinuxPresentTelemetry, PlatformError>
    where
        T: WaylandShmCommitOps,
    {
        let Self {
            slots,
            pixel_format,
            previous_dirty_rects,
            last_committed_slot,
            submitted_frames,
            skipped_unchanged_frames,
            failed_frames,
        } = self;
        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 {
            *failed_frames = failed_frames.saturating_add(1);
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_INVALID_FRAMEBUFFER.to_string(),
            ));
        }
        let dirty_rects: Vec<(u32, u32, u32, u32)> =
            linux_normalize_damage_rects(framebuffer, damage);
        if dirty_rects.is_empty() {
            *skipped_unchanged_frames = skipped_unchanged_frames.saturating_add(1);
            return Ok(LinuxPresentTelemetry {
                mode: LinuxPresentationMode::WaylandShmSoftware,
                outcome: LinuxPresentOutcome::SkippedUnchanged,
                cpu_mirror_active: true,
                upload_bytes: 0,
                dirty_rect_count: 0,
                committed_buffer_slot: *last_committed_slot,
                submitted_frames: *submitted_frames,
                skipped_unchanged_frames: *skipped_unchanged_frames,
                failed_frames: *failed_frames,
            });
        }
        if let Err(err) = ops.dispatch_pending() {
            *failed_frames = failed_frames.saturating_add(1);
            return Err(err);
        }
        let preferred_slot: usize = usize::from(*last_committed_slot == 0);
        let fallback_slot: usize = 1 - preferred_slot;
        let chosen_idx: usize = if !slots[preferred_slot].is_busy() {
            preferred_slot
        } else if !slots[fallback_slot].is_busy() {
            fallback_slot
        } else {
            *failed_frames = failed_frames.saturating_add(1);
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_NO_FREE_BUFFER.to_string(),
            ));
        };
        let slot: &mut WaylandShmBufferSlot = &mut slots[chosen_idx];
        if let Err(err) = slot.ensure_allocated(fb_w, fb_h, *pixel_format, ops) {
            *failed_frames = failed_frames.saturating_add(1);
            return Err(err);
        }
        let copy_rects: Vec<(u32, u32, u32, u32)> = if !slot.has_full_copy {
            vec![(0, 0, fb_w, fb_h)]
        } else {
            let mut merged: Vec<(u32, u32, u32, u32)> =
                Vec::with_capacity(previous_dirty_rects.len() + dirty_rects.len());
            for &(px, py, pw, ph) in previous_dirty_rects.iter() {
                if px < fb_w && py < fb_h {
                    let cw: u32 = pw.min(fb_w - px);
                    let ch: u32 = ph.min(fb_h - py);
                    if cw > 0 && ch > 0 {
                        merged.push((px, py, cw, ch));
                    }
                }
            }
            merged.extend_from_slice(&dirty_rects);
            merged
        };
        let stride: usize = slot.stride as usize;
        let buffer_handle: usize = slot.wl_buffer;
        let fmt: u32 = *pixel_format;
        let upload_bytes: u64 = match slot.mapped_bytes_mut() {
            Some(dst) => linux_copy_rgba_to_wayland_shm(framebuffer, dst, stride, &copy_rects, fmt),
            None => {
                *failed_frames = failed_frames.saturating_add(1);
                return Err(PlatformError::SurfaceError(
                    ERR_LINUX_WL_SHM_ALLOC.to_string(),
                ));
            }
        };
        let wl_damage: Vec<(i32, i32, i32, i32)> = dirty_rects
            .iter()
            .map(|&(x, y, w, h): &(u32, u32, u32, u32)| (x as i32, y as i32, w as i32, h as i32))
            .collect();
        if let Err(err) = ops.attach_damage_commit_flush(buffer_handle, &wl_damage) {
            *failed_frames = failed_frames.saturating_add(1);
            return Err(err);
        }
        slot.has_full_copy = true;
        slot.mark_busy();
        *last_committed_slot = chosen_idx as u8;
        *previous_dirty_rects = dirty_rects;
        *submitted_frames = submitted_frames.saturating_add(1);
        Ok(LinuxPresentTelemetry {
            mode: LinuxPresentationMode::WaylandShmSoftware,
            outcome: LinuxPresentOutcome::Submitted,
            cpu_mirror_active: true,
            upload_bytes,
            dirty_rect_count: wl_damage.len() as u32,
            committed_buffer_slot: chosen_idx as u8,
            submitted_frames: *submitted_frames,
            skipped_unchanged_frames: *skipped_unchanged_frames,
            failed_frames: *failed_frames,
        })
    }
}

/// Native `libwayland-client.so.0` protocol marshaling for `WaylandShmCommitOps`.
impl WaylandShmCommitOps for NativeWaylandShmTransport {
    /// Allocates a `wl_shm_pool` and `wl_buffer` over `libwayland-client.so.0` and binds `WL_BUFFER_LISTENER`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable native Wayland transport.
    /// - `WaylandShmBufferDescriptor` - Shared-memory FD, geometry, format, and release flag pointer.
    ///
    /// # Returns
    ///
    /// - `Result<(usize, usize), PlatformError>` - `(wl_shm_pool*, wl_buffer*)` handles on success.
    fn create_pool_and_buffer(
        &mut self,
        desc: WaylandShmBufferDescriptor,
    ) -> Result<(usize, usize), PlatformError> {
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if self.get_display() == 0
            || self.get_surface() == 0
            || self.get_wl_shm() == 0
            || wl.proxy_marshal_flags == 0
            || wl.shm_pool_interface == 0
            || wl.buffer_interface == 0
        {
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
            ));
        }
        // SAFETY: Invokes `wl_proxy_marshal_flags` for `wl_shm.create_pool` and `wl_shm_pool.create_buffer` using exact Wayland C ABI.
        unsafe {
            let marshal_pool: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
                *mut c_void,
                i32,
                i32,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            let pool: *mut c_void = marshal_pool(
                self.get_wl_shm() as *mut c_void,
                WL_OPCODE_SHM_CREATE_POOL,
                wl.shm_pool_interface as *const c_void,
                WL_SHM_MAX_VERSION,
                0,
                null_mut(),
                desc.get_fd(),
                desc.get_size(),
            );
            if pool.is_null() {
                return Err(PlatformError::SurfaceError(
                    ERR_LINUX_WL_BUFFER_CREATE.to_string(),
                ));
            }
            let marshal_buffer: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
                *mut c_void,
                i32,
                i32,
                i32,
                i32,
                u32,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            let buffer: *mut c_void = marshal_buffer(
                pool,
                WL_OPCODE_SHM_POOL_CREATE_BUFFER,
                wl.buffer_interface as *const c_void,
                WL_SHM_MAX_VERSION,
                0,
                null_mut(),
                0,
                desc.get_width(),
                desc.get_height(),
                desc.get_stride(),
                desc.get_format(),
            );
            if buffer.is_null() {
                self.destroy_pool_and_buffer(pool as usize, 0);
                return Err(PlatformError::SurfaceError(
                    ERR_LINUX_WL_BUFFER_CREATE.to_string(),
                ));
            }
            if wl.proxy_add_listener != 0 && desc.get_release_flag_ptr() != 0 {
                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 _: i32 = add_listener(
                    buffer,
                    (&raw const WL_BUFFER_LISTENER).cast::<c_void>(),
                    desc.get_release_flag_ptr() as *mut c_void,
                );
            }
            Ok((pool as usize, buffer as usize))
        }
    }

    /// Calls `wl_surface_attach`, `wl_surface_damage_buffer` per dirty rect, `wl_surface_commit`, and `wl_display_flush`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable native Wayland transport.
    /// - `usize` - Live `wl_buffer*` handle.
    /// - `&[(i32, i32, i32, i32)]` - Buffer-space damage rectangles.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - `Err` on missing handles, flush failure, or `wl_display_get_error != 0`.
    fn attach_damage_commit_flush(
        &mut self,
        buffer: usize,
        damage_rects: &[(i32, i32, i32, i32)],
    ) -> Result<(), PlatformError> {
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if self.get_display() == 0
            || self.get_surface() == 0
            || buffer == 0
            || wl.proxy_marshal_flags == 0
            || wl.display_flush == 0
        {
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
            ));
        }
        let surface_ver: u32 = self.get_surface_version().max(1);
        let damage_opcode: u32 = if surface_ver >= WL_COMPOSITOR_MAX_VERSION {
            WL_OPCODE_SURFACE_DAMAGE_BUFFER
        } else {
            WL_OPCODE_SURFACE_DAMAGE
        };
        // SAFETY: Marshals `wl_surface.attach`, `wl_surface.damage_buffer`/`damage`, `wl_surface.commit`, and `wl_display_flush`.
        unsafe {
            let surface_ptr: *mut c_void = self.get_surface() as *mut c_void;
            let marshal_attach: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
                *mut c_void,
                i32,
                i32,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            let _: *mut c_void = marshal_attach(
                surface_ptr,
                WL_OPCODE_SURFACE_ATTACH,
                null(),
                surface_ver,
                0,
                buffer as *mut c_void,
                0,
                0,
            );
            let marshal_damage: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
                i32,
                i32,
                i32,
                i32,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            for &(x, y, w, h) in damage_rects.iter() {
                let _: *mut c_void = marshal_damage(
                    surface_ptr,
                    damage_opcode,
                    null(),
                    surface_ver,
                    0,
                    x,
                    y,
                    w,
                    h,
                );
            }
            let marshal_commit: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            let _: *mut c_void = marshal_commit(
                surface_ptr,
                WL_OPCODE_SURFACE_COMMIT,
                null(),
                surface_ver,
                0,
            );
            let wl_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
                transmute(wl.display_flush as *const c_void);
            let flushed: i32 = wl_flush(self.get_display() as *mut c_void);
            if flushed < 0 {
                return Err(PlatformError::SurfaceError(
                    ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
                ));
            }
            if wl.display_get_error != 0 {
                let get_err: unsafe extern "C" fn(*mut c_void) -> i32 =
                    transmute(wl.display_get_error as *const c_void);
                if get_err(self.get_display() as *mut c_void) != 0 {
                    return Err(PlatformError::SurfaceError(
                        ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
                    ));
                }
            }
        }
        Ok(())
    }

    /// Dispatches pending incoming Wayland compositor events such as `wl_buffer.release`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable native Wayland transport.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - `Err` on missing display or protocol error.
    fn dispatch_pending(&mut self) -> Result<(), PlatformError> {
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if self.get_display() == 0 || self.get_surface() == 0 || self.get_wl_shm() == 0 {
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
            ));
        }
        if wl.display_dispatch_pending != 0 {
            // SAFETY: Non-blocking dispatch of queued Wayland events on a live `wl_display*`.
            unsafe {
                let dispatch: unsafe extern "C" fn(*mut c_void) -> i32 =
                    transmute(wl.display_dispatch_pending as *const c_void);
                if dispatch(self.get_display() as *mut c_void) < 0 {
                    return Err(PlatformError::SurfaceError(
                        ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
                    ));
                }
            }
        }
        Ok(())
    }

    /// Destroys a previously allocated `wl_buffer*` and `wl_shm_pool*` pair cleanly.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable native Wayland transport.
    /// - `usize` - `wl_shm_pool*` proxy handle.
    /// - `usize` - `wl_buffer*` proxy handle.
    fn destroy_pool_and_buffer(&mut self, pool: usize, buffer: usize) {
        let wl: &LinuxWaylandSyms = linux_wayland_syms();
        if wl.proxy_marshal_flags == 0 {
            return;
        }
        // SAFETY: Sends `wl_buffer.destroy` and `wl_shm_pool.destroy` with `WL_MARSHAL_FLAG_DESTROY`.
        unsafe {
            let marshal_destroy: unsafe extern "C" fn(
                *mut c_void,
                u32,
                *const c_void,
                u32,
                u32,
            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
            if buffer != 0 {
                let _: *mut c_void = marshal_destroy(
                    buffer as *mut c_void,
                    WL_OPCODE_BUFFER_DESTROY,
                    null(),
                    WL_SHM_MAX_VERSION,
                    WL_MARSHAL_FLAG_DESTROY,
                );
            }
            if pool != 0 {
                let _: *mut c_void = marshal_destroy(
                    pool as *mut c_void,
                    WL_OPCODE_SHM_POOL_DESTROY,
                    null(),
                    WL_SHM_MAX_VERSION,
                    WL_MARSHAL_FLAG_DESTROY,
                );
            }
        }
    }
}

/// Wayland `wl_shm` swapchain accessors on `LinuxWindowRecord`.
impl LinuxWindowRecord {
    /// Returns (initializing on demand) the shared double-buffered `WaylandShmSwapchain` handle for this window.
    ///
    /// # Returns
    ///
    /// - `Arc<Mutex<WaylandShmSwapchain>>` - Shared Wayland shm swapchain handle.
    pub(crate) fn wayland_shm_handle(&mut self) -> Arc<Mutex<WaylandShmSwapchain>> {
        let Self { wayland_shm, .. } = self;
        Arc::clone(wayland_shm.get_or_insert_with(|| {
            Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
                WL_SHM_FORMAT_XRGB8888,
            )))
        }))
    }
}

/// Default initialization for `LinuxPlatform`.
impl Default for LinuxPlatform {
    /// Creates an empty Linux X11 / Wayland platform backend.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized Linux backend.
    fn default() -> Self {
        Self {
            next_id: 1,
            x11_lib: 0,
            windows: HashMap::new(),
            pending_events: Vec::new(),
            clipboard_cache: None,
            pump_paused: false,
        }
    }
}

/// X11/Wayland system event injection and Wayland VSync/output callbacks for `LinuxPlatform`.
impl LinuxPlatform {
    /// Enqueues a normalized Linux `SystemEvent` to be drained on the next `poll_events()` tick.
    ///
    /// # Arguments
    ///
    /// - `SystemEvent` - System event to enqueue.
    pub fn push_system_event(&mut self, event: SystemEvent) {
        self.get_mut_pending_events()
            .push(WindowEvent::System(event));
    }

    /// Records a Wayland `wl_output.mode` refresh rate in millihertz (e.g. `240000` -> `240Hz`) for `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Wayland window identifier.
    /// - `u32` - Output refresh rate in millihertz.
    pub fn on_wayland_output_mode(&mut self, id: WindowId, refresh_milli_hz: u32) {
        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
            rec.set_wayland_output_refresh_milli_hz(refresh_milli_hz);
            let hz: f32 = ((refresh_milli_hz as f32) / 1000.0)
                .clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
            rec.get_mut_state()
                .get_mut_display()
                .set_refresh_rate_hz(hz.round() as u32);
        }
    }

    /// Handles a Wayland `wl_surface::frame` done callback and schedules a redraw when active.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Wayland window identifier.
    pub fn on_wayland_frame_callback(&mut self, id: WindowId) {
        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
            rec.set_wayland_frame_callback_pending(false);
        }
        if !self.get_pump_paused() {
            self.get_mut_pending_events()
                .push(WindowEvent::RedrawRequested(id));
        }
    }

    /// Records a Wayland `wp_presentation` feedback timestamp in nanoseconds for `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Wayland window identifier.
    /// - `u64` - Compositor presentation timestamp in nanoseconds.
    pub fn on_wayland_presentation_feedback(&mut self, id: WindowId, timestamp_ns: u64) {
        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
            rec.set_wayland_presentation_time_ns(timestamp_ns);
        }
    }

    /// Marks Wayland shm double-buffer slot `slot` (`0` or `1`) as released by the compositor for window `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Wayland window identifier.
    /// - `usize` - Released double-buffer slot index (`0` or `1`).
    pub fn on_wayland_buffer_release(&mut self, id: WindowId, slot: usize) {
        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
            let shm_arc: Arc<Mutex<WaylandShmSwapchain>> = rec.wayland_shm_handle();
            if let Ok(mut guard) = shm_arc.lock() {
                guard.release_slot(slot);
            }
        }
    }

    /// Returns whether a CPU software framebuffer mirror is currently active on Linux window `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Linux window identifier.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when presenting via Wayland `wl_shm` or X11 software blitting; `false` when direct GPU Vulkan WSI is active.
    #[must_use]
    pub fn cpu_mirror_active(&self, id: WindowId) -> bool {
        self.get_windows()
            .get(&id)
            .map(LinuxWindowRecord::get_cpu_mirror_active)
            .unwrap_or(true)
    }

    /// Returns the most recent Linux presentation telemetry snapshot for window `id`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Linux window identifier.
    ///
    /// # Returns
    ///
    /// - `Option<LinuxPresentTelemetry>` - Latest presentation telemetry, if the window exists.
    #[must_use]
    pub fn last_present_telemetry(&self, id: WindowId) -> Option<LinuxPresentTelemetry> {
        self.get_windows()
            .get(&id)
            .map(LinuxWindowRecord::get_last_telemetry)
    }

    /// Presents `framebuffer` (or only `damage`) on Linux window `id` and returns explicit `Submitted`/`SkippedUnchanged`/`Failed` telemetry.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target window handle.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    /// - `DamageRegion` - Damaged pixel region updated this frame.
    ///
    /// # Returns
    ///
    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on commit or skip; `Err` on failure.
    pub fn present_framebuffer_with_outcome(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
        damage: DamageRegion,
    ) -> Result<LinuxPresentTelemetry, PlatformError> {
        let (res, should_map, display, window): (
            Result<LinuxPresentTelemetry, PlatformError>,
            bool,
            usize,
            u64,
        ) = {
            let rec: &mut LinuxWindowRecord = self
                .get_mut_windows()
                .get_mut(&id)
                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
            let present_res: Result<LinuxPresentTelemetry, PlatformError> =
                linux_present_window_region(rec, framebuffer, damage);
            let should_map_x11: bool =
                !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible();
            (
                present_res,
                should_map_x11,
                rec.get_display(),
                rec.get_window(),
            )
        };
        if let Ok(telemetry) = res {
            if telemetry.get_outcome() == LinuxPresentOutcome::Submitted && should_map {
                linux_x11_map_window(display, window);
                if let Some(rec) = self.get_mut_windows().get_mut(&id) {
                    rec.set_revealed(true);
                }
            }
            Ok(telemetry)
        } else {
            res
        }
    }

    /// Records a direct Vulkan WSI GPU presentation on Wayland (`VK_KHR_wayland_surface`) or X11 (`VK_KHR_xlib_surface`) with `cpu_mirror_active = false`.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target Linux window handle.
    ///
    /// # Returns
    ///
    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Direct GPU telemetry (`cpu_mirror_active = false`), or `Err` when WSI is unavailable.
    pub fn present_gpu_direct_hook(
        &mut self,
        id: WindowId,
    ) -> Result<LinuxPresentTelemetry, PlatformError> {
        let rec: &mut LinuxWindowRecord = self
            .get_mut_windows()
            .get_mut(&id)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        let wsi_ready: bool = if rec.get_is_wayland() {
            rec.get_wayland_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
        } else {
            rec.get_xlib_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
        };
        let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
        if !wsi_ready {
            telemetry.set_mode(LinuxPresentationMode::GpuDirect);
            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_last_telemetry(telemetry);
            return Err(PlatformError::SurfaceError(
                ERR_LINUX_GPU_DIRECT_UNAVAILABLE.to_string(),
            ));
        }
        telemetry.set_mode(LinuxPresentationMode::GpuDirect);
        telemetry.set_outcome(LinuxPresentOutcome::Submitted);
        telemetry.set_cpu_mirror_active(false);
        telemetry.set_upload_bytes(0);
        telemetry.set_dirty_rect_count(0);
        telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
        rec.set_presentation_mode(LinuxPresentationMode::GpuDirect);
        rec.set_cpu_mirror_active(false);
        rec.set_last_telemetry(telemetry);
        Ok(telemetry)
    }
}

/// `WindowController` implementation for Linux X11 / Wayland.
impl WindowController for LinuxPlatform {
    /// Applies a `WindowCommand` onto the native X11 or Wayland window.
    ///
    /// # Arguments
    ///
    /// - `WindowCommand` - Command to apply.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Execution status.
    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
        match command {
            WindowCommand::SetTitle(id, title) => {
                let rec: &mut LinuxWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                if !rec.get_is_wayland() {
                    linux_x11_set_title(rec.get_display(), rec.get_window(), &title);
                }
                rec.get_mut_config().set_title(title);
                Ok(())
            }
            WindowCommand::SetSize(id, width, height) => {
                let rec: &mut LinuxWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                let w: u32 = width.max(1);
                let h: u32 = height.max(1);
                if !rec.get_is_wayland() {
                    linux_x11_resize(rec.get_display(), rec.get_window(), w, h);
                }
                let scale: f32 = rec.get_state().get_scale_factor();
                rec.get_mut_config().set_width(w);
                rec.get_mut_config().set_height(h);
                rec.get_mut_state().set_logical_width(w as f32);
                rec.get_mut_state().set_logical_height(h as f32);
                rec.get_mut_state()
                    .set_physical_width(((w as f32) * scale).round() as u32);
                rec.get_mut_state()
                    .set_physical_height(((h as f32) * scale).round() as u32);
                Ok(())
            }
            WindowCommand::Close(id) => {
                let rec: LinuxWindowRecord = self
                    .get_mut_windows()
                    .remove(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                if rec.get_is_wayland() {
                    linux_wayland_disconnect(rec.get_display());
                } else {
                    linux_x11_destroy(rec.get_display(), rec.get_window());
                }
                Ok(())
            }
            WindowCommand::SetRenderMode(id, mode) => {
                let rec: &mut LinuxWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().get_mut_render().set_mode(mode);
                Ok(())
            }
            WindowCommand::RequestRedraw(id) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                self.get_mut_pending_events()
                    .push(WindowEvent::RedrawRequested(id));
                Ok(())
            }
            WindowCommand::SetFullscreen(id, mode) => {
                let rec: &mut LinuxWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().set_fullscreen(mode);
                rec.get_mut_state().set_fullscreen(mode);
                Ok(())
            }
            WindowCommand::SetPosition(id, _, _)
            | WindowCommand::SetResizable(id, _)
            | WindowCommand::SetDecorations(id, _)
            | WindowCommand::SetAlwaysOnTop(id, _)
            | WindowCommand::SetVisible(id, _)
            | WindowCommand::SetCursor(id, _)
            | WindowCommand::SetIme(id, _, _)
            | WindowCommand::SetStatusBarStyle(id, _) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                Ok(())
            }
        }
    }
}

/// `PlatformBackend` implementation for native Linux.
impl PlatformBackend for LinuxPlatform {
    /// Returns `PlatformKind::Linux`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `PlatformKind` - `PlatformKind::Linux`.
    fn kind(&self) -> PlatformKind {
        PlatformKind::Linux
    }

    /// Returns Linux desktop capabilities.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `PlatformCapabilities` - Linux capability flags.
    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities::for_platform(PlatformKind::Linux)
    }

    /// Opens an X11 or Wayland window via dynamic `dlopen`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Linux platform.
    /// - `&WindowConfig` - Declarative window config.
    ///
    /// # Returns
    ///
    /// - `Result<WindowState, PlatformError>` - Initial window state.
    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
        let native: LinuxNativeWindowHandle = linux_create_native_window(config)?;
        if !native.get_is_wayland() {
            self.set_x11_lib(native.get_lib());
        }
        let id: WindowId = WindowId::new(self.get_next_id());
        self.set_next_id(self.get_next_id().wrapping_add(1));
        let mut state: WindowState =
            WindowState::from_config(id, config, native.get_scale_factor());
        let hz: f32 = if native.get_is_wayland() {
            linux_display_refresh_rate_hz(null_mut(), 0)
        } else {
            linux_display_refresh_rate_hz(
                native.get_display() as *mut c_void,
                native.get_window() as usize,
            )
        };
        state
            .get_mut_display()
            .set_refresh_rate_hz(hz.round() as u32);
        let initial_mode: LinuxPresentationMode = if native.get_is_wayland() {
            if native.get_wayland_vulkan_wsi()
                && config.get_render().get_mode() != RenderMode::Software
            {
                LinuxPresentationMode::GpuDirect
            } else {
                LinuxPresentationMode::WaylandShmSoftware
            }
        } else if native.get_xlib_vulkan_wsi()
            && config.get_render().get_mode() != RenderMode::Software
        {
            LinuxPresentationMode::GpuDirect
        } else {
            LinuxPresentationMode::X11Software
        };
        let initial_cpu_mirror: bool = initial_mode != LinuxPresentationMode::GpuDirect;
        self.get_mut_windows().insert(
            id,
            LinuxWindowRecord {
                config: config.clone(),
                state,
                is_wayland: native.get_is_wayland(),
                display: native.get_display(),
                window: native.get_window(),
                gc: native.get_gc(),
                visual: native.get_visual(),
                depth: native.get_depth(),
                wm_delete_atom: native.get_wm_delete_atom(),
                revealed: native.get_is_wayland(),
                mit_shm_available: native.get_mit_shm_available(),
                wayland_vulkan_wsi: native.get_wayland_vulkan_wsi(),
                xlib_vulkan_wsi: native.get_xlib_vulkan_wsi(),
                wl_compositor: native.get_wl_compositor(),
                wl_shm: native.get_wl_shm(),
                wl_surface_version: native.get_wl_surface_version(),
                wayland_output_refresh_milli_hz: 0,
                wayland_presentation_time_ns: 0,
                wayland_frame_callback_pending: false,
                presentation_mode: initial_mode,
                cpu_mirror_active: initial_cpu_mirror,
                last_telemetry: LinuxPresentTelemetry {
                    mode: initial_mode,
                    outcome: LinuxPresentOutcome::SkippedUnchanged,
                    cpu_mirror_active: initial_cpu_mirror,
                    upload_bytes: 0,
                    dirty_rect_count: 0,
                    committed_buffer_slot: 0,
                    submitted_frames: 0,
                    skipped_unchanged_frames: 0,
                    failed_frames: 0,
                },
                wayland_shm: if native.get_is_wayland() {
                    Some(Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
                        WL_SHM_FORMAT_XRGB8888,
                    ))))
                } else {
                    None
                },
            },
        );
        Ok(state)
    }

    /// Queries live `WindowState` for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    /// - `WindowId` - Window handle.
    ///
    /// # Returns
    ///
    /// - `Option<WindowState>` - Window state if open.
    fn window_state(&self, id: WindowId) -> Option<WindowState> {
        self.get_windows()
            .get(&id)
            .map(LinuxWindowRecord::get_state)
    }

    /// Returns `RawWindowHandle::Xlib` or `RawWindowHandle::Wayland` for Vulkan/EGL surface binding.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    /// - `WindowId` - Window handle.
    ///
    /// # Returns
    ///
    /// - `RawWindowHandle` - Native Linux display/window handle.
    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
        match self.get_windows().get(&id) {
            Some(rec) => {
                if rec.get_is_wayland() {
                    RawWindowHandle::Wayland {
                        surface: rec.get_window() as usize,
                        display: rec.get_display(),
                    }
                } else {
                    RawWindowHandle::Xlib {
                        window: rec.get_window(),
                        display: rec.get_display(),
                    }
                }
            }
            None => RawWindowHandle::Headless,
        }
    }

    /// Pumps pending X11 events and drains queued Linux events.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Linux platform.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Pending events.
    fn poll_events(&mut self) -> Vec<WindowEvent> {
        let Self {
            windows,
            pending_events,
            ..
        } = self;
        linux_x11_pump_events(windows, pending_events);
        take(pending_events)
    }

    /// Blocks on Wayland `wl_display_dispatch` or X11 `XNextEvent` with zero CPU usage until an OS event wakes the connection.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Events received upon wake.
    fn wait_for_events(&mut self) -> Vec<WindowEvent> {
        let Self {
            windows,
            pending_events,
            ..
        } = self;
        if pending_events.is_empty() && !windows.is_empty() {
            linux_x11_wait_events(windows, pending_events);
        }
        take(pending_events)
    }

    /// Updates Linux background frame-pump pause state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Linux platform.
    /// - `bool` - `true` when paused in background; `false` when active.
    fn set_frame_pump_paused(&mut self, paused: bool) {
        self.set_pump_paused(paused);
    }

    /// Returns whether the Linux frame pump is currently paused for background freeze.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when paused in background.
    fn is_frame_pump_paused(&self) -> bool {
        self.get_pump_paused()
    }

    /// Presents `framebuffer` to the active Linux window surface via X11 `XCreateImage` + `XPutImage`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable Linux platform.
    /// - `WindowId` - Target window handle.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Presentation status.
    fn present_framebuffer(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
    ) -> Result<(), PlatformError> {
        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
    }

    /// Presents `framebuffer` (or only `damage`) onto the active Linux X11 or Wayland window and maps X11 windows after Frame 1.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Target window handle.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    /// - `DamageRegion` - Damaged pixel region updated this frame.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Presentation status.
    fn present_framebuffer_region(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
        damage: DamageRegion,
    ) -> Result<(), PlatformError> {
        let _: LinuxPresentTelemetry =
            self.present_framebuffer_with_outcome(id, framebuffer, damage)?;
        Ok(())
    }

    /// Reads cached clipboard text.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Clipboard contents.
    fn read_clipboard(&self) -> Option<String> {
        let Self {
            clipboard_cache, ..
        } = self;
        clipboard_cache.clone()
    }

    /// Writes `text` to clipboard cache.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable platform.
    /// - `&str` - Clipboard text.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Write status.
    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
        self.set_clipboard_cache(Some(text.to_string()));
        let _: bool = write_system_clipboard(text);
        Ok(())
    }

    /// Returns active system theme mode.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `ThemeMode` - Active appearance mode.
    fn system_theme(&self) -> ThemeMode {
        ThemeMode::Light
    }

    /// Queries the native Linux display refresh rate via XRandR or `EUV_REFRESH_RATE_HZ`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Active display refresh rate in Hertz.
    fn display_refresh_rate_hz(&self) -> f32 {
        if let Some(wl_milli_hz) = self
            .get_windows()
            .values()
            .find(|rec: &&LinuxWindowRecord| {
                rec.get_is_wayland() && rec.get_wayland_output_refresh_milli_hz() >= 24_000
            })
            .map(LinuxWindowRecord::get_wayland_output_refresh_milli_hz)
        {
            return ((wl_milli_hz as f32) / 1000.0).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
        }
        let (display, window): (*mut c_void, usize) = self
            .get_windows()
            .values()
            .find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland())
            .map(|rec: &LinuxWindowRecord| {
                (rec.get_display() as *mut c_void, rec.get_window() as usize)
            })
            .unwrap_or((null_mut(), 0));
        linux_display_refresh_rate_hz(display, window)
    }
}