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 T` - Wayland pool/buffer transport.
125    ///
126    /// # Returns
127    ///
128    /// - `Result<(), PlatformError>` - `Ok(())` when mapped and ready to write.
129    fn ensure_allocated<T>(
130        &mut self,
131        req_width: u32,
132        req_height: u32,
133        req_format: u32,
134        ops: &mut T,
135    ) -> Result<(), PlatformError>
136    where
137        T: 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 T` - 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<T>(
309        &mut self,
310        framebuffer: &Framebuffer,
311        damage: DamageRegion,
312        ops: &mut T,
313    ) -> Result<LinuxPresentTelemetry, PlatformError>
314    where
315        T: 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(|&(x, y, w, h): &(u32, u32, u32, u32)| (x as i32, y as i32, w as i32, h as i32))
406            .collect();
407        if let Err(err) = ops.attach_damage_commit_flush(buffer_handle, &wl_damage) {
408            *failed_frames = failed_frames.saturating_add(1);
409            return Err(err);
410        }
411        slot.has_full_copy = true;
412        slot.mark_busy();
413        *last_committed_slot = chosen_idx as u8;
414        *previous_dirty_rects = dirty_rects;
415        *submitted_frames = submitted_frames.saturating_add(1);
416        Ok(LinuxPresentTelemetry {
417            mode: LinuxPresentationMode::WaylandShmSoftware,
418            outcome: LinuxPresentOutcome::Submitted,
419            cpu_mirror_active: true,
420            upload_bytes,
421            dirty_rect_count: wl_damage.len() as u32,
422            committed_buffer_slot: chosen_idx as u8,
423            submitted_frames: *submitted_frames,
424            skipped_unchanged_frames: *skipped_unchanged_frames,
425            failed_frames: *failed_frames,
426        })
427    }
428}
429
430/// Native `libwayland-client.so.0` protocol marshaling for `WaylandShmCommitOps`.
431impl WaylandShmCommitOps for NativeWaylandShmTransport {
432    /// Allocates a `wl_shm_pool` and `wl_buffer` over `libwayland-client.so.0` and binds `WL_BUFFER_LISTENER`.
433    ///
434    /// # Arguments
435    ///
436    /// - `&Self` - Mutable native Wayland transport.
437    /// - `WaylandShmBufferDescriptor` - Shared-memory FD, geometry, format, and release flag pointer.
438    ///
439    /// # Returns
440    ///
441    /// - `Result<(usize, usize), PlatformError>` - `(wl_shm_pool*, wl_buffer*)` handles on success.
442    fn create_pool_and_buffer(
443        &mut self,
444        desc: WaylandShmBufferDescriptor,
445    ) -> Result<(usize, usize), PlatformError> {
446        let wl: &LinuxWaylandSyms = linux_wayland_syms();
447        if self.get_display() == 0
448            || self.get_surface() == 0
449            || self.get_wl_shm() == 0
450            || wl.proxy_marshal_flags == 0
451            || wl.shm_pool_interface == 0
452            || wl.buffer_interface == 0
453        {
454            return Err(PlatformError::SurfaceError(
455                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
456            ));
457        }
458        // SAFETY: Invokes `wl_proxy_marshal_flags` for `wl_shm.create_pool` and `wl_shm_pool.create_buffer` using exact Wayland C ABI.
459        unsafe {
460            let marshal_pool: unsafe extern "C" fn(
461                *mut c_void,
462                u32,
463                *const c_void,
464                u32,
465                u32,
466                *mut c_void,
467                i32,
468                i32,
469            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
470            let pool: *mut c_void = marshal_pool(
471                self.get_wl_shm() as *mut c_void,
472                WL_OPCODE_SHM_CREATE_POOL,
473                wl.shm_pool_interface as *const c_void,
474                WL_SHM_MAX_VERSION,
475                0,
476                null_mut(),
477                desc.get_fd(),
478                desc.get_size(),
479            );
480            if pool.is_null() {
481                return Err(PlatformError::SurfaceError(
482                    ERR_LINUX_WL_BUFFER_CREATE.to_string(),
483                ));
484            }
485            let marshal_buffer: unsafe extern "C" fn(
486                *mut c_void,
487                u32,
488                *const c_void,
489                u32,
490                u32,
491                *mut c_void,
492                i32,
493                i32,
494                i32,
495                i32,
496                u32,
497            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
498            let buffer: *mut c_void = marshal_buffer(
499                pool,
500                WL_OPCODE_SHM_POOL_CREATE_BUFFER,
501                wl.buffer_interface as *const c_void,
502                WL_SHM_MAX_VERSION,
503                0,
504                null_mut(),
505                0,
506                desc.get_width(),
507                desc.get_height(),
508                desc.get_stride(),
509                desc.get_format(),
510            );
511            if buffer.is_null() {
512                self.destroy_pool_and_buffer(pool as usize, 0);
513                return Err(PlatformError::SurfaceError(
514                    ERR_LINUX_WL_BUFFER_CREATE.to_string(),
515                ));
516            }
517            if wl.proxy_add_listener != 0 && desc.get_release_flag_ptr() != 0 {
518                let add_listener: unsafe extern "C" fn(
519                    *mut c_void,
520                    *const c_void,
521                    *mut c_void,
522                ) -> i32 = transmute(wl.proxy_add_listener as *const c_void);
523                let _: i32 = add_listener(
524                    buffer,
525                    (&raw const WL_BUFFER_LISTENER).cast::<c_void>(),
526                    desc.get_release_flag_ptr() as *mut c_void,
527                );
528            }
529            Ok((pool as usize, buffer as usize))
530        }
531    }
532
533    /// Calls `wl_surface_attach`, `wl_surface_damage_buffer` per dirty rect, `wl_surface_commit`, and `wl_display_flush`.
534    ///
535    /// # Arguments
536    ///
537    /// - `&Self` - Mutable native Wayland transport.
538    /// - `usize` - Live `wl_buffer*` handle.
539    /// - `&[(i32, i32, i32, i32)]` - Buffer-space damage rectangles.
540    ///
541    /// # Returns
542    ///
543    /// - `Result<(), PlatformError>` - `Err` on missing handles, flush failure, or `wl_display_get_error != 0`.
544    fn attach_damage_commit_flush(
545        &mut self,
546        buffer: usize,
547        damage_rects: &[(i32, i32, i32, i32)],
548    ) -> Result<(), PlatformError> {
549        let wl: &LinuxWaylandSyms = linux_wayland_syms();
550        if self.get_display() == 0
551            || self.get_surface() == 0
552            || buffer == 0
553            || wl.proxy_marshal_flags == 0
554            || wl.display_flush == 0
555        {
556            return Err(PlatformError::SurfaceError(
557                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
558            ));
559        }
560        let surface_ver: u32 = self.get_surface_version().max(1);
561        let damage_opcode: u32 = if surface_ver >= WL_COMPOSITOR_MAX_VERSION {
562            WL_OPCODE_SURFACE_DAMAGE_BUFFER
563        } else {
564            WL_OPCODE_SURFACE_DAMAGE
565        };
566        // SAFETY: Marshals `wl_surface.attach`, `wl_surface.damage_buffer`/`damage`, `wl_surface.commit`, and `wl_display_flush`.
567        unsafe {
568            let surface_ptr: *mut c_void = self.get_surface() as *mut c_void;
569            let marshal_attach: unsafe extern "C" fn(
570                *mut c_void,
571                u32,
572                *const c_void,
573                u32,
574                u32,
575                *mut c_void,
576                i32,
577                i32,
578            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
579            let _: *mut c_void = marshal_attach(
580                surface_ptr,
581                WL_OPCODE_SURFACE_ATTACH,
582                null(),
583                surface_ver,
584                0,
585                buffer as *mut c_void,
586                0,
587                0,
588            );
589            let marshal_damage: unsafe extern "C" fn(
590                *mut c_void,
591                u32,
592                *const c_void,
593                u32,
594                u32,
595                i32,
596                i32,
597                i32,
598                i32,
599            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
600            for &(x, y, w, h) in damage_rects.iter() {
601                let _: *mut c_void = marshal_damage(
602                    surface_ptr,
603                    damage_opcode,
604                    null(),
605                    surface_ver,
606                    0,
607                    x,
608                    y,
609                    w,
610                    h,
611                );
612            }
613            let marshal_commit: unsafe extern "C" fn(
614                *mut c_void,
615                u32,
616                *const c_void,
617                u32,
618                u32,
619            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
620            let _: *mut c_void = marshal_commit(
621                surface_ptr,
622                WL_OPCODE_SURFACE_COMMIT,
623                null(),
624                surface_ver,
625                0,
626            );
627            let wl_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
628                transmute(wl.display_flush as *const c_void);
629            let flushed: i32 = wl_flush(self.get_display() as *mut c_void);
630            if flushed < 0 {
631                return Err(PlatformError::SurfaceError(
632                    ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
633                ));
634            }
635            if wl.display_get_error != 0 {
636                let get_err: unsafe extern "C" fn(*mut c_void) -> i32 =
637                    transmute(wl.display_get_error as *const c_void);
638                if get_err(self.get_display() as *mut c_void) != 0 {
639                    return Err(PlatformError::SurfaceError(
640                        ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
641                    ));
642                }
643            }
644        }
645        Ok(())
646    }
647
648    /// Dispatches pending incoming Wayland compositor events such as `wl_buffer.release`.
649    ///
650    /// # Arguments
651    ///
652    /// - `&Self` - Mutable native Wayland transport.
653    ///
654    /// # Returns
655    ///
656    /// - `Result<(), PlatformError>` - `Err` on missing display or protocol error.
657    fn dispatch_pending(&mut self) -> Result<(), PlatformError> {
658        let wl: &LinuxWaylandSyms = linux_wayland_syms();
659        if self.get_display() == 0 || self.get_surface() == 0 || self.get_wl_shm() == 0 {
660            return Err(PlatformError::SurfaceError(
661                ERR_LINUX_WL_SURFACE_MISSING.to_string(),
662            ));
663        }
664        if wl.display_dispatch_pending != 0 {
665            // SAFETY: Non-blocking dispatch of queued Wayland events on a live `wl_display*`.
666            unsafe {
667                let dispatch: unsafe extern "C" fn(*mut c_void) -> i32 =
668                    transmute(wl.display_dispatch_pending as *const c_void);
669                if dispatch(self.get_display() as *mut c_void) < 0 {
670                    return Err(PlatformError::SurfaceError(
671                        ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
672                    ));
673                }
674            }
675        }
676        Ok(())
677    }
678
679    /// Destroys a previously allocated `wl_buffer*` and `wl_shm_pool*` pair cleanly.
680    ///
681    /// # Arguments
682    ///
683    /// - `&Self` - Mutable native Wayland transport.
684    /// - `usize` - `wl_shm_pool*` proxy handle.
685    /// - `usize` - `wl_buffer*` proxy handle.
686    fn destroy_pool_and_buffer(&mut self, pool: usize, buffer: usize) {
687        let wl: &LinuxWaylandSyms = linux_wayland_syms();
688        if wl.proxy_marshal_flags == 0 {
689            return;
690        }
691        // SAFETY: Sends `wl_buffer.destroy` and `wl_shm_pool.destroy` with `WL_MARSHAL_FLAG_DESTROY`.
692        unsafe {
693            let marshal_destroy: unsafe extern "C" fn(
694                *mut c_void,
695                u32,
696                *const c_void,
697                u32,
698                u32,
699            ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
700            if buffer != 0 {
701                let _: *mut c_void = marshal_destroy(
702                    buffer as *mut c_void,
703                    WL_OPCODE_BUFFER_DESTROY,
704                    null(),
705                    WL_SHM_MAX_VERSION,
706                    WL_MARSHAL_FLAG_DESTROY,
707                );
708            }
709            if pool != 0 {
710                let _: *mut c_void = marshal_destroy(
711                    pool as *mut c_void,
712                    WL_OPCODE_SHM_POOL_DESTROY,
713                    null(),
714                    WL_SHM_MAX_VERSION,
715                    WL_MARSHAL_FLAG_DESTROY,
716                );
717            }
718        }
719    }
720}
721
722/// Wayland `wl_shm` swapchain accessors on `LinuxWindowRecord`.
723impl LinuxWindowRecord {
724    /// Returns (initializing on demand) the shared double-buffered `WaylandShmSwapchain` handle for this window.
725    ///
726    /// # Returns
727    ///
728    /// - `Arc<Mutex<WaylandShmSwapchain>>` - Shared Wayland shm swapchain handle.
729    pub(crate) fn wayland_shm_handle(&mut self) -> Arc<Mutex<WaylandShmSwapchain>> {
730        let Self { wayland_shm, .. } = self;
731        Arc::clone(wayland_shm.get_or_insert_with(|| {
732            Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
733                WL_SHM_FORMAT_XRGB8888,
734            )))
735        }))
736    }
737}
738
739/// Default initialization for `LinuxPlatform`.
740impl Default for LinuxPlatform {
741    /// Creates an empty Linux X11 / Wayland platform backend.
742    ///
743    /// # Returns
744    ///
745    /// - `Self` - Initialized Linux backend.
746    fn default() -> Self {
747        Self {
748            next_id: 1,
749            x11_lib: 0,
750            windows: HashMap::new(),
751            pending_events: Vec::new(),
752            clipboard_cache: None,
753            pump_paused: false,
754        }
755    }
756}
757
758/// X11/Wayland system event injection and Wayland VSync/output callbacks for `LinuxPlatform`.
759impl LinuxPlatform {
760    /// Enqueues a normalized Linux `SystemEvent` to be drained on the next `poll_events()` tick.
761    ///
762    /// # Arguments
763    ///
764    /// - `SystemEvent` - System event to enqueue.
765    pub fn push_system_event(&mut self, event: SystemEvent) {
766        self.get_mut_pending_events()
767            .push(WindowEvent::System(event));
768    }
769
770    /// Records a Wayland `wl_output.mode` refresh rate in millihertz (e.g. `240000` -> `240Hz`) for `id`.
771    ///
772    /// # Arguments
773    ///
774    /// - `WindowId` - Target Wayland window identifier.
775    /// - `u32` - Output refresh rate in millihertz.
776    pub fn on_wayland_output_mode(&mut self, id: WindowId, refresh_milli_hz: u32) {
777        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
778            rec.set_wayland_output_refresh_milli_hz(refresh_milli_hz);
779            let hz: f32 = ((refresh_milli_hz as f32) / 1000.0)
780                .clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
781            rec.get_mut_state()
782                .get_mut_display()
783                .set_refresh_rate_hz(hz.round() as u32);
784        }
785    }
786
787    /// Handles a Wayland `wl_surface::frame` done callback and schedules a redraw when active.
788    ///
789    /// # Arguments
790    ///
791    /// - `WindowId` - Target Wayland window identifier.
792    pub fn on_wayland_frame_callback(&mut self, id: WindowId) {
793        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
794            rec.set_wayland_frame_callback_pending(false);
795        }
796        if !self.get_pump_paused() {
797            self.get_mut_pending_events()
798                .push(WindowEvent::RedrawRequested(id));
799        }
800    }
801
802    /// Records a Wayland `wp_presentation` feedback timestamp in nanoseconds for `id`.
803    ///
804    /// # Arguments
805    ///
806    /// - `WindowId` - Target Wayland window identifier.
807    /// - `u64` - Compositor presentation timestamp in nanoseconds.
808    pub fn on_wayland_presentation_feedback(&mut self, id: WindowId, timestamp_ns: u64) {
809        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
810            rec.set_wayland_presentation_time_ns(timestamp_ns);
811        }
812    }
813
814    /// Marks Wayland shm double-buffer slot `slot` (`0` or `1`) as released by the compositor for window `id`.
815    ///
816    /// # Arguments
817    ///
818    /// - `WindowId` - Target Wayland window identifier.
819    /// - `usize` - Released double-buffer slot index (`0` or `1`).
820    pub fn on_wayland_buffer_release(&mut self, id: WindowId, slot: usize) {
821        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
822            let shm_arc: Arc<Mutex<WaylandShmSwapchain>> = rec.wayland_shm_handle();
823            if let Ok(mut guard) = shm_arc.lock() {
824                guard.release_slot(slot);
825            }
826        }
827    }
828
829    /// Returns whether a CPU software framebuffer mirror is currently active on Linux window `id`.
830    ///
831    /// # Arguments
832    ///
833    /// - `WindowId` - Target Linux window identifier.
834    ///
835    /// # Returns
836    ///
837    /// - `bool` - `true` when presenting via Wayland `wl_shm` or X11 software blitting; `false` when direct GPU Vulkan WSI is active.
838    #[must_use]
839    pub fn cpu_mirror_active(&self, id: WindowId) -> bool {
840        self.get_windows()
841            .get(&id)
842            .map(LinuxWindowRecord::get_cpu_mirror_active)
843            .unwrap_or(true)
844    }
845
846    /// Returns the most recent Linux presentation telemetry snapshot for window `id`.
847    ///
848    /// # Arguments
849    ///
850    /// - `WindowId` - Target Linux window identifier.
851    ///
852    /// # Returns
853    ///
854    /// - `Option<LinuxPresentTelemetry>` - Latest presentation telemetry, if the window exists.
855    #[must_use]
856    pub fn last_present_telemetry(&self, id: WindowId) -> Option<LinuxPresentTelemetry> {
857        self.get_windows()
858            .get(&id)
859            .map(LinuxWindowRecord::get_last_telemetry)
860    }
861
862    /// Presents `framebuffer` (or only `damage`) on Linux window `id` and returns explicit `Submitted`/`SkippedUnchanged`/`Failed` telemetry.
863    ///
864    /// # Arguments
865    ///
866    /// - `WindowId` - Target window handle.
867    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
868    /// - `DamageRegion` - Damaged pixel region updated this frame.
869    ///
870    /// # Returns
871    ///
872    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Presentation telemetry on commit or skip; `Err` on failure.
873    pub fn present_framebuffer_with_outcome(
874        &mut self,
875        id: WindowId,
876        framebuffer: &Framebuffer,
877        damage: DamageRegion,
878    ) -> Result<LinuxPresentTelemetry, PlatformError> {
879        let (res, should_map, display, window): (
880            Result<LinuxPresentTelemetry, PlatformError>,
881            bool,
882            usize,
883            u64,
884        ) = {
885            let rec: &mut LinuxWindowRecord = self
886                .get_mut_windows()
887                .get_mut(&id)
888                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
889            let present_res: Result<LinuxPresentTelemetry, PlatformError> =
890                linux_present_window_region(rec, framebuffer, damage);
891            let should_map_x11: bool =
892                !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible();
893            (
894                present_res,
895                should_map_x11,
896                rec.get_display(),
897                rec.get_window(),
898            )
899        };
900        if let Ok(telemetry) = res {
901            if telemetry.get_outcome() == LinuxPresentOutcome::Submitted && should_map {
902                linux_x11_map_window(display, window);
903                if let Some(rec) = self.get_mut_windows().get_mut(&id) {
904                    rec.set_revealed(true);
905                }
906            }
907            Ok(telemetry)
908        } else {
909            res
910        }
911    }
912
913    /// Records a direct Vulkan WSI GPU presentation on Wayland (`VK_KHR_wayland_surface`) or X11 (`VK_KHR_xlib_surface`) with `cpu_mirror_active = false`.
914    ///
915    /// # Arguments
916    ///
917    /// - `WindowId` - Target Linux window handle.
918    ///
919    /// # Returns
920    ///
921    /// - `Result<LinuxPresentTelemetry, PlatformError>` - Direct GPU telemetry (`cpu_mirror_active = false`), or `Err` when WSI is unavailable.
922    pub fn present_gpu_direct_hook(
923        &mut self,
924        id: WindowId,
925    ) -> Result<LinuxPresentTelemetry, PlatformError> {
926        let rec: &mut LinuxWindowRecord = self
927            .get_mut_windows()
928            .get_mut(&id)
929            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
930        let wsi_ready: bool = if rec.get_is_wayland() {
931            rec.get_wayland_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
932        } else {
933            rec.get_xlib_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
934        };
935        let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
936        if !wsi_ready {
937            telemetry.set_mode(LinuxPresentationMode::GpuDirect);
938            telemetry.set_outcome(LinuxPresentOutcome::Failed);
939            telemetry.set_upload_bytes(0);
940            telemetry.set_dirty_rect_count(0);
941            telemetry.set_failed_frames(telemetry.get_failed_frames().saturating_add(1));
942            rec.set_last_telemetry(telemetry);
943            return Err(PlatformError::SurfaceError(
944                ERR_LINUX_GPU_DIRECT_UNAVAILABLE.to_string(),
945            ));
946        }
947        telemetry.set_mode(LinuxPresentationMode::GpuDirect);
948        telemetry.set_outcome(LinuxPresentOutcome::Submitted);
949        telemetry.set_cpu_mirror_active(false);
950        telemetry.set_upload_bytes(0);
951        telemetry.set_dirty_rect_count(0);
952        telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
953        rec.set_presentation_mode(LinuxPresentationMode::GpuDirect);
954        rec.set_cpu_mirror_active(false);
955        rec.set_last_telemetry(telemetry);
956        Ok(telemetry)
957    }
958}
959
960/// `WindowController` implementation for Linux X11 / Wayland.
961impl WindowController for LinuxPlatform {
962    /// Applies a `WindowCommand` onto the native X11 or Wayland window.
963    ///
964    /// # Arguments
965    ///
966    /// - `WindowCommand` - Command to apply.
967    ///
968    /// # Returns
969    ///
970    /// - `Result<(), PlatformError>` - Execution status.
971    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
972        match command {
973            WindowCommand::SetTitle(id, title) => {
974                let rec: &mut LinuxWindowRecord = self
975                    .get_mut_windows()
976                    .get_mut(&id)
977                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
978                if !rec.get_is_wayland() {
979                    linux_x11_set_title(rec.get_display(), rec.get_window(), &title);
980                }
981                rec.get_mut_config().set_title(title);
982                Ok(())
983            }
984            WindowCommand::SetSize(id, width, height) => {
985                let rec: &mut LinuxWindowRecord = self
986                    .get_mut_windows()
987                    .get_mut(&id)
988                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
989                let w: u32 = width.max(1);
990                let h: u32 = height.max(1);
991                if !rec.get_is_wayland() {
992                    linux_x11_resize(rec.get_display(), rec.get_window(), w, h);
993                }
994                let scale: f32 = rec.get_state().get_scale_factor();
995                rec.get_mut_config().set_width(w);
996                rec.get_mut_config().set_height(h);
997                rec.get_mut_state().set_logical_width(w as f32);
998                rec.get_mut_state().set_logical_height(h as f32);
999                rec.get_mut_state()
1000                    .set_physical_width(((w as f32) * scale).round() as u32);
1001                rec.get_mut_state()
1002                    .set_physical_height(((h as f32) * scale).round() as u32);
1003                Ok(())
1004            }
1005            WindowCommand::Close(id) => {
1006                let rec: LinuxWindowRecord = self
1007                    .get_mut_windows()
1008                    .remove(&id)
1009                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1010                if rec.get_is_wayland() {
1011                    linux_wayland_disconnect(rec.get_display());
1012                } else {
1013                    linux_x11_destroy(rec.get_display(), rec.get_window());
1014                }
1015                Ok(())
1016            }
1017            WindowCommand::SetRenderMode(id, mode) => {
1018                let rec: &mut LinuxWindowRecord = self
1019                    .get_mut_windows()
1020                    .get_mut(&id)
1021                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1022                rec.get_mut_config().get_mut_render().set_mode(mode);
1023                Ok(())
1024            }
1025            WindowCommand::RequestRedraw(id) => {
1026                if !self.get_windows().contains_key(&id) {
1027                    return Err(PlatformError::WindowNotFound(id.get_value()));
1028                }
1029                self.get_mut_pending_events()
1030                    .push(WindowEvent::RedrawRequested(id));
1031                Ok(())
1032            }
1033            WindowCommand::SetFullscreen(id, mode) => {
1034                let rec: &mut LinuxWindowRecord = self
1035                    .get_mut_windows()
1036                    .get_mut(&id)
1037                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1038                rec.get_mut_config().set_fullscreen(mode);
1039                rec.get_mut_state().set_fullscreen(mode);
1040                Ok(())
1041            }
1042            WindowCommand::SetPosition(id, _, _)
1043            | WindowCommand::SetResizable(id, _)
1044            | WindowCommand::SetDecorations(id, _)
1045            | WindowCommand::SetAlwaysOnTop(id, _)
1046            | WindowCommand::SetVisible(id, _)
1047            | WindowCommand::SetCursor(id, _)
1048            | WindowCommand::SetIme(id, _, _)
1049            | WindowCommand::SetStatusBarStyle(id, _) => {
1050                if !self.get_windows().contains_key(&id) {
1051                    return Err(PlatformError::WindowNotFound(id.get_value()));
1052                }
1053                Ok(())
1054            }
1055        }
1056    }
1057}
1058
1059/// `PlatformBackend` implementation for native Linux.
1060impl PlatformBackend for LinuxPlatform {
1061    /// Returns `PlatformKind::Linux`.
1062    ///
1063    /// # Arguments
1064    ///
1065    /// - `&Self` - Platform reference.
1066    ///
1067    /// # Returns
1068    ///
1069    /// - `PlatformKind` - `PlatformKind::Linux`.
1070    fn kind(&self) -> PlatformKind {
1071        PlatformKind::Linux
1072    }
1073
1074    /// Returns Linux desktop capabilities.
1075    ///
1076    /// # Arguments
1077    ///
1078    /// - `&Self` - Platform reference.
1079    ///
1080    /// # Returns
1081    ///
1082    /// - `PlatformCapabilities` - Linux capability flags.
1083    fn capabilities(&self) -> PlatformCapabilities {
1084        PlatformCapabilities::for_platform(PlatformKind::Linux)
1085    }
1086
1087    /// Opens an X11 or Wayland window via dynamic `dlopen`.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&Self` - Mutable Linux platform.
1092    /// - `&WindowConfig` - Declarative window config.
1093    ///
1094    /// # Returns
1095    ///
1096    /// - `Result<WindowState, PlatformError>` - Initial window state.
1097    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1098        let native: LinuxNativeWindowHandle = linux_create_native_window(config)?;
1099        if !native.get_is_wayland() {
1100            self.set_x11_lib(native.get_lib());
1101        }
1102        let id: WindowId = WindowId::new(self.get_next_id());
1103        self.set_next_id(self.get_next_id().wrapping_add(1));
1104        let mut state: WindowState =
1105            WindowState::from_config(id, config, native.get_scale_factor());
1106        let hz: f32 = if native.get_is_wayland() {
1107            linux_display_refresh_rate_hz(null_mut(), 0)
1108        } else {
1109            linux_display_refresh_rate_hz(
1110                native.get_display() as *mut c_void,
1111                native.get_window() as usize,
1112            )
1113        };
1114        state
1115            .get_mut_display()
1116            .set_refresh_rate_hz(hz.round() as u32);
1117        let initial_mode: LinuxPresentationMode = if native.get_is_wayland() {
1118            if native.get_wayland_vulkan_wsi()
1119                && config.get_render().get_mode() != RenderMode::Software
1120            {
1121                LinuxPresentationMode::GpuDirect
1122            } else {
1123                LinuxPresentationMode::WaylandShmSoftware
1124            }
1125        } else if native.get_xlib_vulkan_wsi()
1126            && config.get_render().get_mode() != RenderMode::Software
1127        {
1128            LinuxPresentationMode::GpuDirect
1129        } else {
1130            LinuxPresentationMode::X11Software
1131        };
1132        let initial_cpu_mirror: bool = initial_mode != LinuxPresentationMode::GpuDirect;
1133        self.get_mut_windows().insert(
1134            id,
1135            LinuxWindowRecord {
1136                config: config.clone(),
1137                state,
1138                is_wayland: native.get_is_wayland(),
1139                display: native.get_display(),
1140                window: native.get_window(),
1141                gc: native.get_gc(),
1142                visual: native.get_visual(),
1143                depth: native.get_depth(),
1144                wm_delete_atom: native.get_wm_delete_atom(),
1145                revealed: native.get_is_wayland(),
1146                mit_shm_available: native.get_mit_shm_available(),
1147                wayland_vulkan_wsi: native.get_wayland_vulkan_wsi(),
1148                xlib_vulkan_wsi: native.get_xlib_vulkan_wsi(),
1149                wl_compositor: native.get_wl_compositor(),
1150                wl_shm: native.get_wl_shm(),
1151                wl_surface_version: native.get_wl_surface_version(),
1152                wayland_output_refresh_milli_hz: 0,
1153                wayland_presentation_time_ns: 0,
1154                wayland_frame_callback_pending: false,
1155                presentation_mode: initial_mode,
1156                cpu_mirror_active: initial_cpu_mirror,
1157                last_telemetry: LinuxPresentTelemetry {
1158                    mode: initial_mode,
1159                    outcome: LinuxPresentOutcome::SkippedUnchanged,
1160                    cpu_mirror_active: initial_cpu_mirror,
1161                    upload_bytes: 0,
1162                    dirty_rect_count: 0,
1163                    committed_buffer_slot: 0,
1164                    submitted_frames: 0,
1165                    skipped_unchanged_frames: 0,
1166                    failed_frames: 0,
1167                },
1168                wayland_shm: if native.get_is_wayland() {
1169                    Some(Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
1170                        WL_SHM_FORMAT_XRGB8888,
1171                    ))))
1172                } else {
1173                    None
1174                },
1175            },
1176        );
1177        Ok(state)
1178    }
1179
1180    /// Queries live `WindowState` for `id`.
1181    ///
1182    /// # Arguments
1183    ///
1184    /// - `&Self` - Platform reference.
1185    /// - `WindowId` - Window handle.
1186    ///
1187    /// # Returns
1188    ///
1189    /// - `Option<WindowState>` - Window state if open.
1190    fn window_state(&self, id: WindowId) -> Option<WindowState> {
1191        self.get_windows()
1192            .get(&id)
1193            .map(LinuxWindowRecord::get_state)
1194    }
1195
1196    /// Returns `RawWindowHandle::Xlib` or `RawWindowHandle::Wayland` for Vulkan/EGL surface binding.
1197    ///
1198    /// # Arguments
1199    ///
1200    /// - `&Self` - Platform reference.
1201    /// - `WindowId` - Window handle.
1202    ///
1203    /// # Returns
1204    ///
1205    /// - `RawWindowHandle` - Native Linux display/window handle.
1206    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
1207        match self.get_windows().get(&id) {
1208            Some(rec) => {
1209                if rec.get_is_wayland() {
1210                    RawWindowHandle::Wayland {
1211                        surface: rec.get_window() as usize,
1212                        display: rec.get_display(),
1213                    }
1214                } else {
1215                    RawWindowHandle::Xlib {
1216                        window: rec.get_window(),
1217                        display: rec.get_display(),
1218                    }
1219                }
1220            }
1221            None => RawWindowHandle::Headless,
1222        }
1223    }
1224
1225    /// Pumps pending X11 events and drains queued Linux events.
1226    ///
1227    /// # Arguments
1228    ///
1229    /// - `&Self` - Mutable Linux platform.
1230    ///
1231    /// # Returns
1232    ///
1233    /// - `Vec<WindowEvent>` - Pending events.
1234    fn poll_events(&mut self) -> Vec<WindowEvent> {
1235        let Self {
1236            windows,
1237            pending_events,
1238            ..
1239        } = self;
1240        linux_x11_pump_events(windows, pending_events);
1241        take(pending_events)
1242    }
1243
1244    /// Blocks on Wayland `wl_display_dispatch` or X11 `XNextEvent` with zero CPU usage until an OS event wakes the connection.
1245    ///
1246    /// # Returns
1247    ///
1248    /// - `Vec<WindowEvent>` - Events received upon wake.
1249    fn wait_for_events(&mut self) -> Vec<WindowEvent> {
1250        let Self {
1251            windows,
1252            pending_events,
1253            ..
1254        } = self;
1255        if pending_events.is_empty() && !windows.is_empty() {
1256            linux_x11_wait_events(windows, pending_events);
1257        }
1258        take(pending_events)
1259    }
1260
1261    /// Updates Linux background frame-pump pause state.
1262    ///
1263    /// # Arguments
1264    ///
1265    /// - `&Self` - Mutable Linux platform.
1266    /// - `bool` - `true` when paused in background; `false` when active.
1267    fn set_frame_pump_paused(&mut self, paused: bool) {
1268        self.set_pump_paused(paused);
1269    }
1270
1271    /// Returns whether the Linux frame pump is currently paused for background freeze.
1272    ///
1273    /// # Arguments
1274    ///
1275    /// - `&Self` - Platform reference.
1276    ///
1277    /// # Returns
1278    ///
1279    /// - `bool` - `true` when paused in background.
1280    fn is_frame_pump_paused(&self) -> bool {
1281        self.get_pump_paused()
1282    }
1283
1284    /// Presents `framebuffer` to the active Linux window surface via X11 `XCreateImage` + `XPutImage`.
1285    ///
1286    /// # Arguments
1287    ///
1288    /// - `&Self` - Mutable Linux platform.
1289    /// - `WindowId` - Target window handle.
1290    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1291    ///
1292    /// # Returns
1293    ///
1294    /// - `Result<(), PlatformError>` - Presentation status.
1295    fn present_framebuffer(
1296        &mut self,
1297        id: WindowId,
1298        framebuffer: &Framebuffer,
1299    ) -> Result<(), PlatformError> {
1300        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
1301    }
1302
1303    /// Presents `framebuffer` (or only `damage`) onto the active Linux X11 or Wayland window and maps X11 windows after Frame 1.
1304    ///
1305    /// # Arguments
1306    ///
1307    /// - `WindowId` - Target window handle.
1308    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1309    /// - `DamageRegion` - Damaged pixel region updated this frame.
1310    ///
1311    /// # Returns
1312    ///
1313    /// - `Result<(), PlatformError>` - Presentation status.
1314    fn present_framebuffer_region(
1315        &mut self,
1316        id: WindowId,
1317        framebuffer: &Framebuffer,
1318        damage: DamageRegion,
1319    ) -> Result<(), PlatformError> {
1320        let _: LinuxPresentTelemetry =
1321            self.present_framebuffer_with_outcome(id, framebuffer, damage)?;
1322        Ok(())
1323    }
1324
1325    /// Reads cached clipboard text.
1326    ///
1327    /// # Arguments
1328    ///
1329    /// - `&Self` - Platform reference.
1330    ///
1331    /// # Returns
1332    ///
1333    /// - `Option<String>` - Clipboard contents.
1334    fn read_clipboard(&self) -> Option<String> {
1335        let Self {
1336            clipboard_cache, ..
1337        } = self;
1338        clipboard_cache.clone()
1339    }
1340
1341    /// Writes `text` to clipboard cache.
1342    ///
1343    /// # Arguments
1344    ///
1345    /// - `&Self` - Mutable platform.
1346    /// - `&str` - Clipboard text.
1347    ///
1348    /// # Returns
1349    ///
1350    /// - `Result<(), PlatformError>` - Write status.
1351    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1352        self.set_clipboard_cache(Some(text.to_string()));
1353        let _: bool = write_system_clipboard(text);
1354        Ok(())
1355    }
1356
1357    /// Returns active system theme mode.
1358    ///
1359    /// # Arguments
1360    ///
1361    /// - `&Self` - Platform reference.
1362    ///
1363    /// # Returns
1364    ///
1365    /// - `ThemeMode` - Active appearance mode.
1366    fn system_theme(&self) -> ThemeMode {
1367        ThemeMode::Light
1368    }
1369
1370    /// Queries the native Linux display refresh rate via XRandR or `EUV_REFRESH_RATE_HZ`.
1371    ///
1372    /// # Arguments
1373    ///
1374    /// - `&Self` - Platform reference.
1375    ///
1376    /// # Returns
1377    ///
1378    /// - `f32` - Active display refresh rate in Hertz.
1379    fn display_refresh_rate_hz(&self) -> f32 {
1380        if let Some(wl_milli_hz) = self
1381            .get_windows()
1382            .values()
1383            .find(|rec: &&LinuxWindowRecord| {
1384                rec.get_is_wayland() && rec.get_wayland_output_refresh_milli_hz() >= 24_000
1385            })
1386            .map(LinuxWindowRecord::get_wayland_output_refresh_milli_hz)
1387        {
1388            return ((wl_milli_hz as f32) / 1000.0).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
1389        }
1390        let (display, window): (*mut c_void, usize) = self
1391            .get_windows()
1392            .values()
1393            .find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland())
1394            .map(|rec: &LinuxWindowRecord| {
1395                (rec.get_display() as *mut c_void, rec.get_window() as usize)
1396            })
1397            .unwrap_or((null_mut(), 0));
1398        linux_display_refresh_rate_hz(display, window)
1399    }
1400}