Skip to main content

egui_pop_api/bus/
shell.rs

1//! The shell's windows on the bus (ADR 0029, slice 4): the main window's
2//! close, quitting, and a window's content moving into the main window and
3//! back (`pop.window.reparent`).
4//!
5//! - The main window's close, whatever asked it (the system's close
6//!   request, its title bar's Close, [`AppHandle::close_window`],
7//!   [`AppHandle::quit`]), is one `pop.window.close` of the main window. Its
8//!   step may be vetoed by a before-hook (unsaved work): the close is then
9//!   cancelled and nothing changed. With another window open and the
10//!   application not quitting, the window worked in last moves into the
11//!   main window instead (ADR 0025): a `pop.window.reparent`, and the close is
12//!   cancelled.
13//! - Closing the main window closes every other window first, each by its
14//!   own `pop.window.close` (`pop.window.children`; reason `quit` or
15//!   `parent-closed`), so each owner's state closes with its window.
16//! - `pop.window.reparent` runs `pop.window.registry` (the content moves; the
17//!   registry holds the window or lets it go), `pop.window.place` (each id
18//!   keeps its own place), `pop.window.focus` (the main window is the one
19//!   worked in), then the invariants.
20//!
21//! A detached panel's window docked back is a `pop.window.reparent` too (the
22//! workbench's listener moves its panels first, [`super::panels`]); while
23//! a window's content holds the main window, the detached panels' windows
24//! leave the registry with the shell, and come back with it.
25//!
26//! The system window's own close request stays the way a window's title
27//! bar asks it where its content may refuse ([`crate::windows::WindowUi::keep_open`]):
28//! the window's pass then asks `pop.window.close`. The raw viewport commands
29//! of these paths are here, and nowhere else in the shell.
30
31use std::sync::{Arc, Mutex};
32
33use bus_contract::{Bus, ListenOpts, Point as _};
34use egui::{Context, ViewportCommand, ViewportId};
35use egui_pop_core::lock;
36use serde_json::json;
37
38use super::{
39    FOCUS, OWNER, PLACE, REGISTRY, Reason, Registry, WindowKind, WindowReparent, WindowRequest,
40    asking, emit,
41};
42use crate::app::AppHandle;
43use crate::windows::WindowId;
44
45/// The `window.reparent` step: the request as steps trace it (before-hooks
46/// may veto it).
47pub const STEP_WINDOW_REPARENT: egui_pop_model::ids::StepId =
48    egui_pop_model::ids::StepId::from_static("window.reparent");
49
50/// The key of a main window's close answered by a move into it.
51pub(super) const MOVED_IN: &str = "moved_in";
52
53/// Declares the `window.reparent` step.
54pub(super) fn declare(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::ctx::CtxError> {
55    ctx.step(
56        crate::steps::StepSpec::new(
57            STEP_WINDOW_REPARENT,
58            "A window's content moves to another window (`window`, `parent`: `main` to move into the main window, none to go back to a window of its own): its listeners on the bus run in their declared order.",
59        )
60        .args(json!({ "window": "import", "kind": "app", "owner": "app", "reason": "user", "parent": "main" })),
61    )?;
62    Ok(())
63}
64
65/// Registers the listeners of `pop.window.reparent`: the registry, the place,
66/// the focus (the invariants, last, are the bus's).
67pub(super) fn install(kernel: &dyn Bus, registry: &Arc<Mutex<Registry>>) {
68    let mine = || ListenOpts::new().owner(OWNER);
69    let registry = registry.clone();
70    let listened = [
71        kernel.listen::<WindowReparent>(REGISTRY, mine().before(PLACE), move |req, did| {
72            let Some(app) = asking() else { return Ok(()) };
73            if req.kind == WindowKind::Panel {
74                // A detached panel's window, docked back: the workbench's
75                // listener moved its panels; the window goes.
76                if req.parent.as_deref() == Some(WindowId::MAIN)
77                    && lock(&registry).close(&req.window)
78                {
79                    // Its popups and native windows go with its panels.
80                    lock(&registry).adopt(&req.window, WindowId::MAIN);
81                    super::panels::left(&app, &req.window);
82                    let mut w = app.windows_mut();
83                    w.moved_events
84                        .push(("window.closed", json!({ "window": req.window })));
85                    w.moved_events.push((
86                        "window.moved",
87                        json!({ "window": req.window, "to": WindowId::MAIN }),
88                    ));
89                    did.push(format!("{REGISTRY}: `{}` docked in the main window", req.window));
90                }
91                return Ok(());
92            }
93            let id = WindowId::new(&req.window);
94            match req.parent.as_deref() {
95                Some(WindowId::MAIN) => {
96                    if app.move_into_root(&id) {
97                        let mut registry = lock(&registry);
98                        registry.close(&req.window);
99                        did.push(format!(
100                            "{REGISTRY}: `{}` drawn in the main window",
101                            req.window
102                        ));
103                        // Its dialogs and file choices go with its content.
104                        let adopted = registry.adopt(&req.window, WindowId::MAIN);
105                        if adopted > 0 {
106                            did.push(format!(
107                                "{REGISTRY}: {adopted} of its popups now the main window's"
108                            ));
109                        }
110                        did.extend(super::panels::follow_shell(&app, &mut registry, true));
111                    }
112                }
113                None => {
114                    if app.move_out_of_root() {
115                        let mut registry = lock(&registry);
116                        registry.open(req, Some(id.deferred_viewport()));
117                        did.push(format!(
118                            "{REGISTRY}: `{}` in a window of its own",
119                            req.window
120                        ));
121                        did.extend(super::panels::follow_shell(&app, &mut registry, false));
122                    }
123                }
124                Some(other) => {
125                    return Err(format!(
126                        "`{}` cannot move into `{other}`: only the main window takes another's content",
127                        req.window
128                    )
129                    .into());
130                }
131            }
132            Ok(())
133        }),
134        kernel.listen::<WindowReparent>(PLACE, mine().after(REGISTRY), |_, did| {
135            let Some(app) = asking() else { return Ok(()) };
136            if app.keep_moved_places() > 0 {
137                did.push(format!("{PLACE}: each keeps its place"));
138            }
139            Ok(())
140        }),
141        kernel.listen::<WindowReparent>(FOCUS, mine().after(PLACE), |_, did| {
142            let Some(app) = asking() else { return Ok(()) };
143            // The content moved in is the one worked in; the main window
144            // asked to its front is too.
145            app.request_window_activate(WindowRequest::new(
146                WindowId::MAIN,
147                WindowKind::Main,
148                OWNER,
149                Reason::System,
150            ));
151            did.push(format!("{FOCUS}: the main window is active"));
152            Ok(())
153        }),
154    ];
155    for l in listened {
156        debug_assert!(l.is_ok(), "{l:?}");
157    }
158}
159
160/// `pop.window.children`'s part on the main window's close: every other
161/// window is closed by its own `pop.window.close` first, its owner's state
162/// with it (`quit` when the application quits, else `parent-closed`).
163pub(super) fn close_children_of_main(app: &AppHandle, req: &WindowRequest, did: &mut Vec<String>) {
164    let reason = if req.reason == Reason::Quit {
165        Reason::Quit
166    } else {
167        Reason::ParentClosed
168    };
169    let children: Vec<WindowRequest> = app
170        .windows_list()
171        .into_iter()
172        .filter(|w| w.kind == WindowKind::App)
173        .map(|w| {
174            let mut child = WindowRequest::new(w.id, w.kind, w.owner, reason);
175            child.cause = req.cause;
176            child.parent(WindowId::MAIN)
177        })
178        .collect();
179    let mut closed = 0;
180    for child in children {
181        if app.request_window_close(child) {
182            closed += 1;
183        }
184    }
185    if closed > 0 {
186        did.push(format!("{}: {closed} windows closed", super::CHILDREN));
187    }
188}
189
190/// The step of the main window's close, when another window moves into
191/// it instead (not quitting, one open): the `pop.window.reparent` asked, and
192/// what the step returns.
193pub(super) fn move_in_instead(app: &AppHandle, req: &WindowRequest) -> Option<serde_json::Value> {
194    if req.kind != WindowKind::Main || req.reason == Reason::Quit {
195        return None;
196    }
197    let id = app.window_to_move_in()?;
198    let owner = app
199        .windows_list()
200        .into_iter()
201        .find(|w| w.id == id.as_str())
202        .map_or_else(|| "app".to_string(), |w| w.owner);
203    let mut moving = WindowRequest::new(id.as_str(), WindowKind::App, owner, Reason::User)
204        .parent(WindowId::MAIN);
205    moving.cause = req.cause;
206    let moved = app.request_window_reparent(moving);
207    Some(json!({ MOVED_IN: id, "reparented": moved }))
208}
209
210impl AppHandle {
211    /// Asks for a window's content to move to another window
212    /// (`pop.window.reparent`): `parent` `main` moves an application window's
213    /// content into the main window (its own window goes); no `parent`
214    /// moves the content the main window holds back to a window of its
215    /// own. Its listeners all run now, in their declared order; a
216    /// before-hook on the `window.reparent` step may veto it
217    /// (`window.refused`). Whether it moved.
218    ///
219    /// <div class="warning">Experimental: may change in any release
220    /// (docs/stability.md).</div>
221    pub fn request_window_reparent(&self, request: WindowRequest) -> bool {
222        let args = serde_json::to_value(&request).unwrap_or_default();
223        let outcome = self.step(&STEP_WINDOW_REPARENT, args, |app, args| {
224            let req = serde_json::from_value::<WindowRequest>(args.clone())
225                .map_err(|e| format!("not a window request: {e}"))?;
226            let did = emit::<WindowReparent>(app, req);
227            Ok(json!({ "did": did }))
228        });
229        let said = std::mem::take(&mut self.windows_mut().moved_events);
230        match outcome {
231            crate::steps::Outcome::Vetoed { by, reason } => {
232                self.publish(
233                    "egui_pop",
234                    request.cause,
235                    "window.refused",
236                    json!({ "request": WindowReparent::ID.as_str(), "window": request.window, "owner": request.owner, "vetoed_by": by, "reason": reason }),
237                );
238                false
239            }
240            crate::steps::Outcome::Done(result) => {
241                let moved = !said.is_empty();
242                for (name, data) in said {
243                    self.publish("egui_pop", request.cause, name, data);
244                }
245                result.is_ok() && moved
246            }
247        }
248    }
249
250    /// Asks the main window's close (`pop.window.close` of the main window):
251    /// whether it closed (not vetoed, no window moved into it instead).
252    pub(crate) fn ask_main_close(&self, reason: Reason) -> bool {
253        self.request_window_close(WindowRequest::new(
254            WindowId::MAIN,
255            WindowKind::Main,
256            "app",
257            reason,
258        ))
259    }
260
261    /// The main window's pass saw the system ask its close: unless a
262    /// `pop.window.close` of the main window already ran (it asked the
263    /// system), one is asked now; vetoed, or answered by a window moving
264    /// into it, the system's close is cancelled.
265    pub(crate) fn main_close_seen(&self, ctx: &Context) {
266        if !ctx.input(|i| i.viewport().close_requested()) {
267            return;
268        }
269        let quit_asked = self.take_quitting();
270        let closing = !lock(&self.0.bus.registry).holds(WindowId::MAIN);
271        if quit_asked || closing {
272            return;
273        }
274        if !self.ask_main_close(Reason::User) {
275            ctx.send_viewport_cmd(ViewportCommand::CancelClose);
276        }
277    }
278
279    /// `pop.window.registry`'s part on the main window's close: the system is
280    /// asked to close it, unless it asked already.
281    pub(super) fn registry_close_main(&self) {
282        let ctx = self.egui();
283        if !ctx.input_for(ViewportId::ROOT, |i| i.viewport().close_requested()) {
284            ctx.send_viewport_cmd_to(ViewportId::ROOT, ViewportCommand::Close);
285        }
286        ctx.request_repaint_of(ViewportId::ROOT);
287    }
288
289    /// The main window asked to its front while a window's content holds
290    /// it: that content goes back to a window of its own, a
291    /// `pop.window.reparent` with no parent.
292    pub(crate) fn ask_home(&self) {
293        let Some(id) = self.take_going_home() else {
294            return;
295        };
296        self.request_window_reparent(WindowRequest::new(
297            id.as_str(),
298            WindowKind::App,
299            "app",
300            Reason::User,
301        ));
302    }
303
304    /// The `frame.close` step's default: the main window's `pop.window.close`;
305    /// another window's close request to the system, which its content may
306    /// refuse before its pass asks `pop.window.close`. Whether a close was
307    /// asked.
308    pub(crate) fn frame_close(&self, ctx: &Context) -> bool {
309        if ctx.viewport_id() == ViewportId::ROOT {
310            return self.ask_main_close(Reason::User);
311        }
312        ctx.send_viewport_cmd(ViewportCommand::Close);
313        true
314    }
315}