Skip to main content

strata_platform/
window.rs

1//! Window configuration, platform window traits, and mock implementations.
2
3use crate::events::PlatformEvent;
4use crate::surface::{FramePacer, RefreshRate, SurfaceConfig, SurfaceHandle};
5use std::collections::VecDeque;
6use std::time::Instant;
7
8/// Operating mode of the platform window.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum WindowMode {
11    #[default]
12    Windowed,
13    BorderlessFullscreen,
14    ExclusiveFullscreen,
15    Minimized,
16    Maximized,
17}
18
19/// Window frame decoration style.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub enum WindowDecoration {
22    #[default]
23    NativeOs,
24    ClientSideDecorations,
25    FramelessTransparent,
26}
27
28/// Operating system color scheme / theme preference.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
30pub enum ThemeMode {
31    #[default]
32    System,
33    Light,
34    Dark,
35}
36
37/// Cursor icon style.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
39pub enum CursorIcon {
40    #[default]
41    Default,
42    Pointer,
43    Text,
44    Crosshair,
45    Move,
46    NotAllowed,
47    Wait,
48    Grab,
49    Grabbing,
50    ResizeN,
51    ResizeS,
52    ResizeE,
53    ResizeW,
54    ResizeNe,
55    ResizeNw,
56    ResizeSe,
57    ResizeSw,
58    ColResize,
59    RowResize,
60    Help,
61    None,
62}
63
64/// Monitor workarea placement and sticky docking anchor for a platform window.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub enum WindowAnchor {
67    TopLeft,
68    TopRight,
69    BottomLeft,
70    BottomRight,
71    Center,
72}
73
74impl WindowAnchor {
75    /// Returns true if this anchor pins ("sticks") the window to a monitor workarea corner.
76    pub const fn is_sticky_dock(self) -> bool {
77        matches!(
78            self,
79            Self::TopLeft | Self::TopRight | Self::BottomLeft | Self::BottomRight
80        )
81    }
82
83    /// Computes target `(x, y)` coordinates within a monitor workarea for a window of `(win_w, win_h)`.
84    pub const fn compute_position(
85        self,
86        workarea_x: i32,
87        workarea_y: i32,
88        workarea_w: i32,
89        workarea_h: i32,
90        win_w: i32,
91        win_h: i32,
92    ) -> (i32, i32) {
93        match self {
94            Self::TopLeft => (workarea_x, workarea_y),
95            Self::TopRight => (workarea_x + workarea_w - win_w, workarea_y),
96            Self::BottomLeft => (workarea_x, workarea_y + workarea_h - win_h),
97            Self::BottomRight => (
98                workarea_x + workarea_w - win_w,
99                workarea_y + workarea_h - win_h,
100            ),
101            Self::Center => (
102                workarea_x + (workarea_w - win_w) / 2,
103                workarea_y + (workarea_h - win_h) / 2,
104            ),
105        }
106    }
107}
108
109/// Configuration used when creating or reconfiguring a platform window.
110#[derive(Debug, Clone)]
111pub struct WindowConfig {
112    pub title: String,
113    pub width: u32,
114    pub height: u32,
115    pub min_width: Option<u32>,
116    pub min_height: Option<u32>,
117    pub max_width: Option<u32>,
118    pub max_height: Option<u32>,
119    pub resizable: bool,
120    pub mode: WindowMode,
121    pub decoration: WindowDecoration,
122    pub theme: ThemeMode,
123    pub transparent: bool,
124    pub always_on_top: bool,
125    pub anchor: Option<WindowAnchor>,
126    pub dock_bottom_right: bool,
127    pub single_instance_id: Option<String>,
128    pub vibrancy: crate::vibrancy::VibrancyEffect,
129    /// Swapchain presentation mode (`Immediate` / `Mailbox` for uncapped 3D viewports, `Fifo` default).
130    pub present_mode: crate::surface::PresentMode,
131}
132
133impl WindowConfig {
134    /// Sets swapchain present mode (e.g. `PresentMode::Immediate` for uncapped framerate).
135    pub fn with_present_mode(mut self, present_mode: crate::surface::PresentMode) -> Self {
136        self.present_mode = present_mode;
137        self
138    }
139
140    /// Configures the window to enforce a single-instance mutex and focus existing instance on launch.
141    pub fn with_single_instance(mut self, app_id: impl Into<String>) -> Self {
142        self.single_instance_id = Some(app_id.into());
143        self
144    }
145
146    /// Configures window backdrop blur and vibrancy (Mica, Acrylic, NSVisualEffectView).
147    pub fn with_vibrancy(mut self, vibrancy: crate::vibrancy::VibrancyEffect) -> Self {
148        self.vibrancy = vibrancy;
149        self
150    }
151
152    /// Configures monitor workarea placement or corner docking for this window.
153    pub fn with_anchor(mut self, anchor: WindowAnchor) -> Self {
154        self.anchor = Some(anchor);
155        if anchor == WindowAnchor::BottomRight {
156            self.dock_bottom_right = true;
157        }
158        self
159    }
160
161    /// Pins the window to the bottom-right corner of the primary monitor's workarea ("stuck" mode).
162    pub fn with_dock_bottom_right(mut self, dock_bottom_right: bool) -> Self {
163        self.dock_bottom_right = dock_bottom_right;
164        if dock_bottom_right && self.anchor.is_none() {
165            self.anchor = Some(WindowAnchor::BottomRight);
166        } else if !dock_bottom_right && self.anchor == Some(WindowAnchor::BottomRight) {
167            self.anchor = None;
168        }
169        self
170    }
171
172    /// Resolves the effective window anchor, honoring both `anchor` and `dock_bottom_right`.
173    pub const fn effective_anchor(&self) -> Option<WindowAnchor> {
174        if let Some(anchor) = self.anchor {
175            Some(anchor)
176        } else if self.dock_bottom_right {
177            Some(WindowAnchor::BottomRight)
178        } else {
179            None
180        }
181    }
182
183    /// Returns true when the window is docked ("stuck") to a monitor workarea corner.
184    pub const fn is_docked(&self) -> bool {
185        match self.effective_anchor() {
186            Some(anchor) => anchor.is_sticky_dock(),
187            None => false,
188        }
189    }
190
191    /// Computes target `(x, y)` coordinates in the given monitor workarea if an anchor is configured.
192    pub const fn compute_anchored_position(
193        &self,
194        workarea_x: i32,
195        workarea_y: i32,
196        workarea_w: i32,
197        workarea_h: i32,
198    ) -> Option<(i32, i32)> {
199        match self.effective_anchor() {
200            Some(anchor) => Some(anchor.compute_position(
201                workarea_x,
202                workarea_y,
203                workarea_w,
204                workarea_h,
205                self.width as i32,
206                self.height as i32,
207            )),
208            None => None,
209        }
210    }
211}
212
213impl Default for WindowConfig {
214    fn default() -> Self {
215        Self {
216            title: "Strata Application".to_string(),
217            width: 1280,
218            height: 800,
219            min_width: Some(320),
220            min_height: Some(240),
221            max_width: None,
222            max_height: None,
223            resizable: true,
224            mode: WindowMode::Windowed,
225            decoration: WindowDecoration::NativeOs,
226            theme: ThemeMode::System,
227            transparent: false,
228            always_on_top: false,
229            anchor: None,
230            dock_bottom_right: false,
231            single_instance_id: None,
232            vibrancy: crate::vibrancy::VibrancyEffect::None,
233            present_mode: crate::surface::PresentMode::Fifo,
234        }
235    }
236}
237
238/// Physical display monitor descriptor.
239#[derive(Debug, Clone, PartialEq)]
240pub struct MonitorInfo {
241    pub id: u64,
242    pub name: String,
243    pub x: i32,
244    pub y: i32,
245    pub width: u32,
246    pub height: u32,
247    pub scale_factor: f32,
248    pub refresh_rate: u32,
249    pub is_primary: bool,
250}
251
252impl MonitorInfo {
253    /// Creates a new monitor descriptor.
254    pub fn new(
255        id: u64,
256        name: impl Into<String>,
257        x: i32,
258        y: i32,
259        width: u32,
260        height: u32,
261        scale_factor: f32,
262        refresh_rate: u32,
263        is_primary: bool,
264    ) -> Self {
265        Self {
266            id,
267            name: name.into(),
268            x,
269            y,
270            width,
271            height,
272            scale_factor,
273            refresh_rate,
274            is_primary,
275        }
276    }
277
278    /// Default standard 1080p 1.0x display.
279    pub fn standard_1080p() -> Self {
280        Self::new(1, "Primary Display", 0, 0, 1920, 1080, 1.0, 60, true)
281    }
282
283    /// High-DPI 4K 2.0x display.
284    pub fn hidpi_4k() -> Self {
285        Self::new(2, "4K UHD Display", 1920, 0, 3840, 2160, 2.0, 120, false)
286    }
287}
288
289/// Abstract platform window trait defining common cross-platform window operations.
290pub trait PlatformWindow {
291    fn title(&self) -> &str;
292    fn set_title(&mut self, title: &str);
293    fn size(&self) -> (u32, u32);
294    fn set_size(&mut self, width: u32, height: u32);
295    fn scale_factor(&self) -> f32;
296    fn set_scale_factor(&mut self, scale_factor: f32);
297    fn mode(&self) -> WindowMode;
298    fn set_mode(&mut self, mode: WindowMode);
299    fn is_focused(&self) -> bool;
300    fn set_focused(&mut self, focused: bool);
301    fn cursor(&self) -> CursorIcon;
302    fn set_cursor(&mut self, cursor: CursorIcon);
303    fn request_redraw(&mut self);
304    fn is_redraw_requested(&self) -> bool;
305    fn poll_events(&mut self) -> Vec<PlatformEvent>;
306    fn push_event(&mut self, event: PlatformEvent);
307    /// Returns the monitor containing the center of this window, if known.
308    fn current_monitor(&self) -> Option<MonitorInfo> {
309        None
310    }
311    /// Returns the list of currently connected physical display monitors.
312    fn available_monitors(&self) -> Vec<MonitorInfo> {
313        Vec::new()
314    }
315    /// Returns the primary system monitor.
316    fn primary_monitor(&self) -> Option<MonitorInfo> {
317        None
318    }
319    /// Transmits an incremental AccessKit/OS accessibility tree update to native screen readers.
320    fn on_accessibility_update(&mut self, _json_payload: &str) {}
321    /// Sets candidate window positioning following active text caret coordinate.
322    fn set_ime_cursor_location(&mut self, _x: i32, _y: i32, _width: i32, _height: i32) {}
323    /// Updates surrounding text buffer for context-aware IME prediction.
324    fn set_ime_surrounding_text(&mut self, _text: &str, _cursor_index: i32) {}
325    /// Resets active IME composition session.
326    fn reset_ime(&mut self) {}
327    /// Initiates an interactive window drag operation with the native window manager.
328    fn begin_window_drag(&mut self, _x: f32, _y: f32) {}
329    /// Initiates an interactive window resize operation with the native window manager.
330    fn begin_window_resize(&mut self, _edge: crate::csd::CsdHitZone, _x: f32, _y: f32) {}
331    /// Toggles the window maximized state and returns true if the window is now maximized.
332    fn toggle_maximize(&mut self) -> bool {
333        let current = self.mode();
334        let new_mode = if current == WindowMode::Maximized {
335            WindowMode::Windowed
336        } else {
337            WindowMode::Maximized
338        };
339        self.set_mode(new_mode);
340        new_mode == WindowMode::Maximized
341    }
342}
343
344/// Contract for platform windows supporting direct software/swapchain pixel blitting.
345pub trait NativeSurfaceWindow: PlatformWindow {
346    /// Blits a 32-bit BGRA uncompressed buffer to the window client area.
347    fn present_surface(
348        &mut self,
349        pixels: &[u8],
350        width: u32,
351        height: u32,
352    ) -> Result<(), crate::surface::PresentError>;
353}
354
355/// Headless mock platform window for deterministic testing, CI automation, and headless rendering.
356#[derive(Debug, Clone)]
357pub struct MockPlatformWindow {
358    pub config: WindowConfig,
359    pub scale_factor: f32,
360    pub is_focused: bool,
361    pub cursor: CursorIcon,
362    pub redraw_requested: bool,
363    pub event_queue: VecDeque<PlatformEvent>,
364    pub last_accessibility_update: Option<String>,
365    pub ime_cursor_location: Option<(i32, i32, i32, i32)>,
366    pub ime_surrounding: Option<(String, i32)>,
367    pub monitors: Vec<MonitorInfo>,
368    pub current_monitor_id: Option<u64>,
369}
370
371impl MockPlatformWindow {
372    /// Creates a new mock window with the specified configuration.
373    pub fn new(config: WindowConfig) -> Self {
374        Self {
375            config,
376            scale_factor: 1.0,
377            is_focused: true,
378            cursor: CursorIcon::Default,
379            redraw_requested: false,
380            event_queue: VecDeque::new(),
381            last_accessibility_update: None,
382            ime_cursor_location: None,
383            ime_surrounding: None,
384            monitors: vec![MonitorInfo::standard_1080p()],
385            current_monitor_id: Some(1),
386        }
387    }
388
389    /// Creates a mock window with default configuration.
390    pub fn new_mock() -> Self {
391        Self::new(WindowConfig::default())
392    }
393
394    /// Injects an event into the window's event queue.
395    pub fn inject_event(&mut self, event: PlatformEvent) {
396        self.push_event(event);
397    }
398
399    /// Consumes and clears the redraw request flag.
400    pub fn take_redraw_request(&mut self) -> bool {
401        let requested = self.redraw_requested;
402        self.redraw_requested = false;
403        requested
404    }
405
406    /// Adds a monitor to the mock topology.
407    pub fn add_monitor(&mut self, monitor: MonitorInfo) {
408        self.monitors.push(monitor);
409    }
410
411    /// Moves the window to another monitor, automatically updating high-DPI scaling.
412    pub fn move_to_monitor(&mut self, monitor_id: u64) {
413        if let Some(monitor) = self.monitors.iter().find(|m| m.id == monitor_id).cloned() {
414            self.current_monitor_id = Some(monitor_id);
415            if (self.scale_factor - monitor.scale_factor).abs() > 0.001 {
416                self.set_scale_factor(monitor.scale_factor);
417            }
418        }
419    }
420}
421
422impl PlatformWindow for MockPlatformWindow {
423    fn title(&self) -> &str {
424        &self.config.title
425    }
426
427    fn set_title(&mut self, title: &str) {
428        self.config.title = title.to_string();
429    }
430
431    fn size(&self) -> (u32, u32) {
432        (self.config.width, self.config.height)
433    }
434
435    fn set_size(&mut self, width: u32, height: u32) {
436        self.config.width = width;
437        self.config.height = height;
438        self.push_event(PlatformEvent::WindowResized { width, height });
439    }
440
441    fn scale_factor(&self) -> f32 {
442        self.scale_factor
443    }
444
445    fn set_scale_factor(&mut self, scale_factor: f32) {
446        self.scale_factor = scale_factor;
447        self.push_event(PlatformEvent::ScaleFactorChanged { scale_factor });
448    }
449
450    fn mode(&self) -> WindowMode {
451        self.config.mode
452    }
453
454    fn set_mode(&mut self, mode: WindowMode) {
455        let old = self.config.mode;
456        self.config.mode = mode;
457        if old != mode {
458            self.push_event(PlatformEvent::WindowMaximized(
459                mode == WindowMode::Maximized,
460            ));
461        }
462    }
463
464    fn is_focused(&self) -> bool {
465        self.is_focused
466    }
467
468    fn set_focused(&mut self, focused: bool) {
469        self.is_focused = focused;
470        self.push_event(PlatformEvent::WindowFocused(focused));
471    }
472
473    fn cursor(&self) -> CursorIcon {
474        self.cursor
475    }
476
477    fn set_cursor(&mut self, cursor: CursorIcon) {
478        self.cursor = cursor;
479    }
480
481    fn request_redraw(&mut self) {
482        self.redraw_requested = true;
483    }
484
485    fn is_redraw_requested(&self) -> bool {
486        self.redraw_requested
487    }
488
489    fn poll_events(&mut self) -> Vec<PlatformEvent> {
490        self.event_queue.drain(..).collect()
491    }
492
493    fn push_event(&mut self, event: PlatformEvent) {
494        self.event_queue.push_back(event);
495    }
496
497    fn current_monitor(&self) -> Option<MonitorInfo> {
498        self.current_monitor_id
499            .and_then(|id| self.monitors.iter().find(|m| m.id == id).cloned())
500    }
501
502    fn available_monitors(&self) -> Vec<MonitorInfo> {
503        self.monitors.clone()
504    }
505
506    fn primary_monitor(&self) -> Option<MonitorInfo> {
507        self.monitors.iter().find(|m| m.is_primary).cloned()
508    }
509
510    fn on_accessibility_update(&mut self, json_payload: &str) {
511        self.last_accessibility_update = Some(json_payload.to_string());
512    }
513
514    fn set_ime_cursor_location(&mut self, x: i32, y: i32, width: i32, height: i32) {
515        self.ime_cursor_location = Some((x, y, width, height));
516    }
517
518    fn set_ime_surrounding_text(&mut self, text: &str, cursor_index: i32) {
519        self.ime_surrounding = Some((text.to_string(), cursor_index));
520    }
521
522    fn reset_ime(&mut self) {
523        self.ime_cursor_location = None;
524        self.ime_surrounding = None;
525    }
526}
527
528impl NativeSurfaceWindow for MockPlatformWindow {
529    fn present_surface(
530        &mut self,
531        _pixels: &[u8],
532        _width: u32,
533        _height: u32,
534    ) -> Result<(), crate::surface::PresentError> {
535        self.redraw_requested = false;
536        Ok(())
537    }
538}
539
540/// Live interactive platform window with surface configuration, frame pacing, and event queuing.
541#[derive(Debug, Clone)]
542pub struct LivePlatformWindow {
543    pub config: WindowConfig,
544    pub surface_config: SurfaceConfig,
545    pub surface_handle: SurfaceHandle,
546    pub frame_pacer: FramePacer,
547    pub scale_factor: f32,
548    pub is_focused: bool,
549    pub cursor: CursorIcon,
550    pub redraw_requested: bool,
551    pub event_queue: VecDeque<PlatformEvent>,
552    pub monitors: Vec<MonitorInfo>,
553    pub current_monitor_id: Option<u64>,
554    pub display_buffer: Vec<u8>,
555    pub is_native_presented: bool,
556}
557
558impl LivePlatformWindow {
559    /// Creates a live platform window initialized with the given configuration.
560    pub fn new(config: WindowConfig) -> Self {
561        let scale_factor = 1.0;
562        let surface_config = SurfaceConfig {
563            width: config.width,
564            height: config.height,
565            scale_factor,
566            ..Default::default()
567        };
568        let surface_handle = {
569            #[cfg(target_os = "linux")]
570            {
571                if std::env::var_os("WAYLAND_DISPLAY").is_some() {
572                    SurfaceHandle {
573                        window_id: 1001,
574                        raw_window_ptr: 0x574C4E44,  // "WLND"
575                        raw_display_ptr: 0x574C4453, // "WLDS"
576                        width: config.width,
577                        height: config.height,
578                        scale_factor_snapped: (scale_factor * 64.0) as u32,
579                    }
580                } else if std::env::var_os("DISPLAY").is_some() {
581                    SurfaceHandle {
582                        window_id: 1002,
583                        raw_window_ptr: 0x58313157,  // "X11W"
584                        raw_display_ptr: 0x58313144, // "X11D"
585                        width: config.width,
586                        height: config.height,
587                        scale_factor_snapped: (scale_factor * 64.0) as u32,
588                    }
589                } else {
590                    SurfaceHandle::new_headless(config.width, config.height, scale_factor)
591                }
592            }
593            #[cfg(target_os = "windows")]
594            {
595                SurfaceHandle {
596                    window_id: 2001,
597                    raw_window_ptr: 0x57494E32,  // "WIN2"
598                    raw_display_ptr: 0x47444931, // "GDI1"
599                    width: config.width,
600                    height: config.height,
601                    scale_factor_snapped: (scale_factor * 64.0) as u32,
602                }
603            }
604            #[cfg(target_os = "macos")]
605            {
606                SurfaceHandle {
607                    window_id: 3001,
608                    raw_window_ptr: 0x434F4341,  // "COCA"
609                    raw_display_ptr: 0x4150504C, // "APPL"
610                    width: config.width,
611                    height: config.height,
612                    scale_factor_snapped: (scale_factor * 64.0) as u32,
613                }
614            }
615            #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
616            {
617                SurfaceHandle::new_headless(config.width, config.height, scale_factor)
618            }
619        };
620        let frame_pacer = FramePacer::new(RefreshRate::Hz60);
621        Self {
622            config,
623            surface_config,
624            surface_handle,
625            frame_pacer,
626            scale_factor,
627            is_focused: true,
628            cursor: CursorIcon::Default,
629            redraw_requested: true,
630            event_queue: VecDeque::new(),
631            monitors: vec![MonitorInfo::standard_1080p()],
632            current_monitor_id: Some(1),
633            display_buffer: Vec::new(),
634            is_native_presented: false,
635        }
636    }
637
638    /// Access surface configuration descriptor.
639    pub fn surface_config(&self) -> &SurfaceConfig {
640        &self.surface_config
641    }
642
643    /// Mutable access to frame pacer.
644    pub fn frame_pacer_mut(&mut self) -> &mut FramePacer {
645        &mut self.frame_pacer
646    }
647
648    /// Returns abstract surface handle.
649    pub fn surface_handle(&self) -> SurfaceHandle {
650        self.surface_handle
651    }
652
653    /// Consumes and clears redraw request flag.
654    pub fn take_redraw_request(&mut self) -> bool {
655        let requested = self.redraw_requested;
656        self.redraw_requested = false;
657        requested
658    }
659}
660
661impl PlatformWindow for LivePlatformWindow {
662    fn title(&self) -> &str {
663        &self.config.title
664    }
665
666    fn set_title(&mut self, title: &str) {
667        self.config.title = title.to_string();
668    }
669
670    fn size(&self) -> (u32, u32) {
671        (self.config.width, self.config.height)
672    }
673
674    fn set_size(&mut self, width: u32, height: u32) {
675        self.config.width = width;
676        self.config.height = height;
677        self.surface_config.width = width;
678        self.surface_config.height = height;
679        self.surface_handle.width = width;
680        self.surface_handle.height = height;
681        self.request_redraw();
682        self.push_event(PlatformEvent::WindowResized { width, height });
683    }
684
685    fn scale_factor(&self) -> f32 {
686        self.scale_factor
687    }
688
689    fn set_scale_factor(&mut self, scale_factor: f32) {
690        self.scale_factor = scale_factor;
691        self.surface_config.scale_factor = scale_factor;
692        self.surface_handle.scale_factor_snapped = (scale_factor * 64.0) as u32;
693        self.request_redraw();
694        self.push_event(PlatformEvent::ScaleFactorChanged { scale_factor });
695    }
696
697    fn mode(&self) -> WindowMode {
698        self.config.mode
699    }
700
701    fn set_mode(&mut self, mode: WindowMode) {
702        self.config.mode = mode;
703    }
704
705    fn is_focused(&self) -> bool {
706        self.is_focused
707    }
708
709    fn set_focused(&mut self, focused: bool) {
710        self.is_focused = focused;
711        self.push_event(PlatformEvent::WindowFocused(focused));
712    }
713
714    fn cursor(&self) -> CursorIcon {
715        self.cursor
716    }
717
718    fn set_cursor(&mut self, cursor: CursorIcon) {
719        self.cursor = cursor;
720    }
721
722    fn request_redraw(&mut self) {
723        self.redraw_requested = true;
724    }
725
726    fn is_redraw_requested(&self) -> bool {
727        self.redraw_requested
728    }
729
730    fn poll_events(&mut self) -> Vec<PlatformEvent> {
731        self.event_queue.drain(..).collect()
732    }
733
734    fn push_event(&mut self, event: PlatformEvent) {
735        self.event_queue.push_back(event);
736    }
737
738    fn current_monitor(&self) -> Option<MonitorInfo> {
739        self.current_monitor_id
740            .and_then(|id| self.monitors.iter().find(|m| m.id == id).cloned())
741    }
742
743    fn available_monitors(&self) -> Vec<MonitorInfo> {
744        self.monitors.clone()
745    }
746
747    fn primary_monitor(&self) -> Option<MonitorInfo> {
748        self.monitors.iter().find(|m| m.is_primary).cloned()
749    }
750
751    fn set_ime_cursor_location(&mut self, x: i32, y: i32, width: i32, height: i32) {
752        #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
753        crate::gtk_window::gtk_set_ime_cursor_location(x, y, width, height);
754        #[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
755        let _ = (x, y, width, height);
756    }
757
758    fn set_ime_surrounding_text(&mut self, text: &str, cursor_index: i32) {
759        #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
760        crate::gtk_window::gtk_set_ime_surrounding_text(text, cursor_index);
761        #[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
762        let _ = (text, cursor_index);
763    }
764
765    fn reset_ime(&mut self) {
766        #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
767        crate::gtk_window::gtk_reset_ime();
768    }
769}
770
771impl NativeSurfaceWindow for LivePlatformWindow {
772    fn present_surface(
773        &mut self,
774        pixels: &[u8],
775        width: u32,
776        height: u32,
777    ) -> Result<(), crate::surface::PresentError> {
778        self.redraw_requested = false;
779        let expected_bytes = (width as usize) * (height as usize) * 4;
780        if pixels.len() < expected_bytes {
781            return Err(crate::surface::PresentError::BufferTooSmall);
782        }
783        self.display_buffer.resize(expected_bytes, 0);
784        self.display_buffer
785            .copy_from_slice(&pixels[..expected_bytes]);
786        self.is_native_presented = true;
787        Ok(())
788    }
789}
790
791/// Control flow returned by event loop handlers.
792#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
793pub enum EventLoopControl {
794    #[default]
795    Poll,
796    Wait,
797    WaitUntil(Instant),
798    Exit,
799}
800
801/// Abstract platform event loop trait.
802pub trait EventLoop {
803    fn run<F>(&mut self, handler: F)
804    where
805        F: FnMut(PlatformEvent, &mut EventLoopControl);
806}
807
808/// Headless mock event loop for simulated frame dispatching and testing.
809#[derive(Debug, Default)]
810pub struct MockEventLoop {
811    pending_events: VecDeque<PlatformEvent>,
812    control: EventLoopControl,
813}
814
815impl MockEventLoop {
816    pub fn new() -> Self {
817        Self {
818            pending_events: VecDeque::new(),
819            control: EventLoopControl::Poll,
820        }
821    }
822
823    pub fn queue_event(&mut self, event: PlatformEvent) {
824        self.pending_events.push_back(event);
825    }
826
827    pub fn step<F>(&mut self, mut handler: F) -> EventLoopControl
828    where
829        F: FnMut(PlatformEvent, &mut EventLoopControl),
830    {
831        while let Some(event) = self.pending_events.pop_front() {
832            handler(event, &mut self.control);
833            if self.control == EventLoopControl::Exit {
834                return EventLoopControl::Exit;
835            }
836        }
837        self.control
838    }
839}
840
841impl EventLoop for MockEventLoop {
842    fn run<F>(&mut self, mut handler: F)
843    where
844        F: FnMut(PlatformEvent, &mut EventLoopControl),
845    {
846        while self.control != EventLoopControl::Exit {
847            if self.pending_events.is_empty() {
848                break;
849            }
850            if self.step(&mut handler) == EventLoopControl::Exit {
851                break;
852            }
853        }
854    }
855}