Skip to main content

egui_pop_api/bus/
panels.rs

1//! The detached panels' windows on the bus (ADR 0029, slice 4): the
2//! workbench owns them.
3//!
4//! - Detaching a panel into a window of its own is that window's
5//!   `pop.window.open` (`panel:<id>`, kind [`WindowKind::Panel`], owner
6//!   [`WORKBENCH_OWNER`]).
7//! - Docking a detached panel back (`workbench.attach`, or moving it to an
8//!   area, as a tab dragged there does) is its window's `pop.window.reparent`
9//!   into the main window.
10//! - Closing a detached panel's window (its title bar, the system's
11//!   close, `workbench.close_window`, or anyone asking `pop.window.close` of
12//!   it) is its `pop.window.close`; its panels dock back.
13//!
14//! The workbench's listener on the three points ([`WORKBENCH_WINDOW`])
15//! changes the layout, whoever asked, before the registry holds or lets
16//! go of the window. A workbench change that adds, removes or renames a
17//! window some other way (a panel joining another window's tabs, a layout
18//! put in, panels declared again) asks the same requests in the same call,
19//! once the layout changed: the listener then finds nothing left to do.
20//! While a window's content holds the main window, the detached panels are
21//! not drawn: the registry lets their windows go with that move and holds
22//! them again when the content goes back.
23//!
24//! The raw viewport calls of the detached panels' windows are here, and
25//! nowhere in the workbench.
26
27use bus_contract::{Bus, ListenOpts};
28use egui::{Context, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId};
29use egui_pop_model::ids::PanelId;
30use egui_pop_model::layout::Auxiliary;
31use serde_json::json;
32
33use super::{
34    CHILDREN, FOCUS, REGISTRY, Reason, WindowClose, WindowKind, WindowOpen, WindowReparent,
35    WindowRequest, asking,
36};
37use crate::app::AppHandle;
38use crate::window_invariants::PANEL_PREFIX;
39use crate::windows::WindowId;
40use crate::workbench::Change;
41
42/// What owns the detached panels' windows.
43pub const WORKBENCH_OWNER: &str = "egui_pop.workbench";
44/// The workbench's listener on the window points: the layout follows the
45/// request, whoever asked.
46pub const WORKBENCH_WINDOW: &str = "pop.workbench.window";
47
48/// A detached panel's window id in the registry (`panel:<id>`).
49pub(crate) fn window_of_panel(panel: &PanelId) -> String {
50    format!("{PANEL_PREFIX}{}", panel.as_str())
51}
52
53/// The panel naming a detached panel's window, from its registry id.
54fn panel_of_window(id: &str) -> Option<PanelId> {
55    PanelId::new(id.strip_prefix(PANEL_PREFIX)?).ok()
56}
57
58/// A request about a detached panel's window, the workbench asking.
59fn request(id: &str, reason: Reason) -> WindowRequest {
60    WindowRequest::new(id, WindowKind::Panel, WORKBENCH_OWNER, reason)
61}
62
63/// Registers the workbench's listener on `pop.window.open`, `pop.window.close`
64/// and `pop.window.reparent`.
65pub(super) fn install(kernel: &dyn Bus) {
66    let mine = || ListenOpts::new().owner(WORKBENCH_OWNER);
67    let listened = [
68        kernel.listen::<WindowOpen>(WORKBENCH_WINDOW, mine().before(REGISTRY), |req, did| {
69            let Some((app, panel)) = panel_request(req) else {
70                return Ok(());
71            };
72            // Nothing to do when the layout has the window already: the
73            // panel alone in it, or a window the workbench made that the
74            // registry does not hold yet (a tab group detached whole).
75            let named = app
76                .workbench_mut()
77                .layout
78                .window_of(&panel)
79                .filter(|a| a.panel == panel)
80                .map(|a| a.tabs.is_empty());
81            let made = match named {
82                Some(true) => true,
83                Some(false) => !app.windows_list().iter().any(|w| w.id == req.window),
84                None => false,
85            };
86            if !made {
87                app.workbench_mut().apply(&Change::Detach(panel.clone()))?;
88                did.push(format!("{WORKBENCH_WINDOW}: `{panel}` detached"));
89            }
90            Ok(())
91        }),
92        kernel.listen::<WindowClose>(
93            WORKBENCH_WINDOW,
94            mine().after(CHILDREN).before(FOCUS),
95            |req, did| dock_back(req, did, "its window closed"),
96        ),
97        kernel.listen::<WindowReparent>(WORKBENCH_WINDOW, mine().before(REGISTRY), |req, did| {
98            if req.kind == WindowKind::Panel && req.parent.as_deref() != Some(WindowId::MAIN) {
99                return Err(format!(
100                    "`{}` moves only into the main window; detaching a panel is `pop.window.open`",
101                    req.window
102                )
103                .into());
104            }
105            dock_back(req, did, "docked back")
106        }),
107    ];
108    for l in listened {
109        debug_assert!(l.is_ok(), "{l:?}");
110    }
111}
112
113/// A request about a detached panel's window: the application asking,
114/// and the panel naming the window.
115fn panel_request(req: &WindowRequest) -> Option<(AppHandle, PanelId)> {
116    if req.kind != WindowKind::Panel {
117        return None;
118    }
119    Some((asking()?, panel_of_window(&req.window)?))
120}
121
122/// `pop.workbench.window` on a window closed or moved into the main window:
123/// its panels dock back in their areas, while the layout still has it.
124fn dock_back(
125    req: &WindowRequest,
126    did: &mut Vec<String>,
127    how: &str,
128) -> Result<(), bus_contract::HookError> {
129    let Some((app, panel)) = panel_request(req) else {
130        return Ok(());
131    };
132    let held = app
133        .workbench_mut()
134        .layout
135        .auxiliary
136        .iter()
137        .any(|a| a.panel == panel);
138    if held {
139        app.workbench_mut()
140            .apply(&Change::CloseWindow(panel.clone()))?;
141        did.push(format!("{WORKBENCH_WINDOW}: `{panel}` {how}"));
142    }
143    Ok(())
144}
145
146/// The request a workbench change asks first, when it opens, docks back
147/// or closes one detached panel's window: its result as the change's
148/// step returns it. `None`: the change is done by the workbench itself
149/// (then [`AppHandle::sync_panel_windows`] asks what it changed).
150pub(crate) fn ask(app: &AppHandle, change: &Change) -> Option<Result<serde_json::Value, String>> {
151    // The detached panels are not drawn while a window's content holds
152    // the main window: their windows are not on screen to ask about.
153    if app.root_has_content() {
154        return None;
155    }
156    let (panel, window) = {
157        let wb = app.workbench_mut();
158        let panel = match change {
159            Change::Detach(p) | Change::Attach(p) | Change::CloseWindow(p) => p.clone(),
160            _ => return None,
161        };
162        // Refused or unknown: the workbench says why.
163        let spec = wb.spec(&panel).cloned()?;
164        let window = wb.layout.window_of(&panel).cloned();
165        if let Change::Detach(_) = change
166            && spec
167                .refuses(&crate::mounts::panel_host(
168                    egui_pop_model::panels::Place::Window,
169                ))
170                .is_some()
171        {
172            return None;
173        }
174        (panel, window)
175    };
176    match change {
177        Change::Detach(_) => {
178            if window
179                .as_ref()
180                .is_some_and(|a| a.panel == panel && a.tabs.is_empty())
181            {
182                return None;
183            }
184            app.request_panel_window_open(&panel, Reason::Command);
185            let detached = app.workbench_mut().layout.window_of(&panel).is_some();
186            Some(if detached {
187                Ok(json!({ "panel": panel, "detached": true }))
188            } else {
189                Err(format!("`{panel}` was not detached"))
190            })
191        }
192        Change::Attach(_) => {
193            // A tab among others: the window stays (the workbench moves it).
194            let a = window.filter(|a| a.tabs.is_empty())?;
195            let req = request(&window_of_panel(&a.panel), Reason::Command).parent(WindowId::MAIN);
196            app.request_window_reparent(req);
197            let docked = app.workbench_mut().layout.window_of(&panel).is_none();
198            Some(if docked {
199                Ok(json!({ "panel": panel, "detached": false }))
200            } else {
201                Err(format!(
202                    "`{panel}` stays in its window: its move was refused"
203                ))
204            })
205        }
206        _ => {
207            let a = window?;
208            let panels: Vec<PanelId> = a.panels().cloned().collect();
209            let closed =
210                app.request_window_close(request(&window_of_panel(&a.panel), Reason::User));
211            Some(if closed {
212                Ok(json!({ "panel": panel, "detached": false, "docked": panels }))
213            } else {
214                Err(format!(
215                    "the window of `{panel}` stays: its close was refused"
216                ))
217            })
218        }
219    }
220}
221
222/// `pop.window.registry`'s part when a detached panel's window leaves it:
223/// the backend lists its viewport until the main pass after the one that
224/// last showed it.
225pub(super) fn left(app: &AppHandle, id: &str) {
226    if let Some(v) = crate::window_invariants::viewport_of(WindowKind::Panel, id) {
227        app.excuse_backend_once(v, false);
228    }
229}
230
231/// The ids of the detached panels' windows the main window shows: none
232/// while a window's content holds it.
233pub(crate) fn shown(app: &AppHandle) -> Vec<String> {
234    if app.root_has_content() {
235        return Vec::new();
236    }
237    app.workbench_mut()
238        .layout
239        .auxiliary
240        .iter()
241        .map(|a| window_of_panel(&a.panel))
242        .collect()
243}
244
245/// `pop.window.registry`'s part when a window's content moves into the main
246/// window (`into_main`), or back out: the detached panels' windows go
247/// from the screen with the shell, and come back with it. What it did.
248pub(super) fn follow_shell(
249    app: &AppHandle,
250    registry: &mut super::Registry,
251    into_main: bool,
252) -> Option<String> {
253    if into_main {
254        let before = registry.records.len();
255        registry.records.retain(|r| r.kind != WindowKind::Panel);
256        let gone = before - registry.records.len();
257        (gone > 0).then(|| format!("{REGISTRY}: {gone} detached panels' windows hidden"))
258    } else {
259        let back = shown(app);
260        for id in &back {
261            let viewport = crate::window_invariants::viewport_of(WindowKind::Panel, id);
262            registry.open(&request(id, Reason::Command), viewport);
263        }
264        (!back.is_empty()).then(|| {
265            format!(
266                "{REGISTRY}: {} detached panels' windows shown again",
267                back.len()
268            )
269        })
270    }
271}
272
273impl AppHandle {
274    /// Asks `pop.window.open` of a panel's own window, the workbench asking:
275    /// its listener detaches the panel, the registry holds the window, and
276    /// `window.opened` follows.
277    fn request_panel_window_open(&self, panel: &PanelId, reason: Reason) {
278        let id = window_of_panel(panel);
279        let did = self.ask_window_open(request(&id, reason));
280        self.publish(
281            "egui_pop",
282            None,
283            "window.opened",
284            json!({ "window": id, "kind": WindowKind::Panel, "owner": WORKBENCH_OWNER, "reason": reason, "did": did }),
285        );
286    }
287
288    /// The detached panels' windows after a workbench change made by the
289    /// workbench itself (`before`: the windows it had): each window come
290    /// is its `pop.window.open`; each gone its `pop.window.reparent` into the main
291    /// window when one of its panels is docked now, else its
292    /// `pop.window.close`. Asked in the call that changed the layout, never
293    /// from a later pass.
294    pub(crate) fn sync_panel_windows(&self, before: &[Auxiliary]) {
295        if self.root_has_content() {
296            return;
297        }
298        let shown = shown(self);
299        let held: Vec<String> = self
300            .windows_list()
301            .into_iter()
302            .filter(|w| w.kind == WindowKind::Panel)
303            .map(|w| w.id)
304            .collect();
305        for id in held.iter().filter(|id| !shown.contains(id)) {
306            let docked = before
307                .iter()
308                .find(|a| window_of_panel(&a.panel) == *id)
309                .is_some_and(|a| {
310                    let wb = self.workbench_mut();
311                    a.panels().any(|p| wb.layout.area_of(p).is_some())
312                });
313            let req = request(id, Reason::Command);
314            if docked {
315                self.request_window_reparent(req.parent(WindowId::MAIN));
316            } else {
317                self.request_window_close(req);
318            }
319        }
320        for id in shown.iter().filter(|id| !held.contains(id)) {
321            if let Some(panel) = panel_of_window(id) {
322                self.request_panel_window_open(&panel, Reason::Command);
323            }
324        }
325    }
326}
327
328/// Shows a detached panel's window for this pass: an immediate viewport
329/// (the registry holds it, `pop.window.open` asked it).
330pub(crate) fn show_window<T>(
331    ctx: &Context,
332    viewport: ViewportId,
333    builder: ViewportBuilder,
334    content: impl FnMut(&mut egui::Ui, ViewportClass) -> T,
335) -> T {
336    ctx.show_viewport_immediate(viewport, builder, content)
337}
338
339/// A detached panel's window given another place by the application on
340/// purpose (a layout applied): what changed from `from` to `to` is asked
341/// of the system once, each command logged with its reason (#5241). A
342/// place the system told is never asked back: the window's builder keeps
343/// the place it opened with.
344pub(crate) fn ask_place(
345    ctx: &Context,
346    viewport: ViewportId,
347    panel: &PanelId,
348    from: crate::window::WindowState,
349    to: crate::window::WindowState,
350) {
351    let mut commands = Vec::new();
352    if to.fullscreen != from.fullscreen {
353        commands.push(ViewportCommand::Fullscreen(to.fullscreen));
354    }
355    if to.maximized != from.maximized {
356        commands.push(ViewportCommand::Maximized(to.maximized));
357    }
358    if !to.maximized && !to.fullscreen {
359        if to.size != from.size {
360            commands.push(ViewportCommand::InnerSize(to.size));
361        }
362        if let Some(at) = to.position
363            && Some(at) != from.position
364        {
365            commands.push(ViewportCommand::OuterPosition(at));
366        }
367    }
368    for c in commands {
369        log::info!(
370            target: "egui_pop::window_size",
371            "`{panel}`'s window asked {c:?}: the application changed its place in the layout"
372        );
373        ctx.send_viewport_cmd_to(viewport, c);
374    }
375}
376
377/// The system asked a detached panel's window to close and its
378/// `pop.window.close` was refused: the system's close is cancelled.
379pub(crate) fn keep_open(vctx: &Context) {
380    vctx.send_viewport_cmd(ViewportCommand::CancelClose);
381}