Skip to main content

egui_pop_api/bus/
overlays.rs

1//! The overlay stack and egui's popups on the bus (ADR 0029, slice 6):
2//! menus, the palette, flyouts, popovers, hover cards.
3//!
4//! - Every overlay of every window's stack (`egui_pop_core::overlay`) and
5//!   every egui popup the stack follows (a context menu, a menu bar's
6//!   menu, the jobs popover, a hover card) is a popup of the registry: its
7//!   opening is its `pop.popup.open`, its closing its `pop.popup.close`, asked in
8//!   the call that opened or closed it ([`overlay::watch`]), with how it
9//!   closed (`how`: `escape`, `outside`, `chosen`, `owner`, `below`,
10//!   `gone`).
11//! - A popup's close asked by anyone else (its window closing under it,
12//!   `pop.window.children` with `parent-closed`) closes it in the stack
13//!   ([`STACK`], a listener of `pop.popup.close`), with what was above it.
14//! - An owner names its overlay's popup and itself
15//!   ([`AppHandle::name_overlay`]); an overlay not named is
16//!   `overlay:<id>@<window>`, owned by [`OVERLAY_OWNER`].
17//! - Dialogs and file choices ask their own requests: the stack leaves
18//!   theirs alone.
19//!
20//! Off the bus, as the ADR's exceptions say: egui's tooltips and the
21//! lists of a field (a combo box's choices, completions), drawn only while
22//! their widget is, per-frame painting.
23
24use std::cell::RefCell;
25use std::collections::{HashMap, HashSet};
26use std::sync::Arc;
27
28use bus_contract::ListenOpts;
29use egui::{Id, ViewportId};
30use egui_pop_core::overlay::{self, Change, Closing};
31
32use super::{OWNER, PopupClose, REGISTRY, Reason, WindowKind, WindowRequest, asking};
33use crate::app::{AppHandle, WeakApp};
34
35/// The owner of an overlay its owner did not name.
36pub const OVERLAY_OWNER: &str = "egui_pop.overlay";
37/// Closes in the stack a popup closed by a request (`pop.popup.close`).
38pub const STACK: &str = "pop.overlay.stack";
39/// The start of an unnamed overlay's popup id.
40pub const POPUP_PREFIX: &str = "overlay:";
41
42/// The overlays the bus knows.
43#[derive(Debug, Default)]
44pub(crate) struct Overlays {
45    /// Named by their owner, in a window: the popup id and the owner.
46    named: HashMap<(Id, ViewportId), (String, String)>,
47    /// Asking their own requests (dialogs, file choices).
48    own: HashSet<Id>,
49    /// Open: popup id → the overlay.
50    open: HashMap<String, (Id, ViewportId)>,
51}
52
53thread_local! {
54    /// The applications whose context the stack is watched in.
55    static WATCHED: RefCell<Vec<WeakApp>> = const { RefCell::new(Vec::new()) };
56}
57
58/// Watches the overlays of `ctx` for `app`: each opening and closing is
59/// its popup's request.
60pub(crate) fn watch(ctx: &egui::Context, app: &AppHandle) {
61    WATCHED.with_borrow_mut(|w| {
62        w.retain(|a| a.get().is_ok());
63        w.push(app.downgrade());
64    });
65    overlay::watch(
66        ctx,
67        Some(Arc::new(|ctx: &egui::Context, change: &Change| {
68            let app = WATCHED.with_borrow(|w| {
69                w.iter()
70                    .filter_map(|a| a.get().ok())
71                    .find(|a| a.egui() == *ctx)
72            });
73            if let Some(app) = app {
74                app.overlay_changed(change);
75            }
76        })),
77    );
78}
79
80/// Registers the stack's listener on `pop.popup.close`.
81pub(super) fn install(kernel: &dyn bus_contract::Bus) {
82    let l = kernel.listen::<PopupClose>(
83        STACK,
84        ListenOpts::new().owner(OWNER).before(REGISTRY),
85        |req, did| {
86            let Some(app) = asking() else { return Ok(()) };
87            // Not open, or the stack itself telling of its close.
88            let Some((id, window)) = app.0.bus.overlays.borrow_mut().open.remove(&req.window)
89            else {
90                return Ok(());
91            };
92            if overlay::close_in_window(&app.egui(), window, id) {
93                did.push(format!("{STACK}: closed"));
94            }
95            Ok(())
96        },
97    );
98    debug_assert!(l.is_ok(), "{l:?}");
99    let l = kernel.listen::<PopupClose>(
100        crate::palette::POPUP_LISTENER,
101        ListenOpts::new().owner(crate::palette::OWNER).before(STACK),
102        |req, did| {
103            let Some(app) = asking() else { return Ok(()) };
104            if crate::palette::popup_closed(&app, &req.window) {
105                did.push(format!("{}: closed", crate::palette::POPUP_LISTENER));
106            }
107            Ok(())
108        },
109    );
110    debug_assert!(l.is_ok(), "{l:?}");
111    crate::menus::listen_popup(kernel);
112}
113
114/// The request's reason for how an overlay closed.
115fn reason_of(how: Closing) -> Reason {
116    match how {
117        Closing::Escape | Closing::Outside | Closing::Chosen => Reason::User,
118        Closing::Below => Reason::ParentClosed,
119        _ => Reason::Command,
120    }
121}
122
123impl AppHandle {
124    /// Names the popup an overlay of the stack (or an egui popup it
125    /// follows) is in the registry while shown in `window`, and its owner:
126    /// `palette@main`, `egui_pop.palette`. Call it before showing it; a
127    /// popup not named is `overlay:<id>@<window>`, owned by
128    /// [`OVERLAY_OWNER`].
129    ///
130    /// <div class="warning">Experimental: may change in any release
131    /// (docs/stability.md).</div>
132    pub fn name_overlay(&self, id: Id, window: ViewportId, popup: String, owner: &str) {
133        let mut o = self.0.bus.overlays.borrow_mut();
134        let named = (popup, owner.to_string());
135        if o.named.get(&(id, window)) != Some(&named) {
136            o.named.insert((id, window), named);
137        }
138    }
139
140    /// An overlay whose owner asks its popup's requests itself (a dialog,
141    /// a file choice): the stack's watch leaves it alone.
142    pub(crate) fn overlay_on_its_own(&self, id: Id) {
143        self.0.bus.overlays.borrow_mut().own.insert(id);
144    }
145
146    /// Closes an overlay by its popup's `pop.popup.close`, the person having
147    /// closed it (`how`: Escape, an item chosen), or by itself when the
148    /// registry does not hold it. Whether the request closed it.
149    pub(crate) fn close_overlay(&self, ctx: &egui::Context, id: Id, how: Closing) -> bool {
150        let popup = self.open_popup_of(&self.0.bus.overlays.borrow(), id, ctx.viewport_id());
151        let Some(popup) = popup else {
152            overlay::close(ctx, id);
153            return false;
154        };
155        let record = self.windows_list().into_iter().find(|w| w.id == popup);
156        let Some(record) = record else {
157            self.0.bus.overlays.borrow_mut().open.remove(&popup);
158            overlay::close(ctx, id);
159            return false;
160        };
161        let mut req = WindowRequest::new(popup, WindowKind::Popup, record.owner, reason_of(how))
162            .how(how.as_str());
163        req.parent = record.parent;
164        self.request_popup_close(req)
165    }
166
167    /// The open popup of an overlay shown in `window` (one overlay may be
168    /// open in several windows: the palette), else any of that overlay.
169    fn open_popup_of(&self, o: &Overlays, id: Id, window: ViewportId) -> Option<String> {
170        let named = o.named.get(&(id, window)).map(|n| n.0.clone());
171        named
172            .filter(|p| o.open.contains_key(p))
173            .or_else(|| {
174                let here = format!("{POPUP_PREFIX}{id:?}@{}", self.registry_window_of(window));
175                o.open.contains_key(&here).then_some(here)
176            })
177            .or_else(|| {
178                o.open
179                    .iter()
180                    .find(|(_, (i, _))| *i == id)
181                    .map(|(p, _)| p.clone())
182            })
183    }
184
185    /// The popup id and owner of an overlay shown in `window`, unless it
186    /// asks its own requests.
187    fn overlay_popup(&self, id: Id, window: ViewportId) -> Option<(String, String)> {
188        let o = self.0.bus.overlays.borrow();
189        if o.own.contains(&id) {
190            return None;
191        }
192        Some(o.named.get(&(id, window)).cloned().unwrap_or_else(|| {
193            (
194                format!("{POPUP_PREFIX}{id:?}@{}", self.registry_window_of(window)),
195                OVERLAY_OWNER.to_string(),
196            )
197        }))
198    }
199
200    /// An overlay opened or closed in the stack: its popup's request.
201    fn overlay_changed(&self, change: &Change) {
202        let Some(how) = change.closed else {
203            let Some((popup, owner)) = self.overlay_popup(change.id, change.window) else {
204                return;
205            };
206            self.0
207                .bus
208                .overlays
209                .borrow_mut()
210                .open
211                .insert(popup.clone(), (change.id, change.window));
212            let req = WindowRequest::new(popup.clone(), WindowKind::Popup, owner, Reason::User)
213                .parent(self.registry_window_of(change.window));
214            if !self.request_popup_open(req) {
215                self.0.bus.overlays.borrow_mut().open.remove(&popup);
216            }
217            return;
218        };
219        // Taken off first: the stack's listener leaves it (it is closed).
220        let popup = {
221            let mut o = self.0.bus.overlays.borrow_mut();
222            if o.own.contains(&change.id) {
223                return;
224            }
225            let popup = self.open_popup_of(&o, change.id, change.window);
226            if let Some(p) = &popup {
227                o.open.remove(p);
228            }
229            popup
230        };
231        let Some(popup) = popup else { return };
232        let Some(record) = self.windows_list().into_iter().find(|w| w.id == popup) else {
233            return;
234        };
235        let mut req = WindowRequest::new(popup, WindowKind::Popup, record.owner, reason_of(how))
236            .how(how.as_str());
237        req.parent = record.parent;
238        self.request_popup_close(req);
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn the_person_closing_is_user_a_parent_closing_is_parent_closed() {
248        for how in [Closing::Escape, Closing::Outside, Closing::Chosen] {
249            assert_eq!(reason_of(how), Reason::User);
250        }
251        assert_eq!(reason_of(Closing::Below), Reason::ParentClosed);
252        assert_eq!(reason_of(Closing::Owner), Reason::Command);
253        assert_eq!(reason_of(Closing::Gone), Reason::Command);
254    }
255}