Skip to main content

native_gui_core/
windowing.rs

1use crate::WidgetId;
2
3/// Window features a backend can apply without approximating their behavior.
4#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
5pub struct WindowCapabilities {
6    pub anchored_popups: bool,
7    pub popup_focus_dismissal: bool,
8    pub transient_ownership: bool,
9    pub undecorated: bool,
10    pub always_on_top: bool,
11    pub uniform_translucency: bool,
12    pub shape_rounded: bool,
13    pub shape_region: bool,
14    pub show_fade: bool,
15    pub show_slide: bool,
16}
17
18impl WindowCapabilities {
19    /// Returns a capability set with every flag disabled.
20    pub const fn none() -> Self {
21        Self {
22            anchored_popups: false,
23            popup_focus_dismissal: false,
24            transient_ownership: false,
25            undecorated: false,
26            always_on_top: false,
27            uniform_translucency: false,
28            shape_rounded: false,
29            shape_region: false,
30            show_fade: false,
31            show_slide: false,
32        }
33    }
34}
35
36/// The semantic role of a top-level window.
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub enum WindowRole {
39    #[default]
40    Normal,
41    Popup,
42    Splash,
43}
44
45/// Stacking order relative to other application windows.
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub enum Stacking {
48    #[default]
49    Normal,
50    AlwaysOnTop,
51}
52
53/// Whether showing a window may take keyboard focus.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
55pub enum WindowFocusPolicy {
56    #[default]
57    Take,
58    NoTake,
59}
60
61/// The preferred edge for anchoring a transient window.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum AnchorEdge {
64    Below,
65    Above,
66    LeftOf,
67    RightOf,
68    Pointer,
69}
70
71/// A window's desired screen or widget-relative position.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum WindowPlacement {
74    Screen {
75        x: i32,
76        y: i32,
77    },
78    Anchored {
79        widget_id: WidgetId,
80        edge: AnchorEdge,
81        offset: (i32, i32),
82    },
83}
84
85impl Default for WindowPlacement {
86    fn default() -> Self {
87        Self::Screen { x: 0, y: 0 }
88    }
89}
90
91/// The supported v0 window-shape vocabulary.
92#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
93pub enum WindowShape {
94    #[default]
95    Rect,
96    Rounded {
97        radius: i32,
98    },
99}
100
101/// A non-blocking window show or hide effect.
102#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
103pub enum ShowEffect {
104    #[default]
105    None,
106    Fade {
107        duration_ms: u32,
108    },
109    Slide {
110        edge: AnchorEdge,
111        duration_ms: u32,
112    },
113}
114
115/// Options applied to a top-level window.
116#[derive(Debug, Clone, Copy, PartialEq)]
117pub struct WindowOptions {
118    pub role: WindowRole,
119    pub transient_for: Option<WidgetId>,
120    pub placement: WindowPlacement,
121    pub decorations: bool,
122    pub stacking: Stacking,
123    pub focus: WindowFocusPolicy,
124    pub dismiss_on_focus_loss: bool,
125    pub opacity: f32,
126    pub shape: WindowShape,
127    pub show_effect: ShowEffect,
128    pub hide_effect: ShowEffect,
129}
130
131impl Default for WindowOptions {
132    fn default() -> Self {
133        Self {
134            role: WindowRole::Normal,
135            transient_for: None,
136            placement: WindowPlacement::default(),
137            decorations: true,
138            stacking: Stacking::Normal,
139            focus: WindowFocusPolicy::Take,
140            dismiss_on_focus_loss: false,
141            opacity: 1.0,
142            shape: WindowShape::Rect,
143            show_effect: ShowEffect::None,
144            hide_effect: ShowEffect::None,
145        }
146    }
147}
148
149/// Why a popup session was dismissed by the user or window system.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum PopupDismissReason {
152    FocusLost,
153    Escape,
154    OwnerClosed,
155    Replaced,
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161    use crate::error::GuiError;
162    use crate::test_support::MockBackend;
163    use crate::test_support::MockWindowEffect;
164    use crate::{Backend, Ui, UiEvent, WidgetKind};
165
166    fn full_capabilities() -> WindowCapabilities {
167        WindowCapabilities {
168            anchored_popups: true,
169            popup_focus_dismissal: true,
170            transient_ownership: true,
171            undecorated: true,
172            always_on_top: true,
173            uniform_translucency: true,
174            shape_rounded: true,
175            shape_region: false,
176            show_fade: true,
177            show_slide: true,
178        }
179    }
180
181    fn popup_options(owner: WidgetId, anchor: WidgetId) -> WindowOptions {
182        WindowOptions {
183            role: WindowRole::Popup,
184            transient_for: Some(owner),
185            placement: WindowPlacement::Anchored {
186                widget_id: anchor,
187                edge: AnchorEdge::Below,
188                offset: (0, 2),
189            },
190            ..WindowOptions::default()
191        }
192    }
193
194    fn assert_capability_refusal(
195        capabilities: WindowCapabilities,
196        options: WindowOptions,
197        expected: &str,
198    ) {
199        let mut backend = MockBackend::default();
200        backend.set_window_capabilities(capabilities);
201        let mut ui = Ui::new(backend);
202        let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
203        let anchor = ui.create(WidgetKind::Button, Some("anchor")).unwrap();
204        let target = ui.create(WidgetKind::Window, Some("target")).unwrap();
205        let mut options = options;
206        if options.role == WindowRole::Popup {
207            options.transient_for = Some(owner);
208            options.placement = WindowPlacement::Anchored {
209                widget_id: anchor,
210                edge: AnchorEdge::Below,
211                offset: (0, 0),
212            };
213        }
214        assert_eq!(
215            ui.set_window_options(target, options).unwrap_err(),
216            GuiError::UnsupportedCapability(expected.to_owned()),
217            "expected {expected}"
218        );
219    }
220
221    #[test]
222    fn backend_defaults_to_no_extended_window_capabilities() {
223        assert_eq!(WindowCapabilities::default(), WindowCapabilities::none());
224        let mut backend = MockBackend::default();
225        backend.set_window_capabilities(WindowCapabilities::none());
226        assert_eq!(backend.window_capabilities(), WindowCapabilities::none());
227    }
228
229    #[test]
230    fn window_options_validate_and_round_trip_through_mock() {
231        let mut ui = Ui::new(MockBackend::default());
232        let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
233        let anchor = ui.create(WidgetKind::Button, Some("anchor")).unwrap();
234        let popup = ui.create(WidgetKind::Window, Some("popup")).unwrap();
235        let options = popup_options(owner, anchor);
236        ui.set_window_options(popup, options).unwrap();
237        assert_eq!(ui.window_options(popup).unwrap(), options);
238        assert_eq!(ui.backend().window_options.get(&popup), Some(&options));
239        assert!(ui.focus_order().contains(&popup));
240
241        let button = ui.create(WidgetKind::Button, Some("not a window")).unwrap();
242        assert_eq!(
243            ui.set_window_options(button, WindowOptions::default())
244                .unwrap_err(),
245            GuiError::UnsupportedWidget("set_window_options")
246        );
247        assert_eq!(
248            ui.window_options(WidgetId(u64::MAX)).unwrap_err(),
249            GuiError::WidgetNotFound(u64::MAX)
250        );
251
252        let mut invalid = WindowOptions {
253            opacity: f32::NAN,
254            ..WindowOptions::default()
255        };
256        assert!(matches!(
257            ui.set_window_options(owner, invalid),
258            Err(GuiError::Backend(_))
259        ));
260        invalid.opacity = 1.0;
261        invalid.shape = WindowShape::Rounded { radius: 0 };
262        assert!(matches!(
263            ui.set_window_options(owner, invalid),
264            Err(GuiError::Backend(_))
265        ));
266        invalid.shape = WindowShape::Rect;
267        invalid.placement = WindowPlacement::Anchored {
268            widget_id: WidgetId(u64::MAX),
269            edge: AnchorEdge::Below,
270            offset: (0, 0),
271        };
272        assert_eq!(
273            ui.set_window_options(owner, invalid).unwrap_err(),
274            GuiError::WidgetNotFound(u64::MAX)
275        );
276
277        let nested_owner = ui.create(WidgetKind::Window, Some("nested owner")).unwrap();
278        let nested_popup = ui.create(WidgetKind::Window, Some("nested popup")).unwrap();
279        let mut nested_options = WindowOptions {
280            transient_for: Some(owner),
281            ..WindowOptions::default()
282        };
283        ui.set_window_options(nested_owner, nested_options)
284            .expect("a window can own a transient");
285        nested_options.transient_for = Some(nested_owner);
286        ui.set_window_options(nested_popup, nested_options)
287            .expect("a transient can own another transient");
288        assert!(matches!(
289            ui.set_window_options(
290                owner,
291                WindowOptions {
292                    transient_for: Some(nested_popup),
293                    ..WindowOptions::default()
294                }
295            ),
296            Err(GuiError::Backend(_))
297        ));
298    }
299
300    #[test]
301    fn each_extended_window_capability_has_a_typed_refusal() {
302        let caps = full_capabilities();
303        let mut missing = caps;
304        missing.anchored_popups = false;
305        assert_capability_refusal(
306            missing,
307            WindowOptions {
308                role: WindowRole::Popup,
309                ..WindowOptions::default()
310            },
311            "window_popup",
312        );
313
314        let mut missing = caps;
315        missing.popup_focus_dismissal = false;
316        assert_capability_refusal(
317            missing,
318            WindowOptions {
319                role: WindowRole::Popup,
320                dismiss_on_focus_loss: true,
321                ..WindowOptions::default()
322            },
323            "window_popup_focus_dismiss",
324        );
325
326        let mut missing = caps;
327        missing.transient_ownership = false;
328        assert_capability_refusal(
329            missing,
330            WindowOptions {
331                transient_for: Some(WidgetId(1)),
332                ..WindowOptions::default()
333            },
334            "window_transient",
335        );
336
337        let mut missing = caps;
338        missing.undecorated = false;
339        assert_capability_refusal(
340            missing,
341            WindowOptions {
342                decorations: false,
343                ..WindowOptions::default()
344            },
345            "window_undecorated",
346        );
347
348        let mut missing = caps;
349        missing.always_on_top = false;
350        assert_capability_refusal(
351            missing,
352            WindowOptions {
353                stacking: Stacking::AlwaysOnTop,
354                ..WindowOptions::default()
355            },
356            "window_always_on_top",
357        );
358
359        let mut missing = caps;
360        missing.uniform_translucency = false;
361        assert_capability_refusal(
362            missing,
363            WindowOptions {
364                opacity: 0.5,
365                ..WindowOptions::default()
366            },
367            "window_translucent",
368        );
369
370        let mut missing = caps;
371        missing.shape_rounded = false;
372        assert_capability_refusal(
373            missing,
374            WindowOptions {
375                shape: WindowShape::Rounded { radius: 8 },
376                ..WindowOptions::default()
377            },
378            "window_shape_rounded",
379        );
380
381        let mut missing = caps;
382        missing.show_fade = false;
383        assert_capability_refusal(
384            missing,
385            WindowOptions {
386                show_effect: ShowEffect::Fade { duration_ms: 100 },
387                ..WindowOptions::default()
388            },
389            "window_show_fade",
390        );
391
392        let mut missing = caps;
393        missing.show_slide = false;
394        assert_capability_refusal(
395            missing,
396            WindowOptions {
397                hide_effect: ShowEffect::Slide {
398                    edge: AnchorEdge::Below,
399                    duration_ms: 100,
400                },
401                ..WindowOptions::default()
402            },
403            "window_show_slide",
404        );
405
406        let mut missing = caps;
407        missing.undecorated = false;
408        assert_capability_refusal(
409            missing,
410            WindowOptions {
411                role: WindowRole::Splash,
412                decorations: false,
413                stacking: Stacking::AlwaysOnTop,
414                focus: WindowFocusPolicy::NoTake,
415                ..WindowOptions::default()
416            },
417            "window_splash",
418        );
419    }
420
421    #[test]
422    fn popup_sessions_dismiss_once_and_owner_close_is_ordered() {
423        let mut ui = Ui::new(MockBackend::default());
424        let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
425        let anchor = ui.create(WidgetKind::Button, Some("anchor")).unwrap();
426        let popup = ui.create(WidgetKind::Window, Some("popup")).unwrap();
427        let replacement = ui.create(WidgetKind::Window, Some("replacement")).unwrap();
428        let options = popup_options(owner, anchor);
429        ui.set_window_options(popup, options).unwrap();
430        ui.set_window_options(replacement, options).unwrap();
431
432        ui.show(popup).unwrap();
433        assert_eq!(ui.backend().modal_loop_depth(), 0);
434        assert!(ui
435            .backend_mut()
436            .inject_popup_dismissal(popup, PopupDismissReason::FocusLost));
437        assert!(!ui
438            .backend_mut()
439            .inject_popup_dismissal(popup, PopupDismissReason::Escape));
440        assert_eq!(
441            ui.poll_event().unwrap(),
442            Some(UiEvent::PopupDismissed {
443                widget_id: popup,
444                reason: PopupDismissReason::FocusLost,
445            })
446        );
447        assert!(!ui.is_visible(popup));
448
449        ui.show(popup).unwrap();
450        assert!(ui
451            .backend_mut()
452            .inject_popup_dismissal(popup, PopupDismissReason::Escape));
453        assert_eq!(
454            ui.poll_event().unwrap(),
455            Some(UiEvent::PopupDismissed {
456                widget_id: popup,
457                reason: PopupDismissReason::Escape,
458            })
459        );
460
461        ui.show(popup).unwrap();
462        ui.show(replacement).unwrap();
463        assert_eq!(
464            ui.poll_event().unwrap(),
465            Some(UiEvent::PopupDismissed {
466                widget_id: popup,
467                reason: PopupDismissReason::Replaced,
468            })
469        );
470        ui.backend_mut().inject_window_closed(owner);
471        assert_eq!(
472            ui.poll_event().unwrap(),
473            Some(UiEvent::PopupDismissed {
474                widget_id: replacement,
475                reason: PopupDismissReason::OwnerClosed,
476            })
477        );
478        assert_eq!(
479            ui.poll_event().unwrap(),
480            Some(UiEvent::WindowClosed { widget_id: owner })
481        );
482    }
483
484    #[test]
485    fn app_hide_remove_and_dismiss_stay_silent() {
486        let mut ui = Ui::new(MockBackend::default());
487        let owner = ui.create(WidgetKind::Window, Some("owner")).unwrap();
488        let anchor = ui.create(WidgetKind::Button, Some("anchor")).unwrap();
489        let popup = ui.create(WidgetKind::Window, Some("popup")).unwrap();
490        ui.set_window_options(popup, popup_options(owner, anchor))
491            .unwrap();
492
493        ui.show(popup).unwrap();
494        ui.hide(popup).unwrap();
495        assert_eq!(ui.poll_event().unwrap(), None);
496        ui.show(popup).unwrap();
497        ui.dismiss_popup(popup).unwrap();
498        assert_eq!(ui.poll_event().unwrap(), None);
499        ui.show(popup).unwrap();
500        ui.remove(popup).unwrap();
501        assert_eq!(ui.poll_event().unwrap(), None);
502        assert!(ui.window_options(popup).is_err());
503
504        let popup = ui.create(WidgetKind::Window, Some("owned popup")).unwrap();
505        ui.set_window_options(popup, popup_options(owner, anchor))
506            .unwrap();
507        ui.show(popup).unwrap();
508        ui.hide(owner).unwrap();
509        assert!(!ui.is_visible(popup));
510        assert_eq!(ui.poll_event().unwrap(), None);
511        ui.show(owner).unwrap();
512        ui.show(popup).unwrap();
513        ui.remove(owner).unwrap();
514        assert!(ui.widget(popup).is_none());
515        assert_eq!(ui.poll_event().unwrap(), None);
516    }
517
518    #[test]
519    fn splash_show_is_nonblocking_and_capability_checked_as_a_composite() {
520        let mut ui = Ui::new(MockBackend::default());
521        let splash = ui.create(WidgetKind::Window, Some("splash")).unwrap();
522        ui.set_window_options(
523            splash,
524            WindowOptions {
525                role: WindowRole::Splash,
526                decorations: false,
527                stacking: Stacking::AlwaysOnTop,
528                focus: WindowFocusPolicy::NoTake,
529                ..WindowOptions::default()
530            },
531        )
532        .unwrap();
533        ui.show(splash).unwrap();
534        assert_eq!(ui.backend().modal_loop_depth(), 0);
535
536        let mut capabilities = full_capabilities();
537        capabilities.always_on_top = false;
538        ui.backend_mut().set_window_capabilities(capabilities);
539        assert_eq!(
540            ui.set_window_options(
541                splash,
542                WindowOptions {
543                    role: WindowRole::Splash,
544                    decorations: false,
545                    stacking: Stacking::AlwaysOnTop,
546                    focus: WindowFocusPolicy::NoTake,
547                    ..WindowOptions::default()
548                }
549            )
550            .unwrap_err(),
551            GuiError::UnsupportedCapability("window_splash".to_owned())
552        );
553    }
554
555    #[test]
556    fn show_and_hide_effects_are_recorded_without_blocking() {
557        let mut ui = Ui::new(MockBackend::default());
558        let window = ui.create(WidgetKind::Window, Some("effects")).unwrap();
559        let options = WindowOptions {
560            show_effect: ShowEffect::Fade { duration_ms: 80 },
561            hide_effect: ShowEffect::Slide {
562                edge: AnchorEdge::Below,
563                duration_ms: 120,
564            },
565            ..WindowOptions::default()
566        };
567        ui.set_window_options(window, options).unwrap();
568        ui.show(window).unwrap();
569        ui.hide(window).unwrap();
570
571        assert_eq!(
572            ui.backend().window_effects,
573            vec![
574                MockWindowEffect::Show {
575                    widget_id: window,
576                    effect: options.show_effect,
577                },
578                MockWindowEffect::Hide {
579                    widget_id: window,
580                    effect: options.hide_effect,
581                },
582            ]
583        );
584        assert_eq!(ui.backend().modal_loop_depth(), 0);
585    }
586}