1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
22pub struct DisplayId(pub u64);
23
24impl DisplayId {
25 #[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
40impl 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#[non_exhaustive]
62#[derive(Debug, Clone, PartialEq, Default, JsObject)]
63pub struct Display {
64 pub id: DisplayId,
66 pub bounds: Bounds<Points>,
68 pub visible_bounds: Bounds<Points>,
71 pub primary: bool,
74 pub name: String,
77 pub scale_factor: f32,
79 pub refresh_rate: Option<f32>,
81 pub cutouts: Vec<Bounds<Points>>,
84}
85
86impl Display {
87 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#[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#[non_exhaustive]
148#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, JsObject)]
149pub struct WindowPlacement {
150 #[prop(default)]
152 #[serde(default)]
153 pub mode: WindowMode,
154 pub bounds: Bounds<Points>,
157}
158
159const GRAB: Size<Points> = Size {
163 width: Points(100.0),
164 height: Points(20.0),
165};
166
167const TITLE_STRIP: Points = Points(40.0);
169
170impl WindowPlacement {
171 pub fn new(mode: WindowMode, bounds: Bounds<Points>) -> WindowPlacement {
173 WindowPlacement { mode, bounds }
174 }
175
176 pub fn with_bounds(self, bounds: Bounds<Points>) -> WindowPlacement {
178 WindowPlacement { bounds, ..self }
179 }
180
181 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
221fn 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#[non_exhaustive]
244#[derive(Debug, Clone, Copy, PartialEq, Default, JsObject)]
245pub struct WindowState {
246 pub mode: WindowMode,
248 pub minimized: bool,
250 pub visible: bool,
254 pub focused: bool,
256 pub bounds: Bounds<Points>,
259 pub content_bounds: Bounds<Points>,
261 pub placement: WindowPlacement,
264 pub display: Option<DisplayId>,
267 pub scale_factor: f32,
269}
270
271impl WindowState {
272 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 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 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 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 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 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 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 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 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 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 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 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 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 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}