1use super::*;
2
3impl Default for WaylandShmBufferSlot {
5 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
27impl Drop for WaylandShmBufferSlot {
29 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
44impl WaylandShmBufferSlot {
46 #[must_use]
52 pub fn is_busy(&self) -> bool {
53 let Self { busy, .. } = self;
54 busy.load(Ordering::Acquire)
55 }
56
57 pub fn mark_busy(&mut self) {
59 let Self { busy, .. } = self;
60 busy.store(true, Ordering::Release);
61 }
62
63 pub fn release(&mut self) {
65 let Self { busy, .. } = self;
66 busy.store(false, Ordering::Release);
67 }
68
69 #[must_use]
75 pub fn release_flag_ptr(&self) -> usize {
76 let Self { busy, .. } = self;
77 (&raw const **busy) as usize
78 }
79
80 #[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 Some(unsafe { from_raw_parts(*mapped_ptr as *const u8, *mapped_len) })
97 }
98
99 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 Some(unsafe { from_raw_parts_mut(*mapped_ptr as *mut u8, *mapped_len) })
115 }
116
117 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
213impl Default for WaylandShmSwapchain {
215 fn default() -> Self {
221 Self::with_format(WL_SHM_FORMAT_XRGB8888)
222 }
223}
224
225impl WaylandShmSwapchain {
227 #[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 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 #[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 #[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 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, ©_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
439impl WaylandShmCommitOps for NativeWaylandShmTransport {
441 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 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 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 damage_opcode: u32 = if surface_ver >= WL_COMPOSITOR_MAX_VERSION {
571 WL_OPCODE_SURFACE_DAMAGE_BUFFER
572 } else {
573 WL_OPCODE_SURFACE_DAMAGE
574 };
575 unsafe {
577 let surface_ptr: *mut c_void = self.get_surface() as *mut c_void;
578 let marshal_attach: unsafe extern "C" fn(
579 *mut c_void,
580 u32,
581 *const c_void,
582 u32,
583 u32,
584 *mut c_void,
585 i32,
586 i32,
587 ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
588 let _: *mut c_void = marshal_attach(
589 surface_ptr,
590 WL_OPCODE_SURFACE_ATTACH,
591 null(),
592 surface_ver,
593 0,
594 buffer as *mut c_void,
595 0,
596 0,
597 );
598 let marshal_damage: unsafe extern "C" fn(
599 *mut c_void,
600 u32,
601 *const c_void,
602 u32,
603 u32,
604 i32,
605 i32,
606 i32,
607 i32,
608 ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
609 for &(pos_x, pos_y, width_val, height_val) in damage_rects.iter() {
610 let _: *mut c_void = marshal_damage(
611 surface_ptr,
612 damage_opcode,
613 null(),
614 surface_ver,
615 0,
616 pos_x,
617 pos_y,
618 width_val,
619 height_val,
620 );
621 }
622 let marshal_commit: unsafe extern "C" fn(
623 *mut c_void,
624 u32,
625 *const c_void,
626 u32,
627 u32,
628 ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
629 let _: *mut c_void = marshal_commit(
630 surface_ptr,
631 WL_OPCODE_SURFACE_COMMIT,
632 null(),
633 surface_ver,
634 0,
635 );
636 let wl_flush: unsafe extern "C" fn(*mut c_void) -> i32 =
637 transmute(wl.display_flush as *const c_void);
638 let flushed: i32 = wl_flush(self.get_display() as *mut c_void);
639 if flushed < 0 {
640 return Err(PlatformError::SurfaceError(
641 ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
642 ));
643 }
644 if wl.display_get_error != 0 {
645 let get_err: unsafe extern "C" fn(*mut c_void) -> i32 =
646 transmute(wl.display_get_error as *const c_void);
647 if get_err(self.get_display() as *mut c_void) != 0 {
648 return Err(PlatformError::SurfaceError(
649 ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
650 ));
651 }
652 }
653 }
654 Ok(())
655 }
656
657 fn dispatch_pending(&mut self) -> Result<(), PlatformError> {
667 let wl: &LinuxWaylandSyms = linux_wayland_syms();
668 if self.get_display() == 0 || self.get_surface() == 0 || self.get_wl_shm() == 0 {
669 return Err(PlatformError::SurfaceError(
670 ERR_LINUX_WL_SURFACE_MISSING.to_string(),
671 ));
672 }
673 if wl.display_dispatch_pending != 0 {
674 unsafe {
676 let dispatch: unsafe extern "C" fn(*mut c_void) -> i32 =
677 transmute(wl.display_dispatch_pending as *const c_void);
678 if dispatch(self.get_display() as *mut c_void) < 0 {
679 return Err(PlatformError::SurfaceError(
680 ERR_LINUX_WL_DISPLAY_FLUSH.to_string(),
681 ));
682 }
683 }
684 }
685 Ok(())
686 }
687
688 fn destroy_pool_and_buffer(&mut self, pool: usize, buffer: usize) {
696 let wl: &LinuxWaylandSyms = linux_wayland_syms();
697 if wl.proxy_marshal_flags == 0 {
698 return;
699 }
700 unsafe {
702 let marshal_destroy: unsafe extern "C" fn(
703 *mut c_void,
704 u32,
705 *const c_void,
706 u32,
707 u32,
708 ) -> *mut c_void = transmute(wl.proxy_marshal_flags as *const c_void);
709 if buffer != 0 {
710 let _: *mut c_void = marshal_destroy(
711 buffer as *mut c_void,
712 WL_OPCODE_BUFFER_DESTROY,
713 null(),
714 WL_SHM_MAX_VERSION,
715 WL_MARSHAL_FLAG_DESTROY,
716 );
717 }
718 if pool != 0 {
719 let _: *mut c_void = marshal_destroy(
720 pool as *mut c_void,
721 WL_OPCODE_SHM_POOL_DESTROY,
722 null(),
723 WL_SHM_MAX_VERSION,
724 WL_MARSHAL_FLAG_DESTROY,
725 );
726 }
727 }
728 }
729}
730
731impl LinuxWindowRecord {
733 pub(crate) fn wayland_shm_handle(&mut self) -> Arc<Mutex<WaylandShmSwapchain>> {
739 let Self { wayland_shm, .. } = self;
740 Arc::clone(wayland_shm.get_or_insert_with(|| {
741 Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
742 WL_SHM_FORMAT_XRGB8888,
743 )))
744 }))
745 }
746}
747
748impl Default for LinuxPlatform {
750 fn default() -> Self {
756 Self {
757 next_id: 1,
758 x11_lib: 0,
759 windows: HashMap::new(),
760 pending_events: Vec::new(),
761 clipboard_cache: None,
762 pump_paused: false,
763 }
764 }
765}
766
767impl LinuxPlatform {
769 pub fn push_system_event(&mut self, event: SystemEvent) {
775 self.get_mut_pending_events()
776 .push(WindowEvent::System(event));
777 }
778
779 pub fn on_wayland_output_mode(&mut self, id: WindowId, refresh_milli_hz: u32) {
786 if let Some(rec) = self.get_mut_windows().get_mut(&id) {
787 rec.set_wayland_output_refresh_milli_hz(refresh_milli_hz);
788 let hz: f32 = ((refresh_milli_hz as f32) / 1000.0)
789 .clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
790 rec.get_mut_state()
791 .get_mut_display()
792 .set_refresh_rate_hz(hz.round() as u32);
793 }
794 }
795
796 pub fn on_wayland_frame_callback(&mut self, id: WindowId) {
802 if let Some(rec) = self.get_mut_windows().get_mut(&id) {
803 rec.set_wayland_frame_callback_pending(false);
804 }
805 if !self.get_pump_paused() {
806 self.get_mut_pending_events()
807 .push(WindowEvent::RedrawRequested(id));
808 }
809 }
810
811 pub fn on_wayland_presentation_feedback(&mut self, id: WindowId, timestamp_ns: u64) {
818 if let Some(rec) = self.get_mut_windows().get_mut(&id) {
819 rec.set_wayland_presentation_time_ns(timestamp_ns);
820 }
821 }
822
823 pub fn on_wayland_buffer_release(&mut self, id: WindowId, slot: usize) {
830 if let Some(rec) = self.get_mut_windows().get_mut(&id) {
831 let shm_arc: Arc<Mutex<WaylandShmSwapchain>> = rec.wayland_shm_handle();
832 if let Ok(mut guard) = shm_arc.lock() {
833 guard.release_slot(slot);
834 }
835 }
836 }
837
838 #[must_use]
848 pub fn cpu_mirror_active(&self, id: WindowId) -> bool {
849 self.get_windows()
850 .get(&id)
851 .map(LinuxWindowRecord::get_cpu_mirror_active)
852 .unwrap_or(true)
853 }
854
855 #[must_use]
865 pub fn last_present_telemetry(&self, id: WindowId) -> Option<LinuxPresentTelemetry> {
866 self.get_windows()
867 .get(&id)
868 .map(LinuxWindowRecord::get_last_telemetry)
869 }
870
871 pub fn present_framebuffer_with_outcome(
883 &mut self,
884 id: WindowId,
885 framebuffer: &Framebuffer,
886 damage: DamageRegion,
887 ) -> Result<LinuxPresentTelemetry, PlatformError> {
888 let (res, should_map, display, window): (
889 Result<LinuxPresentTelemetry, PlatformError>,
890 bool,
891 usize,
892 u64,
893 ) = {
894 let rec: &mut LinuxWindowRecord = self
895 .get_mut_windows()
896 .get_mut(&id)
897 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
898 let present_res: Result<LinuxPresentTelemetry, PlatformError> =
899 linux_present_window_region(rec, framebuffer, damage);
900 let should_map_x11: bool =
901 !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible();
902 (
903 present_res,
904 should_map_x11,
905 rec.get_display(),
906 rec.get_window(),
907 )
908 };
909 if let Ok(telemetry) = res {
910 if telemetry.get_outcome() == LinuxPresentOutcome::Submitted && should_map {
911 linux_x11_map_window(display, window);
912 if let Some(rec) = self.get_mut_windows().get_mut(&id) {
913 rec.set_revealed(true);
914 }
915 }
916 Ok(telemetry)
917 } else {
918 res
919 }
920 }
921
922 pub fn present_gpu_direct_hook(
932 &mut self,
933 id: WindowId,
934 ) -> Result<LinuxPresentTelemetry, PlatformError> {
935 let rec: &mut LinuxWindowRecord = self
936 .get_mut_windows()
937 .get_mut(&id)
938 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
939 let wsi_ready: bool = if rec.get_is_wayland() {
940 rec.get_wayland_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
941 } else {
942 rec.get_xlib_vulkan_wsi() && rec.get_display() != 0 && rec.get_window() != 0
943 };
944 let mut telemetry: LinuxPresentTelemetry = rec.get_last_telemetry();
945 if !wsi_ready {
946 telemetry.set_mode(LinuxPresentationMode::GpuDirect);
947 telemetry.set_outcome(LinuxPresentOutcome::Failed);
948 telemetry.set_upload_bytes(0);
949 telemetry.set_dirty_rect_count(0);
950 telemetry.set_failed_frames(telemetry.get_failed_frames().saturating_add(1));
951 rec.set_last_telemetry(telemetry);
952 return Err(PlatformError::SurfaceError(
953 ERR_LINUX_GPU_DIRECT_UNAVAILABLE.to_string(),
954 ));
955 }
956 telemetry.set_mode(LinuxPresentationMode::GpuDirect);
957 telemetry.set_outcome(LinuxPresentOutcome::Submitted);
958 telemetry.set_cpu_mirror_active(false);
959 telemetry.set_upload_bytes(0);
960 telemetry.set_dirty_rect_count(0);
961 telemetry.set_submitted_frames(telemetry.get_submitted_frames().saturating_add(1));
962 rec.set_presentation_mode(LinuxPresentationMode::GpuDirect);
963 rec.set_cpu_mirror_active(false);
964 rec.set_last_telemetry(telemetry);
965 Ok(telemetry)
966 }
967}
968
969impl WindowController for LinuxPlatform {
971 fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
981 match command {
982 WindowCommand::SetTitle(id, title) => {
983 let rec: &mut LinuxWindowRecord = self
984 .get_mut_windows()
985 .get_mut(&id)
986 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
987 if !rec.get_is_wayland() {
988 linux_x11_set_title(rec.get_display(), rec.get_window(), &title);
989 }
990 rec.get_mut_config().set_title(title);
991 Ok(())
992 }
993 WindowCommand::SetSize(id, width, height) => {
994 let rec: &mut LinuxWindowRecord = self
995 .get_mut_windows()
996 .get_mut(&id)
997 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
998 let width_val: u32 = width.max(1);
999 let height_val: u32 = height.max(1);
1000 if !rec.get_is_wayland() {
1001 linux_x11_resize(rec.get_display(), rec.get_window(), width_val, height_val);
1002 }
1003 let scale: f32 = rec.get_state().get_scale_factor();
1004 rec.get_mut_config().set_width(width_val);
1005 rec.get_mut_config().set_height(height_val);
1006 rec.get_mut_state().set_logical_width(width_val as f32);
1007 rec.get_mut_state().set_logical_height(height_val as f32);
1008 rec.get_mut_state()
1009 .set_physical_width(((width_val as f32) * scale).round() as u32);
1010 rec.get_mut_state()
1011 .set_physical_height(((height_val as f32) * scale).round() as u32);
1012 Ok(())
1013 }
1014 WindowCommand::Close(id) => {
1015 let rec: LinuxWindowRecord = self
1016 .get_mut_windows()
1017 .remove(&id)
1018 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1019 if rec.get_is_wayland() {
1020 linux_wayland_disconnect(rec.get_display());
1021 } else {
1022 linux_x11_destroy(rec.get_display(), rec.get_window());
1023 }
1024 Ok(())
1025 }
1026 WindowCommand::SetRenderMode(id, mode) => {
1027 let rec: &mut LinuxWindowRecord = self
1028 .get_mut_windows()
1029 .get_mut(&id)
1030 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1031 rec.get_mut_config().get_mut_render().set_mode(mode);
1032 Ok(())
1033 }
1034 WindowCommand::RequestRedraw(id) => {
1035 if !self.get_windows().contains_key(&id) {
1036 return Err(PlatformError::WindowNotFound(id.get_value()));
1037 }
1038 self.get_mut_pending_events()
1039 .push(WindowEvent::RedrawRequested(id));
1040 Ok(())
1041 }
1042 WindowCommand::SetFullscreen(id, mode) => {
1043 let rec: &mut LinuxWindowRecord = self
1044 .get_mut_windows()
1045 .get_mut(&id)
1046 .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1047 rec.get_mut_config().set_fullscreen(mode);
1048 rec.get_mut_state().set_fullscreen(mode);
1049 Ok(())
1050 }
1051 WindowCommand::SetPosition(id, _, _)
1052 | WindowCommand::SetResizable(id, _)
1053 | WindowCommand::SetDecorations(id, _)
1054 | WindowCommand::SetAlwaysOnTop(id, _)
1055 | WindowCommand::SetVisible(id, _)
1056 | WindowCommand::SetCursor(id, _)
1057 | WindowCommand::SetIme(id, _, _)
1058 | WindowCommand::SetStatusBarStyle(id, _) => {
1059 if !self.get_windows().contains_key(&id) {
1060 return Err(PlatformError::WindowNotFound(id.get_value()));
1061 }
1062 Ok(())
1063 }
1064 }
1065 }
1066}
1067
1068impl PlatformBackend for LinuxPlatform {
1070 fn kind(&self) -> PlatformKind {
1080 PlatformKind::Linux
1081 }
1082
1083 fn capabilities(&self) -> PlatformCapabilities {
1093 PlatformCapabilities::for_platform(PlatformKind::Linux)
1094 }
1095
1096 fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1107 let native: LinuxNativeWindowHandle = linux_create_native_window(config)?;
1108 if !native.get_is_wayland() {
1109 self.set_x11_lib(native.get_lib());
1110 }
1111 let id: WindowId = WindowId::new(self.get_next_id());
1112 self.set_next_id(self.get_next_id().wrapping_add(1));
1113 let mut state: WindowState =
1114 WindowState::from_config(id, config, native.get_scale_factor());
1115 let hz: f32 = if native.get_is_wayland() {
1116 linux_display_refresh_rate_hz(null_mut(), 0)
1117 } else {
1118 linux_display_refresh_rate_hz(
1119 native.get_display() as *mut c_void,
1120 native.get_window() as usize,
1121 )
1122 };
1123 state
1124 .get_mut_display()
1125 .set_refresh_rate_hz(hz.round() as u32);
1126 let initial_mode: LinuxPresentationMode = if native.get_is_wayland() {
1127 if native.get_wayland_vulkan_wsi()
1128 && config.get_render().get_mode() != RenderMode::Software
1129 {
1130 LinuxPresentationMode::GpuDirect
1131 } else {
1132 LinuxPresentationMode::WaylandShmSoftware
1133 }
1134 } else if native.get_xlib_vulkan_wsi()
1135 && config.get_render().get_mode() != RenderMode::Software
1136 {
1137 LinuxPresentationMode::GpuDirect
1138 } else {
1139 LinuxPresentationMode::X11Software
1140 };
1141 let initial_cpu_mirror: bool = initial_mode != LinuxPresentationMode::GpuDirect;
1142 self.get_mut_windows().insert(
1143 id,
1144 LinuxWindowRecord {
1145 config: config.clone(),
1146 state,
1147 is_wayland: native.get_is_wayland(),
1148 display: native.get_display(),
1149 window: native.get_window(),
1150 gc: native.get_gc(),
1151 visual: native.get_visual(),
1152 depth: native.get_depth(),
1153 wm_delete_atom: native.get_wm_delete_atom(),
1154 revealed: native.get_is_wayland(),
1155 mit_shm_available: native.get_mit_shm_available(),
1156 wayland_vulkan_wsi: native.get_wayland_vulkan_wsi(),
1157 xlib_vulkan_wsi: native.get_xlib_vulkan_wsi(),
1158 wl_compositor: native.get_wl_compositor(),
1159 wl_shm: native.get_wl_shm(),
1160 wl_surface_version: native.get_wl_surface_version(),
1161 wayland_output_refresh_milli_hz: 0,
1162 wayland_presentation_time_ns: 0,
1163 wayland_frame_callback_pending: false,
1164 presentation_mode: initial_mode,
1165 cpu_mirror_active: initial_cpu_mirror,
1166 last_telemetry: LinuxPresentTelemetry {
1167 mode: initial_mode,
1168 outcome: LinuxPresentOutcome::SkippedUnchanged,
1169 cpu_mirror_active: initial_cpu_mirror,
1170 upload_bytes: 0,
1171 dirty_rect_count: 0,
1172 committed_buffer_slot: 0,
1173 submitted_frames: 0,
1174 skipped_unchanged_frames: 0,
1175 failed_frames: 0,
1176 },
1177 wayland_shm: if native.get_is_wayland() {
1178 Some(Arc::new(Mutex::new(WaylandShmSwapchain::with_format(
1179 WL_SHM_FORMAT_XRGB8888,
1180 ))))
1181 } else {
1182 None
1183 },
1184 },
1185 );
1186 Ok(state)
1187 }
1188
1189 fn window_state(&self, id: WindowId) -> Option<WindowState> {
1200 self.get_windows()
1201 .get(&id)
1202 .map(LinuxWindowRecord::get_state)
1203 }
1204
1205 fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
1216 match self.get_windows().get(&id) {
1217 Some(rec) => {
1218 if rec.get_is_wayland() {
1219 RawWindowHandle::Wayland {
1220 surface: rec.get_window() as usize,
1221 display: rec.get_display(),
1222 }
1223 } else {
1224 RawWindowHandle::Xlib {
1225 window: rec.get_window(),
1226 display: rec.get_display(),
1227 }
1228 }
1229 }
1230 None => RawWindowHandle::Headless,
1231 }
1232 }
1233
1234 fn poll_events(&mut self) -> Vec<WindowEvent> {
1244 let Self {
1245 windows,
1246 pending_events,
1247 ..
1248 } = self;
1249 linux_x11_pump_events(windows, pending_events);
1250 take(pending_events)
1251 }
1252
1253 fn wait_for_events(&mut self) -> Vec<WindowEvent> {
1259 let Self {
1260 windows,
1261 pending_events,
1262 ..
1263 } = self;
1264 if pending_events.is_empty() && !windows.is_empty() {
1265 linux_x11_wait_events(windows, pending_events);
1266 }
1267 take(pending_events)
1268 }
1269
1270 fn set_frame_pump_paused(&mut self, paused: bool) {
1277 self.set_pump_paused(paused);
1278 }
1279
1280 fn is_frame_pump_paused(&self) -> bool {
1290 self.get_pump_paused()
1291 }
1292
1293 fn present_framebuffer(
1305 &mut self,
1306 id: WindowId,
1307 framebuffer: &Framebuffer,
1308 ) -> Result<(), PlatformError> {
1309 self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
1310 }
1311
1312 fn present_framebuffer_region(
1324 &mut self,
1325 id: WindowId,
1326 framebuffer: &Framebuffer,
1327 damage: DamageRegion,
1328 ) -> Result<(), PlatformError> {
1329 let _: LinuxPresentTelemetry =
1330 self.present_framebuffer_with_outcome(id, framebuffer, damage)?;
1331 Ok(())
1332 }
1333
1334 fn read_clipboard(&self) -> Option<String> {
1344 let Self {
1345 clipboard_cache, ..
1346 } = self;
1347 clipboard_cache.clone()
1348 }
1349
1350 fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1361 self.set_clipboard_cache(Some(text.to_string()));
1362 let _: bool = write_system_clipboard(text);
1363 Ok(())
1364 }
1365
1366 fn system_theme(&self) -> ThemeMode {
1376 ThemeMode::Light
1377 }
1378
1379 fn display_refresh_rate_hz(&self) -> f32 {
1389 if let Some(wl_milli_hz) = self
1390 .get_windows()
1391 .values()
1392 .find(|rec: &&LinuxWindowRecord| {
1393 rec.get_is_wayland() && rec.get_wayland_output_refresh_milli_hz() >= 24_000
1394 })
1395 .map(LinuxWindowRecord::get_wayland_output_refresh_milli_hz)
1396 {
1397 return ((wl_milli_hz as f32) / 1000.0).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
1398 }
1399 let (display, window): (*mut c_void, usize) = self
1400 .get_windows()
1401 .values()
1402 .find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland())
1403 .map(|rec: &LinuxWindowRecord| {
1404 (rec.get_display() as *mut c_void, rec.get_window() as usize)
1405 })
1406 .unwrap_or((null_mut(), 0));
1407 linux_display_refresh_rate_hz(display, window)
1408 }
1409}