Skip to main content

egui_pop_core/
overlay.rs

1//! The overlay stack: dialogs, popovers and menus above the interface.
2//!
3//! [`OverlayStack`] is the model, pure and tested by its invariants:
4//!
5//! - Escape dismisses the **top** overlay only (if it allows it);
6//! - a click outside dismisses the dismissable overlays above the one
7//!   clicked (or all of them), stopping at a modal: nothing below a modal
8//!   receives the click;
9//! - closing an overlay closes every overlay opened above it;
10//! - each overlay remembers the widget focused when it opened; when it
11//!   closes, the focus goes back there (see **Focus** below).
12//!
13//! [`show`] is the egui side: it keeps the stack in the context, draws an
14//! overlay (a modal with a backdrop, or an area placed next to an anchor
15//! with [`crate::placement`]) and restores the focus. [`hold`] keeps in
16//! the stack an overlay its owner lays out and draws itself (a side
17//! area's flyout), so it closes by the same rules.
18//!
19//! **Keys held.** A modal coming up reads no key that was already down:
20//! the press in that very pass goes, and so does each repeat until the key
21//! is released. Else the key that opened it would answer it, unseen: egui
22//! clicks a focused widget on Enter or Space, the press and every repeat,
23//! and the modal's first focus is such a widget. A modal closing does the
24//! same for what is behind it: the Enter that accepts it does not click the
25//! button the focus goes back to, which would open it again.
26//!
27//! **Focus.** While a modal's layer is on top, egui takes the focus off any
28//! widget below it as that widget is drawn, and it stays on top for the
29//! pass after the last one drawing it. So the focus goes back once the
30//! widget can hold it, a pass or two after the closing, unless something
31//! else took the focus meanwhile (the command a dialog ran). An overlay
32//! opening in that gap (the next dialog of a queue) inherits the place, and
33//! gives it back in its turn. A widget gone by then takes nothing.
34//!
35//! **egui popups.** A combo box's list, a context menu or an egui menu
36//! opened from inside an overlay is an egui area of its own, drawn while
37//! the overlay is drawn but outside its rect. Both [`show`] and [`hold`]
38//! note the layers first drawn while the overlay draws: a press on one of
39//! them is inside the overlay, not a click away, and while one is open
40//! Escape is left to it (it closes first, the overlay at the next
41//! press).
42//!
43//! **Tab.** A [`Kind::Popover`] on top of the stack keeps Tab, cycling through
44//! its stops ([`crate::focus::keep_tab`]), with the focus plugin installed. A
45//! menu's keys are its own, and an overlay held by its owner ([`hold`], a flyout)
46//! lets the focus leave.
47//!
48//! **Windows.** Each window has its own stack: an overlay belongs to the
49//! window it is shown in (a detached panel's window, egui's viewport),
50//! and Escape and outside clicks there close only its overlays. A modal
51//! open in one window blocks the others ([`block_window`]), and
52//! [`modal_open`] says whether one is open anywhere; [`stack`] and
53//! [`rects`] are the current window's.
54//!
55//! **Resizable modals.** A modal declared with
56//! [`OverlaySpec::resizable`] is dragged by its edges and corners, down
57//! to a least size and within the window; it keeps the size asked when
58//! the window gets too small for it, and takes it back when the window
59//! grows again. Its bottom right corner is a handle (the kit's
60//! `dialog-grip`) for the keyboard too: it takes the focus, the arrows
61//! resize (with Shift, by bigger steps), and it is a splitter named
62//! "Resize" and the overlay's label, the size its value.
63//! [`modal_size`] reads the size, [`modal_resizing`] says whether a drag
64//! is going on. Every other modal is as wide as it is declared and as
65//! high as its content, as before.
66//!
67//! egui's `Window` has such edges, but it is not a modal (no backdrop,
68//! no stack) and names nothing for assistive technology; `Resize` only
69//! has a corner. So the grips are here, on the modal's own area.
70//!
71//! ```
72//! use egui_pop_core::overlay::{self, Kind, OverlaySpec};
73//!
74//! let ctx = egui::Context::default();
75//! let spec = OverlaySpec::new("big", "Big dialog", Kind::Modal)
76//!     .resizable(egui::vec2(500.0, 300.0), egui::vec2(200.0, 100.0));
77//! let mut open = true;
78//! let mut out = ctx.run_ui(Default::default(), |ui| {
79//!     overlay::show(ui.ctx(), &spec, &mut open, None, |ui| {
80//!         ui.label("Whatever the size, this fills it.");
81//!     });
82//! });
83//! out.textures_delta.clear();
84//! assert_eq!(overlay::modal_size(&ctx, spec.id), Some(egui::vec2(500.0, 300.0)));
85//! ```
86
87use std::collections::{BTreeSet, HashMap};
88
89use egui::{
90    Context, Event, Id, Key, LayerId, NumExt as _, Rect, Sense, Ui, UiBuilder, Vec2, ViewportId,
91};
92use serde::Serialize;
93
94use crate::placement::{Placement, Side, place};
95use crate::pointer::DragKind;
96use crate::state::{forget_window, lock, pass, shared, shared_of_window};
97
98/// What kind of overlay.
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
100#[serde(rename_all = "lowercase")]
101pub enum Kind {
102    /// Blocks what is below; Escape closes it, a click outside does not.
103    Modal,
104    /// Floats next to an anchor; Escape or a click outside closes it (a
105    /// press on its anchor is not outside: the widget that opened it
106    /// toggles it).
107    Popover,
108    /// As a popover, for menus.
109    Menu,
110}
111
112/// How a modal may be resized ([`OverlaySpec::resizable`]): sizes of its
113/// content, in points, as [`OverlaySpec::width`] is.
114#[derive(Clone, Copy, Debug, PartialEq)]
115pub struct ModalSize {
116    /// The size it opens at (the window may hold it smaller).
117    pub size: Vec2,
118    /// The least size a drag leaves it (the window may hold it smaller).
119    pub min: Vec2,
120}
121
122/// An overlay as declared.
123#[derive(Clone, Debug, PartialEq, Serialize)]
124pub struct OverlaySpec {
125    #[serde(skip)]
126    pub id: Id,
127    /// What it is, for the debug bridge and accessibility.
128    pub label: String,
129    pub kind: Kind,
130    pub dismiss_on_escape: bool,
131    pub dismiss_on_outside: bool,
132    /// A modal's width, when the dialog width token is too narrow (a
133    /// settings window).
134    pub width: Option<f32>,
135    /// A modal's offset from the window's centre, in points (a dialog
136    /// moved by the user).
137    #[serde(skip)]
138    pub offset: egui::Vec2,
139    /// How much of the theme's backdrop a modal dims the interface with
140    /// (`backdrop.opacity`): 1 by default, 0 for none (the interface stays
141    /// as it is, still blocked).
142    pub dim: f32,
143    /// A modal the person resizes; it then has the size asked, whatever
144    /// `width` says.
145    #[serde(skip)]
146    pub resize: Option<ModalSize>,
147}
148
149impl OverlaySpec {
150    pub fn new(id: impl std::hash::Hash + std::fmt::Debug, label: &str, kind: Kind) -> Self {
151        Self {
152            id: Id::unique(id),
153            label: label.into(),
154            kind,
155            dismiss_on_escape: true,
156            dismiss_on_outside: kind != Kind::Modal,
157            width: None,
158            offset: egui::Vec2::ZERO,
159            dim: 1.0,
160            resize: None,
161        }
162    }
163
164    /// A modal the person resizes: opening at `size` (of its content, in
165    /// points), dragged by its edges and corners down to `min` and
166    /// within the window. It has that size whatever its content needs:
167    /// what does not fit is clipped, so `add` lays itself out in the
168    /// room it is given. `width` no longer counts, and only a modal can
169    /// be resized (a popover or a menu says so in the log and stays as
170    /// it is).
171    pub fn resizable(mut self, size: Vec2, min: Vec2) -> Self {
172        if self.kind != Kind::Modal {
173            log::warn!(target: "egui_pop", "overlay `{}`: only a modal can be resized", self.label);
174            return self;
175        }
176        self.resize = Some(ModalSize { size, min });
177        self
178    }
179
180    /// A modal this far from the window's centre (points).
181    pub fn offset(mut self, offset: egui::Vec2) -> Self {
182        self.offset = offset;
183        self
184    }
185
186    /// A modal dimming the interface with this share of the theme's
187    /// backdrop (0 to 1).
188    pub fn dim(mut self, dim: f32) -> Self {
189        self.dim = dim.clamp(0.0, 1.0);
190        self
191    }
192
193    /// A modal this wide (points; capped to the window).
194    pub fn width(mut self, width: f32) -> Self {
195        self.width = Some(width);
196        self
197    }
198
199    /// Escape does not close it (a modal waiting for an answer).
200    pub fn keep_on_escape(mut self) -> Self {
201        self.dismiss_on_escape = false;
202        self
203    }
204}
205
206/// Why an overlay closed.
207#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
208#[serde(rename_all = "snake_case")]
209pub enum Reason {
210    Escape,
211    Outside,
212    /// Closed by its owner (or because it was below).
213    Closed,
214    /// An overlay below it closed.
215    Parent,
216}
217
218/// An overlay that closed, and where the focus goes.
219#[derive(Clone, Debug, PartialEq, Serialize)]
220pub struct Closed {
221    #[serde(skip)]
222    pub id: Id,
223    pub label: String,
224    pub reason: Reason,
225    #[serde(skip)]
226    pub restore_focus: Option<Id>,
227}
228
229#[derive(Clone, Debug, PartialEq)]
230struct Entry {
231    spec: OverlaySpec,
232    restore_focus: Option<Id>,
233    rect: Option<Rect>,
234    /// The widget it was placed next to, when one was given.
235    anchor: Option<Rect>,
236    /// The egui layers (popups, menus) drawn from inside it last pass.
237    popups: Vec<LayerId>,
238    /// A resizable modal's size, once shown.
239    geometry: Option<Geometry>,
240}
241
242/// Where a resizable modal is, as the person left it.
243#[derive(Clone, Copy, Debug, PartialEq)]
244struct Geometry {
245    /// Its content's size as asked: the window may hold it smaller.
246    size: Vec2,
247    /// Its centre's distance from where its declaration puts it: dragging
248    /// an edge leaves the opposite one in place.
249    shift: Vec2,
250    /// The whole dialog's rectangle when a grip was pressed, during a
251    /// drag.
252    grabbed: Option<Rect>,
253}
254
255impl Geometry {
256    /// The whole dialog's rectangle: `chrome` around the content, at
257    /// least `min` of content, inside `bounds`.
258    fn placed(&self, offset: Vec2, min: Vec2, chrome: Vec2, bounds: Rect) -> Rect {
259        let max = bounds.size();
260        let size = (self.size + chrome)
261            .at_most(max)
262            .at_least((min + chrome).at_most(max));
263        let rect = Rect::from_center_size(bounds.center() + offset + self.shift, size);
264        let left = rect.min.x.at_least(bounds.min.x) - rect.min.x;
265        let right = rect.max.x.at_most(bounds.max.x) - rect.max.x;
266        let top = rect.min.y.at_least(bounds.min.y) - rect.min.y;
267        let bottom = rect.max.y.at_most(bounds.max.y) - rect.max.y;
268        rect.translate(egui::vec2(left + right, top + bottom))
269    }
270
271    /// Takes the size and place of the whole dialog's `rect`.
272    fn set(&mut self, rect: Rect, offset: Vec2, chrome: Vec2, bounds: Rect) {
273        self.size = (rect.size() - chrome).round();
274        self.shift = rect.center() - bounds.center() - offset;
275    }
276}
277
278/// A grab on a resizable modal: the sides it moves (-1 the left or top
279/// one, 1 the right or bottom one, 0 neither).
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
281struct Grip {
282    x: i8,
283    y: i8,
284}
285
286/// The edges first and the corners last, which win where they overlap;
287/// the handle is the last one.
288const GRIPS: [Grip; 8] = [
289    Grip { x: 0, y: -1 },
290    Grip { x: 0, y: 1 },
291    Grip { x: -1, y: 0 },
292    Grip { x: 1, y: 0 },
293    Grip { x: -1, y: -1 },
294    Grip { x: 1, y: -1 },
295    Grip { x: -1, y: 1 },
296    Grip { x: 1, y: 1 },
297];
298
299/// The handle: the bottom right corner.
300const HANDLE: Grip = Grip { x: 1, y: 1 };
301
302impl Grip {
303    /// Where it takes the pointer on the dialog's `rect`: `reach` on
304    /// either side of an edge, `corner` in from a corner.
305    fn zone(self, rect: Rect, reach: f32, corner: f32) -> Rect {
306        let span = |side: i8, min: f32, max: f32| match side {
307            -1 => min - reach..=min + corner,
308            1 => max - corner..=max + reach,
309            _ => min + corner..=max - corner,
310        };
311        let edge = |side: i8, min: f32, max: f32, other: i8| match (side, other) {
312            (-1, 0) => min - reach..=min + reach,
313            (1, 0) => max - reach..=max + reach,
314            _ => span(side, min, max),
315        };
316        Rect::from_x_y_ranges(
317            edge(self.x, rect.min.x, rect.max.x, self.y),
318            edge(self.y, rect.min.y, rect.max.y, self.x),
319        )
320    }
321
322    fn drag_kind(self) -> DragKind {
323        match (self.x, self.y) {
324            (0, _) => DragKind::ResizeVertical,
325            (_, 0) => DragKind::ResizeHorizontal,
326            (a, b) if a == b => DragKind::ResizeNwSe,
327            _ => DragKind::ResizeNeSw,
328        }
329    }
330
331    /// The dialog's rectangle `from`, its sides moved `by` the pointer:
332    /// the others stay, at least `min` remains and all of it is inside
333    /// `bounds`.
334    fn moved(self, from: Rect, by: Vec2, min: Vec2, bounds: Rect) -> Rect {
335        let mut r = from;
336        match self.x {
337            -1 => {
338                r.min.x = (from.min.x + by.x)
339                    .at_most(from.max.x - min.x)
340                    .at_least(bounds.min.x)
341            }
342            1 => {
343                r.max.x = (from.max.x + by.x)
344                    .at_least(from.min.x + min.x)
345                    .at_most(bounds.max.x)
346            }
347            _ => {}
348        }
349        match self.y {
350            -1 => {
351                r.min.y = (from.min.y + by.y)
352                    .at_most(from.max.y - min.y)
353                    .at_least(bounds.min.y)
354            }
355            1 => {
356                r.max.y = (from.max.y + by.y)
357                    .at_least(from.min.y + min.y)
358                    .at_most(bounds.max.y)
359            }
360            _ => {}
361        }
362        r
363    }
364}
365
366/// The stack, bottom first.
367#[derive(Clone, Debug, Default)]
368pub struct OverlayStack {
369    entries: Vec<Entry>,
370}
371
372/// What opening did.
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374pub enum Opened {
375    New,
376    /// It was open already: what was above it closed, it is on top again.
377    Raised,
378}
379
380impl OverlayStack {
381    pub fn new() -> Self {
382        Self::default()
383    }
384
385    /// Opens an overlay on top, remembering the focus to restore.
386    pub fn open(&mut self, spec: OverlaySpec, focused: Option<Id>) -> (Opened, Vec<Closed>) {
387        if let Some(i) = self.position(spec.id) {
388            let closed = self.close_from(i + 1, Reason::Parent);
389            self.entries[i].spec = spec;
390            return (Opened::Raised, closed);
391        }
392        self.entries.push(Entry {
393            spec,
394            restore_focus: focused,
395            rect: None,
396            anchor: None,
397            popups: Vec::new(),
398            geometry: None,
399        });
400        (Opened::New, Vec::new())
401    }
402
403    /// Replaces an open overlay's declaration where it is (its Escape
404    /// rule, its offset), closing nothing; whether it is open.
405    pub fn update(&mut self, spec: OverlaySpec) -> bool {
406        match self.position(spec.id) {
407            Some(i) => {
408                self.entries[i].spec = spec;
409                true
410            }
411            None => false,
412        }
413    }
414
415    fn position(&self, id: Id) -> Option<usize> {
416        self.entries.iter().position(|e| e.spec.id == id)
417    }
418
419    /// Closes from index `i` up, topmost first; the focus to restore is
420    /// the lowest one's.
421    fn close_from(&mut self, i: usize, reason: Reason) -> Vec<Closed> {
422        let mut out = Vec::new();
423        while self.entries.len() > i {
424            let e = self.entries.pop().expect("an entry above i");
425            let r = if self.entries.len() == i {
426                reason
427            } else {
428                Reason::Parent
429            };
430            out.push(Closed {
431                id: e.spec.id,
432                label: e.spec.label,
433                reason: r,
434                restore_focus: e.restore_focus,
435            });
436        }
437        out
438    }
439
440    /// Closes an overlay and everything above it. Closing one that is not
441    /// open closes nothing (the list is empty).
442    pub fn close(&mut self, id: Id) -> Vec<Closed> {
443        match self.position(id) {
444            Some(i) => self.close_from(i, Reason::Closed),
445            None => Vec::new(),
446        }
447    }
448
449    /// Escape: closes the top overlay if it allows it.
450    pub fn escape(&mut self) -> Vec<Closed> {
451        match self.entries.last() {
452            Some(e) if e.spec.dismiss_on_escape => {
453                self.close_from(self.entries.len() - 1, Reason::Escape)
454            }
455            _ => Vec::new(),
456        }
457    }
458
459    /// A click on `hit` (an overlay, or `None` for the interface below):
460    /// closes the dismissable overlays above it, stopping at a modal or
461    /// at one that stays.
462    pub fn click(&mut self, hit: Option<Id>) -> Vec<Closed> {
463        let floor = hit.and_then(|h| self.position(h)).map_or(0, |i| i + 1);
464        let mut cut = self.entries.len();
465        while cut > floor {
466            let e = &self.entries[cut - 1];
467            if e.spec.kind == Kind::Modal || !e.spec.dismiss_on_outside {
468                break;
469            }
470            cut -= 1;
471        }
472        if cut == self.entries.len() {
473            Vec::new()
474        } else {
475            self.close_from(cut, Reason::Outside)
476        }
477    }
478
479    /// The topmost modal, if any: everything below it is blocked.
480    pub fn modal(&self) -> Option<Id> {
481        self.entries
482            .iter()
483            .rev()
484            .find(|e| e.spec.kind == Kind::Modal)
485            .map(|e| e.spec.id)
486    }
487
488    /// Whether input to an overlay (or to the interface, `None`) is
489    /// blocked by a modal above it.
490    pub fn is_blocked(&self, target: Option<Id>) -> bool {
491        let Some(m) = self
492            .entries
493            .iter()
494            .rposition(|e| e.spec.kind == Kind::Modal)
495        else {
496            return false;
497        };
498        match target.and_then(|t| self.position(t)) {
499            Some(i) => i < m,
500            None => true,
501        }
502    }
503
504    pub fn top(&self) -> Option<&OverlaySpec> {
505        self.entries.last().map(|e| &e.spec)
506    }
507
508    /// Whether a modal or a menu is open under `id` (or anywhere, when
509    /// `id` is not open): what opens above one stays unranked, above it
510    /// ([`crate::layers`]).
511    fn over_unranked(&self, id: Id) -> bool {
512        let end = self.position(id).unwrap_or(self.entries.len());
513        self.entries[..end]
514            .iter()
515            .any(|e| matches!(e.spec.kind, Kind::Modal | Kind::Menu))
516    }
517
518    pub fn contains(&self, id: Id) -> bool {
519        self.position(id).is_some()
520    }
521
522    pub fn len(&self) -> usize {
523        self.entries.len()
524    }
525
526    pub fn is_empty(&self) -> bool {
527        self.entries.is_empty()
528    }
529
530    /// The overlays, bottom first.
531    pub fn specs(&self) -> impl Iterator<Item = &OverlaySpec> {
532        self.entries.iter().map(|e| &e.spec)
533    }
534
535    /// Records where an overlay was drawn (for outside clicks).
536    pub fn set_rect(&mut self, id: Id, rect: Rect) {
537        if let Some(i) = self.position(id) {
538            self.entries[i].rect = Some(rect);
539        }
540    }
541
542    /// Records the widget an overlay was placed next to: a press there
543    /// is not outside it.
544    pub fn set_anchor(&mut self, id: Id, anchor: Rect) {
545        if let Some(i) = self.position(id) {
546            self.entries[i].anchor = Some(anchor);
547        }
548    }
549
550    /// Records the egui layers drawn from inside an overlay (a combo
551    /// box's list, a context menu): a press on one of them is not
552    /// outside it, and while one of them is open Escape goes to it.
553    pub fn set_popups(&mut self, id: Id, layers: Vec<LayerId>) {
554        if let Some(i) = self.position(id) {
555            self.entries[i].popups = layers;
556        }
557    }
558
559    /// The egui layers drawn from inside the top overlay last pass.
560    pub fn top_popups(&self) -> &[LayerId] {
561        self.entries.last().map_or(&[], |e| &e.popups)
562    }
563
564    /// The topmost overlay drawn, or anchored, at a point: a press on
565    /// the widget that opened an overlay leaves that overlay to it (its
566    /// click toggles it), instead of closing it on the press and the
567    /// click opening it again.
568    pub fn hit(&self, pos: egui::Pos2) -> Option<Id> {
569        self.hit_on(pos, None)
570    }
571
572    /// As [`Self::hit`], `layer` being the egui layer at the point: a
573    /// press on a popup an overlay opened is inside that overlay.
574    pub fn hit_on(&self, pos: egui::Pos2, layer: Option<LayerId>) -> Option<Id> {
575        self.entries
576            .iter()
577            .rev()
578            .find(|e| {
579                e.rect.is_some_and(|r| r.contains(pos))
580                    || e.anchor.is_some_and(|a| a.contains(pos))
581                    || layer.is_some_and(|l| e.popups.contains(&l))
582            })
583            .map(|e| e.spec.id)
584    }
585}
586
587#[derive(Debug, Default)]
588struct State {
589    pass: u64,
590    stack: OverlayStack,
591    /// Closed since the owners last looked.
592    closed: Vec<Closed>,
593    /// Shown this pass; those not shown again are closed.
594    shown: Vec<Id>,
595    shown_last: Vec<Id>,
596    history: Vec<Closed>,
597    /// The modals in the stack.
598    modals: Vec<Id>,
599    /// Where the focus goes back, once the widget can hold it.
600    focus_back: Option<Id>,
601    /// What opened and closed since the watcher last heard ([`watch`]).
602    notices: Vec<Change>,
603    /// The egui popups followed ([`follow_popup`]): open, and the pass
604    /// each was last seen in.
605    followed: Vec<Followed>,
606}
607
608/// An egui popup [`follow_popup`] follows.
609#[derive(Debug)]
610struct Followed {
611    id: Id,
612    label: String,
613    seen: u64,
614}
615
616const STATE: &str = "core.overlay";
617
618/// The windows other than the main one that have an overlay state.
619#[derive(Debug, Default)]
620struct Windows(BTreeSet<ViewportId>);
621
622fn windows(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<Windows>> {
623    shared::<Windows>(ctx, "core.overlay.windows")
624}
625
626/// The overlay state of the window being drawn: each window has its own
627/// stack, drawn in it and counting its own passes.
628fn state(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<State>> {
629    let viewport = ctx.viewport_id();
630    if viewport != ViewportId::ROOT {
631        lock(&windows(ctx)).0.insert(viewport);
632    }
633    shared_of_window::<State>(ctx, STATE, viewport)
634}
635
636/// Every window's overlay state, the main window's first.
637fn all(ctx: &Context) -> Vec<(ViewportId, std::sync::Arc<std::sync::Mutex<State>>)> {
638    let others: Vec<ViewportId> = lock(&windows(ctx)).0.iter().copied().collect();
639    std::iter::once(ViewportId::ROOT)
640        .chain(others)
641        .map(|v| (v, shared_of_window::<State>(ctx, STATE, v)))
642        .collect()
643}
644
645/// Forgets the overlays of the windows other than the main one that are
646/// not in `live` (closed windows): what they showed is gone with them.
647pub fn retain_windows(ctx: &Context, live: &[ViewportId]) {
648    let gone: Vec<ViewportId> = {
649        let w = windows(ctx);
650        let mut w = lock(&w);
651        let gone = w.0.iter().filter(|v| !live.contains(v)).copied().collect();
652        w.0.retain(|v| live.contains(v));
653        gone
654    };
655    for v in gone {
656        forget_window::<State>(ctx, STATE, v);
657    }
658}
659
660/// The windows where a modal overlay is open, the main window first.
661pub fn modal_windows(ctx: &Context) -> Vec<ViewportId> {
662    all(ctx)
663        .into_iter()
664        .filter(|(_, st)| lock(st).stack.modal().is_some())
665        .map(|(v, _)| v)
666        .collect()
667}
668
669/// Every window's open overlays, bottom first, the main window first
670/// (windows without any left out): what the debug bridge shows of the
671/// windows.
672pub fn stacks(ctx: &Context) -> Vec<(ViewportId, Vec<OverlaySpec>)> {
673    all(ctx)
674        .into_iter()
675        .map(|(v, st)| (v, lock(&st).stack.specs().cloned().collect::<Vec<_>>()))
676        .filter(|(_, specs)| !specs.is_empty())
677        .collect()
678}
679
680/// While a modal overlay is open in another window, blocks the window
681/// being drawn: its keys and typed text are dropped this pass (nothing
682/// below reads them: neither the key dispatcher nor a widget), and a
683/// backdrop over it (the theme's `backdrop`, as under a dialog) takes the
684/// pointer; a click there brings the window of the modal to the front.
685/// Call it at the start of each window's pass, before the keys are
686/// read. Returns the window holding the modal, when this one is blocked.
687///
688/// A dialog opened from a detached panel's window is shown in that window
689/// and blocks every other one, the main window included, and the other
690/// way round: every window of the application waits for the answer.
691pub fn block_window(ctx: &Context) -> Option<ViewportId> {
692    block_window_among(ctx, &|_| true)
693}
694
695/// As [`block_window`], blocked only by a modal open in a window of the
696/// same group (`same` says which windows are): an application window
697/// almost a separate application blocks only itself, and is blocked by
698/// none of the others.
699pub fn block_window_among(ctx: &Context, same: &dyn Fn(ViewportId) -> bool) -> Option<ViewportId> {
700    // Without an application (this crate alone has no bus), the system is
701    // asked directly.
702    block_window_raising(ctx, same, &|owner| {
703        ctx.send_viewport_cmd_to(owner, egui::ViewportCommand::Focus);
704    })
705}
706
707/// As [`block_window_among`], a click on the backdrop asking `raise` to
708/// bring the window of the modal to the front (an application asks its
709/// bus's `pop.window.activate`).
710pub fn block_window_raising(
711    ctx: &Context,
712    same: &dyn Fn(ViewportId) -> bool,
713    raise: &dyn Fn(ViewportId),
714) -> Option<ViewportId> {
715    let here = ctx.viewport_id();
716    let owner = modal_windows(ctx)
717        .into_iter()
718        .find(|v| *v != here && same(*v))?;
719    ctx.input_mut(|i| {
720        i.events.retain(|e| {
721            !matches!(
722                e,
723                egui::Event::Key { .. }
724                    | egui::Event::Text(_)
725                    | egui::Event::Paste(_)
726                    | egui::Event::Copy
727                    | egui::Event::Cut
728                    | egui::Event::Ime(_)
729            )
730        });
731    });
732    let kit = crate::kit::Kit::of(ctx);
733    let backdrop = &kit.backdrop;
734    let fill = backdrop
735        .style(crate::kit::State::REST)
736        .fill
737        .gamma_multiply(backdrop.data.opacity.clamp(0.0, 1.0));
738    let r = egui::Modal::new(Id::unique(("egui_pop.window_blocked", here)))
739        .backdrop_color(fill)
740        .frame(egui::Frame::NONE)
741        .show(ctx, |_| {});
742    if r.backdrop_response.clicked() || r.backdrop_response.drag_started() {
743        raise(owner);
744    }
745    Some(owner)
746}
747
748/// Once per pass, before anything reads the keyboard: Escape and outside
749/// clicks close overlays; overlays no longer shown are closed. Returns
750/// whether Escape was used (and consumed).
751pub fn begin_pass(ctx: &Context) -> bool {
752    let st = state(ctx);
753    let used = begin_pass_in(ctx, &mut lock(&st));
754    tell(ctx, &st);
755    used
756}
757
758fn begin_pass_in(ctx: &Context, s: &mut State) -> bool {
759    let now = pass(ctx);
760    if s.pass == now {
761        return false;
762    }
763    s.pass = now;
764    // A followed popup not seen last pass is gone (its widget went).
765    let window = ctx.viewport_id();
766    let (kept, gone) = std::mem::take(&mut s.followed)
767        .into_iter()
768        .partition::<Vec<_>, _>(|f| f.seen + 1 >= now);
769    s.followed = kept;
770    for f in gone {
771        s.notices
772            .push(Change::closed(window, f.id, f.label, Closing::Gone));
773    }
774    give_focus_back(ctx, s, false);
775    s.shown_last = std::mem::take(&mut s.shown);
776    // A closing is news only to an owner still showing its overlay: one
777    // left unseen would close the overlay the next time it opens.
778    let State {
779        closed, shown_last, ..
780    } = s;
781    closed.retain(|c| shown_last.contains(&c.id));
782    // An overlay whose owner stopped showing it is closed.
783    let gone: Vec<Id> = s
784        .stack
785        .specs()
786        .map(|o| o.id)
787        .filter(|id| !s.shown_last.contains(id))
788        .collect();
789    for id in gone {
790        let closed = s.stack.close(id);
791        settle(ctx, s, closed);
792    }
793    let mut used_escape = false;
794    // An egui popup (a combo box's list, a context menu, a menu) open
795    // from the top overlay takes Escape first: it closes itself.
796    let popup_open = s
797        .stack
798        .top_popups()
799        .iter()
800        .any(|l| egui::Popup::is_id_open(ctx, l.id));
801    if !s.stack.is_empty() && !popup_open && ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
802        let closed = s.stack.escape();
803        if !closed.is_empty() {
804            used_escape = true;
805            ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
806        }
807        settle(ctx, s, closed);
808    }
809    if let Some(pos) = ctx.input(|i| {
810        i.pointer
811            .any_pressed()
812            .then(|| i.pointer.interact_pos())
813            .flatten()
814    }) {
815        let layer = ctx.layer_id_at(pos);
816        let hit = s.stack.hit_on(pos, layer);
817        let closed = s.stack.click(hit);
818        settle(ctx, s, closed);
819    }
820    used_escape
821}
822
823fn settle(ctx: &Context, s: &mut State, closed: Vec<Closed>) {
824    if let Some(target) = closed.last().and_then(|c| c.restore_focus) {
825        s.focus_back = Some(target);
826        give_focus_back(ctx, s, true);
827    }
828    let modals = std::mem::take(&mut s.modals);
829    let (gone, left) = modals
830        .into_iter()
831        .partition::<Vec<Id>, _>(|id| closed.iter().any(|c| c.id == *id));
832    s.modals = left;
833    if !gone.is_empty() {
834        swallow_held_keys(ctx);
835    }
836    let window = ctx.viewport_id();
837    for c in &closed {
838        log::debug!(target: "egui_pop", "overlay `{}` closed: {:?}", c.label, c.reason);
839        s.notices.push(Change::closed(
840            window,
841            c.id,
842            c.label.clone(),
843            c.reason.into(),
844        ));
845    }
846    s.history.extend(closed.iter().cloned());
847    let len = s.history.len();
848    if len > 32 {
849        s.history.drain(..len - 32);
850    }
851    s.closed.extend(closed);
852}
853
854/// Gives the focus back when the widget can hold it; asks for another pass
855/// when a modal's layer still blocks it. `closing`: the overlay closes in
856/// this very call, and its own widget may still hold the focus. Later,
857/// whatever holds the focus took it meanwhile, and keeps it.
858///
859/// upstream: egui drops the focus of a widget drawn under the top modal
860/// layer, the previous pass's (docs/upstream.md).
861fn give_focus_back(ctx: &Context, s: &mut State, closing: bool) {
862    let Some(target) = s.focus_back else {
863        return;
864    };
865    // A widget gone since cannot take it: egui would keep the id as
866    // focused, and AccessKit, told of a focus on a node that does not
867    // exist, panics.
868    let Some(layer) = crate::focus::peek_response(ctx, target).map(|r| r.layer_id) else {
869        s.focus_back = None;
870        return;
871    };
872    if !ctx.memory(|m| m.allows_interaction(layer)) {
873        ctx.request_repaint();
874        return;
875    }
876    s.focus_back = None;
877    if closing || ctx.memory(|m| m.focused()).is_none() {
878        ctx.memory_mut(|m| m.request_focus(target));
879    }
880}
881
882/// How an overlay or a followed egui popup closed, as its watcher hears
883/// it ([`watch`]).
884#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
885#[serde(rename_all = "kebab-case")]
886#[non_exhaustive]
887pub enum Closing {
888    /// Escape.
889    Escape,
890    /// A press outside it.
891    Outside,
892    /// An item of it chosen (a menu's entry, a card's link).
893    Chosen,
894    /// Its owner closed it, or stopped showing it.
895    Owner,
896    /// An overlay below it closed.
897    Below,
898    /// Its widget is no longer drawn.
899    Gone,
900}
901
902impl Closing {
903    /// As the journal writes it (`escape`).
904    pub fn as_str(self) -> &'static str {
905        match self {
906            Closing::Escape => "escape",
907            Closing::Outside => "outside",
908            Closing::Chosen => "chosen",
909            Closing::Owner => "owner",
910            Closing::Below => "below",
911            Closing::Gone => "gone",
912        }
913    }
914}
915
916impl From<Reason> for Closing {
917    fn from(r: Reason) -> Self {
918        match r {
919            Reason::Escape => Closing::Escape,
920            Reason::Outside => Closing::Outside,
921            Reason::Closed => Closing::Owner,
922            Reason::Parent => Closing::Below,
923        }
924    }
925}
926
927/// An overlay or a followed egui popup that opened or closed, in a window.
928#[derive(Clone, Debug, PartialEq)]
929#[non_exhaustive]
930pub struct Change {
931    /// The window it is in.
932    pub window: ViewportId,
933    pub id: Id,
934    pub label: String,
935    /// `None`: it opened; else how it closed.
936    pub closed: Option<Closing>,
937}
938
939impl Change {
940    fn closed(window: ViewportId, id: Id, label: String, how: Closing) -> Self {
941        Self {
942            window,
943            id,
944            label,
945            closed: Some(how),
946        }
947    }
948}
949
950/// What hears every overlay and followed popup opening and closing.
951pub type Watcher = std::sync::Arc<dyn Fn(&Context, &Change) + Send + Sync>;
952
953#[derive(Default)]
954struct Watch(Option<Watcher>);
955
956impl std::fmt::Debug for Watch {
957    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
958        f.write_str(if self.0.is_some() {
959            "Watch(set)"
960        } else {
961            "Watch(none)"
962        })
963    }
964}
965
966fn watcher(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<Watch>> {
967    shared::<Watch>(ctx, "core.overlay.watch")
968}
969
970/// Has `watcher` hear every overlay of every window opening and closing,
971/// and every egui popup [`follow_popup`] follows, in the call that opened
972/// or closed it, once the stack's lock is let go (it may close another
973/// overlay from there, [`close_anywhere`]). An application puts them on
974/// its bus this way (ADR 0029). `None` stops it.
975pub fn watch(ctx: &Context, watcher_fn: Option<Watcher>) {
976    lock(&watcher(ctx)).0 = watcher_fn;
977}
978
979/// Tells the watcher what changed in a window's state.
980fn tell(ctx: &Context, st: &std::sync::Arc<std::sync::Mutex<State>>) {
981    let notices = std::mem::take(&mut lock(st).notices);
982    if notices.is_empty() {
983        return;
984    }
985    let Some(w) = lock(&watcher(ctx)).0.clone() else {
986        return;
987    };
988    for n in &notices {
989        w(ctx, n);
990    }
991}
992
993/// Follows an egui popup that is not in the stack (a context menu, a
994/// menu bar's menu, a popover of egui's, a hover card) for the watcher
995/// ([`watch`]): call it each pass its widget is drawn, `open` saying
996/// whether the popup is open after the widget drew it. Its opening and
997/// its closing are told once each; `how` says how it closed when the
998/// caller knows, else it is told from the pass's input (Escape, a press
999/// in it or outside it). One no longer followed (its widget not drawn)
1000/// is told closed ([`Closing::Gone`]) at the window's next pass.
1001pub fn follow_popup(ctx: &Context, id: Id, label: &str, open: bool, how: Option<Closing>) {
1002    let st = state(ctx);
1003    let now = pass(ctx);
1004    let window = ctx.viewport_id();
1005    {
1006        let mut s = lock(&st);
1007        match (s.followed.iter().position(|f| f.id == id), open) {
1008            (None, true) => {
1009                s.followed.push(Followed {
1010                    id,
1011                    label: label.to_string(),
1012                    seen: now,
1013                });
1014                s.notices.push(Change {
1015                    window,
1016                    id,
1017                    label: label.to_string(),
1018                    closed: None,
1019                });
1020            }
1021            (Some(i), true) => s.followed[i].seen = now,
1022            (Some(i), false) => {
1023                let f = s.followed.remove(i);
1024                let how = how.unwrap_or_else(|| closing_seen(ctx, id));
1025                s.notices.push(Change::closed(window, id, f.label, how));
1026            }
1027            (None, false) => {}
1028        }
1029    }
1030    tell(ctx, &st);
1031}
1032
1033/// Follows the menu egui opens from a widget ([`follow_popup`]): the
1034/// popup of `ui.menu_button`, `Response::context_menu` or
1035/// `egui::Popup::menu(response)` without an id of its own. Call it after
1036/// the menu is drawn, each pass its widget is.
1037pub fn follow_menu(response: &egui::Response, label: &str) {
1038    let id = egui::Popup::default_response_id(response);
1039    let open = egui::Popup::is_id_open(&response.ctx, id);
1040    follow_popup(&response.ctx, id, label, open, None);
1041}
1042
1043/// How a popup egui closed by itself this pass closed: Escape, a press in
1044/// it (an item chosen) or outside it, else its owner.
1045pub fn closing_seen(ctx: &Context, id: Id) -> Closing {
1046    let area = ctx.memory(|m| m.area_rect(id));
1047    ctx.input(|i| {
1048        if i.key_pressed(Key::Escape) {
1049            return Closing::Escape;
1050        }
1051        let pressed = i.pointer.any_pressed() || i.pointer.any_released();
1052        match i.pointer.interact_pos() {
1053            Some(p) if pressed && area.is_some_and(|r| r.contains(p)) => Closing::Chosen,
1054            Some(_) if pressed => Closing::Outside,
1055            _ => Closing::Owner,
1056        }
1057    })
1058}
1059
1060/// Closes an overlay, with those above it, or a followed popup, in
1061/// whichever window it is open: what an application's bus does when a
1062/// popup is closed by a request (its window closing under it). The
1063/// overlays above it are told closed ([`Closing::Below`]); it is not
1064/// (the caller is closing it). Whether it was open.
1065pub fn close_anywhere(ctx: &Context, id: Id) -> bool {
1066    close_where(ctx, id, None)
1067}
1068
1069/// As [`close_anywhere`], in `window` first (an overlay may be open in
1070/// several windows: the palette of each), else in whichever holds it.
1071pub fn close_in_window(ctx: &Context, window: ViewportId, id: Id) -> bool {
1072    close_where(ctx, id, Some(window))
1073}
1074
1075fn close_where(ctx: &Context, id: Id, first: Option<ViewportId>) -> bool {
1076    let here = ctx.viewport_id();
1077    let mut windows = all(ctx);
1078    if let Some(w) = first {
1079        windows.sort_by_key(|(v, _)| *v != w);
1080    }
1081    for (window, st) in windows {
1082        let mut s = lock(&st);
1083        if s.stack.contains(id) {
1084            let closed = s.stack.close(id);
1085            if window == here {
1086                settle(ctx, &mut s, closed);
1087            } else {
1088                settle_elsewhere(window, &mut s, closed);
1089            }
1090            s.notices.retain(|n| n.id != id || n.closed.is_none());
1091            drop(s);
1092            tell(ctx, &st);
1093            return true;
1094        }
1095        if let Some(i) = s.followed.iter().position(|f| f.id == id) {
1096            s.followed.remove(i);
1097            drop(s);
1098            egui::Popup::close_id(ctx, id);
1099            crate::hover_card::close(ctx, id);
1100            return true;
1101        }
1102    }
1103    false
1104}
1105
1106/// [`settle`] for a window other than the one being drawn: nothing of its
1107/// focus or keys is touched (they are not this pass's).
1108fn settle_elsewhere(window: ViewportId, s: &mut State, closed: Vec<Closed>) {
1109    s.modals.retain(|m| !closed.iter().any(|c| c.id == *m));
1110    for c in &closed {
1111        s.notices.push(Change::closed(
1112            window,
1113            c.id,
1114            c.label.clone(),
1115            c.reason.into(),
1116        ));
1117    }
1118    s.history.extend(closed.iter().cloned());
1119    let len = s.history.len();
1120    if len > 32 {
1121        s.history.drain(..len - 32);
1122    }
1123    s.closed.extend(closed);
1124}
1125
1126/// Closes an overlay (and those above it) from code.
1127pub fn close(ctx: &Context, id: Id) {
1128    let st = state(ctx);
1129    {
1130        let mut s = lock(&st);
1131        let closed = s.stack.close(id);
1132        settle(ctx, &mut s, closed);
1133    }
1134    tell(ctx, &st);
1135}
1136
1137/// Closes a popover with nothing to hold Tab, leaving the focus where Tab took
1138/// it: on the stack, or an [`egui::Popup`] of that id.
1139pub(crate) fn close_for_tab(ctx: &Context, id: Id) {
1140    let st = state(ctx);
1141    let mut s = lock(&st);
1142    let mut closed = s.stack.close(id);
1143    for c in &mut closed {
1144        c.restore_focus = None;
1145    }
1146    settle(ctx, &mut s, closed);
1147    drop(s);
1148    tell(ctx, &st);
1149    egui::Popup::close_id(ctx, id);
1150}
1151
1152/// Whether an egui layer is a popup (a combo box's list) the top overlay opened.
1153pub(crate) fn opened_by_top(ctx: &Context, layer: LayerId) -> bool {
1154    let st = state(ctx);
1155    lock(&st).stack.top_popups().contains(&layer)
1156}
1157
1158/// The overlay of the window being drawn that a press at `pos` lands in,
1159/// `layer` being the egui layer on top there: the topmost one drawn or
1160/// anchored there, or whose egui popup (a combo box's list, a context
1161/// menu) is that layer. `None` for the interface below the overlays.
1162pub fn hit_at(ctx: &Context, pos: egui::Pos2, layer: Option<LayerId>) -> Option<Id> {
1163    let st = state(ctx);
1164    lock(&st).stack.hit_on(pos, layer)
1165}
1166
1167/// The window an overlay is open in, if it is open in any.
1168pub fn window_of(ctx: &Context, id: Id) -> Option<ViewportId> {
1169    all(ctx)
1170        .into_iter()
1171        .find(|(_, st)| lock(st).stack.contains(id))
1172        .map(|(v, _)| v)
1173}
1174
1175/// The open overlays of the window being drawn, bottom first.
1176pub fn stack(ctx: &Context) -> Vec<OverlaySpec> {
1177    let st = state(ctx);
1178    let s = lock(&st);
1179    s.stack.specs().cloned().collect()
1180}
1181
1182/// The open overlays with where they were last drawn, bottom first (an
1183/// overlay not drawn yet is left out).
1184pub fn rects(ctx: &Context) -> Vec<(OverlaySpec, Rect)> {
1185    let st = state(ctx);
1186    let s = lock(&st);
1187    s.stack
1188        .entries
1189        .iter()
1190        .filter_map(|e| e.rect.map(|r| (e.spec.clone(), r)))
1191        .collect()
1192}
1193
1194/// The overlays closed lately, oldest first.
1195pub fn recently_closed(ctx: &Context) -> Vec<Closed> {
1196    let st = state(ctx);
1197    lock(&st).history.clone()
1198}
1199
1200/// Where an open overlay was last drawn.
1201pub fn rect(ctx: &Context, id: Id) -> Option<Rect> {
1202    let st = state(ctx);
1203    let s = lock(&st);
1204    s.stack
1205        .entries
1206        .iter()
1207        .find(|e| e.spec.id == id)
1208        .and_then(|e| e.rect)
1209}
1210
1211/// A resizable modal's size as asked, of its content, in points, while
1212/// it is open: what it opened at or what the person last left it at (the
1213/// window may hold it smaller for now). `None` before it is first shown.
1214pub fn modal_size(ctx: &Context, id: Id) -> Option<Vec2> {
1215    let st = state(ctx);
1216    let s = lock(&st);
1217    let at = s.stack.position(id)?;
1218    s.stack.entries[at].geometry.map(|g| g.size)
1219}
1220
1221/// Whether the person is dragging a grip of this resizable modal: a
1222/// size worth keeping comes once the drag is over.
1223pub fn modal_resizing(ctx: &Context, id: Id) -> bool {
1224    let st = state(ctx);
1225    let s = lock(&st);
1226    s.stack
1227        .position(id)
1228        .and_then(|at| s.stack.entries[at].geometry)
1229        .is_some_and(|g| g.grabbed.is_some())
1230}
1231
1232/// The largest size a modal's content can have in the window being
1233/// drawn: a size above it is held back.
1234pub fn modal_max_size(ctx: &Context) -> Vec2 {
1235    (modal_bounds(ctx).size() - dialog_chrome(ctx)).at_least(Vec2::ZERO)
1236}
1237
1238/// What a dialog's frame takes around its content, both sides summed:
1239/// the kit `dialog`'s padding (`padding-x`, `padding-y`) and the room it
1240/// keeps for its widest border of any state, on whole physical pixels
1241/// (`Component::border_room`, what `Component::show` keeps). A dialog's
1242/// outer size is its content's plus this; every modal is sized with it.
1243pub fn dialog_chrome(ctx: &Context) -> Vec2 {
1244    let kit = crate::kit::Kit::of(ctx);
1245    let dialog = &kit.dialog;
1246    let ppp = ctx.pixels_per_point();
1247    let padding = egui::vec2(dialog.data.padding_x, dialog.data.padding_y);
1248    // `Frame` rounds its margin to whole points, as egui lays it out.
1249    let padding = egui::vec2(padding.x.round(), padding.y.round());
1250    2.0 * (padding + Vec2::splat(dialog.border_room(ppp)))
1251}
1252
1253/// Where a resizable modal stays: the window, less the dialog's padding.
1254fn modal_bounds(ctx: &Context) -> Rect {
1255    let kit = crate::kit::Kit::of(ctx);
1256    let data = &kit.dialog.data;
1257    ctx.content_rect()
1258        .shrink2(egui::vec2(data.padding_x, data.padding_y))
1259}
1260
1261/// The windows that are almost separate applications (an application's
1262/// own windows, ADR 0025): each is a group of its own, whose modals
1263/// block only it. Every other window (the main one, its detached
1264/// panels) is in the main window's group.
1265#[derive(Debug, Default)]
1266struct Separate(BTreeSet<ViewportId>);
1267
1268fn separate(ctx: &Context) -> std::sync::Arc<std::sync::Mutex<Separate>> {
1269    shared::<Separate>(ctx, "core.overlay.separate")
1270}
1271
1272/// Says which windows are groups of their own (an application's own
1273/// windows): a modal open in one blocks it alone, and counts for
1274/// [`modal_open`] there only. Replaces the earlier list.
1275pub fn set_separate_windows(ctx: &Context, windows: impl IntoIterator<Item = ViewportId>) {
1276    lock(&separate(ctx)).0 = windows.into_iter().collect();
1277}
1278
1279/// The group a window belongs to: itself for a separate window, the
1280/// main window (`ViewportId::ROOT`) for every other.
1281pub fn group_of(ctx: &Context, window: ViewportId) -> ViewportId {
1282    if window != ViewportId::ROOT && lock(&separate(ctx)).0.contains(&window) {
1283        window
1284    } else {
1285        ViewportId::ROOT
1286    }
1287}
1288
1289/// Whether a modal overlay is open in the group of the window being
1290/// drawn: the main window and its detached panels wait for one another's
1291/// modals (see [`block_window`]); an application's own window waits only
1292/// for its own ([`set_separate_windows`]).
1293pub fn modal_open(ctx: &Context) -> bool {
1294    modal_open_in(ctx, group_of(ctx, ctx.viewport_id()))
1295}
1296
1297/// Whether a modal overlay is open in a group of windows (see
1298/// [`group_of`]).
1299pub fn modal_open_in(ctx: &Context, group: ViewportId) -> bool {
1300    modal_windows(ctx)
1301        .into_iter()
1302        .any(|v| group_of(ctx, v) == group)
1303}
1304
1305/// Whether a modal overlay is open in any window.
1306pub fn modal_open_anywhere(ctx: &Context) -> bool {
1307    !modal_windows(ctx).is_empty()
1308}
1309
1310/// The layers holding widgets so far this pass. egui keeps the layers
1311/// of earlier passes in its list, emptied: only those with a widget
1312/// count.
1313fn layers_now(ctx: &Context) -> Vec<LayerId> {
1314    ctx.viewport(|v| {
1315        v.this_pass
1316            .widgets
1317            .layers()
1318            .filter(|(_, rects)| !rects.is_empty())
1319            .map(|(l, _)| *l)
1320            .collect()
1321    })
1322}
1323
1324/// Notes the floating layers (egui draws popups, menus and tooltips on
1325/// the foreground and tooltip orders) first drawn since `before` (taken
1326/// as the overlay started drawing), but its `own`, as the popups it
1327/// opened.
1328fn note_popups(ctx: &Context, id: Id, before: &[LayerId], own: &[LayerId]) {
1329    let layers = layers_now(ctx)
1330        .into_iter()
1331        .filter(|l| {
1332            matches!(l.order, egui::Order::Foreground | egui::Order::Tooltip)
1333                && !before.contains(l)
1334                && !own.contains(l)
1335        })
1336        .collect();
1337    let st = state(ctx);
1338    lock(&st).stack.set_popups(id, layers);
1339}
1340
1341/// Where a floating overlay goes.
1342#[derive(Clone, Copy, Debug)]
1343pub struct Anchor {
1344    pub rect: Rect,
1345    pub side: Side,
1346}
1347
1348/// Keeps an overlay in the stack for this pass while `*open`, opening
1349/// it the first time; sets `*open` to false when it was closed (Escape,
1350/// a click outside, [`close`]) and returns whether it is still open.
1351fn enter(ctx: &Context, spec: &OverlaySpec, open: &mut bool) -> bool {
1352    begin_pass(ctx);
1353    let st = state(ctx);
1354    let shown = enter_in(ctx, &mut lock(&st), spec, open);
1355    tell(ctx, &st);
1356    shown
1357}
1358
1359fn enter_in(ctx: &Context, s: &mut State, spec: &OverlaySpec, open: &mut bool) -> bool {
1360    if let Some(i) = s.closed.iter().position(|c| c.id == spec.id) {
1361        s.closed.remove(i);
1362        *open = false;
1363        return false;
1364    }
1365    if !*open {
1366        if s.stack.contains(spec.id) {
1367            let closed = s.stack.close(spec.id);
1368            settle(ctx, s, closed);
1369            s.closed.retain(|c| c.id != spec.id);
1370        }
1371        return false;
1372    }
1373    if !s.stack.contains(spec.id) {
1374        // The place of one that just closed, as long as it is owed.
1375        let focused = s.focus_back.take().or_else(|| ctx.memory(|m| m.focused()));
1376        let (_, closed) = s.stack.open(spec.clone(), focused);
1377        settle(ctx, s, closed);
1378        s.notices.push(Change {
1379            window: ctx.viewport_id(),
1380            id: spec.id,
1381            label: spec.label.clone(),
1382            closed: None,
1383        });
1384        if spec.kind == Kind::Modal {
1385            s.modals.push(spec.id);
1386            swallow_held_keys(ctx);
1387        }
1388    } else if s.stack.specs().any(|o| o.id == spec.id && o != spec) {
1389        // Declared differently this pass (Escape kept, moved).
1390        s.stack.update(spec.clone());
1391    }
1392    s.shown.push(spec.id);
1393    true
1394}
1395
1396/// The keys each window ignores until they are released. It works on the
1397/// input before egui reads it: nothing in the pass sees these presses, not
1398/// a focused widget, Tab's or Escape's handling in egui, nor the key
1399/// dispatcher.
1400#[derive(Debug, Default)]
1401struct HeldKeys(HashMap<ViewportId, Vec<Key>>);
1402
1403impl egui::plugin::Plugin for HeldKeys {
1404    fn debug_name(&self) -> &'static str {
1405        "egui_pop_core::overlay::held_keys"
1406    }
1407
1408    fn input_hook(&mut self, _ctx: &Context, input: &mut egui::RawInput) {
1409        if let Some(held) = self.0.get_mut(&input.viewport_id) {
1410            forget_held_presses(&mut input.events, held);
1411            if held.is_empty() {
1412                self.0.remove(&input.viewport_id);
1413            }
1414        }
1415    }
1416}
1417
1418/// Removes the presses of the keys `held`, in the order they came: a
1419/// release ends the hold, and a press after it is a fresh one. The window
1420/// losing the focus ends them all, as it does for egui's own `keys_down`:
1421/// no release will come.
1422fn forget_held_presses(events: &mut Vec<Event>, held: &mut Vec<Key>) {
1423    events.retain(|event| match event {
1424        Event::Key {
1425            key, pressed: true, ..
1426        } => !held.contains(key),
1427        Event::Key {
1428            key,
1429            pressed: false,
1430            ..
1431        } => {
1432            held.retain(|k| k != key);
1433            true
1434        }
1435        // Space comes as a key and as text.
1436        Event::Text(text) if text == " " => !held.contains(&Key::Space),
1437        Event::WindowFocused(false) => {
1438            held.clear();
1439            true
1440        }
1441        _ => true,
1442    });
1443}
1444
1445/// Takes this pass's presses out of the input, and has the keys down
1446/// ignored until they are released ([`HeldKeys`]).
1447fn swallow_held_keys(ctx: &Context) {
1448    let held: Vec<Key> = ctx.input_mut(|i| {
1449        let space = i.key_pressed(Key::Space);
1450        i.events.retain(|e| match e {
1451            Event::Key { pressed, .. } => !*pressed,
1452            Event::Text(text) => !(space && text == " "),
1453            _ => true,
1454        });
1455        i.keys_down.iter().copied().collect()
1456    });
1457    if held.is_empty() {
1458        return;
1459    }
1460    let viewport = ctx.viewport_id();
1461    ctx.add_plugin(HeldKeys::default());
1462    ctx.with_plugin(|p: &mut HeldKeys| p.0.entry(viewport).or_default().extend(held));
1463}
1464
1465/// Holds an overlay its owner draws itself (a flyout laid out against
1466/// the workbench rather than placed by [`crate::placement`]) in the
1467/// stack, under the stack's rules: Escape and a click outside `rect`
1468/// and `anchor` close it, the focus going back where it was. Call it
1469/// each pass while `*open`, with where the overlay is drawn this pass
1470/// and `draw` drawing it (egui popups opened from inside are part of
1471/// it); it sets `*open` to false and returns `None`, without drawing,
1472/// once the overlay closed.
1473pub fn hold<R>(
1474    ctx: &Context,
1475    spec: &OverlaySpec,
1476    open: &mut bool,
1477    anchor: Option<Rect>,
1478    rect: Rect,
1479    draw: impl FnOnce() -> R,
1480) -> Option<R> {
1481    if !enter(ctx, spec, open) {
1482        return None;
1483    }
1484    let st = state(ctx);
1485    {
1486        let mut s = lock(&st);
1487        if let Some(a) = anchor {
1488            s.stack.set_anchor(spec.id, a);
1489        }
1490        s.stack.set_rect(spec.id, rect);
1491    }
1492    let before = layers_now(ctx);
1493    let inner = draw();
1494    note_popups(ctx, spec.id, &before, &[]);
1495    Some(inner)
1496}
1497
1498/// Shows an overlay while `*open`; sets `*open` to false when it closes
1499/// (Escape, a click outside, or [`close`]), restoring the focus. A modal
1500/// is centred (moved by its `offset`) over a backdrop (`dim`); other
1501/// kinds are placed next to `anchor` (or at the pointer).
1502pub fn show<R>(
1503    ctx: &Context,
1504    spec: &OverlaySpec,
1505    open: &mut bool,
1506    anchor: Option<Anchor>,
1507    add: impl FnOnce(&mut Ui) -> R,
1508) -> Option<R> {
1509    if !enter(ctx, spec, open) {
1510        return None;
1511    }
1512    let st = state(ctx);
1513    let kit = crate::kit::Kit::of(ctx);
1514    let rest = crate::kit::State::REST;
1515    let before = layers_now(ctx);
1516    let (inner, rect, own) = match spec.kind {
1517        Kind::Modal if spec.resize.is_some() => resizable_modal(ctx, spec, add),
1518        Kind::Modal => {
1519            let backdrop = &kit.backdrop;
1520            let alpha = (backdrop.data.opacity * spec.dim).clamp(0.0, 1.0);
1521            let dialog = &kit.dialog;
1522            let padding = dialog.data.padding_x;
1523            let r = egui::Modal::new(spec.id)
1524                .area(
1525                    egui::Modal::default_area(spec.id)
1526                        .anchor(egui::Align2::CENTER_CENTER, spec.offset),
1527                )
1528                .backdrop_color(backdrop.style(rest).fill.gamma_multiply(alpha))
1529                .frame(egui::Frame::NONE)
1530                .show(ctx, |ui| {
1531                    let shadow = ui.visuals().window_shadow;
1532                    dialog
1533                        .show(ui, rest, shadow, |ui| {
1534                            let width = spec.width.map_or(dialog.data.width, |w| {
1535                                w.min(ctx.content_rect().width() - 4.0 * padding)
1536                            });
1537                            ui.set_max_width(width);
1538                            if spec.width.is_some() {
1539                                ui.set_min_width(width);
1540                            }
1541                            add(ui)
1542                        })
1543                        .inner
1544                });
1545            let own = vec![r.response.layer_id, r.backdrop_response.layer_id];
1546            (r.inner, r.response.rect, own)
1547        }
1548        Kind::Popover | Kind::Menu => {
1549            let screen = ctx.content_rect();
1550            let last = ctx.memory(|m| m.area_rect(spec.id)).map(|r| r.size());
1551            let size = last.unwrap_or(egui::vec2(200.0, 100.0));
1552            if let Some(a) = anchor {
1553                lock(&st).stack.set_anchor(spec.id, a.rect);
1554            }
1555            let anchor = anchor.unwrap_or_else(|| {
1556                let p = ctx
1557                    .input(|i| i.pointer.interact_pos())
1558                    .unwrap_or(screen.center());
1559                Anchor {
1560                    rect: Rect::from_min_size(p, egui::Vec2::ZERO),
1561                    side: Side::Bottom,
1562                }
1563            });
1564            let placed = place(&Placement::new(anchor.rect, size, screen).side(anchor.side));
1565            // A popover is an overlay (ADR 0026), unless it opens above a
1566            // dialog or a menu; a menu stays unranked, above the overlays.
1567            if spec.kind == Kind::Popover && !lock(&st).stack.over_unranked(spec.id) {
1568                crate::layers::rank(
1569                    ctx,
1570                    LayerId::new(egui::Order::Foreground, spec.id),
1571                    crate::layers::Rank::Overlay,
1572                );
1573            }
1574            let r = egui::Area::new(spec.id)
1575                .order(egui::Order::Foreground)
1576                .fixed_pos(placed.rect.min)
1577                .show(ctx, |ui| {
1578                    let shadow = ui.visuals().popup_shadow;
1579                    let inner = kit.popover.show(ui, rest, shadow, add).inner;
1580                    let top = lock(&st).stack.top().is_some_and(|t| t.id == spec.id);
1581                    if spec.kind == Kind::Popover && top {
1582                        crate::focus::keep_tab(ui);
1583                    }
1584                    inner
1585                });
1586            (r.inner, r.response.rect, vec![r.response.layer_id])
1587        }
1588    };
1589    lock(&st).stack.set_rect(spec.id, rect);
1590    note_popups(ctx, spec.id, &before, &own);
1591    Some(inner)
1592}
1593
1594/// Draws a modal of the size the person gave it ([`OverlaySpec::resizable`]),
1595/// its grips over it.
1596fn resizable_modal<R>(
1597    ctx: &Context,
1598    spec: &OverlaySpec,
1599    add: impl FnOnce(&mut Ui) -> R,
1600) -> (R, Rect, Vec<LayerId>) {
1601    let Some(resize) = spec.resize else {
1602        unreachable!("called for a resizable modal");
1603    };
1604    let st = state(ctx);
1605    let kit = crate::kit::Kit::of(ctx);
1606    let rest = crate::kit::State::REST;
1607    let dialog = &kit.dialog;
1608    let chrome = dialog_chrome(ctx);
1609    let bounds = modal_bounds(ctx);
1610    let geometry = {
1611        let mut s = lock(&st);
1612        let at = s.stack.position(spec.id).expect("entered");
1613        *s.stack.entries[at].geometry.get_or_insert(Geometry {
1614            size: resize.size,
1615            shift: Vec2::ZERO,
1616            grabbed: None,
1617        })
1618    };
1619    let rect = geometry.placed(spec.offset, resize.min, chrome, bounds);
1620    let alpha = (kit.backdrop.data.opacity * spec.dim).clamp(0.0, 1.0);
1621    // Placed by hand, not anchored: the rectangle is known before the
1622    // content, so a size never shows at the last size's place.
1623    let area = egui::Area::new(spec.id)
1624        .kind(egui::UiKind::Modal)
1625        .sense(Sense::hover())
1626        .order(egui::Order::Foreground)
1627        .interactable(true)
1628        .fixed_pos(rect.min);
1629    let r = egui::Modal::new(spec.id)
1630        .area(area)
1631        .backdrop_color(kit.backdrop.style(rest).fill.gamma_multiply(alpha))
1632        .frame(egui::Frame::NONE)
1633        .show(ctx, |ui| {
1634            let shadow = ui.visuals().window_shadow;
1635            let shown = dialog.show(ui, rest, shadow, |ui| {
1636                let room = Rect::from_min_size(ui.max_rect().min, rect.size() - chrome);
1637                ui.advance_cursor_after_rect(room);
1638                let mut content = ui.new_child(
1639                    UiBuilder::new()
1640                        .id_salt("egui_pop.overlay.content")
1641                        .max_rect(room)
1642                        .layout(egui::Layout::top_down(egui::Align::Min)),
1643                );
1644                // Up to the frame's edge: a focus ring may stand out.
1645                content.set_clip_rect(room.expand2(chrome / 2.0).intersect(ui.clip_rect()));
1646                add(&mut content)
1647            });
1648            grips(
1649                ui,
1650                spec,
1651                resize,
1652                geometry.grabbed,
1653                shown.response.rect,
1654                chrome,
1655                bounds,
1656            );
1657            shown.inner
1658        });
1659    let own = vec![r.response.layer_id, r.backdrop_response.layer_id];
1660    (r.inner, r.response.rect, own)
1661}
1662
1663/// A resizable modal's grips over its `rect`: its edges and corners for
1664/// the pointer, the bottom right corner also for the keyboard.
1665fn grips(
1666    ui: &mut Ui,
1667    spec: &OverlaySpec,
1668    resize: ModalSize,
1669    held: Option<Rect>,
1670    rect: Rect,
1671    chrome: Vec2,
1672    bounds: Rect,
1673) {
1674    let ctx = ui.ctx().clone();
1675    let kit = crate::kit::Kit::of(&ctx);
1676    let grip_kit = &kit.dialog_grip;
1677    let (reach, side) = (grip_kit.data.width, grip_kit.data.height);
1678    let min = (resize.min + chrome).at_most(bounds.size());
1679    let st = state(&ctx);
1680    let mut changed = None;
1681    let mut grabbed = None;
1682    let mut released = false;
1683    let mut handle = None;
1684    for grip in GRIPS {
1685        let id = spec.id.with(("egui_pop.overlay.grip", grip.x, grip.y));
1686        let sense = if grip == HANDLE {
1687            Sense::DRAG | Sense::FOCUSABLE
1688        } else {
1689            Sense::DRAG
1690        };
1691        let r = ui.interact(grip.zone(rect, reach, side + reach / 2.0), id, sense);
1692        crate::pointer::drag_cursor(&r, grip.drag_kind());
1693        if r.drag_started() {
1694            grabbed = Some(rect);
1695        }
1696        if r.dragged() {
1697            let from = grabbed.or(held).unwrap_or(rect);
1698            let by = ctx.input(
1699                |i| match (i.pointer.latest_pos(), i.pointer.press_origin()) {
1700                    (Some(now), Some(origin)) => now - origin,
1701                    _ => Vec2::ZERO,
1702                },
1703            );
1704            changed = Some(grip.moved(from, by, min, bounds));
1705        }
1706        if r.drag_stopped() {
1707            released = true;
1708        }
1709        if grip == HANDLE {
1710            handle = Some(r);
1711        }
1712    }
1713    let Some(handle) = handle else {
1714        return;
1715    };
1716    if handle.has_focus() {
1717        ctx.memory_mut(|m| {
1718            m.set_focus_lock_filter(
1719                handle.id,
1720                egui::EventFilter {
1721                    horizontal_arrows: true,
1722                    vertical_arrows: true,
1723                    ..Default::default()
1724                },
1725            )
1726        });
1727        if let Some(by) = arrows(&ctx) {
1728            changed = Some(HANDLE.moved(rect, by, min, bounds));
1729        }
1730    }
1731    let size = rect.size() - chrome;
1732    let name = crate::strings::tr_args(
1733        &ctx,
1734        &crate::strings::DIALOG_RESIZE,
1735        &[("dialog", &spec.label)],
1736    );
1737    handle.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, &name));
1738    ctx.accesskit_node_builder(handle.id, |node| {
1739        node.set_role(egui::accesskit::Role::Splitter);
1740        node.set_value(format!("{} × {}", size.x.round(), size.y.round()));
1741    });
1742    paint_handle(ui, &handle, rect, reach, side);
1743    let mut s = lock(&st);
1744    let Some(g) = s
1745        .stack
1746        .position(spec.id)
1747        .and_then(|at| s.stack.entries[at].geometry.as_mut())
1748    else {
1749        return;
1750    };
1751    let before = *g;
1752    if let Some(from) = grabbed {
1753        g.grabbed = Some(from);
1754    }
1755    if let Some(new) = changed {
1756        g.set(new, spec.offset, chrome, bounds);
1757    }
1758    if released {
1759        g.grabbed = None;
1760    }
1761    if *g != before {
1762        ctx.request_repaint();
1763    }
1764}
1765
1766/// How far the arrows pressed move the handle this pass: a step of the
1767/// theme's spacing, four with Shift.
1768fn arrows(ctx: &Context) -> Option<Vec2> {
1769    let step = crate::theme::Tokens::of(ctx).space.m;
1770    let keys = [
1771        (egui::Key::ArrowLeft, egui::vec2(-1.0, 0.0)),
1772        (egui::Key::ArrowRight, egui::vec2(1.0, 0.0)),
1773        (egui::Key::ArrowUp, egui::vec2(0.0, -1.0)),
1774        (egui::Key::ArrowDown, egui::vec2(0.0, 1.0)),
1775    ];
1776    let mut by = Vec2::ZERO;
1777    ctx.input_mut(|i| {
1778        for (key, way) in keys {
1779            // Shift first: the plain key takes it too.
1780            if i.consume_key(egui::Modifiers::SHIFT, key) {
1781                by += way * step * 4.0;
1782            }
1783            if i.consume_key(egui::Modifiers::NONE, key) {
1784                by += way * step;
1785            }
1786        }
1787    });
1788    (by != Vec2::ZERO).then_some(by)
1789}
1790
1791/// The handle's mark, at the corner of the dialog's `rect`: the kit's
1792/// box, and three lines across it.
1793fn paint_handle(ui: &Ui, r: &egui::Response, rect: Rect, reach: f32, side: f32) {
1794    let ctx = ui.ctx();
1795    let kit = crate::kit::Kit::of(ctx);
1796    let g = &kit.dialog_grip;
1797    let state = crate::kit::State::from_response(r);
1798    let ppp = ctx.pixels_per_point();
1799    let mark = Rect::from_min_size(
1800        rect.max - Vec2::splat(side + reach / 2.0),
1801        Vec2::splat(side),
1802    );
1803    let painter = ui.painter();
1804    g.paint(
1805        &crate::kit::KitCx { painter, ppp },
1806        &crate::kit::Part {
1807            rect: mark,
1808            room: mark,
1809            state,
1810            label: None,
1811        },
1812    );
1813    let style = g.style(state);
1814    let stroke = egui::Stroke::new(crate::scale::snap(style.border_width, ppp), style.text);
1815    for part in [1.0, 0.65, 0.3] {
1816        let along = side * part;
1817        painter.line_segment(
1818            [
1819                mark.max - egui::vec2(along, 0.0),
1820                mark.max - egui::vec2(0.0, along),
1821            ],
1822            stroke,
1823        );
1824    }
1825}
1826
1827#[cfg(test)]
1828mod tests {
1829    use super::*;
1830
1831    fn key_event(key: Key, pressed: bool) -> Event {
1832        Event::Key {
1833            key,
1834            physical_key: None,
1835            pressed,
1836            repeat: false,
1837            modifiers: egui::Modifiers::NONE,
1838        }
1839    }
1840
1841    #[test]
1842    fn a_held_key_s_presses_go_until_its_release_and_a_later_press_stays() {
1843        let mut held = vec![Key::Enter, Key::Space];
1844        let mut events = vec![
1845            key_event(Key::Enter, true),
1846            key_event(Key::Space, true),
1847            Event::Text(" ".to_string()),
1848            key_event(Key::Tab, true),
1849            key_event(Key::Enter, false),
1850            key_event(Key::Enter, true),
1851        ];
1852        forget_held_presses(&mut events, &mut held);
1853        assert_eq!(
1854            events,
1855            [
1856                key_event(Key::Tab, true),
1857                key_event(Key::Enter, false),
1858                key_event(Key::Enter, true),
1859            ]
1860        );
1861        assert_eq!(held, [Key::Space]);
1862    }
1863
1864    #[test]
1865    fn the_window_losing_the_focus_ends_what_is_held() {
1866        let mut held = vec![Key::Enter];
1867        let mut events = vec![
1868            Event::WindowFocused(false),
1869            Event::WindowFocused(true),
1870            key_event(Key::Enter, true),
1871        ];
1872        forget_held_presses(&mut events, &mut held);
1873        assert!(held.is_empty());
1874        assert_eq!(events.len(), 3);
1875    }
1876
1877    #[test]
1878    fn a_grip_moves_its_sides_and_leaves_the_others() {
1879        let bounds = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(800.0, 600.0));
1880        let from = Rect::from_min_max(egui::pos2(100.0, 100.0), egui::pos2(500.0, 400.0));
1881        let min = egui::vec2(100.0, 80.0);
1882        let east = Grip { x: 1, y: 0 };
1883        let r = east.moved(from, egui::vec2(50.0, 30.0), min, bounds);
1884        assert_eq!((r.min, r.max), (from.min, egui::pos2(550.0, 400.0)));
1885        let north_west = Grip { x: -1, y: -1 };
1886        let r = north_west.moved(from, egui::vec2(-20.0, 10.0), min, bounds);
1887        assert_eq!((r.min, r.max), (egui::pos2(80.0, 110.0), from.max));
1888        // Never under the least size, never out of the window.
1889        let r = east.moved(from, egui::vec2(-1000.0, 0.0), min, bounds);
1890        assert_eq!(r.width(), 100.0);
1891        let r = east.moved(from, egui::vec2(1000.0, 0.0), min, bounds);
1892        assert_eq!(r.max.x, 800.0);
1893        let r = north_west.moved(from, egui::vec2(-1000.0, -1000.0), min, bounds);
1894        assert_eq!(r.min, bounds.min);
1895    }
1896
1897    #[test]
1898    fn a_grip_takes_the_pointer_at_its_edge_or_its_corner() {
1899        let r = Rect::from_min_max(egui::pos2(100.0, 100.0), egui::pos2(500.0, 400.0));
1900        let at = |p: (f32, f32)| {
1901            GRIPS
1902                .iter()
1903                .rev()
1904                .find(|g| g.zone(r, 5.0, 15.0).contains(egui::pos2(p.0, p.1)))
1905                .map(|g| (g.x, g.y))
1906        };
1907        assert_eq!(at((500.0, 250.0)), Some((1, 0)));
1908        assert_eq!(at((100.0, 250.0)), Some((-1, 0)));
1909        assert_eq!(at((300.0, 100.0)), Some((0, -1)));
1910        assert_eq!(at((300.0, 403.0)), Some((0, 1)));
1911        assert_eq!(at((495.0, 395.0)), Some((1, 1)));
1912        assert_eq!(at((105.0, 395.0)), Some((-1, 1)));
1913        assert_eq!(at((495.0, 105.0)), Some((1, -1)));
1914        assert_eq!(at((105.0, 105.0)), Some((-1, -1)));
1915        assert_eq!(at((300.0, 250.0)), None);
1916    }
1917
1918    #[test]
1919    fn a_modal_too_big_for_the_window_is_held_back_and_keeps_its_size() {
1920        let bounds = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(400.0, 300.0));
1921        let g = Geometry {
1922            size: egui::vec2(1000.0, 800.0),
1923            shift: egui::vec2(50.0, 0.0),
1924            grabbed: None,
1925        };
1926        let rect = g.placed(
1927            Vec2::ZERO,
1928            egui::vec2(100.0, 100.0),
1929            Vec2::splat(20.0),
1930            bounds,
1931        );
1932        assert_eq!(rect, bounds);
1933        // A least size larger than the window: the window wins.
1934        let small = Geometry {
1935            size: egui::vec2(500.0, 500.0),
1936            ..g
1937        };
1938        let rect = small.placed(Vec2::ZERO, egui::vec2(900.0, 900.0), Vec2::ZERO, bounds);
1939        assert_eq!(rect.size(), bounds.size());
1940        // With room, the offset counts, and it stays inside.
1941        let wide = Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(2000.0, 2000.0));
1942        let rect = g.placed(egui::vec2(10.0, 0.0), Vec2::ZERO, Vec2::ZERO, wide);
1943        assert_eq!(rect.center(), egui::pos2(1060.0, 1000.0));
1944    }
1945
1946    fn spec(name: &str, kind: Kind) -> OverlaySpec {
1947        OverlaySpec::new(name, name, kind)
1948    }
1949
1950    fn labels(c: &[Closed]) -> Vec<&str> {
1951        c.iter().map(|c| c.label.as_str()).collect()
1952    }
1953
1954    #[test]
1955    fn escape_closes_only_the_top_overlay_and_focus_goes_back() {
1956        let mut s = OverlayStack::new();
1957        let f1 = Id::unique("field");
1958        let f2 = Id::unique("button in dialog");
1959        s.open(spec("dialog", Kind::Modal), Some(f1));
1960        s.open(spec("menu", Kind::Menu), Some(f2));
1961        let c = s.escape();
1962        assert_eq!(labels(&c), ["menu"]);
1963        assert_eq!(c[0].restore_focus, Some(f2));
1964        assert_eq!(s.len(), 1);
1965        let c = s.escape();
1966        assert_eq!(labels(&c), ["dialog"]);
1967        assert_eq!(c[0].restore_focus, Some(f1));
1968        assert!(s.escape().is_empty(), "nothing left");
1969        s.open(spec("ask", Kind::Modal).keep_on_escape(), None);
1970        assert!(s.escape().is_empty(), "it stays");
1971    }
1972
1973    #[test]
1974    fn an_overlay_declared_again_changes_in_place() {
1975        let mut s = OverlayStack::new();
1976        s.open(spec("dialog", Kind::Modal), Some(Id::unique("field")));
1977        s.open(spec("menu", Kind::Menu), None);
1978        // Escape kept for a while (a dialog moved by the keys): nothing
1979        // above it closes.
1980        assert!(s.update(spec("dialog", Kind::Modal).keep_on_escape()));
1981        assert_eq!(s.len(), 2);
1982        assert_eq!(labels(&s.escape()), ["menu"]);
1983        assert!(s.escape().is_empty(), "the dialog keeps Escape");
1984        assert!(s.update(spec("dialog", Kind::Modal)));
1985        let c = s.escape();
1986        assert_eq!(labels(&c), ["dialog"]);
1987        assert_eq!(c[0].restore_focus, Some(Id::unique("field")));
1988        assert!(!s.update(spec("ghost", Kind::Modal)));
1989    }
1990
1991    #[test]
1992    fn closing_an_overlay_closes_those_above_it_and_restores_the_lowest_focus() {
1993        let mut s = OverlayStack::new();
1994        s.open(spec("a", Kind::Popover), Some(Id::unique(1)));
1995        s.open(spec("b", Kind::Menu), Some(Id::unique(2)));
1996        s.open(spec("c", Kind::Menu), Some(Id::unique(3)));
1997        let c = s.close(Id::unique("b"));
1998        assert_eq!(labels(&c), ["c", "b"]);
1999        assert_eq!(c[0].reason, Reason::Parent);
2000        assert_eq!(c[1].reason, Reason::Closed);
2001        assert_eq!(c.last().unwrap().restore_focus, Some(Id::unique(2)));
2002        assert_eq!(s.len(), 1);
2003        assert!(s.close(Id::unique("ghost")).is_empty());
2004    }
2005
2006    #[test]
2007    fn a_click_outside_closes_popovers_above_what_it_hit_but_never_a_modal() {
2008        let mut s = OverlayStack::new();
2009        s.open(spec("menu", Kind::Menu), None);
2010        s.open(spec("submenu", Kind::Menu), None);
2011        // A click in the first menu closes the submenu only.
2012        assert_eq!(labels(&s.click(Some(Id::unique("menu")))), ["submenu"]);
2013        // A click on the interface closes the menu.
2014        assert_eq!(labels(&s.click(None)), ["menu"]);
2015        s.open(spec("dialog", Kind::Modal), None);
2016        s.open(spec("popover", Kind::Popover), None);
2017        assert_eq!(labels(&s.click(None)), ["popover"]);
2018        assert!(s.click(None).is_empty(), "the modal stays");
2019        assert_eq!(s.len(), 1);
2020    }
2021
2022    #[test]
2023    fn a_press_on_a_popovers_anchor_is_not_outside_it() {
2024        let mut s = OverlayStack::new();
2025        s.open(spec("popover", Kind::Popover), None);
2026        let id = Id::unique("popover");
2027        s.set_rect(
2028            id,
2029            Rect::from_min_max((100.0, 0.0).into(), (200.0, 80.0).into()),
2030        );
2031        s.set_anchor(
2032            id,
2033            Rect::from_min_max((100.0, 90.0).into(), (140.0, 110.0).into()),
2034        );
2035        // On the anchor: the widget that opened it toggles it.
2036        assert_eq!(s.hit((120.0, 100.0).into()), Some(id));
2037        assert!(s.click(s.hit((120.0, 100.0).into())).is_empty());
2038        // Elsewhere: outside, it closes.
2039        assert_eq!(s.hit((10.0, 100.0).into()), None);
2040        assert_eq!(labels(&s.click(None)), ["popover"]);
2041    }
2042
2043    #[test]
2044    fn a_press_on_a_popup_an_overlay_opened_is_not_outside_it() {
2045        let mut s = OverlayStack::new();
2046        s.open(spec("flyout", Kind::Popover), None);
2047        let id = Id::unique("flyout");
2048        s.set_rect(
2049            id,
2050            Rect::from_min_max((0.0, 0.0).into(), (100.0, 400.0).into()),
2051        );
2052        let combo = LayerId::new(egui::Order::Foreground, Id::unique("combo list"));
2053        s.set_popups(id, vec![combo]);
2054        assert_eq!(s.top_popups(), [combo]);
2055        // On the combo box's list, past the flyout's edge: inside.
2056        let past = (150.0, 50.0).into();
2057        assert_eq!(s.hit_on(past, Some(combo)), Some(id));
2058        assert!(s.click(s.hit_on(past, Some(combo))).is_empty());
2059        // Another layer there, or none: outside, it closes.
2060        let other = LayerId::new(egui::Order::Foreground, Id::unique("elsewhere"));
2061        assert_eq!(s.hit_on(past, Some(other)), None);
2062        assert_eq!(s.hit(past), None);
2063        assert_eq!(labels(&s.click(None)), ["flyout"]);
2064    }
2065
2066    #[test]
2067    fn a_modal_blocks_what_is_below_it() {
2068        let mut s = OverlayStack::new();
2069        s.open(spec("popover", Kind::Popover), None);
2070        assert!(!s.is_blocked(None));
2071        s.open(spec("dialog", Kind::Modal), None);
2072        s.open(spec("menu", Kind::Menu), None);
2073        assert_eq!(s.modal(), Some(Id::unique("dialog")));
2074        assert!(s.is_blocked(None));
2075        assert!(s.is_blocked(Some(Id::unique("popover"))));
2076        assert!(!s.is_blocked(Some(Id::unique("dialog"))));
2077        assert!(!s.is_blocked(Some(Id::unique("menu"))));
2078    }
2079
2080    #[test]
2081    fn opening_an_open_overlay_raises_it() {
2082        let mut s = OverlayStack::new();
2083        s.open(spec("a", Kind::Popover), None);
2084        s.open(spec("b", Kind::Popover), None);
2085        let (o, closed) = s.open(spec("a", Kind::Popover), None);
2086        assert_eq!(o, Opened::Raised);
2087        assert_eq!(labels(&closed), ["b"]);
2088        assert_eq!(s.top().unwrap().label, "a");
2089    }
2090
2091    #[test]
2092    fn invariants_hold_over_random_operations() {
2093        let mut s = OverlayStack::new();
2094        let mut seed: u64 = 7;
2095        let mut next = || {
2096            seed = seed
2097                .wrapping_mul(6364136223846793005)
2098                .wrapping_add(1442695040888963407);
2099            (seed >> 33) as usize
2100        };
2101        for _ in 0..2_000 {
2102            let n = next() % 6;
2103            let kind = [Kind::Modal, Kind::Popover, Kind::Menu][next() % 3];
2104            let before = s.len();
2105            match next() % 4 {
2106                0 => {
2107                    s.open(OverlaySpec::new(n, &n.to_string(), kind), None);
2108                }
2109                1 => {
2110                    let c = s.escape();
2111                    assert!(c.len() <= 1);
2112                }
2113                2 => {
2114                    let c = s.close(Id::unique(n));
2115                    assert_eq!(s.len() + c.len(), before);
2116                }
2117                _ => {
2118                    let modal_before = s.modal();
2119                    s.click(None);
2120                    // A modal never closes from a click.
2121                    assert_eq!(s.modal(), modal_before);
2122                }
2123            }
2124            // Ids are unique in the stack.
2125            let ids: Vec<Id> = s.specs().map(|o| o.id).collect();
2126            let mut dedup = ids.clone();
2127            dedup.sort_by_key(|i| i.value());
2128            dedup.dedup();
2129            assert_eq!(ids.len(), dedup.len());
2130        }
2131    }
2132
2133    /// One pass of a window (`viewport`), with `events`.
2134    fn pass_in(
2135        ctx: &Context,
2136        viewport: ViewportId,
2137        events: Vec<egui::Event>,
2138        add: impl FnMut(&mut Ui),
2139    ) {
2140        let input = egui::RawInput {
2141            viewport_id: viewport,
2142            // egui wants the window it runs among the viewports it is
2143            // told of.
2144            viewports: std::iter::once((viewport, Default::default())).collect(),
2145            events,
2146            ..Default::default()
2147        };
2148        let mut out = ctx.run_ui(input, add);
2149        // Nothing renders: the textures are dropped on purpose.
2150        out.textures_delta.clear();
2151    }
2152
2153    fn key(key: egui::Key) -> egui::Event {
2154        egui::Event::Key {
2155            key,
2156            physical_key: None,
2157            pressed: true,
2158            repeat: false,
2159            modifiers: egui::Modifiers::NONE,
2160        }
2161    }
2162
2163    fn press(pos: egui::Pos2) -> Vec<egui::Event> {
2164        vec![
2165            egui::Event::PointerMoved(pos),
2166            egui::Event::PointerButton {
2167                pos,
2168                button: egui::PointerButton::Primary,
2169                pressed: true,
2170                modifiers: egui::Modifiers::NONE,
2171            },
2172        ]
2173    }
2174
2175    #[test]
2176    fn a_held_overlay_stays_open_on_a_press_in_a_popup_it_drew() {
2177        let ctx = Context::default();
2178        let spec = OverlaySpec::new("flyout", "Flyout", Kind::Popover);
2179        let rect = Rect::from_min_max((0.0, 0.0).into(), (100.0, 300.0).into());
2180        let popup = Id::unique("a combo box's list");
2181        let mut open = true;
2182        // A foreground area past the overlay's edge, drawn while the
2183        // overlay draws, over several passes (egui keeps the layers of
2184        // earlier passes in its list).
2185        let frame = |events: Vec<egui::Event>, open: &mut bool| {
2186            pass_in(&ctx, ViewportId::ROOT, events, |ui| {
2187                hold(ui.ctx(), &spec, open, None, rect, || {
2188                    egui::Area::new(popup)
2189                        .order(egui::Order::Foreground)
2190                        .fixed_pos((150.0, 50.0))
2191                        .show(ui.ctx(), |ui| ui.label("an entry"));
2192                });
2193            });
2194        };
2195        for _ in 0..3 {
2196            frame(Vec::new(), &mut open);
2197        }
2198        assert!(open);
2199        frame(press((160.0, 55.0).into()), &mut open);
2200        frame(Vec::new(), &mut open);
2201        assert!(open, "a press in its popup is inside it");
2202        frame(press((400.0, 200.0).into()), &mut open);
2203        frame(Vec::new(), &mut open);
2204        assert!(!open, "a press elsewhere closes it");
2205    }
2206
2207    #[test]
2208    fn each_window_has_its_stack_and_a_modal_blocks_the_others() {
2209        let ctx = Context::default();
2210        let other = ViewportId::from_hash_of("a detached window");
2211        let dialog = OverlaySpec::new("dialog", "Dialog", Kind::Modal);
2212        let mut open = true;
2213        // Shown in the detached window: it belongs there.
2214        pass_in(&ctx, other, Vec::new(), |ui| {
2215            assert!(
2216                block_window(ui.ctx()).is_none(),
2217                "its own modal does not block it"
2218            );
2219            show(ui.ctx(), &dialog, &mut open, None, |ui| ui.label("Sure?"));
2220        });
2221        assert_eq!(window_of(&ctx, dialog.id), Some(other));
2222        assert_eq!(modal_windows(&ctx), [other]);
2223        assert!(modal_open(&ctx));
2224        // The main window's stack is empty, and its keys are dropped.
2225        let mut seen = Vec::new();
2226        pass_in(&ctx, ViewportId::ROOT, vec![key(egui::Key::A)], |ui| {
2227            assert!(stack(ui.ctx()).is_empty());
2228            assert_eq!(block_window(ui.ctx()), Some(other));
2229            seen = ui.ctx().input(|i| i.events.clone());
2230        });
2231        assert!(seen.is_empty(), "{seen:?}");
2232        // Escape in the main window closes nothing of the other's.
2233        pass_in(&ctx, ViewportId::ROOT, vec![key(egui::Key::Escape)], |ui| {
2234            begin_pass(ui.ctx());
2235        });
2236        assert_eq!(window_of(&ctx, dialog.id), Some(other));
2237        // The window closed: its overlays go with it.
2238        retain_windows(&ctx, &[]);
2239        assert!(!modal_open(&ctx));
2240        pass_in(&ctx, ViewportId::ROOT, vec![key(egui::Key::A)], |ui| {
2241            assert!(block_window(ui.ctx()).is_none());
2242            assert_eq!(ui.ctx().input(|i| i.events.len()), 1);
2243        });
2244    }
2245}
2246
2247/// A dialog's content laid out footer first: the footer (its buttons, a
2248/// status line) always gets its whole height, at the bottom of the room,
2249/// and the body takes what is left above it, scrolled when it needs more.
2250///
2251/// (Compiled, not run: a frame needs the kit's fonts and textures.)
2252///
2253/// ```no_run
2254/// # let ctx = egui::Context::default();
2255/// # let _ = ctx.run_ui(Default::default(), |ui| {
2256/// use egui_pop_core::overlay::DialogLayout;
2257///
2258/// let layout = DialogLayout::new(ui, "my.dialog").fill(true);
2259/// layout.body(ui, |ui, _height| {
2260///     ui.label("a long body");
2261/// });
2262/// layout.footer(ui, |ui| {
2263///     let _ = ui.button("OK");
2264/// });
2265/// # });
2266/// ```
2267///
2268/// The footer's height is the one it was last drawn at (a first estimate:
2269/// a row of buttons); a change asks for another pass.
2270#[derive(Clone, Copy, Debug)]
2271pub struct DialogLayout {
2272    id: Id,
2273    top: f32,
2274    height: f32,
2275    footer: f32,
2276    fill: bool,
2277}
2278
2279impl DialogLayout {
2280    /// The layout of the content of `ui`, from where its cursor is, in the
2281    /// height it has left; `id_salt` tells its footer's measure apart.
2282    pub fn new(ui: &Ui, id_salt: impl std::hash::Hash + std::fmt::Debug) -> Self {
2283        let id = ui.scope_id().with(("egui_pop.dialog_layout", id_salt));
2284        let spacing = ui.spacing().item_spacing.y;
2285        let footer = ui
2286            .ctx()
2287            .data(|d| d.get_temp::<f32>(id))
2288            .unwrap_or(ui.spacing().interact_size.y + spacing);
2289        Self {
2290            id,
2291            top: ui.cursor().min.y,
2292            height: ui.available_height(),
2293            footer,
2294            fill: false,
2295        }
2296    }
2297
2298    /// Whether the body fills the room, the footer at its bottom (a
2299    /// dialog of a set size); else the body is as tall as its content, up
2300    /// to the room, and the footer follows it.
2301    pub fn fill(mut self, fill: bool) -> Self {
2302        self.fill = fill;
2303        self
2304    }
2305
2306    /// At most this height for the body and the footer together (a
2307    /// dialog sized by its content, held to the window).
2308    pub fn max_height(mut self, height: f32) -> Self {
2309        self.height = self.height.min(height.max(0.0));
2310        self
2311    }
2312
2313    /// The height the body has before it scrolls: the room, less the
2314    /// footer. The footer's measure holds the space after it, as much as
2315    /// the body keeps before it: the footer ends on the room's bottom.
2316    pub fn body_height(&self, ui: &Ui) -> f32 {
2317        (self.height - (ui.cursor().min.y - self.top) - self.footer).max(0.0)
2318    }
2319
2320    /// Draws the body, `add` given the height it has before it scrolls
2321    /// (the scroll area's own `Ui` has no end below).
2322    pub fn body<R>(&self, ui: &mut Ui, add: impl FnOnce(&mut Ui, f32) -> R) -> R {
2323        let height = self.body_height(ui);
2324        let area = egui::ScrollArea::vertical()
2325            .id_salt(self.id.with("body"))
2326            .max_height(height)
2327            .auto_shrink([false, !self.fill]);
2328        crate::ui::UiPop::scroll_area(ui, area, |ui| add(ui, height)).inner
2329    }
2330
2331    /// Draws the footer, after the body (at the room's bottom when the
2332    /// body fills it), and keeps its height for the next pass.
2333    pub fn footer<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R {
2334        let start = ui.cursor().min.y;
2335        let r = add(ui);
2336        let height = ui.cursor().min.y - start;
2337        let kept = ui.ctx().data(|d| d.get_temp::<f32>(self.id));
2338        if kept.is_none_or(|k| (k - height).abs() > 0.5) {
2339            ui.ctx().data_mut(|d| d.insert_temp(self.id, height));
2340            ui.ctx().request_repaint();
2341        }
2342        r
2343    }
2344}