Skip to main content

euv_core/platform/linux/
impl.rs

1use super::*;
2
3/// Default initialization for an unallocated `WaylandShmBufferSlot`.
4impl Default for WaylandShmBufferSlot {
5    /// Creates an empty Wayland shared-memory slot with no backing FD or mapping.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Empty unallocated buffer slot.
10    fn default() -> Self {
11        Self {
12            fd: -1,
13            mapped_ptr: 0,
14            mapped_len: 0,
15            width: 0,
16            height: 0,
17            stride: 0,
18            format: WL_SHM_FORMAT_XRGB8888,
19            wl_pool: 0,
20            wl_buffer: 0,
21            busy: Box::new(AtomicBool::new(false)),
22            has_full_copy: false,
23        }
24    }
25}
26
27/// Automatically unmaps POSIX shared memory and closes its FD when a `WaylandShmBufferSlot` is dropped.
28impl Drop for WaylandShmBufferSlot {
29    /// Releases the slot's POSIX `mmap` mapping and file descriptor.
30    fn drop(&mut self) {
31        let Self {
32            fd,
33            mapped_ptr,
34            mapped_len,
35            ..
36        } = self;
37        linux_free_shm_file(*fd, *mapped_ptr, *mapped_len);
38        *fd = -1;
39        *mapped_ptr = 0;
40        *mapped_len = 0;
41    }
42}
43
44/// Shared-memory lifecycle and busy-tracking helpers for `WaylandShmBufferSlot`.
45impl WaylandShmBufferSlot {
46    /// Returns whether the compositor still holds this buffer awaiting `wl_buffer.release`.
47    ///
48    /// # Returns
49    ///
50    /// - `bool` - `true` when busy.
51    #[must_use]
52    pub fn is_busy(&self) -> bool {
53        let Self { busy, .. } = self;
54        busy.load(Ordering::Acquire)
55    }
56
57    /// Marks this buffer slot as busy after `wl_surface.attach` + `wl_surface.commit`.
58    pub fn mark_busy(&mut self) {
59        let Self { busy, .. } = self;
60        busy.store(true, Ordering::Release);
61    }
62
63    /// Clears the busy flag when `wl_buffer.release` arrives from the compositor.
64    pub fn release(&mut self) {
65        let Self { busy, .. } = self;
66        busy.store(false, Ordering::Release);
67    }
68
69    /// Returns the pinned raw pointer to the slot's `AtomicBool` release flag for `wl_buffer_listener`.
70    ///
71    /// # Returns
72    ///
73    /// - `usize` - Stable heap pointer to `AtomicBool`.
74    #[must_use]
75    pub fn release_flag_ptr(&self) -> usize {
76        let Self { busy, .. } = self;
77        (&raw const **busy) as usize
78    }
79
80    /// Returns an immutable slice over the slot's `mmap`ped shared-memory bytes, if allocated.
81    ///
82    /// # Returns
83    ///
84    /// - `Option<&[u8]>` - Mapped pixel buffer slice.
85    #[must_use]
86    pub fn mapped_bytes(&self) -> Option<&[u8]> {
87        let Self {
88            mapped_ptr,
89            mapped_len,
90            ..
91        } = self;
92        if *mapped_ptr == 0 || *mapped_len == 0 {
93            return None;
94        }
95        // SAFETY: `mapped_ptr` points to a valid `mmap`ped region of `*mapped_len` bytes owned by `self`.
96        Some(unsafe { from_raw_parts(*mapped_ptr as *const u8, *mapped_len) })
97    }
98
99    /// Returns a mutable slice over the slot's `mmap`ped shared-memory bytes, if allocated.
100    ///
101    /// # Returns
102    ///
103    /// - `Option<&mut [u8]>` - Mutable mapped pixel buffer slice.
104    fn mapped_bytes_mut(&mut self) -> Option<&mut [u8]> {
105        let Self {
106            mapped_ptr,
107            mapped_len,
108            ..
109        } = self;
110        if *mapped_ptr == 0 || *mapped_len == 0 {
111            return None;
112        }
113        // SAFETY: `mapped_ptr` points to an exclusively borrowed `mmap`ped region of `*mapped_len` bytes.
114        Some(unsafe { from_raw_parts_mut(*mapped_ptr as *mut u8, *mapped_len) })
115    }
116
117    /// Ensures this slot holds an `mmap`ped POSIX shared-memory buffer and Wayland `wl_buffer` matching `(req_width, req_height, req_format)`.
118    ///
119    /// # Arguments
120    ///
121    /// - `u32` - Required physical pixel width.
122    /// - `u32` - Required physical pixel height.
123    /// - `u32` - Required Wayland shm pixel format.
124    /// - `&mut ValueType` - Wayland pool/buffer transport.
125    ///
126    /// # Returns
127    ///
128    /// - `Result<(), PlatformError>` - `Ok(())` when mapped and ready to write.
129    fn ensure_allocated<ValueType>(
130        &mut self,
131        req_width: u32,
132        req_height: u32,
133        req_format: u32,
134        ops: &mut ValueType,
135    ) -> Result<(), PlatformError>
136    where
137        ValueType: WaylandShmCommitOps,
138    {
139        let Self {
140            fd,
141            mapped_ptr,
142            mapped_len,
143            width,
144            height,
145            stride,
146            format,
147            wl_pool,
148            wl_buffer,
149            busy,
150            has_full_copy,
151        } = self;
152        let needed_stride: u32 = req_width.saturating_mul(4);
153        let needed_bytes: usize = (needed_stride as usize).saturating_mul(req_height as usize);
154        if *fd >= 0
155            && *mapped_ptr != 0
156            && *mapped_len == needed_bytes
157            && *width == req_width
158            && *height == req_height
159            && *format == req_format
160            && *wl_buffer != 0
161        {
162            return Ok(());
163        }
164        if *wl_pool != 0 || *wl_buffer != 0 {
165            ops.destroy_pool_and_buffer(*wl_pool, *wl_buffer);
166            *wl_pool = 0;
167            *wl_buffer = 0;
168        }
169        linux_free_shm_file(*fd, *mapped_ptr, *mapped_len);
170        *fd = -1;
171        *mapped_ptr = 0;
172        *mapped_len = 0;
173        *has_full_copy = false;
174        let (new_fd, new_ptr, new_len): (i32, usize, usize) = linux_alloc_shm_file(needed_bytes)?;
175        let flag_ptr: usize = (&raw const **busy) as usize;
176        let desc: WaylandShmBufferDescriptor = WaylandShmBufferDescriptor::new(
177            new_fd,
178            new_len as i32,
179            req_width as i32,
180            req_height as i32,
181            needed_stride as i32,
182            req_format,
183            flag_ptr,
184        );
185        match ops.create_pool_and_buffer(desc) {
186            Ok((pool, buffer)) => {
187                if buffer == 0 {
188                    linux_free_shm_file(new_fd, new_ptr, new_len);
189                    return Err(PlatformError::SurfaceError(
190                        ERR_LINUX_WL_BUFFER_CREATE.to_string(),
191                    ));
192                }
193                *fd = new_fd;
194                *mapped_ptr = new_ptr;
195                *mapped_len = new_len;
196                *width = req_width;
197                *height = req_height;
198                *stride = needed_stride;
199                *format = req_format;
200                *wl_pool = pool;
201                *wl_buffer = buffer;
202                busy.store(false, Ordering::Release);
203                Ok(())
204            }
205            Err(err) => {
206                linux_free_shm_file(new_fd, new_ptr, new_len);
207                Err(err)
208            }
209        }
210    }
211}
212
213/// Default initialization for `WaylandShmSwapchain` using opaque `WL_SHM_FORMAT_XRGB8888`.
214impl Default for WaylandShmSwapchain {
215    /// Creates an unallocated double-buffered Wayland shm swapchain.
216    ///
217    /// # Returns
218    ///
219    /// - `Self` - Initialized swapchain.
220    fn default() -> Self {
221        Self::with_format(WL_SHM_FORMAT_XRGB8888)
222    }
223}
224
225/// Double-buffered Wayland `wl_shm` software presentation, dirty-rect copying, and release tracking.
226impl WaylandShmSwapchain {
227    /// Creates a double-buffered Wayland `wl_shm` swapchain targeting `pixel_format` (`XRGB8888` or `ARGB8888`).
228    ///
229    /// # Arguments
230    ///
231    /// - `u32` - Wayland shm pixel format code.
232    ///
233    /// # Returns
234    ///
235    /// - `Self` - Initialized double-buffered swapchain.
236    #[must_use]
237    pub fn with_format(pixel_format: u32) -> Self {
238        Self {
239            slots: [
240                WaylandShmBufferSlot::default(),
241                WaylandShmBufferSlot::default(),
242            ],
243            pixel_format,
244            previous_dirty_rects: Vec::new(),
245            last_committed_slot: 1,
246            submitted_frames: 0,
247            skipped_unchanged_frames: 0,
248            failed_frames: 0,
249        }
250    }
251
252    /// Marks buffer slot `slot` (`0` or `1`) as released by the compositor.
253    ///
254    /// # Arguments
255    ///
256    /// - `usize` - Slot index (`0` or `1`).
257    pub fn release_slot(&mut self, slot: usize) {
258        let Self { slots, .. } = self;
259        if let Some(target) = slots.get_mut(slot) {
260            target.release();
261        }
262    }
263
264    /// Returns whether buffer slot `slot` (`0` or `1`) is currently held busy by the compositor.
265    ///
266    /// # Arguments
267    ///
268    /// - `usize` - Slot index (`0` or `1`).
269    ///
270    /// # Returns
271    ///
272    /// - `bool` - `true` when the slot is busy.
273    #[must_use]
274    pub fn is_slot_busy(&self, slot: usize) -> bool {
275        let Self { slots, .. } = self;
276        slots
277            .get(slot)
278            .map(WaylandShmBufferSlot::is_busy)
279            .unwrap_or(false)
280    }
281
282    /// Returns an immutable slice over the `mmap`ped pixel bytes of slot `slot` (`0` or `1`), if allocated.
283    ///
284    /// # Arguments
285    ///
286    /// - `usize` - Slot index (`0` or `1`).
287    ///
288    /// # Returns
289    ///
290    /// - `Option<&[u8]>` - Mapped XRGB8888/ARGB8888 shared-memory bytes.
291    #[must_use]
292    pub fn slot_bytes(&self, slot: usize) -> Option<&[u8]> {
293        let Self { slots, .. } = self;
294        slots.get(slot).and_then(WaylandShmBufferSlot::mapped_bytes)
295    }
296
297    /// Presents `framebuffer` over Wayland `wl_shm` with double-buffering, dirty-rect copying, and explicit `Submitted`/`SkippedUnchanged`/`Failed` outcomes.
298    ///
299    /// # Arguments
300    ///
301    /// - `&Framebuffer` - Source RGBA8 framebuffer.
302    /// - `DamageRegion` - Frame damage region.
303    /// - `&mut ValueType` - Wayland shm/surface commit transport.
304    ///
305    /// # Returns
306    ///
307    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on `Submitted` or `SkippedUnchanged`, or `Err` on `Failed`.
308    pub fn present_framebuffer<ValueType>(
309        &mut self,
310        framebuffer: &Framebuffer,
311        damage: DamageRegion,
312        ops: &mut ValueType,
313    ) -> Result<LinuxPresentTelemetry, PlatformError>
314    where
315        ValueType: WaylandShmCommitOps,
316    {
317        let Self {
318            slots,
319            pixel_format,
320            previous_dirty_rects,
321            last_committed_slot,
322            submitted_frames,
323            skipped_unchanged_frames,
324            failed_frames,
325        } = self;
326        let fb_w: u32 = framebuffer.get_width();
327        let fb_h: u32 = framebuffer.get_height();
328        let required_bytes: usize = (fb_w as usize)
329            .saturating_mul(fb_h as usize)
330            .saturating_mul(4);
331        if fb_w == 0 || fb_h == 0 || framebuffer.get_pixels().len() < required_bytes {
332            *failed_frames = failed_frames.saturating_add(1);
333            return Err(PlatformError::SurfaceError(
334                ERR_LINUX_INVALID_FRAMEBUFFER.to_string(),
335            ));
336        }
337        let dirty_rects: Vec<(u32, u32, u32, u32)> =
338            linux_normalize_damage_rects(framebuffer, damage);
339        if dirty_rects.is_empty() {
340            *skipped_unchanged_frames = skipped_unchanged_frames.saturating_add(1);
341            return Ok(LinuxPresentTelemetry {
342                mode: LinuxPresentationMode::WaylandShmSoftware,
343                outcome: LinuxPresentOutcome::SkippedUnchanged,
344                cpu_mirror_active: true,
345                upload_bytes: 0,
346                dirty_rect_count: 0,
347                committed_buffer_slot: *last_committed_slot,
348                submitted_frames: *submitted_frames,
349                skipped_unchanged_frames: *skipped_unchanged_frames,
350                failed_frames: *failed_frames,
351            });
352        }
353        if let Err(err) = ops.dispatch_pending() {
354            *failed_frames = failed_frames.saturating_add(1);
355            return Err(err);
356        }
357        let preferred_slot: usize = usize::from(*last_committed_slot == 0);
358        let fallback_slot: usize = 1 - preferred_slot;
359        let chosen_idx: usize = if !slots[preferred_slot].is_busy() {
360            preferred_slot
361        } else if !slots[fallback_slot].is_busy() {
362            fallback_slot
363        } else {
364            *failed_frames = failed_frames.saturating_add(1);
365            return Err(PlatformError::SurfaceError(
366                ERR_LINUX_WL_NO_FREE_BUFFER.to_string(),
367            ));
368        };
369        let slot: &mut WaylandShmBufferSlot = &mut slots[chosen_idx];
370        if let Err(err) = slot.ensure_allocated(fb_w, fb_h, *pixel_format, ops) {
371            *failed_frames = failed_frames.saturating_add(1);
372            return Err(err);
373        }
374        let copy_rects: Vec<(u32, u32, u32, u32)> = if !slot.has_full_copy {
375            vec![(0, 0, fb_w, fb_h)]
376        } else {
377            let mut merged: Vec<(u32, u32, u32, u32)> =
378                Vec::with_capacity(previous_dirty_rects.len() + dirty_rects.len());
379            for &(px, py, pw, ph) in previous_dirty_rects.iter() {
380                if px < fb_w && py < fb_h {
381                    let cw: u32 = pw.min(fb_w - px);
382                    let ch: u32 = ph.min(fb_h - py);
383                    if cw > 0 && ch > 0 {
384                        merged.push((px, py, cw, ch));
385                    }
386                }
387            }
388            merged.extend_from_slice(&dirty_rects);
389            merged
390        };
391        let stride: usize = slot.stride as usize;
392        let buffer_handle: usize = slot.wl_buffer;
393        let fmt: u32 = *pixel_format;
394        let upload_bytes: u64 = match slot.mapped_bytes_mut() {
395            Some(dst) => linux_copy_rgba_to_wayland_shm(framebuffer, dst, stride, &copy_rects, fmt),
396            None => {
397                *failed_frames = failed_frames.saturating_add(1);
398                return Err(PlatformError::SurfaceError(
399                    ERR_LINUX_WL_SHM_ALLOC.to_string(),
400                ));
401            }
402        };
403        let wl_damage: Vec<(i32, i32, i32, i32)> = dirty_rects
404            .iter()
405            .map(
406                |&(pos_x, pos_y, width_val, height_val): &(u32, u32, u32, u32)| {
407                    (
408                        pos_x as i32,
409                        pos_y as i32,
410                        width_val as i32,
411                        height_val as i32,
412                    )
413                },
414            )
415            .collect();
416        if let Err(err) = ops.attach_damage_commit_flush(buffer_handle, &wl_damage) {
417            *failed_frames = failed_frames.saturating_add(1);
418            return Err(err);
419        }
420        slot.has_full_copy = true;
421        slot.mark_busy();
422        *last_committed_slot = chosen_idx as u8;
423        *previous_dirty_rects = dirty_rects;
424        *submitted_frames = submitted_frames.saturating_add(1);
425        Ok(LinuxPresentTelemetry {
426            mode: LinuxPresentationMode::WaylandShmSoftware,
427            outcome: LinuxPresentOutcome::Submitted,
428            cpu_mirror_active: true,
429            upload_bytes,
430            dirty_rect_count: wl_damage.len() as u32,
431            committed_buffer_slot: chosen_idx as u8,
432            submitted_frames: *submitted_frames,
433            skipped_unchanged_frames: *skipped_unchanged_frames,
434            failed_frames: *failed_frames,
435        })
436    }
437}
438
439/// Native `libwayland-client.so.0` protocol marshaling for `WaylandShmCommitOps`.
440impl WaylandShmCommitOps for NativeWaylandShmTransport {
441    /// Allocates a `wl_shm_pool` and `wl_buffer` over `libwayland-client.so.0` and binds `WL_BUFFER_LISTENER`.
442    ///
443    /// # Arguments
444    ///
445    /// - `&Self` - Mutable native Wayland transport.
446    /// - `WaylandShmBufferDescriptor` - Shared-memory FD, geometry, format, and release flag pointer.
447    ///
448    /// # Returns
449    ///
450    /// - `Result<(usize, usize), PlatformError>` - `(wl_shm_pool*, wl_buffer*)` handles on success.
451    fn create_pool_and_buffer(
452        &mut self,
453        desc: WaylandShmBufferDescriptor,
454    ) -> Result<(usize, usize), PlatformError> {
455        let wl: &LinuxWaylandSyms = linux_wayland_syms();
456        if self.get_display() == 0
457            || self.get_surface() == 0
458            || self.get_wl_shm() == 0
459            || wl.proxy_marshal_flags == 0
460            || wl.shm_pool_interface == 0
461            || wl.buffer_interface == 0
462        {
463            return Err(PlatformError::SurfaceError(
464                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
465            ));
466        }
467        // SAFETY: Invokes `wl_proxy_marshal_flags` for `wl_shm.create_pool` and `wl_shm_pool.create_buffer` using exact Wayland C ABI.
468        unsafe {
469            let marshal_pool: unsafe extern "C" fn(
470                *mut c_void,
471                u32,
472                *const c_void,
473                u32,
474                u32,
475                *mut c_void,
476                i32,
477                i32,
478            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
479            let pool: *mut c_void = marshal_pool(
480                self.get_wl_shm() as *mut c_void,
481                WL_OPCODE_SHM_CREATE_POOL,
482                wl.shm_pool_interface as *const c_void,
483                WL_SHM_MAX_VERSION,
484                0,
485                null_mut(),
486                desc.get_fd(),
487                desc.get_size(),
488            );
489            if pool.is_null() {
490                return Err(PlatformError::SurfaceError(
491                    ERR_LINUX_WL_BUFFER_CREATE.to_string(),
492                ));
493            }
494            let marshal_buffer: unsafe extern "C" fn(
495                *mut c_void,
496                u32,
497                *const c_void,
498                u32,
499                u32,
500                *mut c_void,
501                i32,
502                i32,
503                i32,
504                i32,
505                u32,
506            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
507            let buffer: *mut c_void = marshal_buffer(
508                pool,
509                WL_OPCODE_SHM_POOL_CREATE_BUFFER,
510                wl.buffer_interface as *const c_void,
511                WL_SHM_MAX_VERSION,
512                0,
513                null_mut(),
514                0,
515                desc.get_width(),
516                desc.get_height(),
517                desc.get_stride(),
518                desc.get_format(),
519            );
520            if buffer.is_null() {
521                self.destroy_pool_and_buffer(pool as usize, 0);
522                return Err(PlatformError::SurfaceError(
523                    ERR_LINUX_WL_BUFFER_CREATE.to_string(),
524                ));
525            }
526            if wl.proxy_add_listener != 0 && desc.get_release_flag_ptr() != 0 {
527                let add_listener: unsafe extern "C" fn(
528                    *mut c_void,
529                    *const c_void,
530                    *mut c_void,
531                ) -> i32 = transmute(wl.proxy_add_listener as *const c_void);
532                let _: i32 = add_listener(
533                    buffer,
534                    (&raw const WL_BUFFER_LISTENER).cast::<c_void>(),
535                    desc.get_release_flag_ptr() as *mut c_void,
536                );
537            }
538            Ok((pool as usize, buffer as usize))
539        }
540    }
541
542    /// Calls `wl_surface_attach`, `wl_surface_damage_buffer` per dirty rect, `wl_surface_commit`, and `wl_display_flush`.
543    ///
544    /// # Arguments
545    ///
546    /// - `&Self` - Mutable native Wayland transport.
547    /// - `usize` - Live `wl_buffer*` handle.
548    /// - `&[(i32, i32, i32, i32)]` - Buffer-space damage rectangles.
549    ///
550    /// # Returns
551    ///
552    /// - `Result<(), PlatformError>` - `Err` on missing handles, flush failure, or `wl_display_get_error != 0`.
553    fn attach_damage_commit_flush(
554        &mut self,
555        buffer: usize,
556        damage_rects: &[(i32, i32, i32, i32)],
557    ) -> Result<(), PlatformError> {
558        let wl: &LinuxWaylandSyms = linux_wayland_syms();
559        if self.get_display() == 0
560            || self.get_surface() == 0
561            || buffer == 0
562            || wl.proxy_marshal_flags == 0
563            || wl.display_flush == 0
564        {
565            return Err(PlatformError::SurfaceError(
566                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
567            ));
568        }
569        let surface_ver: u32 = self.get_surface_version().max(1);
570        let buffer_scale: i32 = self.get_buffer_scale().max(1);
571        let damage_opcode: u32 = if surface_ver >= WL_COMPOSITOR_MAX_VERSION {
572            WL_OPCODE_SURFACE_DAMAGE_BUFFER
573        } else {
574            WL_OPCODE_SURFACE_DAMAGE
575        };
576        // SAFETY: Marshals `wl_surface.set_buffer_scale`, `wl_surface.attach`, `wl_surface.damage_buffer`/`damage`, `wl_surface.commit`, and `wl_display_flush`.
577        unsafe {
578            let surface_ptr: *mut c_void = self.get_surface() as *mut c_void;
579            if surface_ver >= WL_SURFACE_BUFFER_SCALE_MIN_VERSION {
580                let marshal_scale: unsafe extern "C" fn(
581                    *mut c_void,
582                    u32,
583                    *const c_void,
584                    u32,
585                    u32,
586                    i32,
587                ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
588                let _: *mut c_void = marshal_scale(
589                    surface_ptr,
590                    WL_OPCODE_SURFACE_SET_BUFFER_SCALE,
591                    null(),
592                    surface_ver,
593                    0,
594                    buffer_scale,
595                );
596            }
597            let marshal_attach: unsafe extern "C" fn(
598                *mut c_void,
599                u32,
600                *const c_void,
601                u32,
602                u32,
603                *mut c_void,
604                i32,
605                i32,
606            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
607            let _: *mut c_void = marshal_attach(
608                surface_ptr,
609                WL_OPCODE_SURFACE_ATTACH,
610                null(),
611                surface_ver,
612                0,
613                buffer as *mut c_void,
614                0,
615                0,
616            );
617            let marshal_damage: unsafe extern "C" fn(
618                *mut c_void,
619                u32,
620                *const c_void,
621                u32,
622                u32,
623                i32,
624                i32,
625                i32,
626                i32,
627            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
628            for &(pos_x, pos_y, width_val, height_val) in damage_rects.iter() {
629                let _: *mut c_void = marshal_damage(
630                    surface_ptr,
631                    damage_opcode,
632                    null(),
633                    surface_ver,
634                    0,
635                    pos_x,
636                    pos_y,
637                    width_val,
638                    height_val,
639                );
640            }
641            let marshal_commit: unsafe extern "C" fn(
642                *mut c_void,
643                u32,
644                *const c_void,
645                u32,
646                u32,
647            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
648            let _: *mut c_void = marshal_commit(
649                surface_ptr,
650                WL_OPCODE_SURFACE_COMMIT,
651                null(),
652                surface_ver,
653                0,
654            );
655            let wl_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
656                transmute(wl.display_flush as *const c_void);
657            let flushed: i32 = wl_flush(self.get_display() as *mut c_void);
658            if flushed < 0 {
659                return Err(PlatformError::SurfaceError(
660                    ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
661                ));
662            }
663            if wl.display_get_error != 0 {
664                let get_err: unsafe extern "C" fn(*mut c_void) -> i32 =
665                    transmute(wl.display_get_error as *const c_void);
666                if get_err(self.get_display() as *mut c_void) != 0 {
667                    return Err(PlatformError::SurfaceError(
668                        ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
669                    ));
670                }
671            }
672        }
673        Ok(())
674    }
675
676    /// Dispatches pending incoming Wayland compositor events such as `wl_buffer.release`.
677    ///
678    /// # Arguments
679    ///
680    /// - `&Self` - Mutable native Wayland transport.
681    ///
682    /// # Returns
683    ///
684    /// - `Result<(), PlatformError>` - `Err` on missing display or protocol error.
685    fn dispatch_pending(&mut self) -> Result<(), PlatformError> {
686        let wl: &LinuxWaylandSyms = linux_wayland_syms();
687        if self.get_display() == 0 || self.get_surface() == 0 || self.get_wl_shm() == 0 {
688            return Err(PlatformError::SurfaceError(
689                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
690            ));
691        }
692        if wl.display_dispatch_pending != 0 {
693            // SAFETY: Non-blocking dispatch of queued Wayland events on a live `wl_display*`.
694            unsafe {
695                let dispatch: unsafe extern "C" fn(*mut c_void) -> i32 =
696                    transmute(wl.display_dispatch_pending as *const c_void);
697                if dispatch(self.get_display() as *mut c_void) < 0 {
698                    return Err(PlatformError::SurfaceError(
699                        ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
700                    ));
701                }
702            }
703        }
704        Ok(())
705    }
706
707    /// Destroys a previously allocated `wl_buffer*` and `wl_shm_pool*` pair cleanly.
708    ///
709    /// # Arguments
710    ///
711    /// - `&Self` - Mutable native Wayland transport.
712    /// - `usize` - `wl_shm_pool*` proxy handle.
713    /// - `usize` - `wl_buffer*` proxy handle.
714    fn destroy_pool_and_buffer(&mut self, pool: usize, buffer: usize) {
715        let wl: &LinuxWaylandSyms = linux_wayland_syms();
716        if wl.proxy_marshal_flags == 0 {
717            return;
718        }
719        // SAFETY: Sends `wl_buffer.destroy` and `wl_shm_pool.destroy` with `WL_MARSHAL_FLAG_DESTROY`.
720        unsafe {
721            let marshal_destroy: unsafe extern "C" fn(
722                *mut c_void,
723                u32,
724                *const c_void,
725                u32,
726                u32,
727            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
728            if buffer != 0 {
729                let _: *mut c_void = marshal_destroy(
730                    buffer as *mut c_void,
731                    WL_OPCODE_BUFFER_DESTROY,
732                    null(),
733                    WL_SHM_MAX_VERSION,
734                    WL_MARSHAL_FLAG_DESTROY,
735                );
736            }
737            if pool != 0 {
738                let _: *mut c_void = marshal_destroy(
739                    pool as *mut c_void,
740                    WL_OPCODE_SHM_POOL_DESTROY,
741                    null(),
742                    WL_SHM_MAX_VERSION,
743                    WL_MARSHAL_FLAG_DESTROY,
744                );
745            }
746        }
747    }
748}
749
750/// Wayland `wl_shm` swapchain accessors on `LinuxWindowRecord`.
751impl LinuxWindowRecord {
752    /// Returns (initializing on demand) the shared double-buffered `WaylandShmSwapchain` handle for this window.
753    ///
754    /// # Returns
755    ///
756    /// - `Arc<Mutex<WaylandShmSwapchain>>` - Shared Wayland shm swapchain handle.
757    pub(crate) fn wayland_shm_handle(&mut self) -> Arc<Mutex<WaylandShmSwapchain>> {
758        let Self { wayland_shm, .. } = self;
759        Arc::clone(wayland_shm.get_or_insert_with(|| {
760            Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
761                WL_SHM_FORMAT_XRGB8888,
762            )))
763        }))
764    }
765}
766
767/// Releases GLES3 textures/buffers/program, EGL context/surface/display, and `wl_egl_window` on drop.
768impl Drop for LinuxEglGlesSurface {
769    /// Destroys all owned GLES3 and EGL handles cleanly.
770    ///
771    /// # Arguments
772    ///
773    /// - `&Self` - Mutable EGL/GLES3 surface being destroyed.
774    fn drop(&mut self) {
775        linux_egl_destroy_surface(self);
776    }
777}
778
779/// Default initialization for `LinuxPlatform`.
780impl Default for LinuxPlatform {
781    /// Creates an empty Linux X11 / Wayland platform backend with a non-blocking wakeup pipe for `poll()`.
782    ///
783    /// # Returns
784    ///
785    /// - `Self` - Initialized Linux backend.
786    fn default() -> Self {
787        let (wake_read_fd, wake_write_fd): (i32, i32) = linux_create_wake_pipe();
788        Self {
789            next_id: 1,
790            x11_lib: 0,
791            windows: HashMap::new(),
792            pending_events: Vec::new(),
793            clipboard_cache: None,
794            pump_paused: false,
795            wake_read_fd,
796            wake_write_fd,
797        }
798    }
799}
800
801/// X11/Wayland system event injection and Wayland VSync/output callbacks for `LinuxPlatform`.
802impl LinuxPlatform {
803    /// Enqueues a normalized Linux `SystemEvent` to be drained on the next `poll_events()` tick.
804    ///
805    /// # Arguments
806    ///
807    /// - `SystemEvent` - System event to enqueue.
808    pub fn push_system_event(&mut self, event: SystemEvent) {
809        self.get_mut_pending_events()
810            .push(WindowEvent::System(event));
811    }
812
813    /// Records a Wayland `wl_output.mode` refresh rate in millihertz (e.g. `240000` -> `240Hz`) for `id`.
814    ///
815    /// # Arguments
816    ///
817    /// - `WindowId` - Target Wayland window identifier.
818    /// - `u32` - Output refresh rate in millihertz.
819    pub fn on_wayland_output_mode(&mut self, id: WindowId, refresh_milli_hz: u32) {
820        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
821            rec.set_wayland_output_refresh_milli_hz(refresh_milli_hz);
822            let hz: f32 = ((refresh_milli_hz as f32) / 1000.0).max(MIN_REFRESH_RATE_HZ);
823            rec.get_mut_state()
824                .get_mut_display()
825                .set_refresh_rate_hz(hz.round() as u32);
826        }
827    }
828
829    /// Handles a Wayland `wl_surface::frame` done callback and schedules a redraw when active.
830    ///
831    /// # Arguments
832    ///
833    /// - `WindowId` - Target Wayland window identifier.
834    pub fn on_wayland_frame_callback(&mut self, id: WindowId) {
835        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
836            rec.set_wayland_frame_callback_pending(false);
837        }
838        if !self.get_pump_paused() {
839            self.get_mut_pending_events()
840                .push(WindowEvent::RedrawRequested(id));
841        }
842    }
843
844    /// Records a Wayland `wp_presentation` feedback timestamp in nanoseconds for `id`.
845    ///
846    /// # Arguments
847    ///
848    /// - `WindowId` - Target Wayland window identifier.
849    /// - `u64` - Compositor presentation timestamp in nanoseconds.
850    pub fn on_wayland_presentation_feedback(&mut self, id: WindowId, timestamp_ns: u64) {
851        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
852            rec.set_wayland_presentation_time_ns(timestamp_ns);
853        }
854    }
855
856    /// Marks Wayland shm double-buffer slot `slot` (`0` or `1`) as released by the compositor for window `id`.
857    ///
858    /// # Arguments
859    ///
860    /// - `WindowId` - Target Wayland window identifier.
861    /// - `usize` - Released double-buffer slot index (`0` or `1`).
862    pub fn on_wayland_buffer_release(&mut self, id: WindowId, slot: usize) {
863        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
864            let shm_arc: Arc<Mutex<WaylandShmSwapchain>> = rec.wayland_shm_handle();
865            if let Ok(mut guard) = shm_arc.lock() {
866                guard.release_slot(slot);
867            }
868        }
869    }
870
871    /// Returns whether a CPU software framebuffer mirror is currently active on Linux window `id`.
872    ///
873    /// # Arguments
874    ///
875    /// - `WindowId` - Target Linux window identifier.
876    ///
877    /// # Returns
878    ///
879    /// - `bool` - `true` when presenting via Wayland `wl_shm` or X11 software blitting; `false` when direct GPU Vulkan WSI is active.
880    #[must_use]
881    pub fn cpu_mirror_active(&self, id: WindowId) -> bool {
882        self.get_windows()
883            .get(&id)
884            .map(LinuxWindowRecord::get_cpu_mirror_active)
885            .unwrap_or(true)
886    }
887
888    /// Returns the most recent Linux presentation telemetry snapshot for window `id`.
889    ///
890    /// # Arguments
891    ///
892    /// - `WindowId` - Target Linux window identifier.
893    ///
894    /// # Returns
895    ///
896    /// - `Option<LinuxPresentTelemetry>` - Latest presentation telemetry, if the window exists.
897    #[must_use]
898    pub fn last_present_telemetry(&self, id: WindowId) -> Option<LinuxPresentTelemetry> {
899        self.get_windows()
900            .get(&id)
901            .map(LinuxWindowRecord::get_last_telemetry)
902    }
903
904    /// Presents `framebuffer` (or only `damage`) on Linux window `id` and returns explicit `Submitted`/`SkippedUnchanged`/`Failed` telemetry.
905    ///
906    /// # Arguments
907    ///
908    /// - `WindowId` - Target window handle.
909    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
910    /// - `DamageRegion` - Damaged pixel region updated this frame.
911    ///
912    /// # Returns
913    ///
914    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on commit or skip; `Err` on failure.
915    pub fn present_framebuffer_with_outcome(
916        &mut self,
917        id: WindowId,
918        framebuffer: &Framebuffer,
919        damage: DamageRegion,
920    ) -> Result<LinuxPresentTelemetry, PlatformError> {
921        let (res, should_map, display, window): (
922            Result<LinuxPresentTelemetry, PlatformError>,
923            bool,
924            usize,
925            u64,
926        ) = {
927            let rec: &mut LinuxWindowRecord = self
928                .get_mut_windows()
929                .get_mut(&id)
930                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
931            let present_res: Result<LinuxPresentTelemetry, PlatformError> =
932                linux_present_window_region(rec, framebuffer, damage);
933            let should_map_x11: bool =
934                !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible();
935            (
936                present_res,
937                should_map_x11,
938                rec.get_display(),
939                rec.get_window(),
940            )
941        };
942        if let Ok(telemetry) = res {
943            if telemetry.get_outcome() == LinuxPresentOutcome::Submitted && should_map {
944                linux_x11_map_window(display, window);
945                if let Some(rec) = self.get_mut_windows().get_mut(&id) {
946                    rec.set_revealed(true);
947                }
948            }
949            Ok(telemetry)
950        } else {
951            res
952        }
953    }
954
955    /// Signals the non-blocking Linux wakeup pipe so a thread blocked in `poll(display_fd, wakeup_pipe)` resumes immediately.
956    ///
957    /// # Arguments
958    ///
959    /// - `&Self` - Linux platform reference.
960    ///
961    /// # Returns
962    ///
963    /// - `bool` - `true` when the wakeup byte was written to the pipe.
964    pub fn wake_event_loop(&self) -> bool {
965        linux_signal_wake_pipe(self.get_wake_write_fd())
966    }
967
968    /// Presents a compiled `DirectGpuFrameBatch` directly via dynamically loaded EGL + GLES3 (`glDrawArraysInstanced`) over Wayland (`wl_egl_window`) or X11 (`Window`) with `wl_surface.frame` VSync pacing.
969    ///
970    /// # Arguments
971    ///
972    /// - `&Self` - Mutable Linux platform backend.
973    /// - `WindowId` - Target Linux window handle.
974    /// - `&DirectGpuFrameBatch` - Compiled 64-byte `GpuPrimitiveInstance` batch and atlas updates.
975    ///
976    /// # Returns
977    ///
978    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Direct GPU telemetry (`cpu_mirror_active = false`, `upload_bytes = 0`), or `Err` so caller falls back cleanly to `wl_shm` / X11 software.
979    pub fn present_direct_gpu_batch(
980        &mut self,
981        id: WindowId,
982        batch: &DirectGpuFrameBatch,
983    ) -> Result<LinuxPresentTelemetry, PlatformError> {
984        let (is_wayland, display, window, should_map, existing_egl): (
985            bool,
986            usize,
987            u64,
988            bool,
989            Option<Arc<Mutex<LinuxEglGlesSurface>>>,
990        ) = {
991            let rec: &LinuxWindowRecord = self
992                .get_windows()
993                .get(&id)
994                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
995            let LinuxWindowRecord { egl_gles, .. } = rec;
996            (
997                rec.get_is_wayland(),
998                rec.get_display(),
999                rec.get_window(),
1000                !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible(),
1001                egl_gles.clone(),
1002            )
1003        };
1004        let egl_arc: Arc<Mutex<LinuxEglGlesSurface>> = match existing_egl {
1005            Some(surf) => surf,
1006            None => {
1007                let created: LinuxEglGlesSurface = linux_egl_create_surface(
1008                    is_wayland,
1009                    display,
1010                    window,
1011                    batch.get_viewport_width(),
1012                    batch.get_viewport_height(),
1013                )
1014                .ok_or_else(|| {
1015                    PlatformError::SurfaceError(ERR_LINUX_EGL_UNAVAILABLE.to_string())
1016                })?;
1017                let wrapped: Arc<Mutex<LinuxEglGlesSurface>> = Arc::new(Mutex::new(created));
1018                if let Some(rec) = self.get_mut_windows().get_mut(&id) {
1019                    let LinuxWindowRecord { egl_gles, .. } = rec;
1020                    *egl_gles = Some(wrapped.clone());
1021                }
1022                wrapped
1023            }
1024        };
1025        let wl_surface: usize = if is_wayland { window as usize } else { 0 };
1026        {
1027            let mut guard: MutexGuard<'_, LinuxEglGlesSurface> = egl_arc
1028                .lock()
1029                .map_err(|_| PlatformError::SurfaceError(ERR_LINUX_EGL_UNAVAILABLE.to_string()))?;
1030            linux_egl_present_batch(&mut guard, wl_surface, batch)?;
1031        }
1032        if should_map {
1033            linux_x11_map_window(display, window);
1034        }
1035        let rec: &mut LinuxWindowRecord = self
1036            .get_mut_windows()
1037            .get_mut(&id)
1038            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1039        if should_map {
1040            rec.set_revealed(true);
1041        }
1042        let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
1043        telemetry.set_mode(LinuxPresentationMode::GpuDirect);
1044        telemetry.set_outcome(LinuxPresentOutcome::Submitted);
1045        telemetry.set_cpu_mirror_active(false);
1046        telemetry.set_upload_bytes(0);
1047        telemetry.set_dirty_rect_count(0);
1048        telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
1049        rec.set_presentation_mode(LinuxPresentationMode::GpuDirect);
1050        rec.set_cpu_mirror_active(false);
1051        rec.set_last_telemetry(telemetry);
1052        Ok(telemetry)
1053    }
1054
1055    /// Presents a complete `GpuFrameSubmission` directly via Linux EGL/GLES3 including `DirectGpuScenePass` (`OceanFluid` + `World3d`) and dirty-subrect atlas uploads.
1056    ///
1057    /// # Arguments
1058    ///
1059    /// - `WindowId` - Target Linux window handle.
1060    /// - `&GpuFrameSubmission` - Direct-GPU batches, optional scene pass, and incremental atlas uploads.
1061    ///
1062    /// # Returns
1063    ///
1064    /// - `Result<(LinuxPresentTelemetry, usize, usize), PlatformError>` - Direct GPU telemetry plus `(draw_calls, uploaded_instances)`.
1065    pub fn present_direct_gpu_submission(
1066        &mut self,
1067        id: WindowId,
1068        submission: &GpuFrameSubmission,
1069    ) -> Result<(LinuxPresentTelemetry, usize, usize), PlatformError> {
1070        let (is_wayland, display, window, should_map, existing_egl): (
1071            bool,
1072            usize,
1073            u64,
1074            bool,
1075            Option<Arc<Mutex<LinuxEglGlesSurface>>>,
1076        ) = {
1077            let rec: &LinuxWindowRecord = self
1078                .get_windows()
1079                .get(&id)
1080                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1081            let LinuxWindowRecord { egl_gles, .. } = rec;
1082            (
1083                rec.get_is_wayland(),
1084                rec.get_display(),
1085                rec.get_window(),
1086                !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible(),
1087                egl_gles.clone(),
1088            )
1089        };
1090        let egl_arc: Arc<Mutex<LinuxEglGlesSurface>> = match existing_egl {
1091            Some(surf) => surf,
1092            None => {
1093                let created: LinuxEglGlesSurface = linux_egl_create_surface(
1094                    is_wayland,
1095                    display,
1096                    window,
1097                    submission.get_width(),
1098                    submission.get_height(),
1099                )
1100                .ok_or_else(|| {
1101                    PlatformError::SurfaceError(ERR_LINUX_EGL_UNAVAILABLE.to_string())
1102                })?;
1103                let wrapped: Arc<Mutex<LinuxEglGlesSurface>> = Arc::new(Mutex::new(created));
1104                if let Some(rec) = self.get_mut_windows().get_mut(&id) {
1105                    let LinuxWindowRecord { egl_gles, .. } = rec;
1106                    *egl_gles = Some(wrapped.clone());
1107                }
1108                wrapped
1109            }
1110        };
1111        let wl_surface: usize = if is_wayland { window as usize } else { 0 };
1112        let (draw_calls, uploaded_instances): (usize, usize) = {
1113            let mut guard: MutexGuard<'_, LinuxEglGlesSurface> = egl_arc
1114                .lock()
1115                .map_err(|_| PlatformError::SurfaceError(ERR_LINUX_EGL_UNAVAILABLE.to_string()))?;
1116            linux_egl_present_submission(&mut guard, wl_surface, submission)?
1117        };
1118        if should_map {
1119            linux_x11_map_window(display, window);
1120        }
1121        let rec: &mut LinuxWindowRecord = self
1122            .get_mut_windows()
1123            .get_mut(&id)
1124            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1125        if should_map {
1126            rec.set_revealed(true);
1127        }
1128        let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
1129        telemetry.set_mode(LinuxPresentationMode::GpuDirect);
1130        telemetry.set_outcome(LinuxPresentOutcome::Submitted);
1131        telemetry.set_cpu_mirror_active(false);
1132        telemetry.set_upload_bytes(0);
1133        telemetry.set_dirty_rect_count(0);
1134        telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
1135        rec.set_presentation_mode(LinuxPresentationMode::GpuDirect);
1136        rec.set_cpu_mirror_active(false);
1137        rec.set_last_telemetry(telemetry);
1138        Ok((telemetry, draw_calls, uploaded_instances))
1139    }
1140
1141    /// Records a direct Vulkan WSI GPU presentation on Wayland (`VK_KHR_wayland_surface`) or X11 (`VK_KHR_xlib_surface`) with `cpu_mirror_active = false`.
1142    ///
1143    /// # Arguments
1144    ///
1145    /// - `WindowId` - Target Linux window handle.
1146    ///
1147    /// # Returns
1148    ///
1149    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Direct GPU telemetry (`cpu_mirror_active = false`), or `Err` when WSI is unavailable.
1150    pub fn present_gpu_direct_hook(
1151        &mut self,
1152        id: WindowId,
1153    ) -> Result<LinuxPresentTelemetry, PlatformError> {
1154        let rec: &mut LinuxWindowRecord = self
1155            .get_mut_windows()
1156            .get_mut(&id)
1157            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1158        let wsi_ready: bool = if rec.get_is_wayland() {
1159            rec.get_wayland_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
1160        } else {
1161            rec.get_xlib_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
1162        };
1163        let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
1164        if !wsi_ready {
1165            telemetry.set_mode(LinuxPresentationMode::GpuDirect);
1166            telemetry.set_outcome(LinuxPresentOutcome::Failed);
1167            telemetry.set_upload_bytes(0);
1168            telemetry.set_dirty_rect_count(0);
1169            telemetry.set_failed_frames(telemetry.get_failed_frames().saturating_add(1));
1170            rec.set_last_telemetry(telemetry);
1171            return Err(PlatformError::SurfaceError(
1172                ERR_LINUX_GPU_DIRECT_UNAVAILABLE.to_string(),
1173            ));
1174        }
1175        telemetry.set_mode(LinuxPresentationMode::GpuDirect);
1176        telemetry.set_outcome(LinuxPresentOutcome::Submitted);
1177        telemetry.set_cpu_mirror_active(false);
1178        telemetry.set_upload_bytes(0);
1179        telemetry.set_dirty_rect_count(0);
1180        telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
1181        rec.set_presentation_mode(LinuxPresentationMode::GpuDirect);
1182        rec.set_cpu_mirror_active(false);
1183        rec.set_last_telemetry(telemetry);
1184        Ok(telemetry)
1185    }
1186}
1187
1188/// `WindowController` implementation for Linux X11 / Wayland.
1189impl WindowController for LinuxPlatform {
1190    /// Applies a `WindowCommand` onto the native X11 or Wayland window.
1191    ///
1192    /// # Arguments
1193    ///
1194    /// - `WindowCommand` - Command to apply.
1195    ///
1196    /// # Returns
1197    ///
1198    /// - `Result<(), PlatformError>` - Execution status.
1199    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
1200        match command {
1201            WindowCommand::SetTitle(id, title) => {
1202                let rec: &mut LinuxWindowRecord = self
1203                    .get_mut_windows()
1204                    .get_mut(&id)
1205                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1206                if !rec.get_is_wayland() {
1207                    linux_x11_set_title(rec.get_display(), rec.get_window(), &title);
1208                }
1209                rec.get_mut_config().set_title(title);
1210                Ok(())
1211            }
1212            WindowCommand::SetSize(id, width, height) => {
1213                let rec: &mut LinuxWindowRecord = self
1214                    .get_mut_windows()
1215                    .get_mut(&id)
1216                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1217                let width_val: u32 = width.max(1);
1218                let height_val: u32 = height.max(1);
1219                let scale: f32 = clamp_viewport_scale(rec.get_state().get_scale_factor());
1220                let phys_w: u32 = compute_lossless_physical_dim(f64::from(width_val), scale);
1221                let phys_h: u32 = compute_lossless_physical_dim(f64::from(height_val), scale);
1222                if !rec.get_is_wayland() {
1223                    linux_x11_resize(rec.get_display(), rec.get_window(), phys_w, phys_h);
1224                }
1225                rec.get_mut_config().set_width(width_val);
1226                rec.get_mut_config().set_height(height_val);
1227                rec.get_mut_state().set_logical_width(width_val as f32);
1228                rec.get_mut_state().set_logical_height(height_val as f32);
1229                rec.get_mut_state().set_physical_width(phys_w);
1230                rec.get_mut_state().set_physical_height(phys_h);
1231                Ok(())
1232            }
1233            WindowCommand::Close(id) => {
1234                let rec: LinuxWindowRecord = self
1235                    .get_mut_windows()
1236                    .remove(&id)
1237                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1238                if rec.get_is_wayland() {
1239                    linux_wayland_disconnect(rec.get_display());
1240                } else {
1241                    linux_x11_destroy(rec.get_display(), rec.get_window());
1242                }
1243                Ok(())
1244            }
1245            WindowCommand::SetRenderMode(id, mode) => {
1246                let rec: &mut LinuxWindowRecord = self
1247                    .get_mut_windows()
1248                    .get_mut(&id)
1249                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1250                rec.get_mut_config().get_mut_render().set_mode(mode);
1251                Ok(())
1252            }
1253            WindowCommand::RequestRedraw(id) => {
1254                if !self.get_windows().contains_key(&id) {
1255                    return Err(PlatformError::WindowNotFound(id.get_value()));
1256                }
1257                self.get_mut_pending_events()
1258                    .push(WindowEvent::RedrawRequested(id));
1259                Ok(())
1260            }
1261            WindowCommand::SetFullscreen(id, mode) => {
1262                let rec: &mut LinuxWindowRecord = self
1263                    .get_mut_windows()
1264                    .get_mut(&id)
1265                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1266                rec.get_mut_config().set_fullscreen(mode);
1267                rec.get_mut_state().set_fullscreen(mode);
1268                Ok(())
1269            }
1270            WindowCommand::SetPosition(id, _, _)
1271            | WindowCommand::SetResizable(id, _)
1272            | WindowCommand::SetDecorations(id, _)
1273            | WindowCommand::SetAlwaysOnTop(id, _)
1274            | WindowCommand::SetVisible(id, _)
1275            | WindowCommand::SetCursor(id, _)
1276            | WindowCommand::SetIme(id, _, _)
1277            | WindowCommand::SetStatusBarStyle(id, _) => {
1278                if !self.get_windows().contains_key(&id) {
1279                    return Err(PlatformError::WindowNotFound(id.get_value()));
1280                }
1281                Ok(())
1282            }
1283        }
1284    }
1285}
1286
1287/// `PlatformBackend` implementation for native Linux.
1288impl PlatformBackend for LinuxPlatform {
1289    /// Returns `PlatformKind::Linux`.
1290    ///
1291    /// # Arguments
1292    ///
1293    /// - `&Self` - Platform reference.
1294    ///
1295    /// # Returns
1296    ///
1297    /// - `PlatformKind` - `PlatformKind::Linux`.
1298    fn kind(&self) -> PlatformKind {
1299        PlatformKind::Linux
1300    }
1301
1302    /// Returns Linux desktop capabilities.
1303    ///
1304    /// # Arguments
1305    ///
1306    /// - `&Self` - Platform reference.
1307    ///
1308    /// # Returns
1309    ///
1310    /// - `PlatformCapabilities` - Linux capability flags.
1311    fn capabilities(&self) -> PlatformCapabilities {
1312        PlatformCapabilities::for_platform(PlatformKind::Linux)
1313    }
1314
1315    /// Opens an X11 or Wayland window via dynamic `dlopen`.
1316    ///
1317    /// # Arguments
1318    ///
1319    /// - `&Self` - Mutable Linux platform.
1320    /// - `&WindowConfig` - Declarative window config.
1321    ///
1322    /// # Returns
1323    ///
1324    /// - `Result<WindowState, PlatformError>` - Initial window state.
1325    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1326        let native: LinuxNativeWindowHandle = linux_create_native_window(config)?;
1327        if !native.get_is_wayland() {
1328            self.set_x11_lib(native.get_lib());
1329        }
1330        let id: WindowId = WindowId::new(self.get_next_id());
1331        self.set_next_id(self.get_next_id().wrapping_add(1));
1332        let mut state: WindowState =
1333            WindowState::from_config(id, config, native.get_scale_factor());
1334        let hz: f32 = if native.get_is_wayland() {
1335            linux_display_refresh_rate_hz(null_mut(), 0)
1336        } else {
1337            linux_display_refresh_rate_hz(
1338                native.get_display() as *mut c_void,
1339                native.get_window() as usize,
1340            )
1341        };
1342        state
1343            .get_mut_display()
1344            .set_refresh_rate_hz(hz.round() as u32);
1345        let initial_mode: LinuxPresentationMode = if native.get_is_wayland() {
1346            if native.get_wayland_vulkan_wsi()
1347                && config.get_render().get_mode() != RenderMode::Software
1348            {
1349                LinuxPresentationMode::GpuDirect
1350            } else {
1351                LinuxPresentationMode::WaylandShmSoftware
1352            }
1353        } else if native.get_xlib_vulkan_wsi()
1354            && config.get_render().get_mode() != RenderMode::Software
1355        {
1356            LinuxPresentationMode::GpuDirect
1357        } else {
1358            LinuxPresentationMode::X11Software
1359        };
1360        let initial_cpu_mirror: bool = initial_mode != LinuxPresentationMode::GpuDirect;
1361        self.get_mut_windows().insert(
1362            id,
1363            LinuxWindowRecord {
1364                config: config.clone(),
1365                state,
1366                is_wayland: native.get_is_wayland(),
1367                display: native.get_display(),
1368                window: native.get_window(),
1369                gc: native.get_gc(),
1370                visual: native.get_visual(),
1371                depth: native.get_depth(),
1372                wm_delete_atom: native.get_wm_delete_atom(),
1373                revealed: native.get_is_wayland(),
1374                mit_shm_available: native.get_mit_shm_available(),
1375                wayland_vulkan_wsi: native.get_wayland_vulkan_wsi(),
1376                xlib_vulkan_wsi: native.get_xlib_vulkan_wsi(),
1377                wl_compositor: native.get_wl_compositor(),
1378                wl_shm: native.get_wl_shm(),
1379                wl_surface_version: native.get_wl_surface_version(),
1380                wayland_output_refresh_milli_hz: 0,
1381                wayland_presentation_time_ns: 0,
1382                wayland_frame_callback_pending: false,
1383                presentation_mode: initial_mode,
1384                cpu_mirror_active: initial_cpu_mirror,
1385                last_telemetry: LinuxPresentTelemetry {
1386                    mode: initial_mode,
1387                    outcome: LinuxPresentOutcome::SkippedUnchanged,
1388                    cpu_mirror_active: initial_cpu_mirror,
1389                    upload_bytes: 0,
1390                    dirty_rect_count: 0,
1391                    committed_buffer_slot: 0,
1392                    submitted_frames: 0,
1393                    skipped_unchanged_frames: 0,
1394                    failed_frames: 0,
1395                },
1396                wayland_shm: if native.get_is_wayland() {
1397                    Some(Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
1398                        WL_SHM_FORMAT_XRGB8888,
1399                    ))))
1400                } else {
1401                    None
1402                },
1403                egl_gles: None,
1404            },
1405        );
1406        Ok(state)
1407    }
1408
1409    /// Queries live `WindowState` for `id`.
1410    ///
1411    /// # Arguments
1412    ///
1413    /// - `&Self` - Platform reference.
1414    /// - `WindowId` - Window handle.
1415    ///
1416    /// # Returns
1417    ///
1418    /// - `Option<WindowState>` - Window state if open.
1419    fn window_state(&self, id: WindowId) -> Option<WindowState> {
1420        self.get_windows()
1421            .get(&id)
1422            .map(LinuxWindowRecord::get_state)
1423    }
1424
1425    /// Returns `RawWindowHandle::Xlib` or `RawWindowHandle::Wayland` for Vulkan/EGL surface binding.
1426    ///
1427    /// # Arguments
1428    ///
1429    /// - `&Self` - Platform reference.
1430    /// - `WindowId` - Window handle.
1431    ///
1432    /// # Returns
1433    ///
1434    /// - `RawWindowHandle` - Native Linux display/window handle.
1435    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
1436        match self.get_windows().get(&id) {
1437            Some(rec) => {
1438                if rec.get_is_wayland() {
1439                    RawWindowHandle::Wayland {
1440                        surface: rec.get_window() as usize,
1441                        display: rec.get_display(),
1442                    }
1443                } else {
1444                    RawWindowHandle::Xlib {
1445                        window: rec.get_window(),
1446                        display: rec.get_display(),
1447                    }
1448                }
1449            }
1450            None => RawWindowHandle::Headless,
1451        }
1452    }
1453
1454    /// Pumps pending X11 events and drains queued Linux events.
1455    ///
1456    /// # Arguments
1457    ///
1458    /// - `&Self` - Mutable Linux platform.
1459    ///
1460    /// # Returns
1461    ///
1462    /// - `Vec<WindowEvent>` - Pending events.
1463    fn poll_events(&mut self) -> Vec<WindowEvent> {
1464        let Self {
1465            windows,
1466            pending_events,
1467            ..
1468        } = self;
1469        linux_x11_pump_events(windows, pending_events);
1470        take(pending_events)
1471    }
1472
1473    /// Blocks via POSIX `poll(display_fd, wakeup_pipe)` with zero CPU usage until a Wayland/X11 event or wakeup signal arrives.
1474    ///
1475    /// # Returns
1476    ///
1477    /// - `Vec<WindowEvent>` - Events received upon wake.
1478    fn wait_for_events(&mut self) -> Vec<WindowEvent> {
1479        let wake_fd: i32 = self.get_wake_read_fd();
1480        let Self {
1481            windows,
1482            pending_events,
1483            ..
1484        } = self;
1485        if pending_events.is_empty() && !windows.is_empty() {
1486            linux_x11_wait_events(windows, pending_events, wake_fd);
1487        }
1488        take(pending_events)
1489    }
1490
1491    /// Updates Linux background frame-pump pause state.
1492    ///
1493    /// # Arguments
1494    ///
1495    /// - `&Self` - Mutable Linux platform.
1496    /// - `bool` - `true` when paused in background; `false` when active.
1497    fn set_frame_pump_paused(&mut self, paused: bool) {
1498        self.set_pump_paused(paused);
1499    }
1500
1501    /// Returns whether the Linux frame pump is currently paused for background freeze.
1502    ///
1503    /// # Arguments
1504    ///
1505    /// - `&Self` - Platform reference.
1506    ///
1507    /// # Returns
1508    ///
1509    /// - `bool` - `true` when paused in background.
1510    fn is_frame_pump_paused(&self) -> bool {
1511        self.get_pump_paused()
1512    }
1513
1514    /// Presents `framebuffer` to the active Linux window surface via X11 `XCreateImage` + `XPutImage`.
1515    ///
1516    /// # Arguments
1517    ///
1518    /// - `&Self` - Mutable Linux platform.
1519    /// - `WindowId` - Target window handle.
1520    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1521    ///
1522    /// # Returns
1523    ///
1524    /// - `Result<(), PlatformError>` - Presentation status.
1525    fn present_framebuffer(
1526        &mut self,
1527        id: WindowId,
1528        framebuffer: &Framebuffer,
1529    ) -> Result<(), PlatformError> {
1530        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
1531    }
1532
1533    /// Presents `framebuffer` (or only `damage`) onto the active Linux X11 or Wayland window and maps X11 windows after Frame 1.
1534    ///
1535    /// # Arguments
1536    ///
1537    /// - `WindowId` - Target window handle.
1538    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1539    /// - `DamageRegion` - Damaged pixel region updated this frame.
1540    ///
1541    /// # Returns
1542    ///
1543    /// - `Result<(), PlatformError>` - Presentation status.
1544    fn present_framebuffer_region(
1545        &mut self,
1546        id: WindowId,
1547        framebuffer: &Framebuffer,
1548        damage: DamageRegion,
1549    ) -> Result<(), PlatformError> {
1550        let _: LinuxPresentTelemetry =
1551            self.present_framebuffer_with_outcome(id, framebuffer, damage)?;
1552        Ok(())
1553    }
1554
1555    /// Presents `submission` directly to the Linux Wayland/X11 EGL/GLES3 surface without CPU RGBA mirroring.
1556    ///
1557    /// # Arguments
1558    ///
1559    /// - `&Self` - Mutable Linux platform.
1560    /// - `WindowId` - Window handle.
1561    /// - `&GpuFrameSubmission` - Direct-GPU primitive batches and atlas payloads.
1562    ///
1563    /// # Returns
1564    ///
1565    /// - `Result<GpuPresentReceipt, PlatformError>` - Direct GPU presentation receipt or unsupported fallback signal.
1566    fn present_gpu_frame(
1567        &mut self,
1568        id: WindowId,
1569        submission: &GpuFrameSubmission,
1570    ) -> Result<GpuPresentReceipt, PlatformError> {
1571        let has_display: bool = self
1572            .get_windows()
1573            .get(&id)
1574            .ok_or(PlatformError::WindowNotFound(id.get_value()))?
1575            .get_display()
1576            != 0;
1577        if !has_display {
1578            return Ok(GpuPresentReceipt::unsupported());
1579        }
1580        match self.present_direct_gpu_submission(id, submission) {
1581            Ok((_, draw_calls, uploaded_instances)) => Ok(GpuPresentReceipt::new(
1582                true,
1583                draw_calls,
1584                uploaded_instances,
1585                0,
1586                0,
1587                false,
1588            )),
1589            Err(PlatformError::SurfaceError(_)) => Ok(GpuPresentReceipt::unsupported()),
1590            Err(err) => Err(err),
1591        }
1592    }
1593
1594    /// Reads cached clipboard text.
1595    ///
1596    /// # Arguments
1597    ///
1598    /// - `&Self` - Platform reference.
1599    ///
1600    /// # Returns
1601    ///
1602    /// - `Option<String>` - Clipboard contents.
1603    fn read_clipboard(&self) -> Option<String> {
1604        let Self {
1605            clipboard_cache, ..
1606        } = self;
1607        clipboard_cache.clone()
1608    }
1609
1610    /// Writes `text` to clipboard cache.
1611    ///
1612    /// # Arguments
1613    ///
1614    /// - `&Self` - Mutable platform.
1615    /// - `&str` - Clipboard text.
1616    ///
1617    /// # Returns
1618    ///
1619    /// - `Result<(), PlatformError>` - Write status.
1620    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1621        self.set_clipboard_cache(Some(text.to_string()));
1622        let _: bool = write_system_clipboard(text);
1623        Ok(())
1624    }
1625
1626    /// Returns active system theme mode.
1627    ///
1628    /// # Arguments
1629    ///
1630    /// - `&Self` - Platform reference.
1631    ///
1632    /// # Returns
1633    ///
1634    /// - `ThemeMode` - Active appearance mode.
1635    fn system_theme(&self) -> ThemeMode {
1636        ThemeMode::Light
1637    }
1638
1639    /// Queries the native Linux display refresh rate via XRandR or `EUV_REFRESH_RATE_HZ`.
1640    ///
1641    /// # Arguments
1642    ///
1643    /// - `&Self` - Platform reference.
1644    ///
1645    /// # Returns
1646    ///
1647    /// - `f32` - Active display refresh rate in Hertz.
1648    fn display_refresh_rate_hz(&self) -> f32 {
1649        if let Some(wl_milli_hz) = self
1650            .get_windows()
1651            .values()
1652            .find(|rec: &&LinuxWindowRecord| {
1653                rec.get_is_wayland() && rec.get_wayland_output_refresh_milli_hz() >= 24_000
1654            })
1655            .map(LinuxWindowRecord::get_wayland_output_refresh_milli_hz)
1656        {
1657            return ((wl_milli_hz as f32) / 1000.0).max(MIN_REFRESH_RATE_HZ);
1658        }
1659        let (display, window): (*mut c_void, usize) = self
1660            .get_windows()
1661            .values()
1662            .find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland())
1663            .map(|rec: &LinuxWindowRecord| {
1664                (rec.get_display() as *mut c_void, rec.get_window() as usize)
1665            })
1666            .unwrap_or((null_mut(), 0));
1667        linux_display_refresh_rate_hz(display, window)
1668    }
1669}