Skip to main content

egui_pop_api/bus/
popups.rs

1//! Popups and native windows on the bus (ADR 0029, slice 5): dialogs and
2//! file choices.
3//!
4//! - A popup opens by its `pop.popup.open` ([`AppHandle::request_popup_open`])
5//!   and closes by its `pop.popup.close` ([`AppHandle::request_popup_close`]),
6//!   whoever asks: its owner when it is answered, a window closing under
7//!   it. Its owner's listener on `pop.popup.close` ends what it showed (a
8//!   dialog cancelled, a file choice cancelled), in that call.
9//! - A native window egui does not paint (the system's file chooser)
10//!   opens by its `pop.window.open` ([`AppHandle::request_native_open`]) and
11//!   closes by its `pop.window.close`.
12//! - A window closing closes its popups and native windows first, each by
13//!   its own request (`pop.window.children`, reason `parent-closed`, or `quit`
14//!   when the application quits), so none is left with a parent gone.
15//! - A window's content moving into the main window takes its popups and
16//!   native windows with it: they become the main window's.
17
18use bus_contract::Point as _;
19use serde_json::json;
20
21use super::{CHILDREN, PopupClose, PopupOpen, Reason, WindowKind, WindowOpen, WindowRequest, emit};
22use crate::app::AppHandle;
23use egui_pop_core::lock;
24
25/// `pop.window.children`'s part on any window: its popups and native windows
26/// are closed, each by its own request, before it goes.
27pub(super) fn close_children(app: &AppHandle, req: &WindowRequest, did: &mut Vec<String>) {
28    let reason = if req.reason == Reason::Quit {
29        Reason::Quit
30    } else {
31        Reason::ParentClosed
32    };
33    let children: Vec<WindowRequest> = app
34        .windows_list()
35        .into_iter()
36        .filter(|w| w.parent.as_deref() == Some(req.window.as_str()))
37        .filter(|w| matches!(w.kind, WindowKind::Popup | WindowKind::Native))
38        .map(|w| {
39            let mut child =
40                WindowRequest::new(w.id, w.kind, w.owner, reason).parent(req.window.clone());
41            child.cause = req.cause;
42            child
43        })
44        .collect();
45    let (mut popups, mut natives) = (0, 0);
46    for child in children {
47        if child.kind == WindowKind::Popup {
48            if app.request_popup_close(child) {
49                popups += 1;
50            }
51        } else if app.request_window_close(child) {
52            natives += 1;
53        }
54    }
55    if popups > 0 {
56        did.push(format!("{CHILDREN}: {popups} popups closed"));
57    }
58    if natives > 0 {
59        did.push(format!("{CHILDREN}: {natives} native windows closed"));
60    }
61}
62
63impl AppHandle {
64    /// Whether the registry holds `id`.
65    fn holds(&self, id: &str) -> bool {
66        lock(&self.0.bus.registry).holds(id)
67    }
68
69    /// Says a popup or native window request refused: `<family>.refused`.
70    fn refuse(&self, family: &str, point: &str, request: &WindowRequest, reason: &str) {
71        log::warn!(
72            target: "egui_pop",
73            "`{point}` of `{}` refused: {reason}",
74            request.window
75        );
76        self.publish(
77            "egui_pop",
78            request.cause,
79            &format!("{family}.refused"),
80            json!({ "request": point, "window": request.window, "owner": request.owner, "reason": reason }),
81        );
82    }
83
84    /// Why an opening request is refused, if it is: of another kind, no
85    /// owner, a parent that is not open.
86    fn open_refusal(&self, request: &WindowRequest, kind: WindowKind) -> Option<&'static str> {
87        if request.kind != kind {
88            Some("not of the kind this request opens")
89        } else if request.owner.trim().is_empty() {
90            Some("no owner")
91        } else if !request.parent.as_deref().is_some_and(|p| self.holds(p)) {
92            Some("its parent window is not open")
93        } else {
94            None
95        }
96    }
97
98    /// The data of a popup or native window's event.
99    fn said(request: &WindowRequest, did: Vec<String>) -> serde_json::Value {
100        let mut data = json!({
101            "window": request.window,
102            "kind": request.kind,
103            "owner": request.owner,
104            "parent": request.parent,
105            "reason": request.reason,
106            "did": did,
107        });
108        if let Some(how) = &request.how {
109            data["how"] = json!(how);
110        }
111        if let Some(c) = request.cause {
112            data["cause"] = json!(c);
113        }
114        data
115    }
116
117    /// Asks for a popup (`pop.popup.open`, kind [`WindowKind::Popup`]) in its
118    /// parent window, which must be open, with an owner: its listeners all
119    /// run now, the registry holding it, and `popup.opened` follows. A
120    /// popup of that id already held is held again under this request. A
121    /// refusal is said as `popup.refused`. Whether it opened.
122    ///
123    /// <div class="warning">Experimental: may change in any release
124    /// (docs/stability.md).</div>
125    pub fn request_popup_open(&self, request: WindowRequest) -> bool {
126        if let Some(why) = self.open_refusal(&request, WindowKind::Popup) {
127            self.refuse("popup", PopupOpen::ID.as_str(), &request, why);
128            return false;
129        }
130        let did = emit::<PopupOpen>(self, request.clone());
131        self.publish(
132            "egui_pop",
133            request.cause,
134            "popup.opened",
135            Self::said(&request, did),
136        );
137        true
138    }
139
140    /// Asks for a popup's close (`pop.popup.close`): its listeners all run
141    /// now, its owner's first (what it showed ends: a dialog or a file
142    /// choice cancelled), then the registry; `popup.closed` follows. A
143    /// popup not open is refused (`popup.refused`). Whether it closed.
144    ///
145    /// <div class="warning">Experimental: may change in any release
146    /// (docs/stability.md).</div>
147    pub fn request_popup_close(&self, request: WindowRequest) -> bool {
148        if !self.holds(&request.window) {
149            self.refuse(
150                "popup",
151                PopupClose::ID.as_str(),
152                &request,
153                "no open popup of this id",
154            );
155            return false;
156        }
157        let did = emit::<PopupClose>(self, request.clone());
158        let closed = !self.holds(&request.window);
159        self.publish(
160            "egui_pop",
161            request.cause,
162            "popup.closed",
163            Self::said(&request, did),
164        );
165        closed
166    }
167
168    /// Asks for a native window egui does not paint (`pop.window.open`, kind
169    /// [`WindowKind::Native`]: the system's file chooser, a web view's own
170    /// window) as a child of an open window, with an owner: the registry
171    /// holds it and `window.opened` follows. It closes by its
172    /// `pop.window.close` ([`AppHandle::request_window_close`]), and with its
173    /// parent. A refusal is said as `window.refused`. Whether it opened.
174    ///
175    /// <div class="warning">Experimental: may change in any release
176    /// (docs/stability.md).</div>
177    pub fn request_native_open(&self, request: WindowRequest) -> bool {
178        if let Some(why) = self.open_refusal(&request, WindowKind::Native) {
179            self.refuse("window", WindowOpen::ID.as_str(), &request, why);
180            return false;
181        }
182        let did = self.ask_window_open(request.clone());
183        self.publish(
184            "egui_pop",
185            request.cause,
186            "window.opened",
187            Self::said(&request, did),
188        );
189        true
190    }
191
192    /// The registry id of the window a viewport shows: the main window,
193    /// an application window, a detached panel's window; the main
194    /// window's when none is held for it. The parent to name for a popup
195    /// or a native window opened from a pass of that viewport.
196    ///
197    /// <div class="warning">Experimental: may change in any release
198    /// (docs/stability.md).</div>
199    pub fn registry_window_of(&self, viewport: egui::ViewportId) -> String {
200        let shown = format!("{viewport:?}");
201        lock(&self.0.bus.registry)
202            .records
203            .iter()
204            .find(|r| {
205                matches!(
206                    r.kind,
207                    WindowKind::Main | WindowKind::App | WindowKind::Panel
208                ) && r.viewport.as_deref() == Some(shown.as_str())
209            })
210            .map_or_else(
211                || crate::windows::WindowId::MAIN.to_string(),
212                |r| r.id.clone(),
213            )
214    }
215}