Skip to main content

quickgui/runtime/
window.rs

1use super::*;
2
3/// Defines when closing the final native window should terminate the application.
4///
5/// The default follows native desktop convention: macOS applications stay resident for Dock
6/// reopen and menu commands, while other desktop targets quit with their last window.
7#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
8pub enum QuitMode {
9    /// Use [`Self::Explicit`] on macOS and [`Self::LastWindowClosed`] elsewhere.
10    #[default]
11    Default,
12    /// Quit automatically after the final window and all of its owned children close.
13    LastWindowClosed,
14    /// Stay in the event loop until [`EventContext::exit`] or the operating system quits the app.
15    Explicit,
16}
17
18/// Source of one application-level quit request.
19#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
20pub enum QuitReason {
21    Explicit,
22    Relaunch,
23    LastWindowClosed,
24    OperatingSystem,
25}
26
27/// Immutable input delivered to the preventable before-quit and will-quit callbacks.
28#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
29pub struct QuitRequest {
30    pub reason: QuitReason,
31}
32
33impl QuitMode {
34    pub(super) const fn quits_when_empty(self) -> bool {
35        match self {
36            Self::Default => cfg!(not(target_os = "macos")),
37            Self::LastWindowClosed => true,
38            Self::Explicit => false,
39        }
40    }
41}
42
43/// GPU selection policy. `Balanced` lets WGPU choose the most appropriate adapter.
44#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
45pub enum PerformanceProfile {
46    #[default]
47    Balanced,
48    LowPower,
49    HighPerformance,
50}
51
52/// Effective light or dark appearance of a native window.
53///
54/// QuickGUI intentionally exposes the semantic palette instead of platform appearance names.
55/// Application content can observe this value through [`ViewContext::appearance`], while native
56/// chrome follows the system unless an explicit per-window preference is configured.
57#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
58pub enum WindowAppearance {
59    #[default]
60    Light,
61    Dark,
62}
63
64impl WindowAppearance {
65    pub const fn is_dark(self) -> bool {
66        matches!(self, Self::Dark)
67    }
68}
69
70/// Compositor treatment for pixels not covered by fully opaque application content.
71///
72/// `Transparent` exposes the desktop directly. `Blurred` uses the platform's native background
73/// blur behind the same alpha-capable WGPU surface. Both remain damage-driven; they do not add an
74/// application animation or polling loop.
75#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
76pub enum WindowBackgroundAppearance {
77    #[default]
78    Opaque,
79    Transparent,
80    Blurred,
81}
82
83impl WindowBackgroundAppearance {
84    pub const fn is_transparent(self) -> bool {
85        !matches!(self, Self::Opaque)
86    }
87
88    pub const fn is_blurred(self) -> bool {
89        matches!(self, Self::Blurred)
90    }
91
92    #[cfg(test)]
93    pub(super) const fn changes_from(self, previous: Self) -> WindowBackgroundChanges {
94        WindowBackgroundChanges {
95            transparency: self.is_transparent() != previous.is_transparent(),
96            blur: self.is_blurred() != previous.is_blurred(),
97        }
98    }
99}
100
101#[cfg(test)]
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub(super) struct WindowBackgroundChanges {
104    pub(super) transparency: bool,
105    pub(super) blur: bool,
106}
107
108/// Semantic macOS material rendered behind transparent application pixels.
109///
110/// The variants intentionally match Electron's current `vibrancy` vocabulary while retaining a
111/// typed Rust-core source of truth. On macOS QuickGUI projects these values through one
112/// `NSVisualEffectView`; other platforms retain the requested state without installing a native
113/// effect.
114#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
115pub enum MacOsVibrancy {
116    AppearanceBased,
117    Titlebar,
118    Selection,
119    Menu,
120    Popover,
121    Sidebar,
122    Header,
123    Sheet,
124    Window,
125    Hud,
126    FullscreenUi,
127    Tooltip,
128    Content,
129    UnderWindow,
130    UnderPage,
131}
132
133/// Whether a macOS vibrancy material follows the window's active state.
134#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
135pub enum MacOsVisualEffectState {
136    #[default]
137    FollowWindow,
138    Active,
139    Inactive,
140}
141
142/// Native window titlebar presentation.
143///
144/// `HiddenInset` is currently meaningful on macOS. It keeps the native window controls while
145/// extending application content through a transparent, titleless titlebar.
146#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
147pub enum TitleBarStyle {
148    #[default]
149    Default,
150    HiddenInset,
151    /// Hide native titlebar chrome and let application content own the complete window.
152    Hidden,
153}
154
155/// Native role and parent relationship of a top-level window.
156#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
157pub enum WindowKind {
158    #[default]
159    Normal,
160    /// A high-level utility or notification window.
161    Popover,
162    /// A transient native popover positioned relative to its parent window's content.
163    SystemPopover,
164    /// A utility window that stays above ordinary application windows.
165    Floating,
166    /// A parent-owned modal sheet on macOS.
167    Dialog,
168}
169
170/// Requested native stacking level independent from a window's ownership role.
171///
172/// The first three variants are the portable levels every backend understands. The remaining
173/// variants name AppKit's `NSWindowLevel` constants; other platforms collapse them to the
174/// topmost hint their window manager exposes. [`WindowLevel::macos_level`] documents the exact
175/// mapping and is used by the macOS backend.
176#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
177pub enum WindowLevel {
178    AlwaysOnBottom,
179    #[default]
180    Normal,
181    AlwaysOnTop,
182    /// AppKit `NSFloatingWindowLevel`.
183    Floating,
184    /// AppKit `NSModalPanelWindowLevel`.
185    ModalPanel,
186    /// AppKit `NSMainMenuWindowLevel`.
187    MainMenu,
188    /// AppKit `NSStatusWindowLevel`.
189    Status,
190    /// AppKit `NSPopUpMenuWindowLevel`.
191    PopUpMenu,
192    /// AppKit `NSScreenSaverWindowLevel`.
193    ScreenSaver,
194}
195
196/// Native taskbar progress presentation for one window.
197#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
198pub enum TaskbarProgressState {
199    /// Remove progress from the taskbar button.
200    #[default]
201    None,
202    Normal,
203    Indeterminate,
204    Paused,
205    Error,
206}
207
208/// Native pointer confinement policy for one window.
209#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
210pub enum CursorGrabMode {
211    /// Let the pointer move without confinement.
212    #[default]
213    None,
214    /// Keep the pointer inside the window when the backend supports confinement.
215    Confined,
216    /// Lock the pointer to the window while continuing to report relative movement.
217    Locked,
218}
219
220impl CursorGrabMode {
221    pub(super) const fn to_winit(self) -> WinitCursorGrabMode {
222        match self {
223            Self::None => WinitCursorGrabMode::None,
224            Self::Confined => WinitCursorGrabMode::Confined,
225            Self::Locked => WinitCursorGrabMode::Locked,
226        }
227    }
228}
229
230impl WindowLevel {
231    pub(super) const fn to_winit(self) -> WinitWindowLevel {
232        match self {
233            Self::AlwaysOnBottom => WinitWindowLevel::AlwaysOnBottom,
234            Self::Normal => WinitWindowLevel::Normal,
235            Self::AlwaysOnTop
236            | Self::Floating
237            | Self::ModalPanel
238            | Self::MainMenu
239            | Self::Status
240            | Self::PopUpMenu
241            | Self::ScreenSaver => WinitWindowLevel::AlwaysOnTop,
242        }
243    }
244
245    /// Raw AppKit `NSWindowLevel` for this stacking policy.
246    ///
247    /// `Normal` is `NSNormalWindowLevel` (0), `AlwaysOnBottom` is one level below it, and
248    /// `AlwaysOnTop` shares `NSFloatingWindowLevel` with [`Self::Floating`] so the historical
249    /// portable value keeps its established behavior.
250    pub const fn macos_level(self) -> i32 {
251        match self {
252            Self::AlwaysOnBottom => -1,
253            Self::Normal => 0,
254            Self::AlwaysOnTop | Self::Floating => 3,
255            Self::ModalPanel => 8,
256            Self::MainMenu => 24,
257            Self::Status => 25,
258            Self::PopUpMenu => 101,
259            Self::ScreenSaver => 1_000,
260        }
261    }
262
263    /// Whether this level keeps the window above ordinary application windows.
264    pub const fn is_above_normal(self) -> bool {
265        self.macos_level() > 0
266    }
267}
268
269/// Persistable window state together with its windowed restore geometry.
270#[derive(Clone, Copy, Debug, PartialEq)]
271pub enum WindowBounds {
272    Windowed(Rect),
273    Maximized(Rect),
274    Fullscreen(Rect),
275}
276
277impl WindowBounds {
278    pub const fn bounds(self) -> Rect {
279        match self {
280            Self::Windowed(bounds) | Self::Maximized(bounds) | Self::Fullscreen(bounds) => bounds,
281        }
282    }
283
284    pub const fn windowed(x: f32, y: f32, width: f32, height: f32) -> Self {
285        Self::Windowed(Rect::new(x, y, width, height))
286    }
287}
288
289impl Default for WindowBounds {
290    fn default() -> Self {
291        Self::Windowed(Rect::new(0.0, 0.0, 960.0, 640.0))
292    }
293}
294
295/// Retained native state available during declarative rendering.
296#[derive(Clone, Copy, Debug, PartialEq)]
297pub struct WindowState {
298    pub handle: WindowHandle,
299    /// Display currently containing the native window, when known.
300    pub display_id: Option<DisplayId>,
301    pub kind: WindowKind,
302    pub bounds: WindowBounds,
303    pub viewport_size: Size,
304    /// Effective native minimum inner size, or `None` when unconstrained.
305    pub minimum_size: Option<Size>,
306    /// Effective native maximum inner size, or `None` when unconstrained.
307    pub maximum_size: Option<Size>,
308    pub scale_factor: f32,
309    pub appearance: WindowAppearance,
310    pub background_appearance: WindowBackgroundAppearance,
311    /// Active macOS semantic vibrancy material, when requested.
312    pub macos_vibrancy: Option<MacOsVibrancy>,
313    pub macos_visual_effect_state: MacOsVisualEffectState,
314    pub focused: bool,
315    /// Whether the native window is permitted to receive keyboard focus.
316    pub focusable: bool,
317    pub visible: bool,
318    pub minimized: bool,
319    pub maximized: bool,
320    pub fullscreen: bool,
321    pub occluded: bool,
322    pub movable: bool,
323    pub resizable: bool,
324    pub minimizable: bool,
325    pub maximizable: bool,
326    pub closable: bool,
327    pub decorated: bool,
328    pub shadow: bool,
329    pub content_protected: bool,
330    pub window_level: WindowLevel,
331    /// Whether native pointer events pass through this window to whatever is behind it.
332    pub ignore_mouse_events: bool,
333    /// Whether pointer motion is still delivered to this window while clicks pass through.
334    pub forward_mouse_events: bool,
335    /// Whether the native window currently accepts any input at all.
336    pub window_enabled: bool,
337    /// Retained content aspect ratio as `width:height`, or `None` when unconstrained.
338    pub aspect_ratio: Option<Size>,
339    /// Whether the macOS close/minimize/zoom buttons are visible.
340    pub window_buttons_visible: bool,
341    /// Whether this window is omitted from the taskbar on supported platforms.
342    pub skip_taskbar: bool,
343    /// Whether this window follows the user across virtual desktops/spaces.
344    pub visible_on_all_workspaces: bool,
345    /// Whole-window native alpha in the inclusive `0.0..=1.0` range.
346    pub opacity: f32,
347    /// Whether an explicit native window icon is installed.
348    pub has_icon: bool,
349    /// Retained taskbar progress mode and bounded completion value.
350    pub taskbar_progress_state: TaskbarProgressState,
351    pub taskbar_progress: f32,
352    /// Whether a Windows taskbar overlay icon is installed.
353    pub has_taskbar_overlay_icon: bool,
354    pub cursor_visible: bool,
355    pub cursor_grab: CursorGrabMode,
356    /// Whether the native window participates in pointer hit testing.
357    pub cursor_hit_test: bool,
358    /// Last known pointer position in logical window coordinates.
359    pub cursor_position: Option<Point>,
360    /// Whether the native titlebar currently represents a document file.
361    pub represented_file: bool,
362    /// Whether native chrome indicates that the represented document has unsaved changes.
363    pub document_edited: bool,
364    /// Whether this window opted into native system tabbing.
365    pub native_tabbing: bool,
366    /// Bounded cached state for the native AppKit tab group.
367    pub native_tabs: WindowTabState,
368    /// Whether the feature-gated retained-tree inspector is open for this window.
369    #[cfg(feature = "inspector")]
370    pub inspector_active: bool,
371}
372
373impl WindowState {
374    /// Capture persistable geometry and display identity for this window.
375    ///
376    /// The rectangle is the windowed restore geometry, so a maximized or fullscreen window still
377    /// persists the size it returns to. Pass the result to
378    /// [`WindowOptions::restore`](WindowOptions::restore) on the next launch.
379    pub fn restore_state(&self, displays: &Displays) -> WindowRestoreState {
380        let bounds = self.bounds.bounds();
381        let display = self.display_id.and_then(|id| displays.find(id));
382        WindowRestoreState {
383            x: bounds.x,
384            y: bounds.y,
385            width: bounds.width,
386            height: bounds.height,
387            maximized: self.maximized,
388            fullscreen: self.fullscreen,
389            display_id: self.display_id.map(DisplayId::get),
390            display_uuid: display
391                .and_then(Display::uuid)
392                .map(crate::DisplayUuid::into_bytes),
393            scale_factor: self.scale_factor,
394        }
395    }
396}
397
398/// Maximum UTF-8 bytes accepted for a native window title.
399pub const MAX_WINDOW_TITLE_BYTES: usize = 16 * 1024;
400/// Maximum encoded bytes accepted for a represented document path.
401pub const MAX_WINDOW_DOCUMENT_PATH_BYTES: usize = 16 * 1024;
402/// Maximum UTF-8 bytes accepted for a native window tabbing identifier.
403pub const MAX_WINDOW_TABBING_IDENTIFIER_BYTES: usize = 4 * 1024;
404/// Maximum native tabs inspected or exposed through one retained [`WindowState`].
405pub const MAX_SYSTEM_WINDOW_TABS: usize = 256;
406/// Maximum logical width or height accepted by a programmatic window-bounds request.
407pub const MAX_WINDOW_LOGICAL_DIMENSION: f32 = 32_768.0;
408/// Maximum absolute desktop coordinate accepted by a programmatic window-bounds request.
409pub const MAX_WINDOW_LOGICAL_COORDINATE: f32 = 16_777_216.0;
410/// Maximum ratio between the two components of a window aspect ratio.
411pub const MAX_WINDOW_ASPECT_RATIO: f32 = 1_000.0;
412/// Maximum window mutations one event callback may queue.
413pub const MAX_WINDOW_COMMANDS_PER_EVENT: usize = 256;
414/// Maximum deferred native window mutations retained by one application effect cycle.
415pub const MAX_PENDING_WINDOW_COMMANDS: usize = 1_024;
416/// Maximum declarative child-window close callbacks retained by one parent window.
417pub const MAX_CHILD_WINDOW_CLOSE_LISTENERS_PER_WINDOW: usize = 256;
418/// Maximum handles returned by one immutable application-window registry snapshot.
419pub const MAX_APPLICATION_WINDOWS: usize = 4_096;
420/// Maximum selected native popup menus retained until their callback is routed.
421pub const MAX_PENDING_NATIVE_POPUP_MENUS: usize = 16;
422
423#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
424pub enum WindowCommandError {
425    #[error("this context is not attached to a native window")]
426    Unavailable,
427    #[error("one event cannot queue more than {MAX_WINDOW_COMMANDS_PER_EVENT} window commands")]
428    QueueFull,
429    #[error("window bounds must be finite, positive, and within the supported desktop range")]
430    InvalidBounds,
431    #[error("a window title cannot exceed {MAX_WINDOW_TITLE_BYTES} UTF-8 bytes")]
432    TitleTooLong,
433    #[error(
434        "a represented document path must be non-empty, NUL-free, and at most {MAX_WINDOW_DOCUMENT_PATH_BYTES} encoded bytes"
435    )]
436    InvalidDocumentPath,
437    #[error(
438        "a native tabbing identifier must be non-empty, NUL-free, and at most {MAX_WINDOW_TABBING_IDENTIFIER_BYTES} UTF-8 bytes"
439    )]
440    InvalidTabbingIdentifier,
441    #[error("a native tab index must be smaller than {MAX_SYSTEM_WINDOW_TABS}")]
442    InvalidTabIndex,
443    #[error("a hidden titlebar cannot expose or reposition native traffic-light buttons")]
444    HiddenTitleBarTrafficLights,
445    #[error("system popovers require one finite parent-relative popover configuration")]
446    InvalidPopoverConfiguration,
447    #[error("a system popover must be opened from an existing parent window")]
448    PopoverParentRequired,
449    #[error("minimum window size cannot exceed maximum window size")]
450    InvalidSizeConstraints,
451    #[error("window opacity must be finite and between 0.0 and 1.0")]
452    InvalidOpacity,
453    #[error("taskbar progress must be finite and between 0.0 and 1.0")]
454    InvalidTaskbarProgress,
455    #[error(
456        "a taskbar overlay description must be NUL-free and at most {MAX_TASKBAR_OVERLAY_DESCRIPTION_BYTES} UTF-8 bytes"
457    )]
458    InvalidTaskbarOverlayDescription,
459    #[error("the per-window native menu declaration is invalid")]
460    InvalidMenus,
461    #[error(
462        "a window aspect ratio must be finite, positive, and within {MAX_WINDOW_ASPECT_RATIO}:1"
463    )]
464    InvalidAspectRatio,
465    #[error("a window cannot be ordered above itself")]
466    InvalidWindowOrder,
467}
468
469/// Constant-size snapshot of one native system window-tab group.
470///
471/// AppKit can technically retain an arbitrary number of windows. QuickGUI inspects at most
472/// [`MAX_SYSTEM_WINDOW_TABS`] at an event boundary and reports `truncated` rather than allocating
473/// a per-frame list.
474#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
475pub struct WindowTabState {
476    pub count: usize,
477    pub selected_index: Option<usize>,
478    pub tab_bar_visible: bool,
479    pub overview_visible: bool,
480    pub truncated: bool,
481}
482
483impl Default for WindowTabState {
484    fn default() -> Self {
485        Self {
486            count: 1,
487            selected_index: Some(0),
488            tab_bar_visible: false,
489            overview_visible: false,
490            truncated: false,
491        }
492    }
493}
494
495impl WindowTabState {
496    pub const fn is_valid(self) -> bool {
497        self.count > 0
498            && self.count <= MAX_SYSTEM_WINDOW_TABS
499            && match self.selected_index {
500                Some(index) => index < self.count,
501                None => true,
502            }
503    }
504}
505
506static NEXT_WINDOW_HANDLE: AtomicU64 = AtomicU64::new(1);
507
508/// Stable application-level identity for a QuickGUI window.
509///
510/// Unlike Winit's native identifier, this handle exists before the platform window is created and
511/// can therefore be returned immediately from [`EventContext::open_window`](crate::EventContext::open_window).
512#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
513pub struct WindowHandle(u64);
514
515impl WindowHandle {
516    pub(crate) fn next() -> Self {
517        Self(NEXT_WINDOW_HANDLE.fetch_add(1, Ordering::Relaxed).max(1))
518    }
519
520    pub const fn as_u64(self) -> u64 {
521        self.0
522    }
523
524    pub const fn from_u64(value: u64) -> Option<Self> {
525        if value == 0 { None } else { Some(Self(value)) }
526    }
527}
528
529/// Immutable bounded application-wide window lookup captured at one core event boundary.
530#[derive(Clone, Debug, Default, Eq, PartialEq)]
531pub struct WindowRegistry {
532    handles: Arc<[WindowHandle]>,
533    active_window: Option<WindowHandle>,
534    truncated: bool,
535}
536
537impl WindowRegistry {
538    pub(crate) fn new(
539        handles: impl Into<Arc<[WindowHandle]>>,
540        active_window: Option<WindowHandle>,
541        truncated: bool,
542    ) -> Self {
543        Self {
544            handles: handles.into(),
545            active_window,
546            truncated,
547        }
548    }
549
550    pub fn windows(&self) -> &[WindowHandle] {
551        &self.handles
552    }
553
554    pub const fn active_window(&self) -> Option<WindowHandle> {
555        self.active_window
556    }
557
558    pub fn contains(&self, handle: WindowHandle) -> bool {
559        self.handles.binary_search(&handle).is_ok()
560    }
561
562    pub const fn is_truncated(&self) -> bool {
563        self.truncated
564    }
565}
566
567/// Initial native and renderer configuration for a window opened by [`App`].
568#[derive(Clone, Debug)]
569pub struct WindowOptions {
570    pub title: String,
571    pub size: Size,
572    pub window_bounds: Option<WindowBounds>,
573    /// Preferred display for default placement and borderless fullscreen.
574    ///
575    /// A disconnected or unknown display falls back to the current primary display.
576    pub display_id: Option<DisplayId>,
577    pub minimum_size: Option<Size>,
578    pub maximum_size: Option<Size>,
579    /// File represented by native document chrome, if any.
580    pub represented_file: Option<PathBuf>,
581    /// Initial unsaved-document indication in native chrome.
582    pub document_edited: bool,
583    /// Non-empty identifier opting this window into native system tabbing.
584    pub tabbing_identifier: Option<String>,
585    pub background: Color,
586    /// Native compositor treatment behind transparent application pixels.
587    pub window_background: WindowBackgroundAppearance,
588    /// macOS semantic material behind the alpha-capable application surface.
589    pub macos_vibrancy: Option<MacOsVibrancy>,
590    /// Activity-state policy for [`Self::macos_vibrancy`].
591    pub macos_visual_effect_state: MacOsVisualEffectState,
592    pub performance_profile: PerformanceProfile,
593    /// Explicit native light/dark preference. `None` follows the current system appearance.
594    pub preferred_appearance: Option<WindowAppearance>,
595    pub title_bar_style: TitleBarStyle,
596    pub kind: WindowKind,
597    /// Parent-relative native placement when `kind` is [`WindowKind::SystemPopover`].
598    pub popover: Option<crate::PopoverOptions>,
599    pub focus: bool,
600    /// Whether the window may receive native keyboard focus after creation.
601    pub focusable: bool,
602    pub show: bool,
603    pub is_movable: bool,
604    pub is_resizable: bool,
605    pub is_minimizable: bool,
606    pub is_maximizable: bool,
607    pub is_closable: bool,
608    /// Whether native border and titlebar decorations are present.
609    pub decorated: bool,
610    /// Requested native shadow. Some platforms always draw decorated-window shadows.
611    pub shadow: bool,
612    /// Prevent supported desktop capture APIs from reading this window's contents.
613    pub content_protected: bool,
614    /// Explicit stacking override. `None` derives a role-appropriate level from [`Self::kind`].
615    pub window_level: Option<WindowLevel>,
616    /// Let native pointer events pass through this window to whatever is behind it.
617    pub ignore_mouse_events: bool,
618    /// Keep delivering pointer motion while [`Self::ignore_mouse_events`] passes clicks through.
619    pub forward_mouse_events: bool,
620    /// Whether the native window accepts input at all. A disabled window stays visible.
621    pub window_enabled: bool,
622    /// Content aspect ratio as `width:height`. `None` leaves resizing unconstrained.
623    pub aspect_ratio: Option<Size>,
624    /// Whether the macOS close/minimize/zoom buttons are visible.
625    pub window_buttons_visible: bool,
626    /// Hide the per-window taskbar entry where the platform exposes one.
627    pub skip_taskbar: bool,
628    /// Keep the window visible on every virtual desktop/space where supported.
629    pub visible_on_all_workspaces: bool,
630    /// Whole-window native alpha.
631    pub opacity: f32,
632    /// Native window icon. macOS uses an application icon rather than per-window icons.
633    pub icon: Option<Image>,
634    /// Initial Windows taskbar progress and overlay state.
635    pub taskbar_progress_state: TaskbarProgressState,
636    pub taskbar_progress: f32,
637    pub taskbar_overlay_icon: Option<Image>,
638    pub taskbar_overlay_description: Option<String>,
639    /// Initial pointer visibility and confinement policy.
640    pub cursor_visible: bool,
641    pub cursor_grab: CursorGrabMode,
642    /// Whether pointer events hit this native window.
643    pub cursor_hit_test: bool,
644    /// Optional initial logical pointer position relative to the window.
645    pub cursor_position: Option<Point>,
646    /// Per-window native menus. `None` inherits the application's current menu declaration.
647    pub window_menus: Option<Vec<Menu>>,
648    /// Top-left position of the macOS close button, in logical points from the window's top-left.
649    pub traffic_light_position: Option<Point>,
650    /// Logical pixels represented by one platform line-wheel unit.
651    pub line_scroll_pixels: f32,
652    /// How long an incomplete multi-stroke key binding waits before its prefix is replayed.
653    pub key_sequence_timeout: Duration,
654    /// Disable non-essential image animation. macOS Reduce Motion is always respected as well.
655    pub reduce_motion: bool,
656    /// Open the retained-tree inspector with this window.
657    #[cfg(feature = "inspector")]
658    pub inspector: bool,
659}
660
661impl Default for WindowOptions {
662    fn default() -> Self {
663        Self {
664            title: "QuickGUI".to_owned(),
665            size: Size::new(960.0, 640.0),
666            window_bounds: None,
667            display_id: None,
668            minimum_size: Some(Size::new(320.0, 240.0)),
669            maximum_size: None,
670            represented_file: None,
671            document_edited: false,
672            tabbing_identifier: None,
673            background: Color::rgb8(18, 18, 20),
674            window_background: WindowBackgroundAppearance::Opaque,
675            macos_vibrancy: None,
676            macos_visual_effect_state: MacOsVisualEffectState::FollowWindow,
677            performance_profile: PerformanceProfile::Balanced,
678            preferred_appearance: None,
679            title_bar_style: TitleBarStyle::Default,
680            kind: WindowKind::Normal,
681            popover: None,
682            focus: true,
683            focusable: true,
684            show: true,
685            is_movable: true,
686            is_resizable: true,
687            is_minimizable: true,
688            is_maximizable: true,
689            is_closable: true,
690            decorated: true,
691            shadow: true,
692            content_protected: false,
693            window_level: None,
694            ignore_mouse_events: false,
695            forward_mouse_events: false,
696            window_enabled: true,
697            aspect_ratio: None,
698            window_buttons_visible: true,
699            skip_taskbar: false,
700            visible_on_all_workspaces: false,
701            opacity: 1.0,
702            icon: None,
703            taskbar_progress_state: TaskbarProgressState::None,
704            taskbar_progress: 0.0,
705            taskbar_overlay_icon: None,
706            taskbar_overlay_description: None,
707            cursor_visible: true,
708            cursor_grab: CursorGrabMode::None,
709            cursor_hit_test: true,
710            cursor_position: None,
711            window_menus: None,
712            traffic_light_position: None,
713            line_scroll_pixels: 40.0,
714            key_sequence_timeout: Duration::from_secs(1),
715            reduce_motion: false,
716            #[cfg(feature = "inspector")]
717            inspector: false,
718        }
719    }
720}
721
722impl WindowOptions {
723    /// Create window options with a title and otherwise production-safe defaults.
724    pub fn new(title: impl Into<String>) -> Self {
725        Self {
726            title: title.into(),
727            ..Self::default()
728        }
729    }
730
731    pub fn title(mut self, title: impl Into<String>) -> Self {
732        self.title = title.into();
733        self
734    }
735
736    pub fn size(mut self, width: f32, height: f32) -> Self {
737        self.size = Size::new(width, height);
738        if let Some(bounds) = &mut self.window_bounds {
739            let state = *bounds;
740            let rect = state.bounds();
741            let rect = Rect::new(rect.x, rect.y, width, height);
742            *bounds = match state {
743                WindowBounds::Windowed(_) => WindowBounds::Windowed(rect),
744                WindowBounds::Maximized(_) => WindowBounds::Maximized(rect),
745                WindowBounds::Fullscreen(_) => WindowBounds::Fullscreen(rect),
746            };
747        }
748        self
749    }
750
751    pub fn window_bounds(mut self, bounds: WindowBounds) -> Self {
752        let rect = bounds.bounds();
753        self.size = Size::new(rect.width, rect.height);
754        self.window_bounds = Some(bounds);
755        self
756    }
757
758    pub fn position(mut self, x: f32, y: f32) -> Self {
759        let bounds = self
760            .window_bounds
761            .unwrap_or_else(|| WindowBounds::Windowed(Rect::from_size(self.size)));
762        let rect = bounds.bounds();
763        let rect = Rect::new(x, y, rect.width, rect.height);
764        self.window_bounds = Some(match bounds {
765            WindowBounds::Windowed(_) => WindowBounds::Windowed(rect),
766            WindowBounds::Maximized(_) => WindowBounds::Maximized(rect),
767            WindowBounds::Fullscreen(_) => WindowBounds::Fullscreen(rect),
768        });
769        self
770    }
771
772    /// Select the display used for automatic placement and fullscreen creation.
773    pub fn display(mut self, display: DisplayId) -> Self {
774        self.display_id = Some(display);
775        self
776    }
777
778    pub fn without_display(mut self) -> Self {
779        self.display_id = None;
780        self
781    }
782
783    pub fn maximized(mut self, maximized: bool) -> Self {
784        let rect = self
785            .window_bounds
786            .map(WindowBounds::bounds)
787            .unwrap_or_else(|| Rect::from_size(self.size));
788        self.window_bounds = Some(if maximized {
789            WindowBounds::Maximized(rect)
790        } else {
791            WindowBounds::Windowed(rect)
792        });
793        self
794    }
795
796    pub fn fullscreen(mut self, fullscreen: bool) -> Self {
797        let rect = self
798            .window_bounds
799            .map(WindowBounds::bounds)
800            .unwrap_or_else(|| Rect::from_size(self.size));
801        self.window_bounds = Some(if fullscreen {
802            WindowBounds::Fullscreen(rect)
803        } else {
804            WindowBounds::Windowed(rect)
805        });
806        self
807    }
808
809    pub fn minimum_size(mut self, width: f32, height: f32) -> Self {
810        self.minimum_size = Some(Size::new(width, height));
811        self
812    }
813
814    pub fn without_minimum_size(mut self) -> Self {
815        self.minimum_size = None;
816        self
817    }
818
819    pub fn maximum_size(mut self, width: f32, height: f32) -> Self {
820        self.maximum_size = Some(Size::new(width, height));
821        self
822    }
823
824    pub fn without_maximum_size(mut self) -> Self {
825        self.maximum_size = None;
826        self
827    }
828
829    /// Represent a file in native document chrome.
830    pub fn represented_file(mut self, path: impl Into<PathBuf>) -> Self {
831        self.represented_file = Some(path.into());
832        self
833    }
834
835    /// GPUI-compatible alias for [`Self::represented_file`].
836    pub fn document_path(self, path: impl Into<PathBuf>) -> Self {
837        self.represented_file(path)
838    }
839
840    pub fn without_represented_file(mut self) -> Self {
841        self.represented_file = None;
842        self
843    }
844
845    /// Override the application's native menus for this window.
846    pub fn window_menus(mut self, menus: impl IntoIterator<Item = Menu>) -> Self {
847        self.window_menus = Some(menus.into_iter().collect());
848        self
849    }
850
851    /// Inherit the application's native menus, including later app-wide replacements.
852    pub fn use_application_menus(mut self) -> Self {
853        self.window_menus = None;
854        self
855    }
856
857    pub fn document_edited(mut self, edited: bool) -> Self {
858        self.document_edited = edited;
859        self
860    }
861
862    /// Opt this window into AppKit system tabbing with an application-defined group identifier.
863    pub fn tabbing_identifier(mut self, identifier: impl Into<String>) -> Self {
864        self.tabbing_identifier = Some(identifier.into());
865        self
866    }
867
868    pub fn without_tabbing_identifier(mut self) -> Self {
869        self.tabbing_identifier = None;
870        self
871    }
872
873    pub fn background(mut self, background: Color) -> Self {
874        self.background = background;
875        self
876    }
877
878    pub fn window_background(mut self, appearance: WindowBackgroundAppearance) -> Self {
879        self.window_background = appearance;
880        self
881    }
882
883    pub(super) const fn uses_transparent_surface(&self) -> bool {
884        self.window_background.is_transparent()
885            || (cfg!(target_os = "macos") && self.macos_vibrancy.is_some())
886    }
887
888    pub(super) const fn uses_legacy_background_blur(&self) -> bool {
889        self.window_background.is_blurred()
890            && !(cfg!(target_os = "macos") && self.macos_vibrancy.is_some())
891    }
892
893    /// Apply one Electron-compatible semantic vibrancy material on macOS.
894    pub fn macos_vibrancy(mut self, vibrancy: MacOsVibrancy) -> Self {
895        self.macos_vibrancy = Some(vibrancy);
896        self
897    }
898
899    pub fn without_macos_vibrancy(mut self) -> Self {
900        self.macos_vibrancy = None;
901        self
902    }
903
904    pub fn macos_visual_effect_state(mut self, state: MacOsVisualEffectState) -> Self {
905        self.macos_visual_effect_state = state;
906        self
907    }
908
909    pub fn performance_profile(mut self, profile: PerformanceProfile) -> Self {
910        self.performance_profile = profile;
911        self
912    }
913
914    /// Force this window's native chrome to use one appearance.
915    pub fn window_appearance(mut self, appearance: WindowAppearance) -> Self {
916        self.preferred_appearance = Some(appearance);
917        self
918    }
919
920    /// Follow the operating system's effective light/dark appearance.
921    pub fn follow_system_appearance(mut self) -> Self {
922        self.preferred_appearance = None;
923        self
924    }
925
926    pub fn title_bar_style(mut self, style: TitleBarStyle) -> Self {
927        self.title_bar_style = style;
928        self.decorated = style != TitleBarStyle::Hidden;
929        self
930    }
931
932    pub fn window_kind(mut self, kind: WindowKind) -> Self {
933        self.kind = kind;
934        if kind != WindowKind::SystemPopover {
935            self.popover = None;
936        }
937        self
938    }
939
940    /// Configure a borderless native `SystemPopover`.
941    ///
942    /// Menu-style grabs focus the panel and dismiss on Escape or an outside mouse press.
943    /// Non-grabbing popovers install no event monitor; `PopoverOptions::accepts_key_focus` independently
944    /// decides whether pointer interaction may make the panel key.
945    pub fn system_popover(mut self, popover: crate::PopoverOptions) -> Self {
946        self.kind = WindowKind::SystemPopover;
947        self.focus = popover.grab;
948        self.focusable = popover.accepts_key_focus;
949        self.popover = Some(popover);
950        self.minimum_size = None;
951        self.maximum_size = None;
952        self.title_bar_style = TitleBarStyle::Hidden;
953        self.decorated = false;
954        self.traffic_light_position = None;
955        self.is_movable = false;
956        self.is_resizable = false;
957        self.is_minimizable = false;
958        self.is_maximizable = false;
959        self.is_closable = false;
960        self
961    }
962
963    pub fn focus(mut self, focus: bool) -> Self {
964        self.focus = focus;
965        self
966    }
967
968    /// Allow or prevent this window from receiving native keyboard focus.
969    pub fn focusable(mut self, focusable: bool) -> Self {
970        self.focusable = focusable;
971        if !focusable {
972            self.focus = false;
973        }
974        self
975    }
976
977    pub fn show(mut self, show: bool) -> Self {
978        self.show = show;
979        self
980    }
981
982    pub fn movable(mut self, movable: bool) -> Self {
983        self.is_movable = movable;
984        self
985    }
986
987    pub fn resizable(mut self, resizable: bool) -> Self {
988        self.is_resizable = resizable;
989        self
990    }
991
992    pub fn minimizable(mut self, minimizable: bool) -> Self {
993        self.is_minimizable = minimizable;
994        self
995    }
996
997    pub fn maximizable(mut self, maximizable: bool) -> Self {
998        self.is_maximizable = maximizable;
999        self
1000    }
1001
1002    pub fn closable(mut self, closable: bool) -> Self {
1003        self.is_closable = closable;
1004        self
1005    }
1006
1007    pub fn decorations(mut self, decorated: bool) -> Self {
1008        self.decorated = decorated;
1009        if !decorated {
1010            self.title_bar_style = TitleBarStyle::Hidden;
1011            self.traffic_light_position = None;
1012        } else if self.title_bar_style == TitleBarStyle::Hidden {
1013            self.title_bar_style = TitleBarStyle::Default;
1014        }
1015        self
1016    }
1017
1018    pub fn shadow(mut self, shadow: bool) -> Self {
1019        self.shadow = shadow;
1020        self
1021    }
1022
1023    pub fn content_protected(mut self, protected: bool) -> Self {
1024        self.content_protected = protected;
1025        self
1026    }
1027
1028    pub fn window_level(mut self, level: WindowLevel) -> Self {
1029        self.window_level = Some(level);
1030        self
1031    }
1032
1033    pub fn automatic_window_level(mut self) -> Self {
1034        self.window_level = None;
1035        self
1036    }
1037
1038    pub fn skip_taskbar(mut self, skip: bool) -> Self {
1039        self.skip_taskbar = skip;
1040        self
1041    }
1042
1043    pub fn visible_on_all_workspaces(mut self, visible: bool) -> Self {
1044        self.visible_on_all_workspaces = visible;
1045        self
1046    }
1047
1048    /// Set whole-window native opacity. Invalid values are rejected when the window is opened.
1049    pub fn opacity(mut self, opacity: f32) -> Self {
1050        self.opacity = opacity;
1051        self
1052    }
1053
1054    pub fn icon(mut self, icon: Image) -> Self {
1055        self.icon = Some(icon);
1056        self
1057    }
1058
1059    pub fn without_icon(mut self) -> Self {
1060        self.icon = None;
1061        self
1062    }
1063
1064    pub fn taskbar_progress(mut self, state: TaskbarProgressState, progress: f32) -> Self {
1065        self.taskbar_progress_state = state;
1066        self.taskbar_progress = progress;
1067        self
1068    }
1069
1070    pub fn taskbar_overlay_icon(mut self, icon: Image, description: impl Into<String>) -> Self {
1071        self.taskbar_overlay_icon = Some(icon);
1072        self.taskbar_overlay_description = Some(description.into());
1073        self
1074    }
1075
1076    pub fn without_taskbar_overlay_icon(mut self) -> Self {
1077        self.taskbar_overlay_icon = None;
1078        self.taskbar_overlay_description = None;
1079        self
1080    }
1081
1082    pub fn cursor_visible(mut self, visible: bool) -> Self {
1083        self.cursor_visible = visible;
1084        self
1085    }
1086
1087    pub fn cursor_grab(mut self, mode: CursorGrabMode) -> Self {
1088        self.cursor_grab = mode;
1089        self
1090    }
1091
1092    pub fn cursor_hit_test(mut self, hit_test: bool) -> Self {
1093        self.cursor_hit_test = hit_test;
1094        self
1095    }
1096
1097    pub fn cursor_position(mut self, position: Point) -> Self {
1098        self.cursor_position = Some(position);
1099        self
1100    }
1101
1102    pub fn without_cursor_position(mut self) -> Self {
1103        self.cursor_position = None;
1104        self
1105    }
1106
1107    pub fn always_on_top(self, always_on_top: bool) -> Self {
1108        self.window_level(if always_on_top {
1109            WindowLevel::AlwaysOnTop
1110        } else {
1111            WindowLevel::Normal
1112        })
1113    }
1114
1115    pub fn always_on_bottom(self, always_on_bottom: bool) -> Self {
1116        self.window_level(if always_on_bottom {
1117            WindowLevel::AlwaysOnBottom
1118        } else {
1119            WindowLevel::Normal
1120        })
1121    }
1122
1123    /// Position the macOS traffic lights in logical points from the window's top-left.
1124    ///
1125    /// The close button uses this exact position; minimize and zoom retain native spacing.
1126    pub fn traffic_light_position(mut self, x: f32, y: f32) -> Self {
1127        self.traffic_light_position = Some(Point::new(x, y));
1128        self
1129    }
1130
1131    pub fn without_traffic_light_position(mut self) -> Self {
1132        self.traffic_light_position = None;
1133        self
1134    }
1135
1136    pub fn reduce_motion(mut self, reduce_motion: bool) -> Self {
1137        self.reduce_motion = reduce_motion;
1138        self
1139    }
1140
1141    /// Open or suppress the retained-tree inspector when this window is created.
1142    #[cfg(feature = "inspector")]
1143    pub fn inspector(mut self, inspector: bool) -> Self {
1144        self.inspector = inspector;
1145        self
1146    }
1147
1148    /// Let clicks fall through this window to whatever is behind it.
1149    ///
1150    /// `forward` keeps pointer motion and hover events flowing to this window while every button
1151    /// press reaches the window below. `false` makes the window completely inert to the pointer.
1152    pub fn ignore_mouse_events(mut self, ignore: bool, forward: bool) -> Self {
1153        self.ignore_mouse_events = ignore;
1154        self.forward_mouse_events = ignore && forward;
1155        self
1156    }
1157
1158    /// Block every native input event while keeping the window visible.
1159    pub fn window_enabled(mut self, enabled: bool) -> Self {
1160        self.window_enabled = enabled;
1161        self
1162    }
1163
1164    /// Constrain live resizing to one `width:height` content aspect ratio.
1165    pub fn aspect_ratio(mut self, width: f32, height: f32) -> Self {
1166        self.aspect_ratio = Some(Size::new(width, height));
1167        self
1168    }
1169
1170    pub fn without_aspect_ratio(mut self) -> Self {
1171        self.aspect_ratio = None;
1172        self
1173    }
1174
1175    /// Show or hide the macOS close/minimize/zoom buttons without removing the titlebar.
1176    pub fn window_button_visibility(mut self, visible: bool) -> Self {
1177        self.window_buttons_visible = visible;
1178        self
1179    }
1180
1181    /// Restore persisted geometry, validating it against the currently connected displays.
1182    ///
1183    /// Bounds that no longer intersect a connected display work area are clamped into the
1184    /// remembered display when it is still present, and otherwise centered on the primary
1185    /// display. See [`WindowRestoreState`].
1186    pub fn restore(mut self, state: &WindowRestoreState, displays: &Displays) -> Self {
1187        let resolved = state.resolve(displays);
1188        self.window_bounds = Some(resolved.bounds);
1189        self.size = Size::new(
1190            resolved.bounds.bounds().width,
1191            resolved.bounds.bounds().height,
1192        );
1193        self.display_id = resolved.display_id;
1194        self
1195    }
1196}
1197
1198/// Persistable window geometry and display identity.
1199///
1200/// Capture it with [`WindowState::restore_state`] and apply it with [`WindowOptions::restore`].
1201/// The struct is `serde`-serializable so an application can store it next to its own settings.
1202/// Every field is validated on the way back in; a stale or hostile value can never place a
1203/// window off every connected display.
1204#[derive(Clone, Copy, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
1205pub struct WindowRestoreState {
1206    /// Windowed restore rectangle in global logical desktop coordinates.
1207    pub x: f32,
1208    pub y: f32,
1209    pub width: f32,
1210    pub height: f32,
1211    pub maximized: bool,
1212    pub fullscreen: bool,
1213    /// Process-level display identifier captured with the bounds, when one was known.
1214    pub display_id: Option<u64>,
1215    /// Stable physical display identity captured with the bounds, when the platform exposes one.
1216    pub display_uuid: Option<[u8; 16]>,
1217    /// Scale factor of the capturing display, used only as a sanity signal.
1218    pub scale_factor: f32,
1219}
1220
1221/// Outcome of validating a [`WindowRestoreState`] against the current display snapshot.
1222#[derive(Clone, Copy, Debug, PartialEq)]
1223pub struct ResolvedWindowRestoreState {
1224    pub bounds: WindowBounds,
1225    pub display_id: Option<DisplayId>,
1226    /// Whether the persisted rectangle had to be clamped or re-centered.
1227    pub adjusted: bool,
1228}
1229
1230impl WindowRestoreState {
1231    /// Build a restore state from an explicit windowed rectangle.
1232    pub const fn new(bounds: Rect) -> Self {
1233        Self {
1234            x: bounds.x,
1235            y: bounds.y,
1236            width: bounds.width,
1237            height: bounds.height,
1238            maximized: false,
1239            fullscreen: false,
1240            display_id: None,
1241            display_uuid: None,
1242            scale_factor: 1.0,
1243        }
1244    }
1245
1246    /// Persisted windowed rectangle in global logical desktop coordinates.
1247    pub const fn bounds(&self) -> Rect {
1248        Rect::new(self.x, self.y, self.width, self.height)
1249    }
1250
1251    /// Whether the persisted values are finite and inside the supported desktop range.
1252    pub fn is_valid(&self) -> bool {
1253        validate_window_bounds(WindowBounds::Windowed(self.bounds())).is_ok()
1254            && self.scale_factor.is_finite()
1255            && self.scale_factor > 0.0
1256    }
1257
1258    /// Resolve this state against a live display snapshot.
1259    ///
1260    /// The remembered display is matched by stable UUID first and by process identifier second.
1261    /// A rectangle that still intersects that display's work area is kept exactly; otherwise it
1262    /// is clamped into the work area. When no remembered display is connected and the rectangle
1263    /// intersects no work area at all, the window is centered on the primary display.
1264    pub fn resolve(&self, displays: &Displays) -> ResolvedWindowRestoreState {
1265        let requested = self.bounds();
1266        let valid = self.is_valid();
1267        let remembered = if valid {
1268            self.display_uuid
1269                .and_then(|uuid| {
1270                    let uuid = crate::DisplayUuid::from_bytes(uuid);
1271                    displays
1272                        .all()
1273                        .iter()
1274                        .find(|display| display.uuid() == Some(uuid))
1275                })
1276                .or_else(|| {
1277                    self.display_id
1278                        .and_then(|id| displays.find(DisplayId::new(id)))
1279                })
1280        } else {
1281            None
1282        };
1283        let intersecting = valid
1284            .then(|| {
1285                displays
1286                    .all()
1287                    .iter()
1288                    .find(|display| display.visible_bounds().intersection(requested).is_some())
1289            })
1290            .flatten();
1291        let (rect, display, adjusted) = match (valid, remembered, intersecting) {
1292            (false, _, _) => match displays.primary() {
1293                Some(primary) => (
1294                    primary.centered_bounds(Size::new(960.0, 640.0)),
1295                    Some(primary.id()),
1296                    true,
1297                ),
1298                None => (Rect::new(0.0, 0.0, 960.0, 640.0), None, true),
1299            },
1300            (true, Some(display), _)
1301                if display.visible_bounds().intersection(requested).is_some() =>
1302            {
1303                (requested, Some(display.id()), false)
1304            }
1305            (true, Some(display), _) => (
1306                display.constrain_bounds(requested),
1307                Some(display.id()),
1308                true,
1309            ),
1310            (true, None, Some(display)) => (requested, Some(display.id()), false),
1311            (true, None, None) => match displays.primary() {
1312                Some(primary) => (
1313                    primary.centered_bounds(Size::new(requested.width, requested.height)),
1314                    Some(primary.id()),
1315                    true,
1316                ),
1317                None => (requested, None, false),
1318            },
1319        };
1320        let bounds = if self.fullscreen {
1321            WindowBounds::Fullscreen(rect)
1322        } else if self.maximized {
1323            WindowBounds::Maximized(rect)
1324        } else {
1325            WindowBounds::Windowed(rect)
1326        };
1327        ResolvedWindowRestoreState {
1328            bounds,
1329            display_id: display,
1330            adjusted,
1331        }
1332    }
1333}
1334
1335pub(crate) fn validate_window_bounds(bounds: WindowBounds) -> Result<(), WindowCommandError> {
1336    let bounds = bounds.bounds();
1337    let valid = bounds.x.is_finite()
1338        && bounds.y.is_finite()
1339        && bounds.width.is_finite()
1340        && bounds.height.is_finite()
1341        && bounds.x.abs() <= MAX_WINDOW_LOGICAL_COORDINATE
1342        && bounds.y.abs() <= MAX_WINDOW_LOGICAL_COORDINATE
1343        && bounds.width > 0.0
1344        && bounds.height > 0.0
1345        && bounds.width <= MAX_WINDOW_LOGICAL_DIMENSION
1346        && bounds.height <= MAX_WINDOW_LOGICAL_DIMENSION;
1347    if valid {
1348        Ok(())
1349    } else {
1350        Err(WindowCommandError::InvalidBounds)
1351    }
1352}
1353
1354pub(crate) fn validate_window_aspect_ratio(ratio: Option<Size>) -> Result<(), WindowCommandError> {
1355    let Some(ratio) = ratio else {
1356        return Ok(());
1357    };
1358    let valid = ratio.width.is_finite()
1359        && ratio.height.is_finite()
1360        && ratio.width > 0.0
1361        && ratio.height > 0.0
1362        && ratio.width / ratio.height <= MAX_WINDOW_ASPECT_RATIO
1363        && ratio.height / ratio.width <= MAX_WINDOW_ASPECT_RATIO;
1364    if valid {
1365        Ok(())
1366    } else {
1367        Err(WindowCommandError::InvalidAspectRatio)
1368    }
1369}
1370
1371/// Clamp one inner size to a `width:height` aspect ratio, preserving its area as closely as the
1372/// portable fallback allows. The width is authoritative because horizontal edge drags are the
1373/// common interactive resize.
1374pub(crate) fn clamp_size_to_aspect_ratio(size: Size, ratio: Size) -> Size {
1375    if !(ratio.width > 0.0
1376        && ratio.height > 0.0
1377        && ratio.width.is_finite()
1378        && ratio.height.is_finite())
1379    {
1380        return size;
1381    }
1382    let width = size.width.max(1.0);
1383    Size::new(width, (width * ratio.height / ratio.width).max(1.0))
1384}
1385
1386pub(crate) fn validate_window_size(size: Size) -> Result<(), WindowCommandError> {
1387    validate_window_bounds(WindowBounds::Windowed(Rect::from_size(size)))
1388}
1389
1390pub(crate) fn validate_window_position(position: Point) -> Result<(), WindowCommandError> {
1391    validate_window_bounds(WindowBounds::Windowed(Rect::new(
1392        position.x, position.y, 1.0, 1.0,
1393    )))
1394}
1395
1396pub(crate) fn validate_window_title(title: &str) -> Result<(), WindowCommandError> {
1397    if title.len() <= MAX_WINDOW_TITLE_BYTES {
1398        Ok(())
1399    } else {
1400        Err(WindowCommandError::TitleTooLong)
1401    }
1402}
1403
1404pub(crate) fn validate_window_document_path(path: &Path) -> Result<(), WindowCommandError> {
1405    let bytes = path.as_os_str().as_encoded_bytes();
1406    if !bytes.is_empty() && bytes.len() <= MAX_WINDOW_DOCUMENT_PATH_BYTES && !bytes.contains(&0) {
1407        Ok(())
1408    } else {
1409        Err(WindowCommandError::InvalidDocumentPath)
1410    }
1411}
1412
1413pub(crate) fn validate_window_tabbing_identifier(
1414    identifier: &str,
1415) -> Result<(), WindowCommandError> {
1416    if !identifier.is_empty()
1417        && identifier.len() <= MAX_WINDOW_TABBING_IDENTIFIER_BYTES
1418        && !identifier.as_bytes().contains(&0)
1419    {
1420        Ok(())
1421    } else {
1422        Err(WindowCommandError::InvalidTabbingIdentifier)
1423    }
1424}
1425
1426pub(super) fn validate_window_options(options: &WindowOptions) -> Result<(), WindowCommandError> {
1427    validate_window_title(&options.title)?;
1428    validate_window_size(options.size)?;
1429    if let Some(bounds) = options.window_bounds {
1430        validate_window_bounds(bounds)?;
1431    }
1432    if let Some(minimum) = options.minimum_size {
1433        validate_window_size(minimum)?;
1434    }
1435    if let Some(maximum) = options.maximum_size {
1436        validate_window_size(maximum)?;
1437    }
1438    validate_window_opacity(options.opacity)?;
1439    validate_window_aspect_ratio(options.aspect_ratio)?;
1440    validate_taskbar_progress(options.taskbar_progress)?;
1441    validate_taskbar_overlay_description(options.taskbar_overlay_description.as_deref())?;
1442    if let Some(position) = options.cursor_position {
1443        validate_window_position(position)?;
1444    }
1445    if let (Some(minimum), Some(maximum)) = (options.minimum_size, options.maximum_size)
1446        && (minimum.width > maximum.width || minimum.height > maximum.height)
1447    {
1448        return Err(WindowCommandError::InvalidSizeConstraints);
1449    }
1450    if let Some(path) = options.represented_file.as_deref() {
1451        validate_window_document_path(path)?;
1452    }
1453    if let Some(identifier) = options.tabbing_identifier.as_deref() {
1454        validate_window_tabbing_identifier(identifier)?;
1455    }
1456    if let Some(menus) = options.window_menus.as_deref() {
1457        validate_menus(menus).map_err(|_| WindowCommandError::InvalidMenus)?;
1458    }
1459    if options.title_bar_style == TitleBarStyle::Hidden && options.traffic_light_position.is_some()
1460    {
1461        return Err(WindowCommandError::HiddenTitleBarTrafficLights);
1462    }
1463    match (options.kind, options.popover.as_ref()) {
1464        (WindowKind::SystemPopover, Some(popover))
1465            if popover.is_valid(MAX_WINDOW_LOGICAL_COORDINATE, MAX_WINDOW_LOGICAL_DIMENSION)
1466                && !options.decorated
1467                && options.title_bar_style == TitleBarStyle::Hidden
1468                && options.minimum_size.is_none()
1469                && options.maximum_size.is_none()
1470                && !options.is_movable
1471                && !options.is_resizable
1472                && !options.is_minimizable
1473                && !options.is_maximizable
1474                && !options.is_closable
1475                && !matches!(
1476                    options.window_bounds,
1477                    Some(WindowBounds::Maximized(_) | WindowBounds::Fullscreen(_))
1478                ) => {}
1479        (WindowKind::SystemPopover, _) | (_, Some(_)) => {
1480            return Err(WindowCommandError::InvalidPopoverConfiguration);
1481        }
1482        (_, None) => {}
1483    }
1484    Ok(())
1485}
1486
1487pub(crate) fn validate_window_opacity(opacity: f32) -> Result<(), WindowCommandError> {
1488    if opacity.is_finite() && (0.0..=1.0).contains(&opacity) {
1489        Ok(())
1490    } else {
1491        Err(WindowCommandError::InvalidOpacity)
1492    }
1493}
1494
1495pub(crate) fn validate_taskbar_progress(progress: f32) -> Result<(), WindowCommandError> {
1496    if progress.is_finite() && (0.0..=1.0).contains(&progress) {
1497        Ok(())
1498    } else {
1499        Err(WindowCommandError::InvalidTaskbarProgress)
1500    }
1501}
1502
1503pub(crate) fn validate_taskbar_overlay_description(
1504    description: Option<&str>,
1505) -> Result<(), WindowCommandError> {
1506    if description.is_some_and(|description| {
1507        description.len() > crate::MAX_TASKBAR_OVERLAY_DESCRIPTION_BYTES
1508            || description.as_bytes().contains(&0)
1509    }) {
1510        Err(WindowCommandError::InvalidTaskbarOverlayDescription)
1511    } else {
1512        Ok(())
1513    }
1514}
1515
1516/// A retained application view. It is only rendered after explicit invalidation or OS damage.
1517pub trait View: Sized + 'static {
1518    fn event(&mut self, _event: &Event, _cx: &mut EventContext) {}
1519    fn render(&mut self, cx: &mut ViewContext<'_, Self>) -> impl IntoElement;
1520    /// Embedding renderers can rebuild a subtree declared with `ViewContext::with_scope`.
1521    /// Return `None` when a mutation needs an ordinary full declaration instead.
1522    fn render_scope(&mut self, _id: ElementId, _cx: &mut ViewContext<'_, Self>) -> Option<Element> {
1523        None
1524    }
1525}
1526
1527pub(super) trait AnyView {
1528    fn event(&mut self, event: &Event, cx: &mut EventContext);
1529    fn render_scopes(&mut self, cx: &mut ViewContext<'_, ()>) -> Option<Vec<crate::ElementUpdate>>;
1530
1531    #[allow(clippy::too_many_arguments)]
1532    fn render(
1533        &mut self,
1534        size: Size,
1535        scale_factor: f32,
1536        metrics: FrameMetrics,
1537        focused: Option<ElementId>,
1538        focused_path: Vec<ElementId>,
1539        listeners: &mut ListenerRegistry,
1540        window: WindowHandle,
1541        window_state: WindowState,
1542        displays: &Displays,
1543        keyboard_layout: &KeyboardLayout,
1544        assets: &Assets,
1545        app_info: Option<&AppInfo>,
1546        app_paths: Option<&AppPaths>,
1547        system_info: &SystemInfo,
1548        system_preferences: &SystemPreferences,
1549        background_tasks: Option<&BackgroundTaskPoolHandle>,
1550        foreground_tasks: &ForegroundTaskSpawner,
1551        globals: &GlobalStore,
1552        event_proxy: Option<&EventLoopProxy<RuntimeEvent>>,
1553    ) -> (Element, bool, Option<Instant>);
1554
1555    fn as_any_mut(&mut self) -> &mut dyn Any;
1556
1557    #[cfg(any(test, feature = "test-support"))]
1558    fn as_any(&self) -> &dyn Any;
1559}
1560
1561pub(super) struct ViewAdapter<V>(V);
1562
1563impl<V: View> AnyView for ViewAdapter<V> {
1564    fn event(&mut self, event: &Event, cx: &mut EventContext) {
1565        self.0.event(event, cx);
1566    }
1567
1568    fn render_scopes(&mut self, cx: &mut ViewContext<'_, ()>) -> Option<Vec<crate::ElementUpdate>> {
1569        cx.with_type::<V, _>(|cx| {
1570            let roots = cx.listeners.prepare_component_updates();
1571            let mut updates = Vec::with_capacity(roots.len());
1572            for scope in roots {
1573                let id = scope.id;
1574                updates.push(cx.refresh_component(scope, |cx| self.0.render_scope(id, cx))?);
1575            }
1576            Some(updates)
1577        })
1578    }
1579
1580    fn render(
1581        &mut self,
1582        size: Size,
1583        scale_factor: f32,
1584        metrics: FrameMetrics,
1585        focused: Option<ElementId>,
1586        focused_path: Vec<ElementId>,
1587        listeners: &mut ListenerRegistry,
1588        window: WindowHandle,
1589        window_state: WindowState,
1590        displays: &Displays,
1591        keyboard_layout: &KeyboardLayout,
1592        assets: &Assets,
1593        app_info: Option<&AppInfo>,
1594        app_paths: Option<&AppPaths>,
1595        system_info: &SystemInfo,
1596        system_preferences: &SystemPreferences,
1597        background_tasks: Option<&BackgroundTaskPoolHandle>,
1598        foreground_tasks: &ForegroundTaskSpawner,
1599        globals: &GlobalStore,
1600        event_proxy: Option<&EventLoopProxy<RuntimeEvent>>,
1601    ) -> (Element, bool, Option<Instant>) {
1602        let mut cx = ViewContext::<V> {
1603            size,
1604            scale_factor,
1605            metrics,
1606            focused,
1607            focused_path,
1608            request_animation_frame: false,
1609            repaint_deadline: None,
1610            listeners,
1611            window,
1612            window_state,
1613            displays,
1614            keyboard_layout,
1615            assets,
1616            app_info,
1617            app_paths,
1618            system_info,
1619            system_preferences,
1620            background_tasks,
1621            foreground_tasks,
1622            globals,
1623            event_proxy,
1624            marker: PhantomData,
1625        };
1626        cx.listeners.clear();
1627        let root = self.0.render(&mut cx).into_element();
1628        cx.listeners.retain_components(&root, None);
1629        (root, cx.request_animation_frame, cx.repaint_deadline)
1630    }
1631
1632    fn as_any_mut(&mut self) -> &mut dyn Any {
1633        &mut self.0
1634    }
1635
1636    #[cfg(any(test, feature = "test-support"))]
1637    fn as_any(&self) -> &dyn Any {
1638        &self.0
1639    }
1640}
1641
1642pub(crate) struct WindowRequest {
1643    pub(crate) handle: WindowHandle,
1644    pub(super) view: Box<dyn AnyView>,
1645    pub(crate) options: WindowOptions,
1646    pub(crate) parent: Option<WindowHandle>,
1647    /// Resolve this anchor from the parent window's retained layout at the event boundary and
1648    /// retain it as the focus-restoration target for the child lifetime.
1649    pub(crate) popover_anchor_element: Option<ElementId>,
1650    #[cfg(all(target_os = "macos", feature = "swift-ui"))]
1651    pub(crate) embedded: Option<crate::MacEmbeddedView>,
1652}
1653
1654impl WindowRequest {
1655    pub(crate) fn new<V: View>(view: V, options: WindowOptions) -> Self {
1656        Self::with_parent(view, options, None)
1657    }
1658
1659    pub(crate) fn with_parent<V: View>(
1660        view: V,
1661        options: WindowOptions,
1662        parent: Option<WindowHandle>,
1663    ) -> Self {
1664        Self::with_handle(view, options, parent, WindowHandle::next())
1665    }
1666
1667    pub(crate) fn with_handle<V: View>(
1668        view: V,
1669        options: WindowOptions,
1670        parent: Option<WindowHandle>,
1671        handle: WindowHandle,
1672    ) -> Self {
1673        Self {
1674            handle,
1675            view: Box::new(ViewAdapter(view)),
1676            options,
1677            parent,
1678            popover_anchor_element: None,
1679            #[cfg(all(target_os = "macos", feature = "swift-ui"))]
1680            embedded: None,
1681        }
1682    }
1683}
1684
1685impl fmt::Debug for WindowRequest {
1686    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1687        let mut debug = formatter.debug_struct("WindowRequest");
1688        debug
1689            .field("handle", &self.handle)
1690            .field("parent", &self.parent)
1691            .field("popover_anchor_element", &self.popover_anchor_element);
1692        #[cfg(all(target_os = "macos", feature = "swift-ui"))]
1693        debug.field("embedded", &self.embedded);
1694        debug
1695            .field("options", &self.options)
1696            .finish_non_exhaustive()
1697    }
1698}
1699
1700#[derive(Debug)]
1701pub(crate) enum WindowCommand {
1702    SetTitle(WindowHandle, String),
1703    SetRepresentedFile(WindowHandle, Option<PathBuf>),
1704    SetDocumentEdited(WindowHandle, bool),
1705    ShowCharacterPalette(WindowHandle),
1706    /// Present the platform dictionary definition for the focused text input's selection.
1707    LookUpSelection(WindowHandle),
1708    SetTabbingIdentifier(WindowHandle, Option<String>),
1709    SelectNextTab(WindowHandle),
1710    SelectPreviousTab(WindowHandle),
1711    SelectTab(WindowHandle, usize),
1712    MergeAllWindows(WindowHandle),
1713    MoveTabToNewWindow(WindowHandle),
1714    ToggleTabBar(WindowHandle),
1715    ToggleTabOverview(WindowHandle),
1716    SetBounds(WindowHandle, WindowBounds),
1717    Move(WindowHandle, Point),
1718    Resize(WindowHandle, Size),
1719    Minimize(WindowHandle),
1720    Restore(WindowHandle),
1721    Zoom(WindowHandle),
1722    ToggleFullscreen(WindowHandle),
1723    SetFullscreen(WindowHandle, bool),
1724    SetVisible(WindowHandle, bool),
1725    SetMovable(WindowHandle, bool),
1726    SetResizable(WindowHandle, bool),
1727    SetMinimumSize(WindowHandle, Option<Size>),
1728    SetMaximumSize(WindowHandle, Option<Size>),
1729    SetMinimizable(WindowHandle, bool),
1730    SetMaximizable(WindowHandle, bool),
1731    SetClosable(WindowHandle, bool),
1732    SetDecorated(WindowHandle, bool),
1733    SetShadow(WindowHandle, bool),
1734    SetContentProtected(WindowHandle, bool),
1735    SetWindowLevel(WindowHandle, Option<WindowLevel>),
1736    MoveToTop(WindowHandle),
1737    MoveAbove(WindowHandle, WindowHandle),
1738    SetIgnoreMouseEvents(WindowHandle, bool, bool),
1739    SetWindowEnabled(WindowHandle, bool),
1740    SetAspectRatio(WindowHandle, Option<Size>),
1741    SetWindowButtonVisibility(WindowHandle, bool),
1742    SetFocusable(WindowHandle, bool),
1743    SetSkipTaskbar(WindowHandle, bool),
1744    SetVisibleOnAllWorkspaces(WindowHandle, bool),
1745    SetOpacity(WindowHandle, f32),
1746    SetIcon(WindowHandle, Option<Image>),
1747    SetTaskbarProgress(WindowHandle, TaskbarProgressState, f32),
1748    SetTaskbarOverlayIcon(WindowHandle, Option<Image>, Option<String>),
1749    SetCursorVisible(WindowHandle, bool),
1750    SetCursorGrab(WindowHandle, CursorGrabMode),
1751    SetCursorHitTest(WindowHandle, bool),
1752    SetCursorPosition(WindowHandle, Point),
1753    SetAppearance(WindowHandle, Option<WindowAppearance>),
1754    SetBackgroundAppearance(WindowHandle, WindowBackgroundAppearance),
1755    SetMacOsVibrancy(WindowHandle, Option<MacOsVibrancy>),
1756    SetMacOsVisualEffectState(WindowHandle, MacOsVisualEffectState),
1757    #[cfg(feature = "inspector")]
1758    SetInspector(WindowHandle, bool),
1759    #[cfg(feature = "inspector")]
1760    ToggleInspector(WindowHandle),
1761    RequestAttention(WindowHandle),
1762}
1763
1764impl WindowCommand {
1765    pub(crate) fn handle(&self) -> WindowHandle {
1766        match self {
1767            Self::SetTitle(handle, _)
1768            | Self::SetRepresentedFile(handle, _)
1769            | Self::SetDocumentEdited(handle, _)
1770            | Self::ShowCharacterPalette(handle)
1771            | Self::LookUpSelection(handle)
1772            | Self::SetTabbingIdentifier(handle, _)
1773            | Self::SelectNextTab(handle)
1774            | Self::SelectPreviousTab(handle)
1775            | Self::SelectTab(handle, _)
1776            | Self::MergeAllWindows(handle)
1777            | Self::MoveTabToNewWindow(handle)
1778            | Self::ToggleTabBar(handle)
1779            | Self::ToggleTabOverview(handle)
1780            | Self::SetBounds(handle, _)
1781            | Self::Move(handle, _)
1782            | Self::Resize(handle, _)
1783            | Self::Minimize(handle)
1784            | Self::Restore(handle)
1785            | Self::Zoom(handle)
1786            | Self::ToggleFullscreen(handle)
1787            | Self::SetFullscreen(handle, _)
1788            | Self::SetVisible(handle, _)
1789            | Self::SetMovable(handle, _)
1790            | Self::SetResizable(handle, _)
1791            | Self::SetMinimumSize(handle, _)
1792            | Self::SetMaximumSize(handle, _)
1793            | Self::SetMinimizable(handle, _)
1794            | Self::SetMaximizable(handle, _)
1795            | Self::SetClosable(handle, _)
1796            | Self::SetDecorated(handle, _)
1797            | Self::SetShadow(handle, _)
1798            | Self::SetContentProtected(handle, _)
1799            | Self::SetWindowLevel(handle, _)
1800            | Self::MoveToTop(handle)
1801            | Self::MoveAbove(handle, _)
1802            | Self::SetIgnoreMouseEvents(handle, _, _)
1803            | Self::SetWindowEnabled(handle, _)
1804            | Self::SetAspectRatio(handle, _)
1805            | Self::SetWindowButtonVisibility(handle, _)
1806            | Self::SetFocusable(handle, _)
1807            | Self::SetSkipTaskbar(handle, _)
1808            | Self::SetVisibleOnAllWorkspaces(handle, _)
1809            | Self::SetOpacity(handle, _)
1810            | Self::SetIcon(handle, _)
1811            | Self::SetTaskbarProgress(handle, _, _)
1812            | Self::SetTaskbarOverlayIcon(handle, _, _)
1813            | Self::SetCursorVisible(handle, _)
1814            | Self::SetCursorGrab(handle, _)
1815            | Self::SetCursorHitTest(handle, _)
1816            | Self::SetCursorPosition(handle, _)
1817            | Self::SetAppearance(handle, _)
1818            | Self::SetBackgroundAppearance(handle, _)
1819            | Self::SetMacOsVibrancy(handle, _)
1820            | Self::SetMacOsVisualEffectState(handle, _)
1821            | Self::RequestAttention(handle) => *handle,
1822            #[cfg(feature = "inspector")]
1823            Self::SetInspector(handle, _) | Self::ToggleInspector(handle) => *handle,
1824        }
1825    }
1826}