Skip to main content

euv_core/platform/linux/
impl.rs

1use super::*;
2
3/// Default initialization for `LinuxPlatform`.
4impl Default for LinuxPlatform {
5    /// Creates an empty Linux X11 / Wayland platform backend.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized Linux backend.
10    fn default() -> Self {
11        Self {
12            next_id: 1,
13            x11_lib: 0,
14            windows: HashMap::new(),
15            pending_events: Vec::new(),
16            clipboard_cache: None,
17            pump_paused: false,
18        }
19    }
20}
21
22/// X11/Wayland system event injection and Wayland VSync/output callbacks for `LinuxPlatform`.
23impl LinuxPlatform {
24    /// Enqueues a normalized Linux `SystemEvent` to be drained on the next `poll_events()` tick.
25    ///
26    /// # Arguments
27    ///
28    /// - `SystemEvent` - System event to enqueue.
29    pub fn push_system_event(&mut self, event: SystemEvent) {
30        self.get_mut_pending_events()
31            .push(WindowEvent::System(event));
32    }
33
34    /// Records a Wayland `wl_output.mode` refresh rate in millihertz (e.g. `240000` -> `240Hz`) for `id`.
35    ///
36    /// # Arguments
37    ///
38    /// - `WindowId` - Target Wayland window identifier.
39    /// - `u32` - Output refresh rate in millihertz.
40    pub fn on_wayland_output_mode(&mut self, id: WindowId, refresh_milli_hz: u32) {
41        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
42            rec.set_wayland_output_refresh_milli_hz(refresh_milli_hz);
43            let hz: f32 = ((refresh_milli_hz as f32) / 1000.0)
44                .clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
45            rec.get_mut_state()
46                .get_mut_display()
47                .set_refresh_rate_hz(hz.round() as u32);
48        }
49    }
50
51    /// Handles a Wayland `wl_surface::frame` done callback and schedules a redraw when active.
52    ///
53    /// # Arguments
54    ///
55    /// - `WindowId` - Target Wayland window identifier.
56    pub fn on_wayland_frame_callback(&mut self, id: WindowId) {
57        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
58            rec.set_wayland_frame_callback_pending(false);
59        }
60        if !self.get_pump_paused() {
61            self.get_mut_pending_events()
62                .push(WindowEvent::RedrawRequested(id));
63        }
64    }
65
66    /// Records a Wayland `wp_presentation` feedback timestamp in nanoseconds for `id`.
67    ///
68    /// # Arguments
69    ///
70    /// - `WindowId` - Target Wayland window identifier.
71    /// - `u64` - Compositor presentation timestamp in nanoseconds.
72    pub fn on_wayland_presentation_feedback(&mut self, id: WindowId, timestamp_ns: u64) {
73        if let Some(rec) = self.get_mut_windows().get_mut(&id) {
74            rec.set_wayland_presentation_time_ns(timestamp_ns);
75        }
76    }
77}
78
79/// `WindowController` implementation for Linux X11 / Wayland.
80impl WindowController for LinuxPlatform {
81    /// Applies a `WindowCommand` onto the native X11 or Wayland window.
82    ///
83    /// # Arguments
84    ///
85    /// - `WindowCommand` - Command to apply.
86    ///
87    /// # Returns
88    ///
89    /// - `Result<(), PlatformError>` - Execution status.
90    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
91        match command {
92            WindowCommand::SetTitle(id, title) => {
93                let rec: &mut LinuxWindowRecord = self
94                    .get_mut_windows()
95                    .get_mut(&id)
96                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
97                if !rec.get_is_wayland() {
98                    linux_x11_set_title(rec.get_display(), rec.get_window(), &title);
99                }
100                rec.get_mut_config().set_title(title);
101                Ok(())
102            }
103            WindowCommand::SetSize(id, width, height) => {
104                let rec: &mut LinuxWindowRecord = self
105                    .get_mut_windows()
106                    .get_mut(&id)
107                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
108                let w: u32 = width.max(1);
109                let h: u32 = height.max(1);
110                if !rec.get_is_wayland() {
111                    linux_x11_resize(rec.get_display(), rec.get_window(), w, h);
112                }
113                let scale: f32 = rec.get_state().get_scale_factor();
114                rec.get_mut_config().set_width(w);
115                rec.get_mut_config().set_height(h);
116                rec.get_mut_state().set_logical_width(w as f32);
117                rec.get_mut_state().set_logical_height(h as f32);
118                rec.get_mut_state()
119                    .set_physical_width(((w as f32) * scale).round() as u32);
120                rec.get_mut_state()
121                    .set_physical_height(((h as f32) * scale).round() as u32);
122                Ok(())
123            }
124            WindowCommand::Close(id) => {
125                let rec: LinuxWindowRecord = self
126                    .get_mut_windows()
127                    .remove(&id)
128                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
129                if rec.get_is_wayland() {
130                    linux_wayland_disconnect(rec.get_display());
131                } else {
132                    linux_x11_destroy(rec.get_display(), rec.get_window());
133                }
134                Ok(())
135            }
136            WindowCommand::SetRenderMode(id, mode) => {
137                let rec: &mut LinuxWindowRecord = self
138                    .get_mut_windows()
139                    .get_mut(&id)
140                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
141                rec.get_mut_config().get_mut_render().set_mode(mode);
142                Ok(())
143            }
144            WindowCommand::RequestRedraw(id) => {
145                if !self.get_windows().contains_key(&id) {
146                    return Err(PlatformError::WindowNotFound(id.get_value()));
147                }
148                self.get_mut_pending_events()
149                    .push(WindowEvent::RedrawRequested(id));
150                Ok(())
151            }
152            WindowCommand::SetFullscreen(id, mode) => {
153                let rec: &mut LinuxWindowRecord = self
154                    .get_mut_windows()
155                    .get_mut(&id)
156                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
157                rec.get_mut_config().set_fullscreen(mode);
158                rec.get_mut_state().set_fullscreen(mode);
159                Ok(())
160            }
161            WindowCommand::SetPosition(id, _, _)
162            | WindowCommand::SetResizable(id, _)
163            | WindowCommand::SetDecorations(id, _)
164            | WindowCommand::SetAlwaysOnTop(id, _)
165            | WindowCommand::SetVisible(id, _)
166            | WindowCommand::SetCursor(id, _)
167            | WindowCommand::SetIme(id, _, _)
168            | WindowCommand::SetStatusBarStyle(id, _) => {
169                if !self.get_windows().contains_key(&id) {
170                    return Err(PlatformError::WindowNotFound(id.get_value()));
171                }
172                Ok(())
173            }
174        }
175    }
176}
177
178/// `PlatformBackend` implementation for native Linux.
179impl PlatformBackend for LinuxPlatform {
180    /// Returns `PlatformKind::Linux`.
181    ///
182    /// # Arguments
183    ///
184    /// - `&Self` - Platform reference.
185    ///
186    /// # Returns
187    ///
188    /// - `PlatformKind` - `PlatformKind::Linux`.
189    fn kind(&self) -> PlatformKind {
190        PlatformKind::Linux
191    }
192
193    /// Returns Linux desktop capabilities.
194    ///
195    /// # Arguments
196    ///
197    /// - `&Self` - Platform reference.
198    ///
199    /// # Returns
200    ///
201    /// - `PlatformCapabilities` - Linux capability flags.
202    fn capabilities(&self) -> PlatformCapabilities {
203        PlatformCapabilities::for_platform(PlatformKind::Linux)
204    }
205
206    /// Opens an X11 or Wayland window via dynamic `dlopen`.
207    ///
208    /// # Arguments
209    ///
210    /// - `&Self` - Mutable Linux platform.
211    /// - `&WindowConfig` - Declarative window config.
212    ///
213    /// # Returns
214    ///
215    /// - `Result<WindowState, PlatformError>` - Initial window state.
216    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
217        let native: LinuxNativeWindowHandle = linux_create_native_window(config)?;
218        if !native.get_is_wayland() {
219            self.set_x11_lib(native.get_lib());
220        }
221        let id: WindowId = WindowId::new(self.get_next_id());
222        self.set_next_id(self.get_next_id().wrapping_add(1));
223        let mut state: WindowState =
224            WindowState::from_config(id, config, native.get_scale_factor());
225        let hz: f32 = if native.get_is_wayland() {
226            linux_display_refresh_rate_hz(null_mut(), 0)
227        } else {
228            linux_display_refresh_rate_hz(
229                native.get_display() as *mut c_void,
230                native.get_window() as usize,
231            )
232        };
233        state
234            .get_mut_display()
235            .set_refresh_rate_hz(hz.round() as u32);
236        self.get_mut_windows().insert(
237            id,
238            LinuxWindowRecord {
239                config: config.clone(),
240                state,
241                is_wayland: native.get_is_wayland(),
242                display: native.get_display(),
243                window: native.get_window(),
244                gc: native.get_gc(),
245                visual: native.get_visual(),
246                depth: native.get_depth(),
247                wm_delete_atom: native.get_wm_delete_atom(),
248                revealed: native.get_is_wayland(),
249                mit_shm_available: native.get_mit_shm_available(),
250                wayland_vulkan_wsi: native.get_wayland_vulkan_wsi(),
251                wayland_output_refresh_milli_hz: 0,
252                wayland_presentation_time_ns: 0,
253                wayland_frame_callback_pending: false,
254            },
255        );
256        Ok(state)
257    }
258
259    /// Queries live `WindowState` for `id`.
260    ///
261    /// # Arguments
262    ///
263    /// - `&Self` - Platform reference.
264    /// - `WindowId` - Window handle.
265    ///
266    /// # Returns
267    ///
268    /// - `Option<WindowState>` - Window state if open.
269    fn window_state(&self, id: WindowId) -> Option<WindowState> {
270        self.get_windows()
271            .get(&id)
272            .map(LinuxWindowRecord::get_state)
273    }
274
275    /// Returns `RawWindowHandle::Xlib` or `RawWindowHandle::Wayland` for Vulkan/EGL surface binding.
276    ///
277    /// # Arguments
278    ///
279    /// - `&Self` - Platform reference.
280    /// - `WindowId` - Window handle.
281    ///
282    /// # Returns
283    ///
284    /// - `RawWindowHandle` - Native Linux display/window handle.
285    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
286        match self.get_windows().get(&id) {
287            Some(rec) => {
288                if rec.get_is_wayland() {
289                    RawWindowHandle::Wayland {
290                        surface: rec.get_window() as usize,
291                        display: rec.get_display(),
292                    }
293                } else {
294                    RawWindowHandle::Xlib {
295                        window: rec.get_window(),
296                        display: rec.get_display(),
297                    }
298                }
299            }
300            None => RawWindowHandle::Headless,
301        }
302    }
303
304    /// Pumps pending X11 events and drains queued Linux events.
305    ///
306    /// # Arguments
307    ///
308    /// - `&Self` - Mutable Linux platform.
309    ///
310    /// # Returns
311    ///
312    /// - `Vec<WindowEvent>` - Pending events.
313    fn poll_events(&mut self) -> Vec<WindowEvent> {
314        let Self {
315            windows,
316            pending_events,
317            ..
318        } = self;
319        linux_x11_pump_events(windows, pending_events);
320        take(pending_events)
321    }
322
323    /// Blocks on Wayland `wl_display_dispatch` or X11 `XNextEvent` with zero CPU usage until an OS event wakes the connection.
324    ///
325    /// # Returns
326    ///
327    /// - `Vec<WindowEvent>` - Events received upon wake.
328    fn wait_for_events(&mut self) -> Vec<WindowEvent> {
329        let Self {
330            windows,
331            pending_events,
332            ..
333        } = self;
334        if pending_events.is_empty() && !windows.is_empty() {
335            linux_x11_wait_events(windows, pending_events);
336        }
337        take(pending_events)
338    }
339
340    /// Updates Linux background frame-pump pause state.
341    ///
342    /// # Arguments
343    ///
344    /// - `&Self` - Mutable Linux platform.
345    /// - `bool` - `true` when paused in background; `false` when active.
346    fn set_frame_pump_paused(&mut self, paused: bool) {
347        self.set_pump_paused(paused);
348    }
349
350    /// Returns whether the Linux frame pump is currently paused for background freeze.
351    ///
352    /// # Arguments
353    ///
354    /// - `&Self` - Platform reference.
355    ///
356    /// # Returns
357    ///
358    /// - `bool` - `true` when paused in background.
359    fn is_frame_pump_paused(&self) -> bool {
360        self.get_pump_paused()
361    }
362
363    /// Presents `framebuffer` to the active Linux window surface via X11 `XCreateImage` + `XPutImage`.
364    ///
365    /// # Arguments
366    ///
367    /// - `&Self` - Mutable Linux platform.
368    /// - `WindowId` - Target window handle.
369    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
370    ///
371    /// # Returns
372    ///
373    /// - `Result<(), PlatformError>` - Presentation status.
374    fn present_framebuffer(
375        &mut self,
376        id: WindowId,
377        framebuffer: &Framebuffer,
378    ) -> Result<(), PlatformError> {
379        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
380    }
381
382    /// Presents `framebuffer` (or only `damage`) onto the active Linux X11 or Wayland window and maps X11 windows after Frame 1.
383    ///
384    /// # Arguments
385    ///
386    /// - `WindowId` - Target window handle.
387    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
388    /// - `DamageRegion` - Damaged pixel region updated this frame.
389    ///
390    /// # Returns
391    ///
392    /// - `Result<(), PlatformError>` - Presentation status.
393    fn present_framebuffer_region(
394        &mut self,
395        id: WindowId,
396        framebuffer: &Framebuffer,
397        damage: DamageRegion,
398    ) -> Result<(), PlatformError> {
399        let dirty_rect: Option<Rect> = if damage.get_full_damage() {
400            None
401        } else {
402            damage.bounds_rect()
403        };
404        let (res, should_map, display, window): (Result<(), PlatformError>, bool, usize, u64) = {
405            let rec: &LinuxWindowRecord = self
406                .get_windows()
407                .get(&id)
408                .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
409            let present_res: Result<(), PlatformError> =
410                linux_x11_present_framebuffer(rec, framebuffer, dirty_rect);
411            (
412                present_res,
413                !rec.get_is_wayland() && !rec.get_revealed() && rec.get_config().get_visible(),
414                rec.get_display(),
415                rec.get_window(),
416            )
417        };
418        if res.is_ok() && should_map {
419            linux_x11_map_window(display, window);
420            if let Some(rec) = self.get_mut_windows().get_mut(&id) {
421                rec.set_revealed(true);
422            }
423        }
424        res
425    }
426
427    /// Reads cached clipboard text.
428    ///
429    /// # Arguments
430    ///
431    /// - `&Self` - Platform reference.
432    ///
433    /// # Returns
434    ///
435    /// - `Option<String>` - Clipboard contents.
436    fn read_clipboard(&self) -> Option<String> {
437        let Self {
438            clipboard_cache, ..
439        } = self;
440        clipboard_cache.clone()
441    }
442
443    /// Writes `text` to clipboard cache.
444    ///
445    /// # Arguments
446    ///
447    /// - `&Self` - Mutable platform.
448    /// - `&str` - Clipboard text.
449    ///
450    /// # Returns
451    ///
452    /// - `Result<(), PlatformError>` - Write status.
453    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
454        self.set_clipboard_cache(Some(text.to_string()));
455        let _: bool = write_system_clipboard(text);
456        Ok(())
457    }
458
459    /// Returns active system theme mode.
460    ///
461    /// # Arguments
462    ///
463    /// - `&Self` - Platform reference.
464    ///
465    /// # Returns
466    ///
467    /// - `ThemeMode` - Active appearance mode.
468    fn system_theme(&self) -> ThemeMode {
469        ThemeMode::Light
470    }
471
472    /// Queries the native Linux display refresh rate via XRandR or `EUV_REFRESH_RATE_HZ`.
473    ///
474    /// # Arguments
475    ///
476    /// - `&Self` - Platform reference.
477    ///
478    /// # Returns
479    ///
480    /// - `f32` - Active display refresh rate in Hertz.
481    fn display_refresh_rate_hz(&self) -> f32 {
482        if let Some(wl_milli_hz) = self
483            .get_windows()
484            .values()
485            .find(|rec: &&LinuxWindowRecord| {
486                rec.get_is_wayland() && rec.get_wayland_output_refresh_milli_hz() >= 24_000
487            })
488            .map(LinuxWindowRecord::get_wayland_output_refresh_milli_hz)
489        {
490            return ((wl_milli_hz as f32) / 1000.0).clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
491        }
492        let (display, window): (*mut c_void, usize) = self
493            .get_windows()
494            .values()
495            .find(|rec: &&LinuxWindowRecord| !rec.get_is_wayland())
496            .map(|rec: &LinuxWindowRecord| {
497                (rec.get_display() as *mut c_void, rec.get_window() as usize)
498            })
499            .unwrap_or((null_mut(), 0));
500        linux_display_refresh_rate_hz(display, window)
501    }
502}