Skip to main content

nsh_core/desktop/
window_state.rs

1//! What the app reads of its windows and the displays (TS `nsh/desktop`'s
2//! `WindowRef.state()`, `windowState()` and `displays()`), and the
3//! placement it saves and restores a window with ([`WindowPlacement`],
4//! GPUI's `WindowBounds`).
5//!
6//! Every rectangle is in points, in screen coordinates: from the primary
7//! display's top left corner, `y` growing down, as
8//! `WindowRef.setBounds` takes them.
9
10use serde::{Deserialize, Serialize};
11
12use super::WindowMode;
13use crate::{
14    element::{JsHost, JsIn, JsObject, JsOwned, JsValue, PropError, TsTypes},
15    geometry::{Bounds, Point, Points, Size, point, size},
16};
17
18/// A display, the same from one launch of the app to the next on the same
19/// machine (an id to compare, not to read: the platform's own name for the
20/// display, hashed). TS: a string.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
22pub struct DisplayId(pub u64);
23
24impl DisplayId {
25    /// The id of the display the platform names `name` (a display's UUID,
26    /// a monitor's device name, a connector): FNV-1a, which gives the same
27    /// id for the same name in every process. For the platform backends,
28    /// which all name displays this way.
29    #[doc(hidden)]
30    pub fn from_name(name: &[u8]) -> DisplayId {
31        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
32        for byte in name {
33            hash ^= u64::from(*byte);
34            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
35        }
36        DisplayId(hash)
37    }
38}
39
40/// TS: `string`, sixteen hexadecimal digits.
41impl JsValue for DisplayId {
42    fn ts_type(_types: &mut TsTypes) -> String {
43        "string".into()
44    }
45
46    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
47        value
48            .as_string()
49            .and_then(|s| u64::from_str_radix(&s, 16).ok())
50            .map(DisplayId)
51            .ok_or_else(|| value.expected("a display id"))
52    }
53
54    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
55        format!("{:016x}", self.0).to_js(host)
56    }
57}
58
59/// A display (GPUI's `PlatformDisplay`): its area, the part of it windows
60/// use, and how it shows them.
61#[non_exhaustive]
62#[derive(Debug, Clone, PartialEq, Default, JsObject)]
63pub struct Display {
64    /// Which display it is, the same in the app's next launch.
65    pub id: DisplayId,
66    /// Its whole area, in screen coordinates.
67    pub bounds: Bounds<Points>,
68    /// The part windows use: its area without the menu bar, the Dock or the
69    /// taskbar (the whole area where the platform does not tell).
70    pub visible_bounds: Bounds<Points>,
71    /// The primary display, whose top left corner screen coordinates start
72    /// from.
73    pub primary: bool,
74    /// Its name as the system shows it (`""` where the platform does not
75    /// tell).
76    pub name: String,
77    /// Device pixels per point.
78    pub scale_factor: f32,
79    /// Frames per second it shows, where the platform tells.
80    pub refresh_rate: Option<f32>,
81    /// The parts of the display a camera housing hides (a MacBook's notch),
82    /// in screen coordinates; empty where it has none.
83    pub cutouts: Vec<Bounds<Points>>,
84}
85
86impl Display {
87    /// A display with `id`, `bounds` and `visible_bounds`, at a scale of 1,
88    /// with no name and no cutouts.
89    pub fn new(
90        id: DisplayId,
91        bounds: Bounds<Points>,
92        visible_bounds: Bounds<Points>,
93        primary: bool,
94    ) -> Display {
95        Display {
96            id,
97            bounds,
98            visible_bounds,
99            primary,
100            name: String::new(),
101            scale_factor: 1.0,
102            refresh_rate: None,
103            cutouts: Vec::new(),
104        }
105    }
106}
107
108/// The notch of a display of `bounds` (screen coordinates), for the macOS
109/// backends, which read its inputs from `NSScreen`: the gap between the
110/// menu bar's two parts beside the camera housing (`left` and `right`, the
111/// sizes of its auxiliary top left and top right areas), at the display's
112/// top and as tall as its safe area's top inset (`top_inset`). Only the
113/// areas' sizes are read, measured in from the display's edges, so the
114/// coordinate space their origins are in does not matter. `None` on a
115/// display without one: an area missing (empty), no inset, no gap.
116#[doc(hidden)]
117pub fn notch(
118    bounds: Bounds<Points>,
119    left: Size<Points>,
120    right: Size<Points>,
121    top_inset: Points,
122) -> Option<Bounds<Points>> {
123    let present = |area: Size<Points>| area.width > Points::ZERO && area.height > Points::ZERO;
124    if !present(left) || !present(right) || top_inset <= Points::ZERO {
125        return None;
126    }
127    let start = bounds.left() + left.width;
128    let end = bounds.right() - right.width;
129    if end <= start {
130        return None;
131    }
132    Some(Bounds::new(
133        point(start, bounds.top()),
134        size(end - start, top_inset),
135    ))
136}
137
138/// A window's mode and its normal bounds (GPUI's `WindowBounds`): what an
139/// app saves to open its window as the user left it, and gives
140/// `WindowRef.setPlacement` (Rust [`crate::element::desktop::WindowRef::set_placement`])
141/// to restore it. A maximized or full screen window carries the bounds it
142/// returns to.
143///
144/// TS: `{ mode: WindowMode; bounds: Bounds }`, which is also its serde form:
145/// what one side saves `JSON.stringify` reads back with `serde_json`, and
146/// the other way round.
147#[non_exhaustive]
148#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, JsObject)]
149pub struct WindowPlacement {
150    /// Normal, maximized (zoomed on macOS) or in full screen.
151    #[prop(default)]
152    #[serde(default)]
153    pub mode: WindowMode,
154    /// Its bounds in the normal mode: where it is, or returns to, in
155    /// points, in screen coordinates.
156    pub bounds: Bounds<Points>,
157}
158
159/// The least of a window's top strip ([`TITLE_STRIP`] tall) that stays
160/// on a display's visible area for `fit_on_displays` to leave it where it
161/// is: enough to take it by its title bar.
162const GRAB: Size<Points> = Size {
163    width: Points(100.0),
164    height: Points(20.0),
165};
166
167/// The top of a window that holds its title bar.
168const TITLE_STRIP: Points = Points(40.0);
169
170impl WindowPlacement {
171    /// A placement in `mode` with normal bounds `bounds`.
172    pub fn new(mode: WindowMode, bounds: Bounds<Points>) -> WindowPlacement {
173        WindowPlacement { mode, bounds }
174    }
175
176    /// The same mode with `bounds`.
177    pub fn with_bounds(self, bounds: Bounds<Points>) -> WindowPlacement {
178        WindowPlacement { bounds, ..self }
179    }
180
181    /// These bounds on the displays there are now (saved bounds of a
182    /// display the user has since unplugged, or of another arrangement):
183    /// unchanged when at least 100 × 20 points of the window's top 40
184    /// points are on a display's visible area, where the user can take it
185    /// by its title bar; otherwise centered on the primary display's
186    /// visible area (the first display's without one), no larger than it.
187    /// A size that is not finite and positive takes the visible area's.
188    /// The mode stays. Without displays (off desktops) the bounds stay.
189    /// What `WindowRef::set_placement` does to the bounds it is given.
190    pub(crate) fn fit_on_displays(self, displays: &[Display]) -> WindowPlacement {
191        let bounds = self.bounds;
192        let valid = |v: Points| v.0.is_finite() && v.0 > 0.0;
193        let sized = valid(bounds.size.width)
194            && valid(bounds.size.height)
195            && bounds.origin.x.0.is_finite()
196            && bounds.origin.y.0.is_finite();
197        if sized && displays.iter().any(|d| grabbable(bounds, d.visible_bounds)) {
198            return self;
199        }
200        let Some(display) = displays
201            .iter()
202            .find(|d| d.primary)
203            .or_else(|| displays.first())
204        else {
205            return self;
206        };
207        let area = display.visible_bounds;
208        let fit = |v: Points, max: Points| if valid(v) { v.min(max) } else { max };
209        let size = Size {
210            width: fit(bounds.size.width, area.size.width),
211            height: fit(bounds.size.height, area.size.height),
212        };
213        let origin = Point {
214            x: area.origin.x + (area.size.width - size.width) / 2.0,
215            y: area.origin.y + (area.size.height - size.height) / 2.0,
216        };
217        self.with_bounds(Bounds::new(origin, size))
218    }
219}
220
221/// Whether enough of `bounds`' top strip is on `area` ([`GRAB`]).
222fn grabbable(bounds: Bounds<Points>, area: Bounds<Points>) -> bool {
223    let strip = Bounds::new(
224        bounds.origin,
225        Size {
226            width: bounds.size.width,
227            height: bounds.size.height.min(TITLE_STRIP),
228        },
229    );
230    if !strip.intersects(&area) {
231        return false;
232    }
233    let on = strip.intersect(&area);
234    on.size.width >= GRAB.width.min(strip.size.width)
235        && on.size.height >= GRAB.height.min(strip.size.height)
236}
237
238/// A window as the platform reports it (TS `WindowRef.state()` and
239/// `windowState()`, Rust [`crate::element::desktop::WindowRef::state`]).
240/// A move or a resize is reported once the window stops for a moment; a
241/// change of mode, of display, of the focus or of being minimized or
242/// hidden at once.
243#[non_exhaustive]
244#[derive(Debug, Clone, Copy, PartialEq, Default, JsObject)]
245pub struct WindowState {
246    /// Its mode.
247    pub mode: WindowMode,
248    /// It is minimized (in the Dock, the taskbar).
249    pub minimized: bool,
250    /// It is on the screen: shown and not minimized (the app not hidden by
251    /// macOS's Hide). One there that `lifecycle()` reports in the
252    /// background is covered by other windows.
253    pub visible: bool,
254    /// It has the keyboard focus.
255    pub focused: bool,
256    /// Its outer frame now, window decorations included, in screen
257    /// coordinates (a maximized or full screen window's as it shows).
258    pub bounds: Bounds<Points>,
259    /// Its content area now, in screen coordinates.
260    pub content_bounds: Bounds<Points>,
261    /// Its mode and normal bounds: what to save to open it the same way
262    /// next time.
263    pub placement: WindowPlacement,
264    /// The display it is on (the one with most of it): one of
265    /// `displays()`.
266    pub display: Option<DisplayId>,
267    /// Device pixels per point.
268    pub scale_factor: f32,
269}
270
271impl WindowState {
272    /// A window on the screen at `bounds` (its content too) in
273    /// `placement`'s mode, at a scale of 1.
274    pub fn new(bounds: Bounds<Points>, placement: WindowPlacement) -> WindowState {
275        WindowState {
276            mode: placement.mode,
277            visible: true,
278            bounds,
279            content_bounds: bounds,
280            placement,
281            scale_factor: 1.0,
282            ..WindowState::default()
283        }
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290    use crate::geometry::px;
291
292    fn rect(x: f32, y: f32, w: f32, h: f32) -> Bounds<Points> {
293        Bounds::new(point(px(x), px(y)), size(px(w), px(h)))
294    }
295
296    #[test]
297    fn a_notch_is_the_gap_between_the_auxiliary_areas() {
298        // A 14-inch MacBook Pro's built-in screen, the primary one.
299        let left = size(px(664.0), px(32.0));
300        let right = size(px(663.0), px(32.0));
301        assert_eq!(
302            notch(rect(0.0, 0.0, 1512.0, 982.0), left, right, px(32.0)),
303            Some(rect(664.0, 0.0, 185.0, 32.0)),
304        );
305    }
306
307    #[test]
308    fn a_display_without_a_notch_has_none() {
309        let bounds = rect(0.0, 0.0, 2560.0, 1440.0);
310        let none = Size::default();
311        assert_eq!(notch(bounds, none, none, px(0.0)), None);
312        // Areas without an inset, or an inset without areas.
313        let left = size(px(1200.0), px(25.0));
314        let right = size(px(1200.0), px(25.0));
315        assert_eq!(notch(bounds, left, right, px(0.0)), None);
316        assert_eq!(notch(bounds, none, none, px(25.0)), None);
317        // Areas that meet leave no gap.
318        let right = size(px(1360.0), px(25.0));
319        assert_eq!(notch(bounds, left, right, px(25.0)), None);
320    }
321
322    #[test]
323    fn a_notch_on_a_secondary_display_is_in_screen_coordinates() {
324        // The built-in screen right of a 2560 × 1440 primary display, its
325        // top 658 points below the primary's.
326        let left = size(px(664.0), px(32.0));
327        let right = size(px(663.0), px(32.0));
328        assert_eq!(
329            notch(rect(2560.0, 658.0, 1512.0, 982.0), left, right, px(32.0)),
330            Some(rect(3224.0, 658.0, 185.0, 32.0)),
331        );
332    }
333
334    fn displays() -> Vec<Display> {
335        vec![
336            // A laptop's screen under a menu bar, and a display to its right.
337            Display::new(
338                DisplayId(1),
339                rect(0.0, 0.0, 1440.0, 900.0),
340                rect(0.0, 25.0, 1440.0, 875.0),
341                true,
342            ),
343            Display::new(
344                DisplayId(2),
345                rect(1440.0, 0.0, 1920.0, 1080.0),
346                rect(1440.0, 0.0, 1920.0, 1080.0),
347                false,
348            ),
349        ]
350    }
351
352    #[test]
353    fn display_ids_are_stable_hashes_of_names() {
354        assert_eq!(DisplayId::from_name(b""), DisplayId(0xcbf2_9ce4_8422_2325));
355        assert_eq!(DisplayId::from_name(b"a"), DisplayId(0xaf63_dc4c_8601_ec8c));
356        assert_ne!(
357            DisplayId::from_name(b"\\\\.\\DISPLAY1"),
358            DisplayId::from_name(b"\\\\.\\DISPLAY2")
359        );
360    }
361
362    #[test]
363    fn bounds_on_a_display_stay() {
364        let on_second = WindowPlacement::new(WindowMode::Normal, rect(2000.0, 100.0, 800.0, 600.0));
365        assert_eq!(on_second.fit_on_displays(&displays()), on_second);
366        // Across two displays.
367        let across = WindowPlacement::new(WindowMode::Maximized, rect(1000.0, 200.0, 900.0, 600.0));
368        assert_eq!(across.fit_on_displays(&displays()), across);
369        // Mostly off the screen, but its title bar can be taken.
370        let corner = WindowPlacement::new(WindowMode::Normal, rect(-700.0, 860.0, 800.0, 600.0));
371        assert_eq!(corner.fit_on_displays(&displays()), corner);
372    }
373
374    #[test]
375    fn bounds_off_every_display_move_to_the_primary_one() {
376        // The display on the left is gone.
377        let gone = WindowPlacement::new(WindowMode::Normal, rect(-1500.0, 100.0, 800.0, 600.0));
378        assert_eq!(
379            gone.fit_on_displays(&displays()),
380            WindowPlacement::new(WindowMode::Normal, rect(320.0, 162.5, 800.0, 600.0))
381        );
382        // Larger than the primary display: as large as its visible area.
383        let large = WindowPlacement::new(WindowMode::FullScreen, rect(5000.0, 0.0, 2560.0, 1440.0));
384        assert_eq!(
385            large.fit_on_displays(&displays()),
386            WindowPlacement::new(WindowMode::FullScreen, rect(0.0, 25.0, 1440.0, 875.0))
387        );
388        // Only its bottom edge shows: its title bar is above the screen.
389        let above = WindowPlacement::new(WindowMode::Normal, rect(100.0, -590.0, 800.0, 600.0));
390        assert_eq!(
391            above.fit_on_displays(&displays()),
392            WindowPlacement::new(WindowMode::Normal, rect(320.0, 162.5, 800.0, 600.0))
393        );
394        // Too little of its title bar shows to take it.
395        let sliver = WindowPlacement::new(WindowMode::Normal, rect(-750.0, 100.0, 800.0, 600.0));
396        assert_ne!(sliver.fit_on_displays(&displays()), sliver);
397    }
398
399    #[test]
400    fn invalid_bounds_take_the_visible_area() {
401        let nan = WindowPlacement::new(WindowMode::Normal, rect(f32::NAN, 0.0, 0.0, -1.0));
402        assert_eq!(
403            nan.fit_on_displays(&displays()),
404            WindowPlacement::new(WindowMode::Normal, rect(0.0, 25.0, 1440.0, 875.0))
405        );
406    }
407
408    #[test]
409    fn without_displays_the_bounds_stay() {
410        let gone = WindowPlacement::new(WindowMode::Normal, rect(-1500.0, 100.0, 800.0, 600.0));
411        assert_eq!(gone.fit_on_displays(&[]), gone);
412        // No primary display: the first one.
413        let second = &displays()[1..];
414        assert_eq!(
415            gone.fit_on_displays(second),
416            WindowPlacement::new(WindowMode::Normal, rect(2000.0, 240.0, 800.0, 600.0))
417        );
418    }
419
420    #[test]
421    fn bounds_save_as_the_ts_object() {
422        let bounds = WindowPlacement::new(WindowMode::Maximized, rect(10.0, 20.5, 800.0, 600.0));
423        let json = serde_json::to_string(&bounds).unwrap();
424        assert_eq!(
425            json,
426            r#"{"mode":"maximized","bounds":{"origin":{"x":10.0,"y":20.5},"size":{"width":800.0,"height":600.0}}}"#
427        );
428        assert_eq!(
429            serde_json::from_str::<WindowPlacement>(&json).unwrap(),
430            bounds
431        );
432        // As `JSON.stringify` writes it.
433        let ts = r#"{"mode":"fullScreen","bounds":{"origin":{"x":-1,"y":0},"size":{"width":800,"height":600}}}"#;
434        assert_eq!(
435            serde_json::from_str::<WindowPlacement>(ts).unwrap(),
436            WindowPlacement::new(WindowMode::FullScreen, rect(-1.0, 0.0, 800.0, 600.0))
437        );
438    }
439}