Skip to main content

nsh_core/desktop/
window.rs

1//! An app's windows (TS `nsh/desktop`'s `Window`, `WindowRef` and
2//! `currentWindow()`; Rust [`crate::element::desktop::window`]).
3//!
4//! Every window of an app renders from the app's one engine: the main
5//! window is the root, every other window a dialog root (a `modal` node)
6//! the platform shows in a window of its own. A window's kind
7//! ([`WindowKind`]) is a set of defaults for its attributes
8//! ([`WindowAttributes::for_kind`]); the core resolves them, keeps one
9//! record of each window's attributes and sends the platform what changed
10//! once per commit ([`DesktopCommand::SetAttributes`](super::DesktopCommand)).
11//! What the user also changes (the bounds, the mode, being open) starts
12//! from the options ([`WindowOptions`]), changes through requests
13//! ([`WindowRequest`]) and comes back as events ([`WindowEvent`]).
14
15use super::{DisplayId, TitleBarStyle, WindowLevel, WindowPlacement, WindowState};
16use crate::{
17    NodeId,
18    element::{JsHost, JsIn, JsKind, JsObject, JsOwned, JsValue, PropEnum, PropError, TsTypes},
19    geometry::{Edges, Percentage, Point, Points, Size},
20};
21
22/// What a window is for: a set of defaults its attributes start from
23/// ([`WindowAttributes::for_kind`]); any attribute set overrides its kind's.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
25pub enum WindowKind {
26    /// The main window and document windows: in the taskbar, activates
27    /// when it opens, resizable, minimizable and maximizable.
28    #[default]
29    Normal,
30    /// Settings, an about box, a confirmation: owned by the window that
31    /// opened it and centered on it, neither minimizable nor maximizable,
32    /// closed by Escape, not in the taskbar.
33    Dialog,
34    /// An inspector, a palette, a tool window: floats over its parent, not
35    /// in the taskbar.
36    Panel,
37    /// A launcher, a tray popover, a command palette: no frame, floats on
38    /// every workspace, closed by Escape and when it loses the focus, not
39    /// in the taskbar.
40    Popup,
41    /// A HUD, captions, annotations: transparent, lets the pointer through,
42    /// never takes the focus, above everything on every workspace. Needs
43    /// the `windows` capability's `overlay`.
44    Overlay,
45}
46
47/// A window's mode (TS `WindowMode`). Minimized is apart from it: a
48/// maximized window that is minimized comes back maximized.
49#[derive(
50    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum, serde::Serialize, serde::Deserialize,
51)]
52#[serde(rename_all = "camelCase")]
53pub enum WindowMode {
54    /// A window of its own size.
55    #[default]
56    Normal,
57    /// Maximized (zoomed on macOS).
58    Maximized,
59    /// In full screen.
60    FullScreen,
61}
62
63/// How the user asked to close a window (`closePress`'s `reason`).
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
65pub enum CloseReason {
66    /// The window's close button (the system's or a view marked
67    /// `windowControl: "close"`).
68    #[default]
69    CloseButton,
70    /// The platform's close key (Command-W, Alt-F4).
71    Shortcut,
72    /// A menu's close item (the window menu, the Dock's or the taskbar's).
73    Menu,
74    /// The taskbar's or the window switcher's close action.
75    Taskbar,
76    /// The system: logging out, shutting down.
77    System,
78}
79
80/// Why a window of the app's own closed (`<Window>`'s `onOpenChange`'s
81/// `reason`): one of the platform's ([`WindowEvent::Closed`]), or the
82/// app's `close()`.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
84pub enum WindowCloseCause {
85    /// The user closed it ([`CloseReason`]) and `closeOnPress` let it close.
86    #[default]
87    ClosePress,
88    /// Escape, with `closeOnEscape`.
89    Escape,
90    /// It lost the focus, with `closeOnBlur`.
91    Blur,
92    /// Its parent closed.
93    ParentClose,
94    /// The app closed it (`WindowRef.close()`): `<Window>` reports it too,
95    /// so the app's `open` state follows. Never from the platform.
96    Close,
97}
98
99/// On which workspaces (macOS Spaces, virtual desktops) a window shows.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
101pub enum Workspaces {
102    /// The one it opened on.
103    #[default]
104    Current,
105    /// Every one.
106    All,
107}
108
109/// Whether a window takes the pointer (the names of a view's
110/// `pointerEvents`).
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
112pub enum WindowPointerEvents {
113    /// It takes the pointer.
114    #[default]
115    Auto,
116    /// Presses and the pointer go through it to what is below. Needs the
117    /// `windows` capability's `overlay`.
118    None,
119    /// Its root view is `box-none`: the window takes the pointer where it
120    /// is over a view in the root that takes it under the views' own
121    /// rules (`hidden`, `pointerEvents`, `hitSlop`, `overflow`), and lets
122    /// it through to what is below everywhere else, as if the window were
123    /// not there. Like a view's `box-none`, a view that fills the root
124    /// still takes the pointer unless it is `box-none` (or `none`) itself;
125    /// a background does not decide it. Needs the `windows` capability's
126    /// `overlay`. Every desktop lets the pointer through this way; on
127    /// Linux a rotated or skewed view and a rounded `clipPath` count by the
128    /// box around them.
129    #[prop(rename = "box-none")]
130    BoxNone,
131}
132
133/// The system material behind a window's content, named for what it is
134/// for; each platform maps it to its own (macOS's visual effect materials,
135/// Windows 11's Mica, Mica Alt and Acrylic).
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
137pub enum Backdrop {
138    /// No material: the window's own background.
139    #[default]
140    None,
141    /// A window's background material.
142    Window,
143    /// A sidebar's.
144    Sidebar,
145    /// A popover's.
146    Popover,
147    /// A heads-up display's.
148    Hud,
149}
150
151/// The state of a window's progress on the taskbar or the Dock.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
153pub enum ProgressState {
154    /// Running.
155    #[default]
156    Normal,
157    /// Running, without a known share done.
158    Indeterminate,
159    /// Paused.
160    Paused,
161    /// Failed.
162    Error,
163}
164
165/// A window's progress, shown on its taskbar button or the Dock's icon.
166#[non_exhaustive]
167#[derive(Debug, Clone, Copy, PartialEq, Default, JsObject)]
168pub struct WindowProgress {
169    /// The share done, from 0 to 1.
170    pub value: Option<Percentage>,
171    /// Its state.
172    #[prop(default)]
173    pub state: ProgressState,
174}
175
176/// The title bar a window has (`titleBar`).
177#[non_exhaustive]
178#[derive(Debug, Clone, Copy, PartialEq, Default, JsObject)]
179pub struct TitleBarOptions {
180    /// `Default`: the system's title bar; `Hidden`: the app draws its own,
181    /// filling the window up to its top edge.
182    #[prop(default)]
183    pub style: TitleBarStyle,
184    /// The app's bar's height in points, the system's window controls
185    /// centered in it; the platform's own without it.
186    pub height: Option<Points>,
187    /// Where the system's window controls go in a hidden title bar, from the
188    /// window's top left corner (macOS's traffic lights).
189    pub controls_offset: Option<Point<Points>>,
190}
191
192/// How a window follows its content's laid-out size (`sizeToContent`).
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
194pub enum SizeToContent {
195    /// It keeps the size it is given.
196    #[default]
197    Off,
198    /// Its width and height follow the content's.
199    Both,
200    /// Its width follows the content's.
201    Width,
202    /// Its height follows the content's.
203    Height,
204}
205
206/// TS: `boolean | "width" | "height"`.
207impl JsValue for SizeToContent {
208    fn ts_type(_types: &mut TsTypes) -> String {
209        "boolean | \"width\" | \"height\"".into()
210    }
211
212    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
213        if let Some(on) = value.as_bool() {
214            return Ok(if on {
215                SizeToContent::Both
216            } else {
217                SizeToContent::Off
218            });
219        }
220        match value.as_string().as_deref() {
221            Some("width") => Ok(SizeToContent::Width),
222            Some("height") => Ok(SizeToContent::Height),
223            _ => Err(value.expected("a boolean, \"width\" or \"height\"")),
224        }
225    }
226
227    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
228        match self {
229            SizeToContent::Off => false.to_js(host),
230            SizeToContent::Both => true.to_js(host),
231            SizeToContent::Width => "width".to_owned().to_js(host),
232            SizeToContent::Height => "height".to_owned().to_js(host),
233        }
234    }
235}
236
237/// Where a window opens (`defaultPosition`).
238#[derive(Debug, Clone, Copy, PartialEq)]
239pub enum WindowPosition {
240    /// Its top left corner at this point, in screen coordinates.
241    At(Point<Points>),
242    /// Centered on its display.
243    Center,
244    /// Centered on its parent.
245    ParentCenter,
246}
247
248/// TS: `Point | "center" | "parentCenter"`.
249impl JsValue for WindowPosition {
250    fn ts_type(_types: &mut TsTypes) -> String {
251        "Point | \"center\" | \"parentCenter\"".into()
252    }
253
254    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
255        match value.as_string().as_deref() {
256            Some("center") => Ok(WindowPosition::Center),
257            Some("parentCenter") => Ok(WindowPosition::ParentCenter),
258            Some(_) => Err(value.expected("a point, \"center\" or \"parentCenter\"")),
259            None => Point::<Points>::from_js(value).map(WindowPosition::At),
260        }
261    }
262
263    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
264        match self {
265            WindowPosition::At(point) => point.to_js(host),
266            WindowPosition::Center => "center".to_owned().to_js(host),
267            WindowPosition::ParentCenter => "parentCenter".to_owned().to_js(host),
268        }
269    }
270}
271
272/// A view of a title bar the app draws that acts as one of the system's
273/// window buttons (`desktop={{ windowControl }}`): the platform hit-tests it
274/// as that button (Windows 11's snap layouts show over a maximize button)
275/// and carries out its press; assistive technologies see the button.
276#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
277pub enum WindowControl {
278    /// Minimizes the window.
279    Minimize,
280    /// Maximizes the window, or restores it.
281    Maximize,
282    /// Closes the window, as its close button (`closeOnPress` applies).
283    Close,
284}
285
286/// An edge or a corner of a frameless window that a view resizes it by
287/// (`desktop={{ windowResize }}`).
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
289pub enum ResizeEdge {
290    /// The top edge.
291    Top,
292    /// The bottom edge.
293    Bottom,
294    /// The left edge.
295    Left,
296    /// The right edge.
297    Right,
298    /// The top left corner.
299    TopLeft,
300    /// The top right corner.
301    TopRight,
302    /// The bottom left corner.
303    BottomLeft,
304    /// The bottom right corner.
305    BottomRight,
306}
307
308/// Declares [`WindowAttributes`] with its fields' JS names, and its
309/// merging, diffing and conversions. A field is an `Option`: set or not
310/// (a partial, a diff); a nullable attribute is an `Option<Option<_>>`,
311/// `Some(None)` clearing it (`null` in JS).
312macro_rules! attributes {
313    (
314        $(
315            $(#[doc = $doc:literal])*
316            $field:ident: $ty:ty = $js:literal, $nullable:tt;
317        )*
318    ) => {
319        /// What only the app changes of a window (TS `WindowAttributes`):
320        /// `<Window>`'s reactive props, `WindowRef.set()`'s argument, and
321        /// the diff the core sends the platform. Every field is optional:
322        /// one left out is not changed. A window's kind gives every
323        /// attribute a default ([`WindowAttributes::for_kind`]).
324        #[non_exhaustive]
325        #[derive(Debug, Clone, PartialEq, Default)]
326        pub struct WindowAttributes {
327            $(
328                $(#[doc = $doc])*
329                pub $field: Option<$ty>,
330            )*
331        }
332
333        impl WindowAttributes {
334            /// The JS names of the attributes, in declaration order.
335            pub const NAMES: &'static [&'static str] = &[$($js),*];
336
337            /// Sets the fields `other` sets.
338            pub fn merge(&mut self, other: &WindowAttributes) {
339                $(
340                    if let Some(v) = &other.$field {
341                        self.$field = Some(v.clone());
342                    }
343                )*
344            }
345
346            /// The fields of `next` that differ from `self` (what was sent):
347            /// `None` when nothing does.
348            pub fn diff(&self, next: &WindowAttributes) -> Option<WindowAttributes> {
349                let mut out = WindowAttributes::default();
350                let mut any = false;
351                $(
352                    if next.$field.is_some() && next.$field != self.$field {
353                        out.$field = next.$field.clone();
354                        any = true;
355                    }
356                )*
357                any.then_some(out)
358            }
359
360            /// No field is set.
361            pub fn is_empty(&self) -> bool {
362                true $(&& self.$field.is_none())*
363            }
364
365            /// Declares TS `WindowAttributes` in `types`, each attribute
366            /// with its doc.
367            pub(crate) fn declare(types: &mut TsTypes) -> String {
368                types.declare("WindowAttributes", |types| {
369                    let mut out = String::from(
370                        "/** What only the app changes of a window: `<Window>`'s props and\n \
371                         * `WindowRef.set()`'s argument. Its kind gives every attribute a\n \
372                         * default. */\nexport interface WindowAttributes {\n",
373                    );
374                    $(
375                        out.push_str("  /**");
376                        let docs: &[&str] = &[$($doc),*];
377                        for (i, line) in docs.iter().enumerate() {
378                            if i > 0 {
379                                out.push_str("\n   *");
380                            }
381                            out.push_str(line);
382                        }
383                        out.push_str(" */\n");
384                        out.push_str(&format!(
385                            "  {}: {};\n",
386                            $js,
387                            <$ty as JsValue>::ts_type(types)
388                        ));
389                    )*
390                    out.push('}');
391                    out
392                })
393            }
394
395            /// The JS names of the fields set.
396            pub fn names(&self) -> Vec<&'static str> {
397                let mut out = Vec::new();
398                $(
399                    if self.$field.is_some() {
400                        out.push($js);
401                    }
402                )*
403                out
404            }
405        }
406
407        /// TS: `WindowAttributes` (declared by `nsh/desktop`), a partial
408        /// one: left-out keys are unchanged, `null` clears a nullable one.
409        impl JsValue for WindowAttributes {
410            fn ts_type(_types: &mut TsTypes) -> String {
411                "Partial<WindowAttributes>".into()
412            }
413
414            fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
415                if value.kind() != JsKind::Object {
416                    return Err(value.expected("an object of window attributes"));
417                }
418                let mut out = WindowAttributes::default();
419                $(
420                    out.$field = attributes!(@read $nullable value, $js, $ty)?;
421                )*
422                Ok(out)
423            }
424
425            fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
426                let owned = JsOwned::new(host, host.new_object()?);
427                let object = owned.get().raw();
428                $(
429                    if let Some(v) = &self.$field {
430                        host.set_field(object, $js, v.to_js(host)?.into_raw())?;
431                    }
432                )*
433                Ok(owned)
434            }
435        }
436    };
437    (@read plain $value:ident, $js:literal, $ty:ty) => {{
438        let v = $value.field($js)?;
439        let v = v.get();
440        if v.kind() == JsKind::Undefined {
441            Ok(None)
442        } else {
443            <$ty>::from_js(v)
444                .map(Some)
445                .map_err(|e| PropError(format!("`{}`: {e}", $js)))
446        }
447    }};
448    (@read nullable $value:ident, $js:literal, $ty:ty) => {{
449        let v = $value.field($js)?;
450        let v = v.get();
451        if v.kind() == JsKind::Undefined {
452            Ok(None)
453        } else {
454            <$ty>::from_js(v)
455                .map(Some)
456                .map_err(|e| PropError(format!("`{}`: {e}", $js)))
457        }
458    }};
459}
460
461attributes! {
462    /// Shown in the title bar, the taskbar, the window switcher and to
463    /// assistive technologies.
464    title: String = "title", plain;
465    /// The title bar: the system's, or hidden for one the app draws.
466    title_bar: TitleBarOptions = "titleBar", plain;
467    /// The system's frame (title bar and border), or none.
468    frame: super::WindowFrameStyle = "frame", plain;
469    /// The least size the user may give it (content size, points).
470    min_size: Option<Size<Points>> = "minSize", nullable;
471    /// The largest size the user may give it (content size, points).
472    max_size: Option<Size<Points>> = "maxSize", nullable;
473    /// The ratio of width to height the user's resizes keep its content
474    /// at (`16 / 9`); the app's own `setBounds` is not limited.
475    aspect_ratio: Option<f32> = "aspectRatio", nullable;
476    /// The window follows its content's laid-out size.
477    size_to_content: SizeToContent = "sizeToContent", plain;
478    /// The user may resize it.
479    resizable: bool = "resizable", plain;
480    /// The user may move it.
481    movable: bool = "movable", plain;
482    /// The user may minimize it.
483    minimizable: bool = "minimizable", plain;
484    /// The user may maximize it.
485    maximizable: bool = "maximizable", plain;
486    /// The user may close it.
487    closable: bool = "closable", plain;
488    /// It takes the keyboard focus.
489    focusable: bool = "focusable", plain;
490    /// It activates (and takes the focus) when it opens or shows.
491    activate: bool = "activate", plain;
492    /// A press of its close button (or the close key) closes it at once;
493    /// `false`: the app hears `closePress` and closes it when it decides.
494    close_on_press: bool = "closeOnPress", plain;
495    /// Escape closes it.
496    close_on_escape: bool = "closeOnEscape", plain;
497    /// Losing the focus closes it.
498    close_on_blur: bool = "closeOnBlur", plain;
499    /// How high it floats.
500    level: WindowLevel = "level", plain;
501    /// It shows in the taskbar.
502    taskbar: bool = "taskbar", plain;
503    /// The workspaces it shows on.
504    workspaces: Workspaces = "workspaces", plain;
505    /// Whether it takes the pointer.
506    pointer_events: WindowPointerEvents = "pointerEvents", plain;
507    /// Its background is transparent.
508    transparent: bool = "transparent", plain;
509    /// The system material behind its content.
510    backdrop: Backdrop = "backdrop", plain;
511    /// The system's shadow around it.
512    shadow: bool = "shadow", plain;
513    /// Progress on its taskbar button or the Dock's icon.
514    progress: Option<WindowProgress> = "progress", nullable;
515}
516
517// `window().attributes(WindowAttributes { .. })`: a static value.
518crate::static_reactive!(WindowAttributes: WindowAttributes);
519
520impl WindowAttributes {
521    /// Every attribute's default for a window of `kind`: what a window
522    /// opened with no attributes of its own has.
523    pub fn for_kind(kind: WindowKind) -> WindowAttributes {
524        let normal = WindowAttributes {
525            title: Some(String::new()),
526            title_bar: Some(TitleBarOptions::default()),
527            frame: Some(super::WindowFrameStyle::Default),
528            min_size: Some(None),
529            max_size: Some(None),
530            aspect_ratio: Some(None),
531            size_to_content: Some(SizeToContent::Off),
532            resizable: Some(true),
533            movable: Some(true),
534            minimizable: Some(true),
535            maximizable: Some(true),
536            closable: Some(true),
537            focusable: Some(true),
538            activate: Some(true),
539            close_on_press: Some(true),
540            close_on_escape: Some(false),
541            close_on_blur: Some(false),
542            level: Some(WindowLevel::Normal),
543            taskbar: Some(true),
544            workspaces: Some(Workspaces::Current),
545            pointer_events: Some(WindowPointerEvents::Auto),
546            transparent: Some(false),
547            backdrop: Some(Backdrop::None),
548            shadow: Some(true),
549            progress: Some(None),
550        };
551        match kind {
552            WindowKind::Normal => normal,
553            WindowKind::Dialog => WindowAttributes {
554                minimizable: Some(false),
555                maximizable: Some(false),
556                close_on_escape: Some(true),
557                taskbar: Some(false),
558                ..normal
559            },
560            WindowKind::Panel => WindowAttributes {
561                minimizable: Some(false),
562                maximizable: Some(false),
563                level: Some(WindowLevel::Floating),
564                taskbar: Some(false),
565                activate: Some(false),
566                ..normal
567            },
568            WindowKind::Popup => WindowAttributes {
569                frame: Some(super::WindowFrameStyle::None),
570                resizable: Some(false),
571                minimizable: Some(false),
572                maximizable: Some(false),
573                close_on_escape: Some(true),
574                close_on_blur: Some(true),
575                level: Some(WindowLevel::Floating),
576                taskbar: Some(false),
577                workspaces: Some(Workspaces::All),
578                ..normal
579            },
580            WindowKind::Overlay => WindowAttributes {
581                frame: Some(super::WindowFrameStyle::None),
582                resizable: Some(false),
583                movable: Some(false),
584                minimizable: Some(false),
585                maximizable: Some(false),
586                closable: Some(false),
587                focusable: Some(false),
588                activate: Some(false),
589                level: Some(WindowLevel::AboveDock),
590                taskbar: Some(false),
591                workspaces: Some(Workspaces::All),
592                pointer_events: Some(WindowPointerEvents::None),
593                transparent: Some(true),
594                shadow: Some(false),
595                ..normal
596            },
597        }
598    }
599
600    /// The attributes of a window of `kind` given `own`: the kind's
601    /// defaults with `own`'s fields over them.
602    pub fn resolve(kind: WindowKind, own: &WindowAttributes) -> WindowAttributes {
603        let mut out = WindowAttributes::for_kind(kind);
604        out.merge(own);
605        out
606    }
607
608    /// Whether these make the window an overlay's: click-through
609    /// (`pointerEvents: "none"`, or `"box-none"` where nothing in it takes
610    /// the pointer), which the `windows` capability's `overlay` grants.
611    pub fn passes_pointer(&self) -> bool {
612        matches!(
613            self.pointer_events,
614            Some(WindowPointerEvents::None | WindowPointerEvents::BoxNone)
615        )
616    }
617
618    /// Keeps the values in their ranges: a size or an aspect ratio not
619    /// finite and positive and a progress out of 0 to 1 are left out (with `false`), the title bar's height capped as
620    /// [`super::title_bar_height`] does.
621    pub fn sanitize(&mut self) -> bool {
622        let mut fine = true;
623        let size_ok = |s: &Size<Points>| {
624            s.width.0.is_finite() && s.height.0.is_finite() && s.width.0 > 0.0 && s.height.0 > 0.0
625        };
626        for size in [&mut self.min_size, &mut self.max_size] {
627            if let Some(Some(s)) = size
628                && !size_ok(s)
629            {
630                *size = None;
631                fine = false;
632            }
633        }
634        if let Some(Some(r)) = self.aspect_ratio
635            && !(r.is_finite() && r > 0.0)
636        {
637            self.aspect_ratio = None;
638            fine = false;
639        }
640        if let Some(Some(p)) = &mut self.progress
641            && let Some(v) = p.value
642        {
643            if !v.0.is_finite() {
644                p.value = None;
645                fine = false;
646            } else {
647                p.value = Some(Percentage(v.0.clamp(0.0, 1.0)));
648            }
649        }
650        if let Some(t) = &mut self.title_bar {
651            t.height = super::title_bar_height(t.height);
652        }
653        fine
654    }
655}
656
657/// A window to open (TS `WindowOptions`): its identity, kind and
658/// relations, the starting values of what the user also changes, and its
659/// attributes ([`WindowAttributes`]).
660#[non_exhaustive]
661#[derive(Debug, Clone, PartialEq, Default)]
662pub struct WindowOptions {
663    /// The app's id for it: one window per id (`"main"` is the main
664    /// window's), and the key its bounds are kept under
665    /// ([`Self::restore_bounds`]).
666    pub id: String,
667    /// What it is for: its attributes' defaults.
668    pub kind: WindowKind,
669    /// The id of the window that owns it: it stays above it, and minimizes
670    /// and closes with it. Dialogs and panels default to the window that
671    /// opened them.
672    pub parent: Option<String>,
673    /// The parent takes no input while it is open (dialogs).
674    pub modal: bool,
675    /// Its content size when it opens, in points.
676    pub default_size: Option<Size<Points>>,
677    /// Where it opens; dialogs default to their parent's center, other
678    /// windows to where the system places them.
679    pub default_position: Option<WindowPosition>,
680    /// The display it opens on.
681    pub display: Option<DisplayId>,
682    /// The mode it opens in.
683    pub default_mode: Option<WindowMode>,
684    /// Opens where the user left it: the core keeps its placement under its
685    /// id in the app's data, and fits it on the displays there are when it
686    /// opens again.
687    pub restore_bounds: bool,
688    /// Its attributes (over its kind's defaults).
689    pub attributes: WindowAttributes,
690}
691
692impl WindowOptions {
693    /// Options of a window with `id`.
694    pub fn new(id: impl Into<String>) -> WindowOptions {
695        WindowOptions {
696            id: id.into(),
697            ..WindowOptions::default()
698        }
699    }
700}
701
702/// Launch-time options for the first app window: nsh.json `"window"`, which
703/// the command line writes into the app's `app.json` (and the dev server's
704/// app info) and the runners read before any JS runs. The same keys as
705/// `WindowOptions` without `id`, `kind`, `parent` and `modal`: every
706/// attribute, `defaultSize`, `defaultPosition`, `display`, `defaultMode`
707/// and `restoreBounds`. The app declares the window with `<Window>` or
708/// [`crate::element::desktop::window()`] and inherits these; its own options
709/// override them. `defaultVisible` is parsed but has no effect in window
710/// model v2: the app host never shows. An unmodified window made before the
711/// app was known (a development host's) follows the attributes the engine
712/// sends with the first frame ([`crate::Core::set_main_window`]).
713///
714/// Only standalone builds read it (their `app.json`). Signed packages
715/// (`.nshpkg`) carry none: they run in host apps, which own their windows.
716#[non_exhaustive]
717#[derive(Debug, Clone, PartialEq, Default)]
718pub struct MainWindowOptions {
719    /// Its content size when it opens.
720    pub default_size: Option<Size<Points>>,
721    /// Where it opens.
722    pub default_position: Option<WindowPosition>,
723    /// The display it opens on (the system's choice when it is not there).
724    pub display: Option<DisplayId>,
725    /// The mode it opens in.
726    pub default_mode: Option<WindowMode>,
727    /// Parsed for compatibility and has no effect in window model v2: the
728    /// host never shows, and the app declares its windows with `<Window>`
729    /// (hide one with `hide()`). Read at launch only.
730    pub default_visible: Option<bool>,
731    /// Opens where the user left it (the runner keeps its placement).
732    pub restore_bounds: bool,
733    /// The attributes the app sets (the platform's main window keeps its
734    /// own for the rest: the app's name as its title, ...).
735    pub attributes: WindowAttributes,
736}
737
738impl MainWindowOptions {
739    /// Where to open the main window with `restoreBounds`: the placement
740    /// the app's last run kept in `storage` (the app's own, as the engine
741    /// is given it), fitted on `displays`, the ones there are now. `None`
742    /// without `restoreBounds`, or with nothing kept: the window opens by
743    /// `defaultSize`, `defaultPosition`, `display` and `defaultMode`. For
744    /// the runners, before they make the window; the engine keeps the
745    /// placement as the window changes ([`crate::Core::set_main_window`]).
746    pub fn kept_placement(
747        &self,
748        storage: &dyn crate::storage::StorageBackend,
749        displays: &[super::Display],
750    ) -> Option<WindowPlacement> {
751        if !self.restore_bounds {
752            return None;
753        }
754        let entries = storage
755            .load()
756            .map_err(|e| log::warn!("nsh: the main window's placement could not be read: {e}"))
757            .ok()?;
758        let json = entries.get(&placement_key("main"))?;
759        let placement = serde_json::from_str::<WindowPlacement>(json).ok()?;
760        Some(placement.fit_on_displays(displays))
761    }
762
763    /// Whether the host shows when the app starts: never in the window model
764    /// v2, where it is the invisible app host. `defaultVisible` is parsed but
765    /// has no effect; the app declares its windows with `<Window>`.
766    #[doc(hidden)]
767    pub fn visible_at_launch(&self) -> bool {
768        false
769    }
770
771    /// The keys `"window"` takes besides the attributes.
772    const KEYS: &'static [&'static str] = &[
773        "defaultSize",
774        "defaultPosition",
775        "display",
776        "defaultMode",
777        "defaultVisible",
778        "restoreBounds",
779    ];
780
781    /// Reads nsh.json's (or `app.json`'s) `"window"`: an unknown key or a
782    /// wrong value is an error, as in the rest of nsh.json.
783    pub fn from_json(json: &crate::JsonValue) -> Result<MainWindowOptions, String> {
784        let object = json
785            .as_object()
786            .ok_or_else(|| "\"window\" is an object".to_owned())?;
787        for key in object.keys() {
788            if !WindowAttributes::NAMES.contains(&key.as_str())
789                && !Self::KEYS.contains(&key.as_str())
790            {
791                return Err(format!("\"window\": unknown key {key:?}"));
792            }
793        }
794        let read =
795            |key: &str| -> Option<&crate::JsonValue> { object.get(key).filter(|v| !v.is_null()) };
796        fn typed<T: JsValue>(key: &str, v: Option<&crate::JsonValue>) -> Result<Option<T>, String> {
797            v.map(|v| {
798                crate::element::from_json::<T>(v).map_err(|e| format!("\"window.{key}\": {e}"))
799            })
800            .transpose()
801        }
802        let mut own = crate::element::from_json::<WindowAttributes>(json)
803            .map_err(|e| format!("\"window\": {e}"))?;
804        own.sanitize();
805        let options = MainWindowOptions {
806            default_size: typed("defaultSize", read("defaultSize"))?,
807            default_position: typed("defaultPosition", read("defaultPosition"))?,
808            display: typed("display", read("display"))?,
809            default_mode: typed("defaultMode", read("defaultMode"))?,
810            default_visible: typed("defaultVisible", read("defaultVisible"))?,
811            restore_bounds: typed("restoreBounds", read("restoreBounds"))?.unwrap_or(false),
812            attributes: own,
813        };
814        if let Some(size) = options.default_size
815            && !(size.width.0.is_finite()
816                && size.height.0.is_finite()
817                && size.width.0 > 0.0
818                && size.height.0 > 0.0)
819        {
820            return Err("\"window.defaultSize\": a positive width and height".into());
821        }
822        Ok(options)
823    }
824}
825
826/// Opens and applies the app's windows of its own in place of the
827/// platform's built-in one. Every desktop backend opens these windows
828/// itself (`<Window>` and `Window.open` work wherever NSH runs on a desktop,
829/// embedded or standalone); a host that wants them as its own windows (a
830/// GPUI app's), or a test's fake, sets this instead. The core hands it every command addressed to a window of the
831/// app's own (opening it, its attributes' diffs, the requests); the main
832/// window's stay with the platform. It reports what happens to a window
833/// back as the platform would: [`WindowEvent`]s on the window's root node
834/// (`EngineControl::dispatch_event` with `EventKind::Window`).
835pub trait WindowBackend: Send + Sync {
836    /// Carries out `command` for the window whose root node is `window`.
837    fn command(&self, window: crate::NodeId, command: &super::DesktopCommand);
838}
839
840/// The TypeScript declarations of `nsh/desktop`'s window types, generated
841/// from the Rust types: the attributes, the options, the placement, the
842/// displays and the names of their enumerations. `nsh-js` declares the
843/// window handle and the component around them.
844#[doc(hidden)]
845pub fn declarations() -> String {
846    use std::fmt::Write as _;
847    let mut types = TsTypes::default();
848    let mut out = String::new();
849    // The enumerations declare themselves (with their own docs) as their
850    // types are asked for; only a type that has no declaration of its own
851    // gets an alias here.
852    WindowKind::ts_type(&mut types);
853    WindowMode::ts_type(&mut types);
854    CloseReason::ts_type(&mut types);
855    WindowCloseCause::ts_type(&mut types);
856    WindowControl::ts_type(&mut types);
857    ResizeEdge::ts_type(&mut types);
858    let _ = write!(
859        out,
860        "/** A display, the same in the app's next launch (sixteen hexadecimal digits). */\n\
861         export type DisplayId = {};\n\n",
862        DisplayId::ts_type(&mut types)
863    );
864    WindowAttributes::declare(&mut types);
865    WindowPlacement::ts_type(&mut types);
866    super::Display::ts_type(&mut types);
867    let options = format!(
868        "/** A window to open (`<Window>`'s props, `Window.open`'s options): its\n \
869         * identity, kind and relations, the starting values of what the user\n \
870         * also changes, and its attributes. */\n\
871         export interface WindowOptions extends Partial<WindowAttributes> {{\n  \
872         /** The app's id for it: one window per id, the key its bounds are kept\n   \
873         * under (`restoreBounds`). `\"main\"` is a conventional first-window id,\n   \
874         * with no special behavior. */\n  \
875         id: string;\n  \
876         /** What it is for: its attributes' defaults (`\"normal\"`). */\n  \
877         kind?: WindowKind;\n  \
878         /** The window that owns it (a `WindowRef` or an id): it stays above\n   \
879         * it and closes with it. */\n  \
880         parent?: WindowRef | string;\n  \
881         /** Its parent takes no input while it is open (dialogs). */\n  \
882         modal?: boolean;\n  \
883         /** Its content size when it opens, in points. */\n  \
884         defaultSize?: {size};\n  \
885         /** Where it opens: a point on the screen, the display's center or\n   \
886         * its parent's. */\n  \
887         defaultPosition?: {position};\n  \
888         /** The display it opens on. */\n  \
889         display?: DisplayId;\n  \
890         /** The mode it opens in. */\n  \
891         defaultMode?: WindowMode;\n  \
892         /** Opens where the user left it: its placement is kept under its id\n   \
893         * and fitted on the displays there are when it opens again. */\n  \
894         restoreBounds?: boolean;\n}}\n",
895        size = Size::<Points>::ts_type(&mut types),
896        position = WindowPosition::ts_type(&mut types),
897    );
898    out.push_str(&options);
899    for declaration in types.declarations() {
900        let _ = write!(out, "\n{declaration}\n");
901    }
902    out
903}
904
905/// TS: `WindowOptions` (declared by `nsh/desktop`): `id`, `kind`,
906/// `parent` (an id; `nsh-js` also takes a `WindowRef`), the creation-time
907/// fields, and every attribute.
908impl JsValue for WindowOptions {
909    fn ts_type(_types: &mut TsTypes) -> String {
910        "WindowOptions".into()
911    }
912
913    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
914        if value.kind() != JsKind::Object {
915            return Err(value.expected("window options"));
916        }
917        fn get<T: JsValue>(object: JsIn<'_>, key: &str) -> Result<Option<T>, PropError> {
918            let v = object.field(key)?;
919            let v = v.get();
920            if v.is_nullish() {
921                return Ok(None);
922            }
923            T::from_js(v)
924                .map(Some)
925                .map_err(|e| PropError(format!("`{key}`: {e}")))
926        }
927        let mut options = WindowOptions {
928            id: get::<String>(value, "id")?.ok_or_else(|| PropError("`id`: a string".into()))?,
929            kind: get(value, "kind")?.unwrap_or_default(),
930            modal: get(value, "modal")?.unwrap_or(false),
931            default_size: get(value, "defaultSize")?,
932            default_position: get(value, "defaultPosition")?,
933            display: get(value, "display")?,
934            default_mode: get(value, "defaultMode")?,
935            restore_bounds: get(value, "restoreBounds")?.unwrap_or(false),
936            attributes: WindowAttributes::from_js(value)?,
937            ..WindowOptions::default()
938        };
939        // A `WindowRef` (an object with an `id`) or an id.
940        let parent = value.field("parent")?;
941        let parent = parent.get();
942        options.parent = match parent.kind() {
943            JsKind::Undefined | JsKind::Null => None,
944            JsKind::String => parent.as_string(),
945            JsKind::Object => get::<String>(parent, "id")?,
946            _ => return Err(PropError("`parent`: a WindowRef or a window id".into())),
947        };
948        if let Some(size) = options.default_size
949            && !(size.width.0.is_finite()
950                && size.height.0.is_finite()
951                && size.width.0 > 0.0
952                && size.height.0 > 0.0)
953        {
954            return Err(PropError(
955                "`defaultSize`: a positive width and height".into(),
956            ));
957        }
958        Ok(options)
959    }
960
961    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
962        let owned = self.attributes.to_js(host)?;
963        let object = owned.get().raw();
964        host.set_field(object, "id", self.id.to_js(host)?.into_raw())?;
965        host.set_field(object, "kind", self.kind.to_js(host)?.into_raw())?;
966        if let Some(parent) = &self.parent {
967            host.set_field(object, "parent", parent.to_js(host)?.into_raw())?;
968        }
969        host.set_field(object, "modal", self.modal.to_js(host)?.into_raw())?;
970        if let Some(v) = self.default_size {
971            host.set_field(object, "defaultSize", v.to_js(host)?.into_raw())?;
972        }
973        if let Some(v) = self.default_position {
974            host.set_field(object, "defaultPosition", v.to_js(host)?.into_raw())?;
975        }
976        if let Some(v) = self.display {
977            host.set_field(object, "display", v.to_js(host)?.into_raw())?;
978        }
979        if let Some(v) = self.default_mode {
980            host.set_field(object, "defaultMode", v.to_js(host)?.into_raw())?;
981        }
982        host.set_field(
983            object,
984            "restoreBounds",
985            self.restore_bounds.to_js(host)?.into_raw(),
986        )?;
987        Ok(owned)
988    }
989}
990
991/// What the platform gets to open a window
992/// ([`DesktopCommand::OpenWindow`](super::DesktopCommand::OpenWindow)): the
993/// options with their attributes resolved (every field set: the kind's
994/// defaults with the app's over them), the parent's root node and the
995/// placement kept from an earlier launch.
996#[non_exhaustive]
997#[derive(Debug, Clone, PartialEq, Default)]
998pub struct OpenWindow {
999    /// The options, [`WindowOptions::attributes`] resolved.
1000    pub options: WindowOptions,
1001    /// The implicit first window `mount` opens around a released app's
1002    /// plain root: the main window that app always had, not a window of
1003    /// its own, so `capabilities.windows` does not grant it.
1004    #[doc(hidden)]
1005    pub implicit: bool,
1006    /// The root node of the parent window, if the app has it open.
1007    pub parent: Option<NodeId>,
1008    /// The placement kept for its id ([`WindowOptions::restore_bounds`]),
1009    /// fitted on the displays there are now: it wins over the default size,
1010    /// position and mode.
1011    pub placement: Option<WindowPlacement>,
1012}
1013
1014/// What the app asks of a window
1015/// ([`DesktopCommand::Request`](super::DesktopCommand::Request)). Requests
1016/// are not results: the platform may decline or adjust one (a window
1017/// manager that does not let windows place themselves), and the window's
1018/// state ([`WindowState`]) says what happened.
1019#[derive(Debug, Clone, PartialEq)]
1020pub enum WindowRequest {
1021    /// Shows it, restoring it when minimized.
1022    Show,
1023    /// Hides it.
1024    Hide,
1025    /// Shows it, brings it to the front of its level and focuses it (the
1026    /// app activates).
1027    Focus,
1028    /// Closes it, whatever `closeOnPress` says (the main window: as the
1029    /// user closing it, the app ends with its last window).
1030    Close,
1031    /// Minimizes it.
1032    Minimize,
1033    /// Brings it back from being minimized, in the mode it had.
1034    Restore,
1035    /// Puts it in this mode (doing it again changes nothing).
1036    SetMode(WindowMode),
1037    /// Moves and sizes it (screen coordinates, points; a field left out
1038    /// keeps its value).
1039    SetBounds(super::WindowFrame),
1040    /// Sizes its content area (what its root view fills) to these, a side
1041    /// left out keeping its size; its top left corner stays. What the core
1042    /// sends for `sizeToContent`, having measured the content.
1043    SetContentSize {
1044        /// The content's width.
1045        width: Option<Points>,
1046        /// The content's height.
1047        height: Option<Points>,
1048    },
1049    /// Puts it in a mode with its normal bounds: restored to the bounds,
1050    /// then maximized or in full screen when the mode says so; the core has
1051    /// fitted the bounds on the displays there are.
1052    SetPlacement(WindowPlacement),
1053    /// Centers it on a display (its own without one).
1054    Center {
1055        /// The display.
1056        display: Option<DisplayId>,
1057    },
1058    /// Asks for the user's attention: the Dock's icon bounces, the taskbar
1059    /// button flashes.
1060    RequestAttention {
1061        /// Until the user activates the app (else once).
1062        critical: bool,
1063    },
1064}
1065
1066/// What a platform reports about a window of the app's own, on its root
1067/// node ([`crate::EventKind::Window`]). The main window reports its state
1068/// in the environment ([`crate::platform::Environment::window_state`]).
1069#[derive(Debug, Clone, PartialEq)]
1070pub enum WindowEvent {
1071    /// Its state changed; a move or a resize is reported once it settles.
1072    State(Box<WindowState>),
1073    /// The area of its title bar while the app hides it
1074    /// ([`TitleBarStyle::Hidden`]), as the environment's
1075    /// [`crate::platform::Environment::title_bar`] is the main window's:
1076    /// `top` the bar's height, `left` and `right` the widths its window
1077    /// controls take; all 0 while the system shows its title bar. Reported
1078    /// before the window's first state and whenever it changes (a change of
1079    /// style, of mode, of display).
1080    TitleBar(Edges<Points>),
1081    /// The user asked to close it: reported whether or not `closeOnPress`
1082    /// let the platform close it (then [`WindowEvent::Closed`] follows).
1083    ClosePress {
1084        /// How they asked.
1085        reason: CloseReason,
1086    },
1087    /// The platform closed it by itself (a policy the app set: its root
1088    /// stays until the app removes it, hidden).
1089    Closed {
1090        /// Which policy.
1091        cause: WindowCloseCause,
1092    },
1093    /// The OS asked the app to show itself: macOS's Dock or Finder reopen,
1094    /// or a second launch on Windows or Linux. Reported on the root only.
1095    /// The app opens or focuses the window it wants; NSH shows none by
1096    /// itself ([`crate::element::desktop::on_reopen`]).
1097    Reopen,
1098    /// The user asked to quit the app (its Quit item, the platform's quit
1099    /// key) while the app listens to quit requests
1100    /// ([`super::DesktopCommand::SetQuitOnRequest`]): the platform did not
1101    /// quit. Reported on the root only.
1102    QuitRequest,
1103}
1104
1105/// The record the core keeps of one window's attributes: what it last sent
1106/// the platform, and what was set since.
1107#[derive(Debug, Clone, Default)]
1108pub(crate) struct WindowRecord {
1109    /// What the platform has.
1110    pub(crate) sent: WindowAttributes,
1111    /// Set since the last commit (merged over `sent`).
1112    pub(crate) pending: WindowAttributes,
1113    /// The content size last sent for `sizeToContent`.
1114    pub(crate) fitted: Option<Size<Points>>,
1115    /// The size it opened at, its content's until the platform reports
1116    /// it (`Core::set_root_size`).
1117    pub(crate) size: Option<Size<Points>>,
1118    /// Whether this window is the implicit first window created by `mount`
1119    /// for a plain root that declared no `<Window>` scenes.
1120    pub(crate) implicit: bool,
1121}
1122
1123impl WindowRecord {
1124    /// A window the platform opened with `attributes`, at `size`.
1125    pub(crate) fn opened(
1126        attributes: WindowAttributes,
1127        size: Option<Size<Points>>,
1128        implicit: bool,
1129    ) -> WindowRecord {
1130        WindowRecord {
1131            sent: attributes,
1132            pending: WindowAttributes::default(),
1133            fitted: None,
1134            size,
1135            implicit,
1136        }
1137    }
1138
1139    /// Which of its sides follow its content (`sizeToContent`): (width,
1140    /// height).
1141    pub(crate) fn fits(&self) -> (bool, bool) {
1142        match self.pending.size_to_content.or(self.sent.size_to_content) {
1143            None | Some(SizeToContent::Off) => (false, false),
1144            Some(SizeToContent::Both) => (true, true),
1145            Some(SizeToContent::Width) => (true, false),
1146            Some(SizeToContent::Height) => (false, true),
1147        }
1148    }
1149
1150    /// What to send this commit: the pending fields that differ from what
1151    /// was sent, now counted as sent.
1152    pub(crate) fn take_diff(&mut self) -> Option<WindowAttributes> {
1153        let pending = std::mem::take(&mut self.pending);
1154        let diff = self.sent.diff(&pending)?;
1155        self.sent.merge(&diff);
1156        Some(diff)
1157    }
1158}
1159
1160/// The key the core keeps a window's placement under in the app's storage
1161/// ([`WindowOptions::restore_bounds`]).
1162pub(crate) fn placement_key(id: &str) -> String {
1163    format!("nsh.window:{id}")
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168    use super::*;
1169    use crate::geometry::{px, size};
1170
1171    #[test]
1172    fn kinds_give_every_attribute_a_default() {
1173        for kind in [
1174            WindowKind::Normal,
1175            WindowKind::Dialog,
1176            WindowKind::Panel,
1177            WindowKind::Popup,
1178            WindowKind::Overlay,
1179        ] {
1180            let a = WindowAttributes::for_kind(kind);
1181            assert_eq!(
1182                a.names().len(),
1183                WindowAttributes::NAMES.len(),
1184                "{kind:?} leaves an attribute out"
1185            );
1186        }
1187        let dialog = WindowAttributes::for_kind(WindowKind::Dialog);
1188        assert_eq!(dialog.close_on_escape, Some(true));
1189        assert_eq!(dialog.taskbar, Some(false));
1190        assert_eq!(dialog.maximizable, Some(false));
1191        let popup = WindowAttributes::for_kind(WindowKind::Popup);
1192        assert_eq!(popup.close_on_blur, Some(true));
1193        assert_eq!(popup.frame, Some(super::super::WindowFrameStyle::None));
1194        let overlay = WindowAttributes::for_kind(WindowKind::Overlay);
1195        assert!(overlay.passes_pointer());
1196        assert_eq!(overlay.focusable, Some(false));
1197        assert!(!WindowAttributes::for_kind(WindowKind::Normal).passes_pointer());
1198    }
1199
1200    #[test]
1201    fn a_box_none_window_passes_the_pointer() {
1202        let json = serde_json::json!({ "pointerEvents": "box-none" });
1203        let a = crate::element::from_json::<WindowAttributes>(&json).unwrap();
1204        assert_eq!(a.pointer_events, Some(WindowPointerEvents::BoxNone));
1205        // It lets the pointer through where nothing takes it: the
1206        // `overlay` grant, as `none`.
1207        assert!(a.passes_pointer());
1208        // The view's spelling only.
1209        let json = serde_json::json!({ "pointerEvents": "boxNone" });
1210        assert!(crate::element::from_json::<WindowAttributes>(&json).is_err());
1211    }
1212
1213    #[test]
1214    fn the_apps_attributes_override_the_kinds() {
1215        let own = WindowAttributes {
1216            taskbar: Some(true),
1217            title: Some("Settings".into()),
1218            ..WindowAttributes::default()
1219        };
1220        let a = WindowAttributes::resolve(WindowKind::Dialog, &own);
1221        assert_eq!(a.taskbar, Some(true));
1222        assert_eq!(a.title.as_deref(), Some("Settings"));
1223        assert_eq!(a.close_on_escape, Some(true));
1224    }
1225
1226    #[test]
1227    fn main_windows_open_where_they_were_kept() {
1228        use crate::{
1229            desktop::{Display, DisplayId, WindowMode},
1230            geometry::{Bounds, point, px, size},
1231            storage::{StorageBackend, StorageChange},
1232        };
1233        struct Kept(String);
1234        impl StorageBackend for Kept {
1235            fn load(&self) -> Result<std::collections::BTreeMap<String, String>, String> {
1236                Ok([("nsh.window:main".to_owned(), self.0.clone())].into())
1237            }
1238            fn write(&self, _: StorageChange) -> Result<(), String> {
1239                Ok(())
1240            }
1241        }
1242        let display = Display::new(
1243            DisplayId(1),
1244            Bounds::new(point(px(0.0), px(0.0)), size(px(1440.0), px(900.0))),
1245            Bounds::new(point(px(0.0), px(25.0)), size(px(1440.0), px(875.0))),
1246            true,
1247        );
1248        let kept = Kept(
1249            r#"{"mode":"maximized","bounds":{"origin":{"x":-3000,"y":0},"size":{"width":800,"height":600}}}"#
1250                .into(),
1251        );
1252        let mut options = MainWindowOptions::default();
1253        assert_eq!(
1254            options.kept_placement(&kept, std::slice::from_ref(&display)),
1255            None
1256        );
1257        options.restore_bounds = true;
1258        // On a display that is gone: centered on the one there is.
1259        assert_eq!(
1260            options.kept_placement(&kept, &[display]),
1261            Some(WindowPlacement::new(
1262                WindowMode::Maximized,
1263                Bounds::new(point(px(320.0), px(162.5)), size(px(800.0), px(600.0)))
1264            ))
1265        );
1266    }
1267
1268    #[test]
1269    fn the_main_window_may_start_hidden() {
1270        let read = |json: &str| {
1271            MainWindowOptions::from_json(&serde_json::from_str::<crate::JsonValue>(json).unwrap())
1272        };
1273        // The host never shows: `defaultVisible` is kept for the first app
1274        // window (the app declares it), not applied to the host.
1275        assert!(!MainWindowOptions::default().visible_at_launch());
1276        let shown = read(r#"{"title":"Mail"}"#).unwrap();
1277        assert_eq!(shown.default_visible, None);
1278        assert!(!shown.visible_at_launch());
1279        assert!(
1280            !read(r#"{"defaultVisible":true}"#)
1281                .unwrap()
1282                .visible_at_launch()
1283        );
1284        let hidden = read(r#"{"defaultVisible":false,"title":"Mail"}"#).unwrap();
1285        assert_eq!(hidden.default_visible, Some(false));
1286        assert!(!hidden.visible_at_launch());
1287        assert_eq!(hidden.attributes.title.as_deref(), Some("Mail"));
1288        // A value of another form is an error, as every key's.
1289        assert!(read(r#"{"defaultVisible":"no"}"#).is_err());
1290    }
1291
1292    #[test]
1293    fn diffs_send_only_what_changed() {
1294        let mut record = WindowRecord::opened(
1295            WindowAttributes::resolve(WindowKind::Normal, &Default::default()),
1296            None,
1297            false,
1298        );
1299        // Setting what it has sends nothing.
1300        record.pending.title = Some(String::new());
1301        assert_eq!(record.take_diff(), None);
1302        // Two sets in one commit: one diff with the last values.
1303        record.pending.merge(&WindowAttributes {
1304            title: Some("A".into()),
1305            ..Default::default()
1306        });
1307        record.pending.merge(&WindowAttributes {
1308            title: Some("B".into()),
1309            level: Some(WindowLevel::Floating),
1310            ..Default::default()
1311        });
1312        let diff = record.take_diff().unwrap();
1313        assert_eq!(diff.names(), ["title", "level"]);
1314        assert_eq!(diff.title.as_deref(), Some("B"));
1315        assert_eq!(record.take_diff(), None);
1316        // Clearing a nullable attribute is a change.
1317        record.pending.min_size = Some(Some(size(px(10.0), px(10.0))));
1318        assert!(record.take_diff().is_some());
1319        record.pending.min_size = Some(None);
1320        assert_eq!(record.take_diff().unwrap().min_size, Some(None));
1321    }
1322
1323    #[test]
1324    fn the_main_windows_record_sends_every_first_set() {
1325        // The main window's record starts empty: the runner applied its
1326        // launch attributes, which the core does not know.
1327        let mut record = WindowRecord::default();
1328        record.pending.title = Some(String::new());
1329        assert_eq!(record.take_diff().unwrap().title.as_deref(), Some(""));
1330    }
1331
1332    #[test]
1333    fn values_out_of_range_are_left_out() {
1334        let mut a = WindowAttributes {
1335            min_size: Some(Some(size(px(-1.0), px(10.0)))),
1336            aspect_ratio: Some(Some(0.0)),
1337            progress: Some(Some(WindowProgress {
1338                value: Some(Percentage(2.0)),
1339                state: ProgressState::Normal,
1340            })),
1341            ..Default::default()
1342        };
1343        assert!(!a.sanitize());
1344        assert_eq!(a.min_size, None);
1345        assert_eq!(a.aspect_ratio, None);
1346        assert_eq!(a.progress.unwrap().unwrap().value, Some(Percentage(1.0)));
1347        for bad in [f32::NAN, f32::INFINITY, -1.5] {
1348            let mut a = WindowAttributes {
1349                aspect_ratio: Some(Some(bad)),
1350                ..Default::default()
1351            };
1352            assert!(!a.sanitize());
1353            assert_eq!(a.aspect_ratio, None);
1354        }
1355        // A ratio given and `null` (cleared) are both kept.
1356        for fine in [Some(16.0 / 9.0), None] {
1357            let mut a = WindowAttributes {
1358                aspect_ratio: Some(fine),
1359                ..Default::default()
1360            };
1361            assert!(a.sanitize());
1362            assert_eq!(a.aspect_ratio, Some(fine));
1363        }
1364    }
1365}