1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
25pub enum WindowKind {
26 #[default]
29 Normal,
30 Dialog,
34 Panel,
37 Popup,
41 Overlay,
45}
46
47#[derive(
50 Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum, serde::Serialize, serde::Deserialize,
51)]
52#[serde(rename_all = "camelCase")]
53pub enum WindowMode {
54 #[default]
56 Normal,
57 Maximized,
59 FullScreen,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
65pub enum CloseReason {
66 #[default]
69 CloseButton,
70 Shortcut,
72 Menu,
74 Taskbar,
76 System,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
84pub enum WindowCloseCause {
85 #[default]
87 ClosePress,
88 Escape,
90 Blur,
92 ParentClose,
94 Close,
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
101pub enum Workspaces {
102 #[default]
104 Current,
105 All,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
112pub enum WindowPointerEvents {
113 #[default]
115 Auto,
116 None,
119 #[prop(rename = "box-none")]
130 BoxNone,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
137pub enum Backdrop {
138 #[default]
140 None,
141 Window,
143 Sidebar,
145 Popover,
147 Hud,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
153pub enum ProgressState {
154 #[default]
156 Normal,
157 Indeterminate,
159 Paused,
161 Error,
163}
164
165#[non_exhaustive]
167#[derive(Debug, Clone, Copy, PartialEq, Default, JsObject)]
168pub struct WindowProgress {
169 pub value: Option<Percentage>,
171 #[prop(default)]
173 pub state: ProgressState,
174}
175
176#[non_exhaustive]
178#[derive(Debug, Clone, Copy, PartialEq, Default, JsObject)]
179pub struct TitleBarOptions {
180 #[prop(default)]
183 pub style: TitleBarStyle,
184 pub height: Option<Points>,
187 pub controls_offset: Option<Point<Points>>,
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
194pub enum SizeToContent {
195 #[default]
197 Off,
198 Both,
200 Width,
202 Height,
204}
205
206impl 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#[derive(Debug, Clone, Copy, PartialEq)]
239pub enum WindowPosition {
240 At(Point<Points>),
242 Center,
244 ParentCenter,
246}
247
248impl 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
277pub enum WindowControl {
278 Minimize,
280 Maximize,
282 Close,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
289pub enum ResizeEdge {
290 Top,
292 Bottom,
294 Left,
296 Right,
298 TopLeft,
300 TopRight,
302 BottomLeft,
304 BottomRight,
306}
307
308macro_rules! attributes {
313 (
314 $(
315 $(#[doc = $doc:literal])*
316 $field:ident: $ty:ty = $js:literal, $nullable:tt;
317 )*
318 ) => {
319 #[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 pub const NAMES: &'static [&'static str] = &[$($js),*];
336
337 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 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 pub fn is_empty(&self) -> bool {
362 true $(&& self.$field.is_none())*
363 }
364
365 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 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 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 title: String = "title", plain;
465 title_bar: TitleBarOptions = "titleBar", plain;
467 frame: super::WindowFrameStyle = "frame", plain;
469 min_size: Option<Size<Points>> = "minSize", nullable;
471 max_size: Option<Size<Points>> = "maxSize", nullable;
473 aspect_ratio: Option<f32> = "aspectRatio", nullable;
476 size_to_content: SizeToContent = "sizeToContent", plain;
478 resizable: bool = "resizable", plain;
480 movable: bool = "movable", plain;
482 minimizable: bool = "minimizable", plain;
484 maximizable: bool = "maximizable", plain;
486 closable: bool = "closable", plain;
488 focusable: bool = "focusable", plain;
490 activate: bool = "activate", plain;
492 close_on_press: bool = "closeOnPress", plain;
495 close_on_escape: bool = "closeOnEscape", plain;
497 close_on_blur: bool = "closeOnBlur", plain;
499 level: WindowLevel = "level", plain;
501 taskbar: bool = "taskbar", plain;
503 workspaces: Workspaces = "workspaces", plain;
505 pointer_events: WindowPointerEvents = "pointerEvents", plain;
507 transparent: bool = "transparent", plain;
509 backdrop: Backdrop = "backdrop", plain;
511 shadow: bool = "shadow", plain;
513 progress: Option<WindowProgress> = "progress", nullable;
515}
516
517crate::static_reactive!(WindowAttributes: WindowAttributes);
519
520impl WindowAttributes {
521 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 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 pub fn passes_pointer(&self) -> bool {
612 matches!(
613 self.pointer_events,
614 Some(WindowPointerEvents::None | WindowPointerEvents::BoxNone)
615 )
616 }
617
618 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#[non_exhaustive]
661#[derive(Debug, Clone, PartialEq, Default)]
662pub struct WindowOptions {
663 pub id: String,
667 pub kind: WindowKind,
669 pub parent: Option<String>,
673 pub modal: bool,
675 pub default_size: Option<Size<Points>>,
677 pub default_position: Option<WindowPosition>,
680 pub display: Option<DisplayId>,
682 pub default_mode: Option<WindowMode>,
684 pub restore_bounds: bool,
688 pub attributes: WindowAttributes,
690}
691
692impl WindowOptions {
693 pub fn new(id: impl Into<String>) -> WindowOptions {
695 WindowOptions {
696 id: id.into(),
697 ..WindowOptions::default()
698 }
699 }
700}
701
702#[non_exhaustive]
717#[derive(Debug, Clone, PartialEq, Default)]
718pub struct MainWindowOptions {
719 pub default_size: Option<Size<Points>>,
721 pub default_position: Option<WindowPosition>,
723 pub display: Option<DisplayId>,
725 pub default_mode: Option<WindowMode>,
727 pub default_visible: Option<bool>,
731 pub restore_bounds: bool,
733 pub attributes: WindowAttributes,
736}
737
738impl MainWindowOptions {
739 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 #[doc(hidden)]
767 pub fn visible_at_launch(&self) -> bool {
768 false
769 }
770
771 const KEYS: &'static [&'static str] = &[
773 "defaultSize",
774 "defaultPosition",
775 "display",
776 "defaultMode",
777 "defaultVisible",
778 "restoreBounds",
779 ];
780
781 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
826pub trait WindowBackend: Send + Sync {
836 fn command(&self, window: crate::NodeId, command: &super::DesktopCommand);
838}
839
840#[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 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
905impl 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 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#[non_exhaustive]
997#[derive(Debug, Clone, PartialEq, Default)]
998pub struct OpenWindow {
999 pub options: WindowOptions,
1001 #[doc(hidden)]
1005 pub implicit: bool,
1006 pub parent: Option<NodeId>,
1008 pub placement: Option<WindowPlacement>,
1012}
1013
1014#[derive(Debug, Clone, PartialEq)]
1020pub enum WindowRequest {
1021 Show,
1023 Hide,
1025 Focus,
1028 Close,
1031 Minimize,
1033 Restore,
1035 SetMode(WindowMode),
1037 SetBounds(super::WindowFrame),
1040 SetContentSize {
1044 width: Option<Points>,
1046 height: Option<Points>,
1048 },
1049 SetPlacement(WindowPlacement),
1053 Center {
1055 display: Option<DisplayId>,
1057 },
1058 RequestAttention {
1061 critical: bool,
1063 },
1064}
1065
1066#[derive(Debug, Clone, PartialEq)]
1070pub enum WindowEvent {
1071 State(Box<WindowState>),
1073 TitleBar(Edges<Points>),
1081 ClosePress {
1084 reason: CloseReason,
1086 },
1087 Closed {
1090 cause: WindowCloseCause,
1092 },
1093 Reopen,
1098 QuitRequest,
1103}
1104
1105#[derive(Debug, Clone, Default)]
1108pub(crate) struct WindowRecord {
1109 pub(crate) sent: WindowAttributes,
1111 pub(crate) pending: WindowAttributes,
1113 pub(crate) fitted: Option<Size<Points>>,
1115 pub(crate) size: Option<Size<Points>>,
1118 pub(crate) implicit: bool,
1121}
1122
1123impl WindowRecord {
1124 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 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 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
1160pub(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 assert!(a.passes_pointer());
1208 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 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 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 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 record.pending.title = Some(String::new());
1301 assert_eq!(record.take_diff(), None);
1302 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 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 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 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}