Skip to main content

crcbl_shell/
role.rs

1//! What kind of window a [`WindowDesc`] asks for: an
2//! application window, a panel, or a popup.
3//!
4//! Most programs want [`WindowRole::Toplevel`], the window every desktop has.
5//! The other two are for desktop furniture — a status bar, a launcher, a
6//! notification, a menu opened from a bar — which every window system has a
7//! different mechanism for, and which no program should have to write three
8//! times:
9//!
10//! | role | Wayland | Win32 | AppKit |
11//! | --- | --- | --- | --- |
12//! | [`Panel`](WindowRole::Panel) | `zwlr_layer_surface_v1` | a topmost tool window; an appbar when it reserves an edge | a non-activating `NSPanel` |
13//! | [`Popup`](WindowRole::Popup) | `xdg_popup` | a `WS_POPUP` tool window | a child `NSPanel` |
14//!
15//! Which roles a backend can build is in its caps —
16//! [`ShellCaps::PANEL`] and
17//! [`ShellCaps::POPUP`] — and asking for one it cannot
18//! is [`ShellError::Unsupported`], never a
19//! toplevel in its place: a bar that silently became a normal window would
20//! cover the desktop it was meant to sit at the edge of.
21
22use crate::geom::LogicalRect;
23use crate::monitor::MonitorId;
24use crate::window::{WindowDesc, WindowId};
25use crate::{ShellBackend, ShellCaps, ShellError};
26
27/// What kind of window to create — see the [module docs](self).
28#[derive(Clone, Copy, Debug, Default, PartialEq)]
29#[non_exhaustive]
30pub enum WindowRole<'a> {
31    /// An ordinary application window: decorated, in the taskbar, moved and
32    /// sized by the user and the window manager.
33    #[default]
34    Toplevel,
35    /// Desktop furniture placed against a monitor's edges — a bar, a dock, a
36    /// launcher, an overlay. See [`PanelDesc`].
37    Panel(PanelDesc<'a>),
38    /// A window anchored to a rectangle of another, above it — a menu, a
39    /// tooltip, a calendar opened from a bar. See [`PopupDesc`].
40    Popup(PopupDesc),
41}
42
43/// Where a [panel](WindowRole::Panel) goes and how it behaves.
44///
45/// Laid out the way `wlr-layer-shell` describes a surface, because that
46/// protocol is the most complete statement of what a panel is: the other
47/// window systems implement a subset, and the backend docs say which.
48///
49/// **Its size is [`WindowDesc::size`], with one
50/// exception: along an axis where it is anchored to both opposite edges, that
51/// size is ignored and the panel stretches between them.** A bar anchored
52/// `TOP | LEFT | RIGHT` with a size of `(0, 50)` is 50 high and as wide as the
53/// monitor. Either way the size it actually gets arrives as the first
54/// [`Resized`](crate::ShellEvent::Resized), as for any window, and is the one
55/// to draw at.
56#[derive(Clone, Copy, Debug, Default, PartialEq)]
57pub struct PanelDesc<'a> {
58    /// The name window-system rules match the panel by: the layer-shell
59    /// namespace on Wayland, which Sway's and Hyprland's per-layer rules key
60    /// on. Empty means [`WindowDesc::app_id`].
61    pub namespace: &'a str,
62    /// The monitor it is placed on, or `None` for the system's choice, which
63    /// is **where the user is** rather than the primary monitor: the
64    /// compositor's pick on Wayland (the focused output on Sway, Hyprland and
65    /// niri), and the monitor under the pointer on Win32 and AppKit. A launcher
66    /// opening on a screen the user is not looking at is the failure this
67    /// avoids.
68    pub monitor: Option<MonitorId>,
69    /// Which band of the stack it lives in.
70    pub layer: PanelLayer,
71    /// The edges it is held against. A panel held against two opposite edges
72    /// stretches between them; one held against none is centred.
73    pub anchor: PanelAnchor,
74    /// Whether, and how, it keeps other windows out of its space.
75    pub reserve: Reserve,
76    /// Space between the panel and the edges it is anchored to, in logical
77    /// units. A margin on an edge it is not anchored to does nothing.
78    pub margins: Margins,
79    /// Whether it takes the keyboard.
80    pub keyboard: PanelKeyboard,
81}
82
83/// The band of the stack a [panel](PanelDesc) lives in, bottom to top.
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
85pub enum PanelLayer {
86    /// Below every application window: a wallpaper, a desktop widget.
87    Background,
88    /// Above the background, below application windows.
89    Bottom,
90    /// Above application windows, below full-screen ones: a status bar.
91    #[default]
92    Top,
93    /// Above everything, full-screen windows included: a launcher, a lock
94    /// screen, a notification.
95    ///
96    /// Win32 has one topmost band, which `Top` uses too, so there an overlay
97    /// is above application windows and shares the band with full-screen
98    /// ones that are topmost themselves.
99    Overlay,
100}
101
102bitflags::bitflags! {
103    /// The monitor edges a [panel](PanelDesc) is held against.
104    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
105    pub struct PanelAnchor: u8 {
106        /// The top edge.
107        const TOP = 1 << 0;
108        /// The bottom edge.
109        const BOTTOM = 1 << 1;
110        /// The left edge.
111        const LEFT = 1 << 2;
112        /// The right edge.
113        const RIGHT = 1 << 3;
114    }
115}
116
117/// Whether a [panel](PanelDesc) keeps other windows out of its space.
118///
119/// **Reserving is a request a window system may be unable to grant**, which is
120/// different from being unable to build the panel at all:
121/// [`ShellCaps::PANEL_RESERVE`] says whether
122/// this backend can. Where it cannot — macOS, which lets nothing but the menu
123/// bar and the Dock reserve screen space — the panel is still created and
124/// simply overlaps what is behind it.
125#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
126pub enum Reserve {
127    /// It reserves nothing, and keeps clear of the space other panels have
128    /// reserved — a launcher placed below a bar rather than over it.
129    /// Layer-shell's exclusive zone 0.
130    #[default]
131    None,
132    /// The edge it is anchored to gives up the panel's own extent: maximised
133    /// windows stop at it. A bar is this. Layer-shell's exclusive zone equal
134    /// to the panel's extent across that edge.
135    ///
136    /// **The panel must name one edge**: anchored to exactly one, or to one and
137    /// both of the edges beside it — `TOP`, or `TOP | LEFT | RIGHT`, reserves
138    /// the top. Any other anchoring has no edge to reserve, and creating it is
139    /// [`ShellError::Unsupported`] on every
140    /// backend; see [`PanelDesc::reserved_edge`].
141    OwnExtent,
142    /// It reserves nothing and is placed as if no other panel reserved
143    /// anything — at the very edge, over other bars. Layer-shell's exclusive
144    /// zone -1.
145    IgnoreOthers,
146}
147
148impl PanelDesc<'_> {
149    /// The edge [`Reserve::OwnExtent`] would reserve: the one anchored edge,
150    /// alone or with both of its neighbours. `None` for any other anchoring,
151    /// which has no single edge to give up.
152    #[must_use]
153    pub fn reserved_edge(&self) -> Option<PanelAnchor> {
154        let vertical = PanelAnchor::LEFT | PanelAnchor::RIGHT;
155        let horizontal = PanelAnchor::TOP | PanelAnchor::BOTTOM;
156        [
157            (PanelAnchor::TOP, vertical),
158            (PanelAnchor::BOTTOM, vertical),
159            (PanelAnchor::LEFT, horizontal),
160            (PanelAnchor::RIGHT, horizontal),
161        ]
162        .into_iter()
163        .find(|&(edge, beside)| self.anchor == edge || self.anchor == edge | beside)
164        .map(|(edge, _)| edge)
165    }
166}
167
168/// Space around a [panel](PanelDesc), in logical units.
169#[derive(Clone, Copy, Debug, Default, PartialEq)]
170pub struct Margins {
171    /// From the top edge.
172    pub top: f64,
173    /// From the right edge.
174    pub right: f64,
175    /// From the bottom edge.
176    pub bottom: f64,
177    /// From the left edge.
178    pub left: f64,
179}
180
181/// Whether a [panel](PanelDesc) takes the keyboard.
182#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
183pub enum PanelKeyboard {
184    /// Never: a click leaves focus where it was. A bar is this.
185    #[default]
186    None,
187    /// When clicked, like an application window.
188    OnDemand,
189    /// Takes it on mapping: a launcher, a lock screen. Keys typed the moment
190    /// it appears are its, or
191    /// [`FocusRefused`](crate::ShellEvent::FocusRefused) says the window
192    /// system would not hand it over.
193    ///
194    /// Held while mapped only where
195    /// [`ShellCaps::PANEL_EXCLUSIVE_KEYBOARD`](crate::ShellCaps::PANEL_EXCLUSIVE_KEYBOARD)
196    /// is set. Elsewhere the user can click another window and the panel
197    /// hears [`Focus`](crate::ShellEvent::Focus) with `focused: false`;
198    /// nothing takes the keyboard back, since that would fight the user and
199    /// the system's foreground rules.
200    Exclusive,
201}
202
203/// Where a [popup](WindowRole::Popup) goes.
204#[derive(Clone, Copy, Debug, PartialEq)]
205pub struct PopupDesc {
206    /// The window it belongs to and moves with. Destroying the parent
207    /// destroys the popup.
208    pub parent: WindowId,
209    /// The rectangle it is placed against, in the parent's logical
210    /// coordinates — the module or button that opened it.
211    pub anchor: LogicalRect,
212    /// Which side of the anchor it opens on. The system flips it to the other
213    /// side, or slides it along this one, rather than let it leave the screen.
214    pub placement: PopupPlacement,
215    /// What input it takes while open.
216    pub input: PopupInput,
217}
218
219/// What input a [popup](PopupDesc) takes.
220#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
221pub enum PopupInput {
222    /// None at all: the pointer passes through it to whatever is beneath, and
223    /// it never activates. A tooltip is this, so hovering stays on the bar
224    /// that showed it.
225    #[default]
226    Passthrough,
227    /// The pointer over it, as any window has; never the keyboard, and a click
228    /// elsewhere leaves it open.
229    Pointer,
230    /// The pointer and the keyboard while it is open. A click outside it or
231    /// `Escape` dismisses it, which arrives as a
232    /// [`CloseRequested`](crate::ShellEvent::CloseRequested) for it. A menu or
233    /// a calendar is this.
234    ///
235    /// `Escape` is still delivered: the popup hears the
236    /// [`Key`](crate::ShellEvent::Key) press first and the `CloseRequested`
237    /// after it, so a consumer can tell a dismissal by the keyboard from one by
238    /// a click, and can answer [`CloseReply::Keep`](crate::CloseReply::Keep)
239    /// to back out of a submenu instead of closing the whole menu. Only a
240    /// fresh press dismisses — an auto-repeat or a release does not.
241    Grab,
242}
243
244/// Whether `key`, delivered to a window whose popup input is `popup`, asks
245/// for that window to close: a fresh press of `Escape` on a
246/// [`PopupInput::Grab`] popup, as that variant documents. `popup` is `None`
247/// for a window that is not a popup.
248///
249/// `Escape` is the key's **symbol**, [`Keysym::ESCAPE`](crcbl_core::input::Keysym::ESCAPE),
250/// not its physical key: an xkb remap such as `caps:escape` dismisses the
251/// popup, and a virtual keyboard whose own keymap puts Down on the scancode a
252/// physical Escape has (`wtype` uses evdev 1) does not.
253///
254/// Every backend that builds popups calls this after queueing the key, and on
255/// `true` queues the window's
256/// [`CloseRequested`](crate::ShellEvent::CloseRequested) through its own
257/// close-request path, so a request already pending is not repeated.
258pub(crate) fn escape_dismisses(popup: Option<PopupInput>, key: &crate::ShellEvent) -> bool {
259    popup == Some(PopupInput::Grab)
260        && matches!(
261            key,
262            crate::ShellEvent::Key {
263                keysym: crcbl_core::input::Keysym::ESCAPE,
264                state: crcbl_core::input::ButtonState::Pressed,
265                repeat: false,
266                ..
267            }
268        )
269}
270
271/// What every backend checks before it builds a window: that its caps cover
272/// the role and the transparency asked for, that a reserved panel names one
273/// edge, and that a panel's monitor exists.
274///
275/// The popup's parent is the backend's to check, since only it knows its
276/// windows.
277pub(crate) fn check(
278    desc: &WindowDesc<'_>,
279    caps: ShellCaps,
280    backend: ShellBackend,
281    has_monitor: impl Fn(MonitorId) -> bool,
282) -> Result<(), ShellError> {
283    let unsupported = |what| Err(ShellError::Unsupported { backend, what });
284    if desc.transparent && !caps.contains(ShellCaps::TRANSPARENT) {
285        return unsupported("transparent windows");
286    }
287    match desc.role {
288        WindowRole::Toplevel => Ok(()),
289        WindowRole::Panel(panel) => check_panel(&panel, caps, backend, has_monitor),
290        WindowRole::Popup(_) if !caps.contains(ShellCaps::POPUP) => unsupported("popup windows"),
291        WindowRole::Popup(_) => Ok(()),
292    }
293}
294
295/// The panel half of [`check`], which
296/// [`Shell::set_panel`](crate::Shell::set_panel) applies to a panel's new
297/// descriptor too, so a panel cannot be reconfigured into one it could not
298/// have been created as.
299fn check_panel(
300    panel: &PanelDesc<'_>,
301    caps: ShellCaps,
302    backend: ShellBackend,
303    has_monitor: impl Fn(MonitorId) -> bool,
304) -> Result<(), ShellError> {
305    let unsupported = |what| Err(ShellError::Unsupported { backend, what });
306    if !caps.contains(ShellCaps::PANEL) {
307        return unsupported("panel windows");
308    }
309    if panel.reserve == Reserve::OwnExtent && panel.reserved_edge().is_none() {
310        return unsupported("a reserved panel that is not held against one edge");
311    }
312    match panel.monitor {
313        Some(monitor) if !has_monitor(monitor) => Err(ShellError::NoSuchMonitor(monitor.0)),
314        _ => Ok(()),
315    }
316}
317
318/// What every backend checks before it reconfigures a panel with
319/// [`Shell::set_panel`](crate::Shell::set_panel): that the window is a panel,
320/// whose descriptor is `was`, that the new descriptor keeps its namespace and
321/// its monitor, and that it passes the checks a new panel would.
322///
323/// The namespace and the monitor are fixed by `wlr-layer-shell`, which names
324/// both in `get_layer_surface` and has no request to change either. Refusing
325/// a change on every backend, rather than only where the protocol does, keeps
326/// a panel that works on one system from failing on another.
327pub(crate) fn check_set_panel(
328    window: WindowId,
329    was: Option<PanelDesc<'_>>,
330    panel: &PanelDesc<'_>,
331    caps: ShellCaps,
332    backend: ShellBackend,
333    has_monitor: impl Fn(MonitorId) -> bool,
334) -> Result<(), ShellError> {
335    let Some(was) = was else {
336        return Err(not_a_panel(window));
337    };
338    if panel.namespace != was.namespace {
339        return Err(ShellError::InvalidDescriptor(
340            "set_panel: a panel's namespace is fixed when it is created".to_string(),
341        ));
342    }
343    if panel.monitor != was.monitor {
344        return Err(ShellError::InvalidDescriptor(
345            "set_panel: a panel's monitor is fixed when it is created".to_string(),
346        ));
347    }
348    check_panel(panel, caps, backend, has_monitor)
349}
350
351/// What [`Shell::set_panel`](crate::Shell::set_panel) answers for a window
352/// that is not a panel, in every backend's words alike.
353pub(crate) fn not_a_panel(window: WindowId) -> ShellError {
354    ShellError::InvalidDescriptor(format!("set_panel: {window:?} is not a panel"))
355}
356
357/// A [`PanelDesc`] kept past the call that gave it, for the backends that
358/// have no panel record of their own: the namespace owned, the rest as given.
359#[derive(Clone, Debug, PartialEq)]
360pub(crate) struct KeptPanel {
361    namespace: String,
362    /// The descriptor with an empty namespace, which [`desc`](Self::desc)
363    /// puts back.
364    desc: PanelDesc<'static>,
365}
366
367impl KeptPanel {
368    pub(crate) fn new(desc: &PanelDesc<'_>) -> Self {
369        Self {
370            namespace: desc.namespace.to_string(),
371            desc: PanelDesc {
372                namespace: "",
373                ..*desc
374            },
375        }
376    }
377
378    /// The descriptor as it was given.
379    pub(crate) fn desc(&self) -> PanelDesc<'_> {
380        PanelDesc {
381            namespace: &self.namespace,
382            ..self.desc
383        }
384    }
385}
386
387/// Which side of its anchor a [popup](PopupDesc) opens on.
388#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
389pub enum PopupPlacement {
390    /// Below the anchor, left edges aligned.
391    #[default]
392    Below,
393    /// Above the anchor, left edges aligned.
394    Above,
395    /// To the left of the anchor, top edges aligned.
396    Left,
397    /// To the right of the anchor, top edges aligned: a submenu.
398    Right,
399}
400
401/// A rectangle in a backend's own Y-down space — desktop pixels on Win32,
402/// flipped screen points on AppKit — for [`place_popup`].
403///
404/// Compiled where its callers are: the two backends that place popups
405/// themselves.
406#[cfg(any(target_os = "windows", target_os = "macos", test))]
407#[derive(Clone, Copy, Debug, PartialEq)]
408pub(crate) struct Placed {
409    pub x: f64,
410    pub y: f64,
411    pub width: f64,
412    pub height: f64,
413}
414
415/// Where a popup of `width × height` goes against `anchor`: on the
416/// `placement` side of it, flipped to the other side when it does not fit in
417/// `area` and the other side does, and slid along the side it is on to stay
418/// in `area`.
419///
420/// The placement `xdg_positioner` is asked for on Wayland, worked out here
421/// for the window systems that have no one to ask. Y grows downwards.
422/// What [`Shell::reposition_popup`](crate::Shell::reposition_popup) answers
423/// for a window that is not a popup, in every backend's words alike.
424pub(crate) fn not_a_popup(window: WindowId) -> ShellError {
425    ShellError::InvalidDescriptor(format!("reposition_popup: {window:?} is not a popup"))
426}
427
428#[cfg(any(target_os = "windows", target_os = "macos", test))]
429pub(crate) fn place_popup(
430    anchor: Placed,
431    (width, height): (f64, f64),
432    placement: PopupPlacement,
433    area: Placed,
434) -> (f64, f64) {
435    let (left, top) = (anchor.x, anchor.y);
436    let (right, bottom) = (left + anchor.width, top + anchor.height);
437    let (area_right, area_bottom) = (area.x + area.width, area.y + area.height);
438    // The near start on the placement's axis, or the flip when only that fits.
439    let side = |near: f64, far: f64, extent: f64, low: f64, high: f64| {
440        if near >= low && near + extent <= high {
441            near
442        } else if far >= low && far + extent <= high {
443            far
444        } else {
445            near
446        }
447    };
448    let slide = |start: f64, extent: f64, low: f64, high: f64| start.min(high - extent).max(low);
449    match placement {
450        PopupPlacement::Below => (
451            slide(left, width, area.x, area_right),
452            side(bottom, top - height, height, area.y, area_bottom),
453        ),
454        PopupPlacement::Above => (
455            slide(left, width, area.x, area_right),
456            side(top - height, bottom, height, area.y, area_bottom),
457        ),
458        PopupPlacement::Left => (
459            side(left - width, right, width, area.x, area_right),
460            slide(top, height, area.y, area_bottom),
461        ),
462        PopupPlacement::Right => (
463            side(right, left - width, width, area.x, area_right),
464            slide(top, height, area.y, area_bottom),
465        ),
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::{
472        PanelAnchor, PanelDesc, PopupDesc, PopupInput, PopupPlacement, Reserve, WindowRole,
473    };
474    use crate::{
475        HeadlessShell, LogicalRect, MonitorId, Shell, ShellCaps, ShellError, ShellEvent, WindowDesc,
476    };
477
478    #[test]
479    fn only_a_fresh_escape_press_on_a_grabbing_popup_dismisses_it() {
480        use crcbl_core::KeyCode;
481        use crcbl_core::input::{ButtonState, DeviceId, Keysym, Modifiers, Scancode};
482
483        let window = crate::WindowId::from_bits(1 << 32).expect("a valid handle");
484        let key = |key_code, keysym, state, repeat| ShellEvent::Key {
485            window,
486            device: DeviceId(1),
487            time: crcbl_core::EventTime::ZERO,
488            scancode: Scancode(0),
489            key_code,
490            keysym,
491            state,
492            repeat,
493            modifiers: Modifiers::empty(),
494        };
495        let pressed = ButtonState::Pressed;
496        let escape = key(Some(KeyCode::Escape), Keysym::ESCAPE, pressed, false);
497        let grab = Some(PopupInput::Grab);
498        assert!(super::escape_dismisses(grab, &escape));
499        // The symbol decides: Caps Lock remapped to Escape (`caps:escape`)
500        // dismisses, and wtype's Down on evdev 1, Escape's scancode, does not.
501        let remapped = key(Some(KeyCode::CapsLock), Keysym::ESCAPE, pressed, false);
502        assert!(super::escape_dismisses(grab, &remapped));
503        let wtype_down = key(Some(KeyCode::Escape), Keysym::DOWN, pressed, false);
504        assert!(!super::escape_dismisses(grab, &wtype_down));
505
506        // Not a release, a repeat, another key, or a key with no symbol.
507        let released = key(
508            Some(KeyCode::Escape),
509            Keysym::ESCAPE,
510            ButtonState::Released,
511            false,
512        );
513        let repeated = key(Some(KeyCode::Escape), Keysym::ESCAPE, pressed, true);
514        let enter = key(Some(KeyCode::Enter), Keysym::RETURN, pressed, false);
515        let unnamed = key(None, Keysym::NONE, pressed, false);
516        for other in [&released, &repeated, &enter, &unnamed] {
517            assert!(!super::escape_dismisses(grab, other), "{other:?}");
518        }
519        // And not on a popup that does not hold the keyboard, or on a window
520        // that is no popup at all.
521        for input in [
522            Some(PopupInput::Pointer),
523            Some(PopupInput::Passthrough),
524            None,
525        ] {
526            assert!(!super::escape_dismisses(input, &escape), "{input:?}");
527        }
528        // Only a key event is a keystroke.
529        assert!(!super::escape_dismisses(
530            grab,
531            &ShellEvent::CloseRequested { window }
532        ));
533    }
534
535    fn panel(anchor: PanelAnchor) -> PanelDesc<'static> {
536        PanelDesc {
537            anchor,
538            ..PanelDesc::default()
539        }
540    }
541
542    #[test]
543    fn a_reserved_edge_is_one_edge_alone_or_with_both_neighbours() {
544        let top = PanelAnchor::TOP;
545        let sides = PanelAnchor::LEFT | PanelAnchor::RIGHT;
546        assert_eq!(panel(top).reserved_edge(), Some(top));
547        assert_eq!(panel(top | sides).reserved_edge(), Some(top));
548        let left = PanelAnchor::LEFT;
549        let ends = PanelAnchor::TOP | PanelAnchor::BOTTOM;
550        assert_eq!(panel(left | ends).reserved_edge(), Some(left));
551        assert_eq!(
552            panel(PanelAnchor::BOTTOM).reserved_edge(),
553            Some(PanelAnchor::BOTTOM)
554        );
555        // A corner, a centre and an everything name no single edge.
556        assert_eq!(panel(top | PanelAnchor::LEFT).reserved_edge(), None);
557        assert_eq!(panel(PanelAnchor::empty()).reserved_edge(), None);
558        assert_eq!(panel(PanelAnchor::all()).reserved_edge(), None);
559        assert_eq!(panel(sides).reserved_edge(), None);
560    }
561
562    fn with_role(role: WindowRole<'_>) -> WindowDesc<'_> {
563        WindowDesc {
564            role,
565            ..WindowDesc::default()
566        }
567    }
568
569    fn refused(result: Result<crate::WindowId, ShellError>) -> &'static str {
570        match result {
571            Err(ShellError::Unsupported { what, .. }) => what,
572            other => panic!("expected Unsupported, got {other:?}"),
573        }
574    }
575
576    #[test]
577    fn a_role_or_transparency_the_caps_lack_is_refused_not_downgraded() {
578        let mut shell = HeadlessShell::new().with_caps(
579            ShellCaps::DESKTOP - (ShellCaps::PANEL | ShellCaps::POPUP | ShellCaps::TRANSPARENT),
580        );
581        let parent = shell
582            .create_window(&WindowDesc::default())
583            .expect("a toplevel");
584        assert_eq!(
585            refused(shell.create_window(&with_role(WindowRole::Panel(PanelDesc::default())))),
586            "panel windows"
587        );
588        let popup = WindowRole::Popup(PopupDesc {
589            parent,
590            anchor: LogicalRect::default(),
591            placement: PopupPlacement::Below,
592            input: PopupInput::Grab,
593        });
594        assert_eq!(
595            refused(shell.create_window(&with_role(popup))),
596            "popup windows"
597        );
598        let transparent = WindowDesc {
599            transparent: true,
600            ..WindowDesc::default()
601        };
602        assert_eq!(
603            refused(shell.create_window(&transparent)),
604            "transparent windows"
605        );
606    }
607
608    #[test]
609    fn a_reserved_panel_needs_one_edge_and_a_real_monitor() {
610        let mut shell = HeadlessShell::new();
611        let cornered = PanelDesc {
612            reserve: Reserve::OwnExtent,
613            ..panel(PanelAnchor::TOP | PanelAnchor::LEFT)
614        };
615        assert_eq!(
616            refused(shell.create_window(&with_role(WindowRole::Panel(cornered)))),
617            "a reserved panel that is not held against one edge"
618        );
619        let bar = PanelDesc {
620            reserve: Reserve::OwnExtent,
621            ..panel(PanelAnchor::TOP | PanelAnchor::LEFT | PanelAnchor::RIGHT)
622        };
623        shell
624            .create_window(&with_role(WindowRole::Panel(bar)))
625            .expect("a bar names the top edge");
626        let elsewhere = PanelDesc {
627            monitor: Some(MonitorId(u32::MAX)),
628            ..PanelDesc::default()
629        };
630        assert!(matches!(
631            shell.create_window(&with_role(WindowRole::Panel(elsewhere))),
632            Err(ShellError::NoSuchMonitor(_))
633        ));
634    }
635
636    #[test]
637    fn a_popup_needs_a_live_parent_and_goes_with_it() {
638        let mut shell = HeadlessShell::new();
639        let parent = shell
640            .create_window(&WindowDesc::default())
641            .expect("a toplevel");
642        let popup_of = |parent| {
643            WindowRole::Popup(PopupDesc {
644                parent,
645                anchor: LogicalRect::default(),
646                placement: PopupPlacement::Below,
647                input: PopupInput::Passthrough,
648            })
649        };
650        let popup = shell
651            .create_window(&with_role(popup_of(parent)))
652            .expect("a popup");
653        let submenu = shell
654            .create_window(&with_role(popup_of(popup)))
655            .expect("a popup's popup");
656        shell.pump(&mut |_| {});
657
658        shell.destroy_window(parent).expect("destroy");
659        let mut destroyed = Vec::new();
660        shell.pump(&mut |event| {
661            if let ShellEvent::WindowDestroyed { window } = event {
662                destroyed.push(window);
663            }
664        });
665        assert_eq!(
666            destroyed,
667            [submenu, popup, parent],
668            "children first, each reported"
669        );
670        assert!(
671            shell.create_window(&with_role(popup_of(parent))).is_err(),
672            "a dead parent"
673        );
674    }
675}