Skip to main content

egui_pop_api/
windows.rs

1//! Application windows: several OS windows in one process, each almost an
2//! application of its own (ADR 0025).
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! The application opens a window with [`AppHandle::open_window`], giving
8//! a [`WindowSpec`] and the window's content: a closure drawing it each
9//! pass, which may hold `Rc` state. Each window is an egui **deferred
10//! viewport**: it repaints on its own, so an idle window sleeps while
11//! another animates. The windows are declared from the main window's pass
12//! ([`App::show`](crate::App::show)); the main window is the root, always
13//! the first window, and its content is the application's shell.
14//!
15//! - **The `Rc` shim.** egui asks a deferred window's callback to be
16//!   `Send + Sync`. eframe runs it on the main thread, so the callback
17//!   holds only the window's viewport id and finds the window and the
18//!   application in a thread-local registry; it asserts (in debug builds)
19//!   that it runs on the thread that opened the window. Off that thread
20//!   the registry is empty and the window draws nothing.
21//! - **Titles come from the content.** [`WindowUi::set_title`] names the
22//!   window after what it does ("Import — card 3"), and a change reaches
23//!   the system's title bar at once.
24//! - **Closing.** A window's close button closes it, unless its content
25//!   calls [`WindowUi::keep_open`] in the pass that sees the request
26//!   ([`WindowUi::close_requested`]). Closing the main window while other
27//!   windows are open does not quit: the close is cancelled and the window
28//!   worked in last moves into the main window (its content, title, id,
29//!   size and, where the platform tells it, position), its own window
30//!   closing. Closing the last window quits.
31//!   Raising the main window ([`WindowId::main`]) then sends that content
32//!   back to a window of its own and draws the shell again, at the main
33//!   window's own size;
34//!   [`AppHandle::quit`] closes everything, moving nothing.
35//! - **Geometry** is read from each window's own pass (egui's
36//!   `ViewportInfo` rects stay empty for deferred windows on Wayland) and
37//!   saved per window id in the persistence directory (`windows.json`),
38//!   then given back when a window of that id opens again. The position
39//!   only where the platform tells it (never on Wayland).
40//! - **Frame.** When the application draws the frame
41//!   ([`FramePlugin::own`](crate::frame::FramePlugin::own)), each window
42//!   is built without the system's decorations and draws the main
43//!   window's title bar (its title, minimize, maximize, close); so does a
44//!   window's content moved into the main window, the shell's bar having
45//!   left with the shell.
46//! - **Per window:** its keys are dispatched in its own pass, with the
47//!   `appWindow` context key naming it (`when: "appWindow == 'import'"`);
48//!   dialogs, the palette and popup menus open over the window worked in
49//!   last; a modal open in one application window blocks that window
50//!   only (the main window and its detached panels block one another,
51//!   as before).
52//! - **Present mode.** On Wayland, a FIFO present waits on the compositor
53//!   in the one UI thread and can stall every window (seen on headless
54//!   mutter). [`AppBuilder::multi_window`](crate::AppBuilder::multi_window)
55//!   makes `run_native` use wgpu's `AutoNoVsync` there (paced by winit's
56//!   frame callbacks), keeping `AutoVsync` elsewhere; [`present_mode`]
57//!   does it for an application running eframe itself.
58//!
59//! Where the backend has no windows of its own (the web, kittest), egui
60//! embeds each window in the main one as an `egui::Window`: the same
61//! content runs there.
62
63use std::cell::{Cell, RefCell};
64use std::collections::BTreeMap;
65use std::fmt;
66use std::thread::ThreadId;
67
68use egui::{Context, Ui, Vec2, ViewportBuilder, ViewportClass, ViewportCommand, ViewportId};
69use serde::{Deserialize, Serialize};
70use serde_json::json;
71
72use crate::app::{AppHandle, WeakApp};
73use crate::bus::{Reason, WindowKind, WindowRequest};
74
75/// The context key naming the application window being drawn (its
76/// [`WindowId`]; `main` in the main window until another moves into it).
77pub const CONTEXT_APP_WINDOW: &str = "appWindow";
78
79/// Where the windows' geometry is kept, under the persistence directory.
80pub const GEOMETRY_DOC: &str = "windows";
81
82/// An application window's id: stable across runs, as its geometry is
83/// saved under it.
84#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
85#[serde(transparent)]
86pub struct WindowId(String);
87
88impl WindowId {
89    /// The main window's id at start.
90    pub const MAIN: &'static str = "main";
91
92    pub fn new(id: impl Into<String>) -> Self {
93        Self(id.into())
94    }
95
96    /// The main window's id at start.
97    pub fn main() -> Self {
98        Self(Self::MAIN.to_string())
99    }
100
101    pub fn as_str(&self) -> &str {
102        &self.0
103    }
104
105    /// The viewport a window of this id gets when it is not the main one.
106    pub(crate) fn deferred_viewport(&self) -> ViewportId {
107        ViewportId::from_hash_of(("egui_pop.app_window", self.0.as_str()))
108    }
109}
110
111impl fmt::Display for WindowId {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.write_str(&self.0)
114    }
115}
116
117impl From<&str> for WindowId {
118    fn from(s: &str) -> Self {
119        Self::new(s)
120    }
121}
122
123/// What a window opens with.
124#[derive(Clone, Debug, PartialEq)]
125pub struct WindowSpec {
126    pub id: WindowId,
127    /// The first title, until the content sets its own.
128    pub title: String,
129    /// The inner size at its first opening (a saved size wins).
130    pub size: Option<Vec2>,
131    pub min_size: Option<Vec2>,
132    /// Draws the main window's bars in this window too
133    /// ([`WindowSpec::shell_bars`]).
134    pub shell_bars: bool,
135    /// Its middle is its centre area, as the main window's is
136    /// ([`WindowSpec::centre_dock`]).
137    pub centre_dock: bool,
138}
139
140impl WindowSpec {
141    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
142        Self {
143            id: WindowId::new(id),
144            title: title.into(),
145            size: None,
146            min_size: None,
147            shell_bars: false,
148            centre_dock: false,
149        }
150    }
151
152    /// The window shows the main window's bars, as VS Code's windows do:
153    /// its title bar holds the [`zones::CAPTION_START`] zone (the
154    /// application's menu button and name, its logo), and the main menu
155    /// (`app.main`) is drawn under it when the application has a menu
156    /// bar ([`AppBuilder::menu_bar`]). The menus are evaluated and run in
157    /// this window's context (`appWindow`): a command whose `when` holds
158    /// only in another window is greyed, its tooltip naming that window.
159    /// Embedded in the main window (no windows of their own), the main
160    /// window's bars are already above it: none is drawn.
161    ///
162    /// [`zones::CAPTION_START`]: crate::zones::CAPTION_START
163    /// [`AppBuilder::menu_bar`]: crate::app::AppBuilder::menu_bar
164    pub fn shell_bars(mut self, on: bool) -> Self {
165        self.shell_bars = on;
166        self
167    }
168
169    /// The window's middle is its centre area's dock, as the main
170    /// window's is: the panels docked in its centre take the whole middle,
171    /// between its sides and above its bottom, and the window draws no
172    /// content of its own (the `content` given at opening is not called).
173    /// The centre is drawn even with no panel in it, saying so, a target
174    /// for a tab dropped there. A window of panels around panels, a home
175    /// window for a set of them.
176    ///
177    /// Without it (the default), the window's content keeps the start of
178    /// the middle and its centre's panels go beside it, once one is placed
179    /// there.
180    pub fn centre_dock(mut self, on: bool) -> Self {
181        self.centre_dock = on;
182        self
183    }
184
185    pub fn size(mut self, size: impl Into<Vec2>) -> Self {
186        self.size = Some(size.into());
187        self
188    }
189
190    pub fn min_size(mut self, size: impl Into<Vec2>) -> Self {
191        self.min_size = Some(size.into());
192        self
193    }
194}
195
196/// A window's place, as saved.
197#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
198pub struct Geometry {
199    /// The inner size, in points.
200    pub size: [f32; 2],
201    /// The outer position, when the platform tells it (not on Wayland).
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub position: Option<[f32; 2]>,
204    #[serde(default)]
205    pub maximized: bool,
206    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
207    pub fullscreen: bool,
208}
209
210impl Geometry {
211    /// The geometry kept once a pass saw `seen`: the states as seen; the
212    /// normal size and position only out of maximized and full screen
213    /// (a maximized window's size is its screen's); the position only
214    /// where the platform tells it, else the one kept earlier stays (a
215    /// run on Wayland keeps the place an X11 or Windows run saw).
216    pub fn follow(kept: Option<Geometry>, seen: Geometry) -> Geometry {
217        let Some(mut g) = kept else { return seen };
218        g.maximized = seen.maximized;
219        g.fullscreen = seen.fullscreen;
220        if !seen.maximized && !seen.fullscreen {
221            g.size = seen.size;
222            if seen.position.is_some() {
223                g.position = seen.position;
224            }
225        }
226        g
227    }
228}
229
230/// An open window, as [`AppHandle::windows`] lists it.
231#[derive(Clone, Debug, PartialEq, Serialize)]
232pub struct WindowInfo {
233    pub id: WindowId,
234    pub title: String,
235    /// The main window (the root viewport).
236    pub main: bool,
237    /// The window the user worked in last.
238    pub active: bool,
239    /// Whether the system says it has the keyboard focus (unknown until
240    /// it drew once).
241    pub focused: Option<bool>,
242    /// Its geometry, as last seen.
243    pub geometry: Option<Geometry>,
244    #[serde(skip)]
245    pub viewport: ViewportId,
246}
247
248/// The window being drawn, for its content.
249pub struct WindowUi<'a> {
250    app: &'a AppHandle,
251    id: WindowId,
252    title: String,
253    class: ViewportClass,
254    close_requested: bool,
255    keep_open: bool,
256    close: bool,
257}
258
259impl fmt::Debug for WindowUi<'_> {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        f.debug_struct("WindowUi")
262            .field("id", &self.id)
263            .field("title", &self.title)
264            .finish_non_exhaustive()
265    }
266}
267
268impl<'a> WindowUi<'a> {
269    pub fn id(&self) -> &WindowId {
270        &self.id
271    }
272
273    pub fn app(&self) -> &'a AppHandle {
274        self.app
275    }
276
277    /// The window's title now.
278    pub fn title(&self) -> &str {
279        &self.title
280    }
281
282    /// Names the window after what it shows; the system's title bar
283    /// follows at once.
284    pub fn set_title(&mut self, title: impl Into<String>) {
285        self.title = title.into();
286    }
287
288    /// The user asked to close the window this pass (its close button,
289    /// the system's shortcut).
290    pub fn close_requested(&self) -> bool {
291        self.close_requested
292    }
293
294    /// Keeps the window open after a close request (to ask a question
295    /// first, then [`WindowUi::close`]).
296    pub fn keep_open(&mut self) {
297        self.keep_open = true;
298    }
299
300    /// Closes the window at the end of this pass.
301    pub fn close(&mut self) {
302        self.close = true;
303    }
304
305    /// Whether the window is drawn inside the main one (a backend without
306    /// windows of its own: the web, kittest).
307    pub fn embedded(&self) -> bool {
308        self.class == ViewportClass::EmbeddedWindow
309    }
310}
311
312/// A window's content: drawn each pass of its window.
313pub type Content = Box<dyn FnMut(&mut Ui, &mut WindowUi<'_>)>;
314
315pub(crate) struct Entry {
316    pub(crate) id: WindowId,
317    pub(crate) title: String,
318    /// The title the system was last given.
319    sent_title: Option<String>,
320    /// Out of its cell while it draws.
321    content: Option<Content>,
322    /// The builder's first geometry, kept as is: a builder changed later
323    /// would move the window.
324    first: (Option<Vec2>, Option<[f32; 2]>, bool, bool),
325    min_size: Option<Vec2>,
326    /// [`WindowSpec::shell_bars`].
327    shell_bars: bool,
328    /// [`WindowSpec::centre_dock`].
329    centre_dock: bool,
330    pub(crate) geometry: Option<Geometry>,
331    pub(crate) focused: Option<bool>,
332    /// The panel focused last in this window, its own `focusedPanel`:
333    /// the main window's focus never reaches it.
334    pub(crate) focused_panel: Option<egui_pop_model::ids::PanelId>,
335    dispatcher: Option<crate::app::WindowKeys>,
336    pub(crate) closed: bool,
337}
338
339/// The main window's slot: the application's shell, or the content of a
340/// window moved into it.
341pub(crate) struct Root {
342    pub(crate) id: WindowId,
343    /// The main window's own id (`main`): its geometry is saved under it,
344    /// whatever content moved in.
345    pub(crate) home: WindowId,
346    /// Set by the application or by the content moved in.
347    pub(crate) title: Option<String>,
348    sent_title: Option<String>,
349    content: Option<Content>,
350    pub(crate) geometry: Option<Geometry>,
351    /// The main window's own title, kept while a window's content holds
352    /// it, given back when the shell comes back.
353    home_title: Option<String>,
354    /// The minimum size of the content moved in, for its own window again.
355    min_size: Option<Vec2>,
356    /// Whether the content moved in shows the main window's bars.
357    shell_bars: bool,
358    /// Whether the window moved in has its centre dock for its middle.
359    centre_dock: bool,
360}
361
362/// The application's windows.
363pub(crate) struct Windows {
364    pub(crate) root: Root,
365    /// The windows other than the main one, in opening order.
366    pub(crate) entries: Vec<Entry>,
367    saved: Option<BTreeMap<String, Geometry>>,
368    /// The main window was asked to its front while a window's content
369    /// holds it: that content goes back to a window of its own at the
370    /// main window's next pass.
371    going_home: bool,
372    /// The application quits ([`AppHandle::quit`]): the main window's
373    /// next close quits instead of moving a window into it.
374    quitting: bool,
375    /// The places a `pop.window.reparent` leaves to `pop.window.place`, each
376    /// under its own id.
377    pub(crate) moved_places: Vec<(WindowId, Geometry)>,
378    /// What a `pop.window.reparent` says once its last listener ran.
379    pub(crate) moved_events: Vec<(&'static str, serde_json::Value)>,
380}
381
382impl Default for Windows {
383    fn default() -> Self {
384        Self {
385            root: Root {
386                id: WindowId::main(),
387                home: WindowId::main(),
388                title: None,
389                sent_title: None,
390                content: None,
391                geometry: None,
392                home_title: None,
393                min_size: None,
394                shell_bars: false,
395                centre_dock: false,
396            },
397            entries: Vec::new(),
398            saved: None,
399            going_home: false,
400            quitting: false,
401            moved_places: Vec::new(),
402            moved_events: Vec::new(),
403        }
404    }
405}
406
407impl Windows {
408    pub(crate) fn entry(&self, id: &WindowId) -> Option<&Entry> {
409        self.entries.iter().find(|e| &e.id == id && !e.closed)
410    }
411
412    fn entry_mut(&mut self, id: &WindowId) -> Option<&mut Entry> {
413        self.entries.iter_mut().find(|e| &e.id == id && !e.closed)
414    }
415
416    pub(crate) fn by_viewport(&self, viewport: ViewportId) -> Option<&Entry> {
417        self.entries
418            .iter()
419            .find(|e| !e.closed && e.id.deferred_viewport() == viewport)
420    }
421
422    pub(crate) fn viewport_of(&self, id: &WindowId) -> Option<ViewportId> {
423        if &self.root.id == id {
424            return Some(ViewportId::ROOT);
425        }
426        self.entry(id).map(|e| e.id.deferred_viewport())
427    }
428}
429
430thread_local! {
431    /// The thread the windows were opened on (the UI thread).
432    static MAIN_THREAD: Cell<Option<ThreadId>> = const { Cell::new(None) };
433    /// A deferred window's viewport to its application and window.
434    static REGISTRY: RefCell<BTreeMap<ViewportId, (WeakApp, WindowId)>> =
435        const { RefCell::new(BTreeMap::new()) };
436}
437
438thread_local! {
439    /// The window group being drawn, or the one a command runs for (its
440    /// `appWindow`), or the one an agent's call names: where a dialog, a
441    /// toast or the palette opened now belongs.
442    static CURRENT: Cell<Option<ViewportId>> = const { Cell::new(None) };
443}
444
445/// The window group being drawn or commanded now, if one is (see
446/// [`AppHandle::window_group`]).
447pub(crate) fn current_group() -> Option<ViewportId> {
448    CURRENT.with(Cell::get)
449}
450
451/// Puts back the group in force before [`enter_group`].
452pub(crate) struct GroupGuard(Option<ViewportId>);
453
454impl Drop for GroupGuard {
455    fn drop(&mut self) {
456        CURRENT.with(|c| c.set(self.0));
457    }
458}
459
460/// Makes `group` the current window group until the guard drops (`None`
461/// leaves the current one).
462pub(crate) fn enter_group(group: Option<ViewportId>) -> GroupGuard {
463    let before = current_group();
464    if group.is_some() {
465        CURRENT.with(|c| c.set(group));
466    }
467    GroupGuard(before)
468}
469
470/// A closed window's viewport leaves the shim: a pass of it finds no
471/// window (and draws its last page, `paint_guard::orphan_pass`).
472pub(crate) fn forget_viewport(viewport: ViewportId) {
473    REGISTRY.with(|r| r.borrow_mut().remove(&viewport));
474}
475
476fn on_main_thread() -> bool {
477    MAIN_THREAD.with(|m| m.get() == Some(std::thread::current().id()))
478}
479
480/// The wgpu present mode a multi-window application should use: on
481/// Wayland (`WAYLAND_DISPLAY` set), `AutoNoVsync`, as a FIFO present can
482/// stall every window behind one surface; `AutoVsync` elsewhere.
483#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
484pub fn wanted_present_mode(wayland: bool) -> eframe::wgpu::PresentMode {
485    if wayland {
486        eframe::wgpu::PresentMode::AutoNoVsync
487    } else {
488        eframe::wgpu::PresentMode::AutoVsync
489    }
490}
491
492/// Sets the options' present mode for several windows
493/// ([`wanted_present_mode`], Wayland read from the environment), unless
494/// the application chose one other than eframe's default. Returns the
495/// mode in force.
496#[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
497pub fn present_mode(options: &mut eframe::NativeOptions) -> eframe::wgpu::PresentMode {
498    let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty());
499    if options.wgpu_options.surface.present_mode == eframe::wgpu::PresentMode::AutoVsync {
500        options.wgpu_options.surface.present_mode = wanted_present_mode(wayland);
501    }
502    options.wgpu_options.surface.present_mode
503}
504
505impl AppHandle {
506    /// Opens an application window, or brings it to the front when one of
507    /// that id is open (its content is then left as it was). `content`
508    /// draws it each pass of its own; it may hold `Rc` state. The main
509    /// window's id (`main`, or a window moved into it) cannot be opened
510    /// again.
511    ///
512    /// It is the `pop.window.open` request ([`AppHandle::request_window_open`])
513    /// with the application (`app`) as its owner.
514    pub fn open_window(
515        &self,
516        spec: WindowSpec,
517        content: impl FnMut(&mut Ui, &mut WindowUi<'_>) + 'static,
518    ) -> WindowId {
519        let id = spec.id.clone();
520        self.request_window_open(spec, "app", Reason::Command, content);
521        id
522    }
523
524    /// The `pop.window.open` request of an application window its owner asks
525    /// for (ADR 0029): opened, or, open already, brought to the front;
526    /// either way its listeners run now, in their declared order (the
527    /// owner's first), and `window.opened` is said after the last one
528    /// when it opened. What they did, one line each. The owner (a plugin's
529    /// id, `app`) is who the window's closes are asked for and whose
530    /// listener on `pop.window.close` closes the state it shows.
531    ///
532    /// <div class="warning">Experimental: may change in any release
533    /// (docs/stability.md).</div>
534    pub fn request_window_open(
535        &self,
536        spec: WindowSpec,
537        owner: &str,
538        reason: Reason,
539        content: impl FnMut(&mut Ui, &mut WindowUi<'_>) + 'static,
540    ) -> Vec<String> {
541        MAIN_THREAD.with(|m| {
542            if m.get().is_none() {
543                m.set(Some(std::thread::current().id()));
544            }
545        });
546        let id = spec.id.clone();
547        let opened = {
548            let mut w = self.windows_mut();
549            if w.root.id == id || w.entry(&id).is_some() {
550                false
551            } else {
552                self.load_geometry(&mut w);
553                let saved = w.saved.as_ref().and_then(|s| s.get(id.as_str()).copied());
554                let first = match saved {
555                    Some(g) => (
556                        Some(Vec2::from(g.size)),
557                        g.position,
558                        g.maximized,
559                        g.fullscreen,
560                    ),
561                    None => (spec.size, None, false, false),
562                };
563                // A window of this id closed earlier is forgotten.
564                w.entries.retain(|e| e.id != id);
565                w.entries.push(Entry {
566                    id: id.clone(),
567                    title: spec.title.clone(),
568                    sent_title: Some(spec.title.clone()),
569                    content: Some(Box::new(content)),
570                    first,
571                    min_size: spec.min_size,
572                    shell_bars: spec.shell_bars,
573                    centre_dock: spec.centre_dock,
574                    geometry: saved,
575                    focused: None,
576                    focused_panel: None,
577                    dispatcher: Some(crate::app::WindowKeys::default()),
578                    closed: false,
579                });
580                true
581            }
582        };
583        if opened {
584            REGISTRY.with(|r| {
585                r.borrow_mut()
586                    .insert(id.deferred_viewport(), (self.downgrade(), id.clone()))
587            });
588            self.app_window_opened(id.deferred_viewport());
589        }
590        // The request runs, opened or brought to the front, and
591        // `window.opened` follows its last listener.
592        let req = WindowRequest::new(id.as_str(), WindowKind::App, owner, reason);
593        let mut did = self.ask_window_open(req);
594        if !opened && self.windows_ref().entry(&id).is_some() {
595            // Open already: brought to the front.
596            self.raise_viewport(id.deferred_viewport(), owner);
597            did.push(format!("{}: brought to the front", crate::bus::RAISE));
598        }
599        if opened {
600            self.publish(
601                "egui_pop",
602                None,
603                "window.opened",
604                json!({ "window": id, "title": spec.title, "owner": owner, "reason": reason, "did": did }),
605            );
606        }
607        self.egui().request_repaint_of(ViewportId::ROOT);
608        did
609    }
610
611    /// Closes an application window (the main one: as its close button
612    /// does, another window moving into it when one is open).
613    ///
614    /// A window's close is the `pop.window.close` request
615    /// ([`AppHandle::request_window_close`]): its owner's state closes
616    /// with it, in this call.
617    pub fn close_window(&self, id: &WindowId) {
618        let is_root = self.windows_mut().root.id == *id;
619        if is_root {
620            self.ask_main_close(Reason::Command);
621            return;
622        }
623        self.close_entry(id, Some("app"), Reason::Command);
624    }
625
626    /// The one way an application window closes, whatever asked (its
627    /// close button, its content, [`AppHandle::close_window`], the
628    /// system): the `pop.window.close` request, asked by `owner` (`None`: the
629    /// window's own owner, for what happens in the window itself).
630    /// Whether a window was open under that id and closed.
631    pub(crate) fn close_entry(&self, id: &WindowId, owner: Option<&str>, reason: Reason) -> bool {
632        if self.windows_ref().entry(id).is_none() {
633            return false;
634        }
635        let owner = match owner {
636            Some(o) => o.to_string(),
637            None => self
638                .windows_list()
639                .into_iter()
640                .find(|r| r.id == id.as_str())
641                .map(|r| r.owner)
642                .unwrap_or_else(|| "app".to_string()),
643        };
644        self.request_window_close(WindowRequest::new(
645            id.as_str(),
646            WindowKind::App,
647            owner,
648            reason,
649        ))
650    }
651
652    /// `pop.window.place`'s part: a closed window's place, kept to be written
653    /// with the others. Whether there was one.
654    pub(crate) fn keep_closing_place(&self, id: &WindowId) -> bool {
655        let geometry = self
656            .windows_ref()
657            .entries
658            .iter()
659            .rev()
660            .find(|e| &e.id == id)
661            .and_then(|e| e.geometry);
662        match geometry {
663            Some(g) => {
664                self.keep_geometry(id, g);
665                true
666            }
667            None => false,
668        }
669    }
670
671    /// Brings a window to the front and gives it the keyboard focus. The
672    /// system may refuse: on Wayland a window cannot take the focus from
673    /// another application's, and may only be marked as wanting it.
674    ///
675    /// The main window's own id ([`WindowId::main`]) while another
676    /// window's content holds it (moved in when the main window was
677    /// closed): that content goes back to a window of its own (its id,
678    /// title and saved geometry), and the main window draws the
679    /// application's shell again, at its next pass.
680    pub fn raise_window(&self, id: &WindowId) {
681        let viewport = {
682            let mut w = self.windows_mut();
683            if w.root.id == *id {
684                Some(ViewportId::ROOT)
685            } else if w.root.home == *id {
686                // Asked at once below; while the content is being drawn,
687                // at the main window's next pass.
688                w.going_home = true;
689                Some(ViewportId::ROOT)
690            } else {
691                w.entry(id).map(|e| e.id.deferred_viewport())
692            }
693        };
694        // `pop.window.activate` (`command`): the registry holds it as the
695        // active window, `pop.window.raise` brings it to the front.
696        if let Some(v) = viewport {
697            self.raise_viewport(v, "app");
698        }
699        if self.windows_ref().root.content.is_some() {
700            self.ask_home();
701        }
702    }
703
704    /// The open windows: the main one first, then the others in opening
705    /// order.
706    pub fn windows(&self) -> Vec<WindowInfo> {
707        let active = self.active_window();
708        let w = self.windows_ref();
709        let root_title = w.root.title.clone().unwrap_or_else(|| self.name());
710        let mut out = vec![WindowInfo {
711            id: w.root.id.clone(),
712            title: root_title,
713            main: true,
714            active: active == ViewportId::ROOT,
715            focused: self.egui().input(|i| {
716                i.raw
717                    .viewports
718                    .get(&ViewportId::ROOT)
719                    .and_then(|v| v.focused)
720            }),
721            geometry: w.root.geometry,
722            viewport: ViewportId::ROOT,
723        }];
724        for e in w.entries.iter().filter(|e| !e.closed) {
725            let viewport = e.id.deferred_viewport();
726            out.push(WindowInfo {
727                id: e.id.clone(),
728                title: e.title.clone(),
729                main: false,
730                active: active == viewport,
731                focused: e.focused,
732                geometry: e.geometry,
733                viewport,
734            });
735        }
736        out
737    }
738
739    /// The application window drawn in a viewport, if one is.
740    pub fn window_at(&self, viewport: ViewportId) -> Option<WindowId> {
741        let w = self.windows_ref();
742        if viewport == ViewportId::ROOT {
743            return Some(w.root.id.clone());
744        }
745        w.by_viewport(viewport).map(|e| e.id.clone())
746    }
747
748    /// The viewport an open application window is drawn in.
749    pub fn window_viewport(&self, id: &WindowId) -> Option<ViewportId> {
750        self.windows_ref().viewport_of(id)
751    }
752
753    /// The window group a viewport belongs to: an application window is
754    /// a group of its own; the main window and its detached panels are
755    /// the main window's (`ViewportId::ROOT`), and so is a window no
756    /// longer open. A group's dialogs, toasts and palette are its own,
757    /// and a modal open in it blocks it alone (`modalOpen` is per group).
758    ///
759    /// Where the windows are embedded in the main one (the web, kittest),
760    /// they are all the main window's group.
761    pub fn window_group(&self, viewport: ViewportId) -> ViewportId {
762        if is_app_window(self, viewport) && !self.egui().embed_viewports() {
763            viewport
764        } else {
765            ViewportId::ROOT
766        }
767    }
768
769    /// The window a group's dialogs, toasts and palette show in: an
770    /// application window itself; in the main window's group, the window
771    /// of it worked in last (the main window, or a detached panel's).
772    pub fn shown_in(&self, group: ViewportId) -> ViewportId {
773        let group = self.window_group(group);
774        if group != ViewportId::ROOT {
775            return group;
776        }
777        let active = self.active_window();
778        if self.window_group(active) == ViewportId::ROOT {
779            active
780        } else {
781            ViewportId::ROOT
782        }
783    }
784
785    /// The window group what opens now belongs to: the window being drawn,
786    /// the one the running command was asked in (its `appWindow`), the
787    /// one an agent's call names; else the active window's.
788    pub fn current_window_group(&self) -> ViewportId {
789        match current_group() {
790            Some(g) => self.window_group(g),
791            None => self.window_group(self.active_window()),
792        }
793    }
794
795    /// The group asked for now ([`AppHandle::current_window_group`]), or,
796    /// when none is, the one of the window being drawn.
797    pub(crate) fn current_window_group_or(&self, drawn: ViewportId) -> ViewportId {
798        self.window_group(current_group().unwrap_or(drawn))
799    }
800
801    /// The application window of a group (see [`AppHandle::window_group`]).
802    pub fn window_of_group(&self, group: ViewportId) -> WindowId {
803        self.window_at(self.window_group(group))
804            .unwrap_or_else(|| self.windows_ref().root.id.clone())
805    }
806
807    /// Tells the overlays which windows are groups of their own.
808    pub(crate) fn sync_separate_windows(&self) {
809        let embedded = self.egui().embed_viewports();
810        let open: Vec<ViewportId> = self
811            .windows_ref()
812            .entries
813            .iter()
814            .filter(|e| !e.closed && !embedded)
815            .map(|e| e.id.deferred_viewport())
816            .collect();
817        egui_pop_core::overlay::set_separate_windows(&self.egui(), open);
818    }
819
820    /// The ids of the application windows shown now, the main window's
821    /// (`main`) first while it shows the shell: where a panel may open.
822    pub(crate) fn shown_window_ids(&self) -> Vec<String> {
823        let w = self.windows_ref();
824        let mut ids = Vec::new();
825        if w.root.id == w.root.home {
826            ids.push(WindowId::MAIN.to_string());
827        } else {
828            // Another window's content holds the main window.
829            ids.push(w.root.id.as_str().to_string());
830        }
831        ids.extend(
832            w.entries
833                .iter()
834                .filter(|e| !e.closed)
835                .map(|e| e.id.as_str().to_string()),
836        );
837        ids
838    }
839
840    /// The application window the user worked in last (a detached
841    /// panel's window counts as the main window's).
842    pub fn active_app_window(&self) -> WindowId {
843        let active = self.active_window();
844        self.window_at(active)
845            .unwrap_or_else(|| self.windows_ref().root.id.clone())
846    }
847
848    /// Sets a window's title (the content of a window usually sets its
849    /// own, through [`WindowUi::set_title`]). The main window's title is
850    /// the application's name until set.
851    pub fn set_window_title(&self, id: &WindowId, title: impl Into<String>) {
852        let title = title.into();
853        let mut w = self.windows_mut();
854        if w.root.id == *id {
855            w.root.title = Some(title);
856            drop(w);
857            self.egui().request_repaint_of(ViewportId::ROOT);
858        } else if let Some(e) = w.entry_mut(id) {
859            e.title = title;
860            let v = e.id.deferred_viewport();
861            drop(w);
862            self.egui().request_repaint_of(v);
863        }
864    }
865
866    /// A window's geometry kept from an earlier run or seen in this one.
867    pub fn window_geometry(&self, id: &WindowId) -> Option<Geometry> {
868        let mut w = self.windows_mut();
869        if w.root.home == *id {
870            return w.root.geometry;
871        }
872        if let Some(e) = w.entry(id) {
873            return e.geometry;
874        }
875        self.load_geometry(&mut w);
876        w.saved.as_ref().and_then(|s| s.get(id.as_str()).copied())
877    }
878
879    pub(crate) fn windows_ref(&self) -> std::cell::Ref<'_, Windows> {
880        self.0.windows.borrow()
881    }
882
883    pub(crate) fn windows_mut(&self) -> std::cell::RefMut<'_, Windows> {
884        self.0.windows.borrow_mut()
885    }
886
887    fn load_geometry(&self, w: &mut Windows) {
888        if w.saved.is_some() {
889            return;
890        }
891        let saved = self
892            .persist()
893            .and_then(|p| std::fs::read_to_string(p.path(GEOMETRY_DOC)).ok())
894            .and_then(|t| serde_json::from_str(&t).ok())
895            .unwrap_or_default();
896        w.saved = Some(saved);
897    }
898
899    /// Notes a window's geometry, saved a short while later.
900    fn keep_geometry(&self, id: &WindowId, g: Geometry) {
901        let text = {
902            let mut w = self.windows_mut();
903            self.load_geometry(&mut w);
904            let saved = w.saved.get_or_insert_with(BTreeMap::new);
905            if saved.get(id.as_str()) == Some(&g) {
906                return;
907            }
908            saved.insert(id.to_string(), g);
909            serde_json::to_string_pretty(saved).unwrap_or_default()
910        };
911        self.save_later(GEOMETRY_DOC, text);
912    }
913
914    /// The window a close of the main window moves into it: the one
915    /// worked in last, when one is open.
916    pub(crate) fn window_to_move_in(&self) -> Option<WindowId> {
917        self.app_windows_by_recency()
918            .into_iter()
919            .map(|id| WindowId::new(&id))
920            .find(|id| self.windows_ref().entry(id).is_some())
921    }
922
923    /// `pop.window.registry`'s part of a `pop.window.reparent` into the main
924    /// window: `id`'s content is drawn by the main window from its next
925    /// pass, which takes its geometry; its own window is no longer
926    /// declared. The places each keeps are left to `pop.window.place`, what is
927    /// said to the request. Whether it moved.
928    pub(crate) fn move_into_root(&self, id: &WindowId) -> bool {
929        let moved = {
930            let mut w = self.windows_mut();
931            let Some(at) = w.entries.iter().position(|e| &e.id == id && !e.closed) else {
932                return false;
933            };
934            let e = w.entries.remove(at);
935            // Each keeps its own geometry: the main window's under its own
936            // id, the content moving in under its id (the main window's
937            // size is not the content's).
938            let kept = [
939                (w.root.home.clone(), w.root.geometry),
940                (e.id.clone(), e.geometry),
941            ];
942            // The main window takes the moved window's geometry: as last
943            // seen, else as it opened.
944            let geometry = e.geometry.or_else(|| {
945                let (size, position, maximized, fullscreen) = e.first;
946                size.map(|s| Geometry {
947                    size: [s.x, s.y],
948                    position,
949                    maximized,
950                    fullscreen,
951                })
952            });
953            let left = std::mem::replace(&mut w.root.id, e.id.clone());
954            let shell_title = w.root.title.replace(e.title.clone());
955            if left == w.root.home {
956                // The shell leaves: its title comes back with it.
957                w.root.home_title = shell_title;
958            }
959            w.root.min_size = e.min_size;
960            w.root.shell_bars = e.shell_bars;
961            w.root.centre_dock = e.centre_dock;
962            w.root.sent_title = None;
963            w.root.content = e.content;
964            (left, e.id, kept, geometry)
965        };
966        let (left, id, kept, geometry) = moved;
967        if let Some(g) = geometry {
968            self.apply_root_geometry(g);
969        }
970        REGISTRY.with(|r| r.borrow_mut().remove(&id.deferred_viewport()));
971        self.sync_separate_windows();
972        {
973            let mut w = self.windows_mut();
974            w.moved_places
975                .extend(kept.into_iter().filter_map(|(at, g)| g.map(|g| (at, g))));
976            w.moved_events
977                .push(("window.closed", json!({ "window": left })));
978            w.moved_events
979                .push(("window.moved", json!({ "window": id, "to": "main" })));
980        }
981        self.egui().request_repaint_of(ViewportId::ROOT);
982        true
983    }
984
985    /// `pop.window.place`'s part of a `pop.window.reparent`: the places the move
986    /// left, each kept under its own id. How many.
987    pub(crate) fn keep_moved_places(&self) -> usize {
988        let places = std::mem::take(&mut self.windows_mut().moved_places);
989        let n = places.len();
990        for (id, g) in places {
991            self.keep_geometry(&id, g);
992        }
993        n
994    }
995
996    /// Gives the main window a geometry, through viewport commands: the
997    /// size always, the position where the platform tells positions (a
998    /// geometry seen on Wayland has none), maximized or not.
999    fn apply_root_geometry(&self, g: Geometry) {
1000        let ctx = self.egui();
1001        let root = ViewportId::ROOT;
1002        log::info!(
1003            target: "egui_pop::window_size",
1004            "the main window asked {g:?}: a window's content moved into it"
1005        );
1006        if g.fullscreen {
1007            ctx.send_viewport_cmd_to(root, ViewportCommand::Fullscreen(true));
1008            return;
1009        }
1010        ctx.send_viewport_cmd_to(root, ViewportCommand::Fullscreen(false));
1011        if g.maximized {
1012            ctx.send_viewport_cmd_to(root, ViewportCommand::Maximized(true));
1013            return;
1014        }
1015        ctx.send_viewport_cmd_to(root, ViewportCommand::Maximized(false));
1016        ctx.send_viewport_cmd_to(root, ViewportCommand::InnerSize(Vec2::from(g.size)));
1017        if let Some([x, y]) = g.position {
1018            ctx.send_viewport_cmd_to(root, ViewportCommand::OuterPosition(egui::pos2(x, y)));
1019        }
1020    }
1021
1022    /// The main window's own id, whatever content it shows now: `main`.
1023    pub fn main_window(&self) -> WindowId {
1024        self.windows_ref().root.home.clone()
1025    }
1026
1027    /// Quits the application: the main window closes, and the other
1028    /// windows with it, none moving into the main window as closing it
1029    /// does otherwise. It is the `pop.window.close` request of the main window
1030    /// with the reason `quit`: each other window is closed by its own
1031    /// `pop.window.close` (`quit`), its owner's state with it. A close vetoed
1032    /// (a before-hook on the `window.close` step: unsaved work) leaves the
1033    /// application as it was.
1034    pub fn quit(&self) {
1035        self.windows_mut().quitting = true;
1036        if !self.ask_main_close(Reason::Quit) {
1037            self.windows_mut().quitting = false;
1038        }
1039        self.egui().request_repaint_of(ViewportId::ROOT);
1040    }
1041
1042    /// Whether [`AppHandle::quit`] was asked and its close not yet seen.
1043    pub fn quitting(&self) -> bool {
1044        self.windows_ref().quitting
1045    }
1046
1047    /// The main window's close is seen: whether it quits
1048    /// ([`AppHandle::quit`] asked it), the flag being spent.
1049    pub(crate) fn take_quitting(&self) -> bool {
1050        std::mem::take(&mut self.windows_mut().quitting)
1051    }
1052
1053    /// The main window was asked to its front while a window's content
1054    /// holds it ([`AppHandle::raise_window`]): the window whose content it
1055    /// is, the flag spent.
1056    pub(crate) fn take_going_home(&self) -> Option<WindowId> {
1057        let mut w = self.windows_mut();
1058        let going = std::mem::take(&mut w.going_home);
1059        (going && w.root.id != w.root.home && w.root.content.is_some()).then(|| w.root.id.clone())
1060    }
1061
1062    /// `pop.window.registry`'s part of a `pop.window.reparent` out of the main
1063    /// window, the inverse of [`AppHandle::move_into_root`]: the content
1064    /// it holds goes back to a window of its own, and the main window
1065    /// draws the shell again. Whether one went back.
1066    pub(crate) fn move_out_of_root(&self) -> bool {
1067        let back = {
1068            let mut w = self.windows_mut();
1069            w.going_home = false;
1070            if w.root.id == w.root.home {
1071                return false;
1072            }
1073            let Some(content) = w.root.content.take() else {
1074                return false;
1075            };
1076            self.load_geometry(&mut w);
1077            let home = w.root.home.clone();
1078            let id = std::mem::replace(&mut w.root.id, home.clone());
1079            let title = w.root.title.take().unwrap_or_default();
1080            let home_title = w.root.home_title.take();
1081            w.root.title = home_title.or_else(|| Some(self.name()).filter(|n| !n.is_empty()));
1082            w.root.sent_title = None;
1083            let min_size = w.root.min_size.take();
1084            let shell_bars = std::mem::take(&mut w.root.shell_bars);
1085            let centre_dock = std::mem::take(&mut w.root.centre_dock);
1086            // The content's geometry was saved under its id when it moved
1087            // in: its window opens again with it. The main window's own was
1088            // saved under its id then: it takes it back.
1089            let saved = w.saved.as_ref().and_then(|s| s.get(id.as_str()).copied());
1090            let home_geometry = w.saved.as_ref().and_then(|s| s.get(home.as_str()).copied());
1091            let first = match saved {
1092                Some(g) => (
1093                    Some(Vec2::from(g.size)),
1094                    g.position,
1095                    g.maximized,
1096                    g.fullscreen,
1097                ),
1098                None => (None, None, false, false),
1099            };
1100            w.entries.retain(|e| e.id != id);
1101            w.entries.push(Entry {
1102                id: id.clone(),
1103                title: title.clone(),
1104                sent_title: Some(title.clone()),
1105                content: Some(content),
1106                first,
1107                min_size,
1108                shell_bars,
1109                centre_dock,
1110                geometry: saved,
1111                focused: None,
1112                focused_panel: None,
1113                dispatcher: Some(crate::app::WindowKeys::default()),
1114                closed: false,
1115            });
1116            (home, id, title, home_geometry)
1117        };
1118        let (home, id, title, home_geometry) = back;
1119        if let Some(g) = home_geometry {
1120            self.apply_root_geometry(g);
1121        }
1122        REGISTRY.with(|r| {
1123            r.borrow_mut()
1124                .insert(id.deferred_viewport(), (self.downgrade(), id.clone()))
1125        });
1126        self.sync_separate_windows();
1127        {
1128            let mut w = self.windows_mut();
1129            w.moved_events.push((
1130                "window.moved",
1131                json!({ "window": id, "from": home, "to": id, "title": title }),
1132            ));
1133            w.moved_events
1134                .push(("window.opened", json!({ "window": home })));
1135        }
1136        self.egui().request_repaint_of(ViewportId::ROOT);
1137        true
1138    }
1139
1140    /// Whether window `id`'s middle is its centre area's dock
1141    /// ([`WindowSpec::centre_dock`]), in its own window or moved into the
1142    /// main one.
1143    pub(crate) fn window_centre_dock(&self, id: &WindowId) -> bool {
1144        let w = self.windows_ref();
1145        if w.root.id == *id {
1146            return w.root.centre_dock;
1147        }
1148        w.entry(id).is_some_and(|e| e.centre_dock)
1149    }
1150
1151    /// Whether the main window shows a window's content moved into it
1152    /// rather than the application's shell.
1153    pub(crate) fn root_has_content(&self) -> bool {
1154        self.windows_ref().root.content.is_some()
1155    }
1156
1157    /// The main window's part of the pass: its title, its geometry, and
1158    /// the content moved into it, if any (drawn in `ui`; `false` when the
1159    /// shell is to be drawn).
1160    pub(crate) fn root_pass(&self, ui: &mut Ui) -> bool {
1161        let ctx = ui.ctx().clone();
1162        if let Some(seen) = read_geometry(&ctx) {
1163            // While a window's content holds it, the geometry is that
1164            // window's: the main window's own stays as it was.
1165            let (id, g) = {
1166                let mut w = self.windows_mut();
1167                let g = if w.root.id == w.root.home {
1168                    let g = Geometry::follow(w.root.geometry, seen);
1169                    w.root.geometry = Some(g);
1170                    g
1171                } else {
1172                    seen
1173                };
1174                (w.root.id.clone(), g)
1175            };
1176            if ctx.input(|i| i.viewport().close_requested()) {
1177                self.keep_geometry(&id, g);
1178            }
1179        }
1180        let content = self.windows_mut().root.content.take();
1181        let drawn = match content {
1182            Some(mut content) => {
1183                let (id, title, bars) = {
1184                    let w = self.windows_ref();
1185                    (
1186                        w.root.id.clone(),
1187                        w.root.title.clone().unwrap_or_default(),
1188                        w.root.shell_bars,
1189                    )
1190                };
1191                let mut wui = WindowUi {
1192                    app: self,
1193                    id,
1194                    title,
1195                    class: ViewportClass::Root,
1196                    close_requested: false,
1197                    keep_open: false,
1198                    close: false,
1199                };
1200                // The shell's title bar left with the shell: the content
1201                // gets the frame an application window has.
1202                let title = wui.title.clone();
1203                let drawn_id = wui.id.clone();
1204                framed(ui, self, &title, bars, |ui| {
1205                    crate::workbench::window_areas::show(self, ui, &drawn_id, |ui| {
1206                        content(ui, &mut wui);
1207                    });
1208                });
1209                let mut w = self.windows_mut();
1210                // A request asked while it drew (the main window closed,
1211                // another window moved in) may have changed what the main
1212                // window holds: this content then went.
1213                if w.root.id == drawn_id {
1214                    if w.root.content.is_none() {
1215                        w.root.content = Some(content);
1216                    }
1217                    w.root.title = Some(wui.title);
1218                }
1219                drop(w);
1220                if wui.close {
1221                    self.ask_main_close(Reason::User);
1222                }
1223                true
1224            }
1225            None => false,
1226        };
1227        let title = {
1228            let w = self.windows_ref();
1229            w.root
1230                .title
1231                .clone()
1232                .filter(|t| w.root.sent_title.as_ref() != Some(t))
1233        };
1234        if let Some(t) = title {
1235            ctx.send_viewport_cmd(ViewportCommand::Title(t.clone()));
1236            self.windows_mut().root.sent_title = Some(t);
1237        }
1238        drawn
1239    }
1240
1241    /// An application window moved to `at` by `pop.window.place` (its screen
1242    /// gone): its builder asks that place from now on, so the next pass
1243    /// does not move it back.
1244    pub(crate) fn app_window_moved(&self, viewport: ViewportId, at: egui::Pos2) {
1245        let mut w = self.windows_mut();
1246        if let Some(e) = w
1247            .entries
1248            .iter_mut()
1249            .find(|e| e.id.deferred_viewport() == viewport)
1250        {
1251            e.first.1 = Some([at.x, at.y]);
1252        }
1253    }
1254
1255    /// Declares the open windows, from the main window's pass: a window
1256    /// not declared in a pass of its parent is closed by egui.
1257    pub(crate) fn declare_windows(&self, ctx: &Context) {
1258        if ctx.viewport_id() != ViewportId::ROOT {
1259            return;
1260        }
1261        let app_id = self.app_id();
1262        // The application draws each window's frame as the main window's
1263        // (`frame::window_frame`), or the system draws them all.
1264        let own = crate::frame::own_frame(self);
1265        let rounded = egui_pop_core::frame::rounding(ctx);
1266        let screens = crate::window::screens();
1267        let builders: Vec<(ViewportId, ViewportBuilder)> = {
1268            let mut w = self.windows_mut();
1269            // Not declared from this pass: the backend lets their system
1270            // window go, and their last page with it.
1271            for e in w.entries.iter().filter(|e| e.closed) {
1272                crate::paint_guard::closed_for_good(e.id.deferred_viewport());
1273            }
1274            w.entries.retain(|e| !e.closed);
1275            w.entries
1276                .iter()
1277                .map(|e| {
1278                    let mut b = ViewportBuilder::default()
1279                        .with_title(e.title.clone())
1280                        .with_decorations(!own);
1281                    // Transparent for its rounded corners.
1282                    if own && rounded {
1283                        b = b.with_transparent(true);
1284                    }
1285                    if !app_id.is_empty() {
1286                        b = b.with_app_id(app_id.clone());
1287                    }
1288                    let (size, pos, maximized, fullscreen) = e.first;
1289                    // A kept place off every screen comes back onto one.
1290                    let place = size.map(|s| {
1291                        crate::window::WindowState {
1292                            position: pos.map(egui::Pos2::from),
1293                            size: s,
1294                            maximized,
1295                            fullscreen,
1296                        }
1297                        .repair(&screens)
1298                    });
1299                    if let Some(p) = place {
1300                        b = b.with_inner_size(p.size);
1301                        if let Some(at) = p.position {
1302                            b = b.with_position(at);
1303                        }
1304                    }
1305                    if maximized {
1306                        b = b.with_maximized(true);
1307                    }
1308                    if fullscreen {
1309                        b = b.with_fullscreen(true);
1310                    }
1311                    if let Some(m) = e.min_size {
1312                        b = b.with_min_inner_size(m);
1313                    }
1314                    (e.id.deferred_viewport(), b)
1315                })
1316                .collect()
1317        };
1318        self.sync_separate_windows();
1319        for (viewport, builder) in builders {
1320            ctx.show_viewport_deferred(viewport, builder, move |ui, class| {
1321                window_pass(viewport, ui, class)
1322            });
1323        }
1324        // A closed window the backend still lists past the delay: shown
1325        // hidden for one pass (egui's backend hides it), then dropped.
1326        for viewport in self.watch_closed_windows(ctx) {
1327            ctx.show_viewport_deferred(
1328                viewport,
1329                ViewportBuilder::default().with_visible(false),
1330                move |ui, _| {
1331                    crate::paint_guard::orphan_pass(ui, viewport, "it is closed");
1332                },
1333            );
1334        }
1335    }
1336
1337    /// A deferred window's keys, dispatched in its own pass with its
1338    /// dispatcher; the commands run before the main window's next pass,
1339    /// in this window's context: its own focused panel, its `appWindow`.
1340    fn dispatch_window_keys(&self, ctx: &Context, id: &WindowId) {
1341        self.follow_window_focus(ctx, id);
1342        let Some(mut keys) = self
1343            .windows_mut()
1344            .entry_mut(id)
1345            .and_then(|e| e.dispatcher.take())
1346        else {
1347            return;
1348        };
1349        let keymap = self.shared_keymap();
1350        let mut cx = self.when_context();
1351        cx.set(CONTEXT_APP_WINDOW, id.as_str());
1352        let dispatched = if self.capturing_keys() {
1353            Vec::new()
1354        } else {
1355            keys.dispatcher(self).process(ctx, &keymap, &cx)
1356        };
1357        if let Some(e) = self.windows_mut().entry_mut(id) {
1358            e.dispatcher = Some(keys);
1359        }
1360        for d in dispatched {
1361            // F6 goes through this window's regions, which only its own
1362            // pass knows: run here, not before the main window's pass.
1363            let back = if d.command == crate::workbench::CMD_NEXT_REGION {
1364                Some(false)
1365            } else if d.command == crate::workbench::CMD_PREVIOUS_REGION {
1366                Some(true)
1367            } else {
1368                None
1369            };
1370            if let Some(back) = back {
1371                let user = egui_pop_model::commands::Origin::User;
1372                if let Err(e) = crate::workbench::go_to_region(self, &user, back) {
1373                    log::debug!("F6 in window `{id}`: {e}");
1374                }
1375                continue;
1376            }
1377            self.run_in_context(d.command, serde_json::Value::Null, cx.clone());
1378        }
1379    }
1380}
1381
1382impl AppHandle {
1383    /// Keeps an application window's own focused panel up with where its
1384    /// focus went: the last panel the pointer pressed in or a widget of
1385    /// which took the focus, kept while the focus goes elsewhere.
1386    fn follow_window_focus(&self, ctx: &Context, id: &WindowId) {
1387        let Some(moved) = egui_pop_core::focus::take_moved(ctx) else {
1388            return;
1389        };
1390        let chain = match moved {
1391            egui_pop_core::focus::Moved::Pressed(c) | egui_pop_core::focus::Moved::Focused(c) => c,
1392            egui_pop_core::focus::Moved::Left => return,
1393        };
1394        let Some(panel) = self.workbench_mut().panel_of(&chain) else {
1395            return;
1396        };
1397        if let Some(e) = self.windows_mut().entry_mut(id) {
1398            e.focused_panel = Some(panel);
1399        }
1400    }
1401
1402    /// An application window's own focused panel (`None` for the main
1403    /// window, whose focus is the workbench's).
1404    pub(crate) fn window_focused_panel(
1405        &self,
1406        viewport: ViewportId,
1407    ) -> Option<egui_pop_model::ids::PanelId> {
1408        self.windows_ref()
1409            .by_viewport(viewport)
1410            .and_then(|e| e.focused_panel.clone())
1411    }
1412}
1413
1414/// An application window's frame around its content, with the main
1415/// window's bars when it asks for them ([`WindowSpec::shell_bars`]).
1416fn framed(ui: &mut Ui, app: &AppHandle, title: &str, bars: bool, content: impl FnOnce(&mut Ui)) {
1417    crate::frame::window_frame(ui, app, title, bars, |ui| {
1418        if bars {
1419            menu_bar(ui, app);
1420        }
1421        content(ui);
1422    });
1423}
1424
1425/// The main menu (`app.main`) at the top of an application window, in
1426/// its context, when the application has a menu bar.
1427fn menu_bar(ui: &mut Ui, app: &AppHandle) {
1428    if !app.menu_bar() {
1429        return;
1430    }
1431    let id = egui::Id::unique(("egui_pop.window_menu", ui.ctx().viewport_id()));
1432    egui::Panel::top(id).show(ui, |ui| {
1433        egui_pop_core::focus::scope(ui, "topBar", &[], |ui| {
1434            egui::MenuBar::new().ui(ui, |ui| {
1435                crate::menus::bar(ui, app, &crate::app::MENU_MAIN);
1436            });
1437        });
1438    });
1439}
1440
1441/// Reads a window's geometry from its own pass.
1442fn read_geometry(ctx: &Context) -> Option<Geometry> {
1443    ctx.input(|i| {
1444        let v = i.viewport();
1445        let size = v
1446            .inner_rect
1447            .map(|r| r.size())
1448            .unwrap_or_else(|| i.viewport_rect().size());
1449        if size.x <= 0.0 || size.y <= 0.0 {
1450            return None;
1451        }
1452        Some(Geometry {
1453            size: [size.x, size.y],
1454            position: v.outer_rect.map(|r| [r.min.x, r.min.y]),
1455            maximized: v.maximized.unwrap_or(false),
1456            fullscreen: v.fullscreen.unwrap_or(false),
1457        })
1458    })
1459}
1460
1461/// A deferred window's pass: the shim from egui's `Send + Sync` callback
1462/// to the application's `Rc` state, through the thread-local registry.
1463fn window_pass(viewport: ViewportId, ui: &mut Ui, class: ViewportClass) {
1464    let on_main = on_main_thread();
1465    debug_assert!(on_main, "an application window drawn off the UI thread");
1466    if !on_main {
1467        log::error!(target: "egui_pop", "an application window drawn off the UI thread");
1468        return;
1469    }
1470    let Some((weak, id)) = REGISTRY.with(|r| r.borrow().get(&viewport).cloned()) else {
1471        crate::paint_guard::orphan_pass(ui, viewport, "no application window has it");
1472        return;
1473    };
1474    let Ok(app) = weak.get() else {
1475        crate::paint_guard::orphan_pass(ui, viewport, "its application is gone");
1476        return;
1477    };
1478    // What opens while it draws (a dialog, a toast, a command asked from
1479    // its content) belongs to it.
1480    let _group = enter_group(Some(viewport));
1481    let ctx = ui.ctx().clone();
1482    let own_window = class != ViewportClass::EmbeddedWindow;
1483    let (content, title, bars) = {
1484        let mut w = app.windows_mut();
1485        let Some(e) = w.entry_mut(&id) else {
1486            drop(w);
1487            crate::paint_guard::orphan_pass(ui, viewport, "its window is closed");
1488            return;
1489        };
1490        let Some(content) = e.content.take() else {
1491            return;
1492        };
1493        if own_window {
1494            e.focused = ctx.input(|i| i.viewport().focused);
1495            if let Some(g) = read_geometry(&ctx) {
1496                e.geometry = Some(Geometry::follow(e.geometry, g));
1497            }
1498        }
1499        (content, e.title.clone(), e.shell_bars)
1500    };
1501    let mut content = content;
1502    if own_window {
1503        app.note_window(&ctx);
1504        crate::bus::files::begin_pass(&ctx, id.as_str());
1505        crate::bus::drag::begin_pass(&ctx, id.as_str());
1506        app.block_window(&ctx, &|v| v == viewport);
1507        egui_pop_core::overlay::begin_pass(&ctx);
1508        app.dispatch_window_keys(&ctx, &id);
1509        app.raise_in_pass(&ctx);
1510    }
1511    if let Some((from, to)) = egui_pop_core::scale::changed(&ctx) {
1512        app.publish(
1513            "egui_pop",
1514            None,
1515            "scale.changed",
1516            json!({ "viewport": id, "from": from, "to": to }),
1517        );
1518    }
1519    let close_requested = own_window && ctx.input(|i| i.viewport().close_requested());
1520    let mut wui = WindowUi {
1521        app: &app,
1522        id: id.clone(),
1523        title,
1524        class,
1525        close_requested,
1526        keep_open: false,
1527        close: false,
1528    };
1529    let mut painted = false;
1530    let mut fallback = false;
1531    if own_window {
1532        let title = wui.title.clone();
1533        framed(ui, &app, &title, bars, |ui| {
1534            // What the content paints, under the title bar.
1535            let mark = crate::paint_guard::mark(ui);
1536            crate::workbench::window_areas::show(&app, ui, &id, |ui| content(ui, &mut wui));
1537            painted = crate::paint_guard::painted_since(ui.ctx(), &mark);
1538        });
1539    } else {
1540        // Embedded in the main window: egui's window frame is its frame.
1541        crate::workbench::window_areas::show(&app, ui, &id, |ui| content(ui, &mut wui));
1542    }
1543    if own_window {
1544        app.show_zone(ui, &crate::zones::WINDOW_OVERLAYS);
1545        // Files dropped on this window: its `pop.files.drop`.
1546        crate::bus::files::end_pass(&app, ui);
1547        // A drag's target under the pointer kept; what it did said.
1548        crate::bus::drag::end_pass(&app, &ctx);
1549        // A menu opened as a popup in this window (`menus::popup_at`).
1550        crate::menus::draw_popup(&ctx, &app);
1551        // A window whose content paints nothing: said, and a page that
1552        // closes it.
1553        if app.watch_app_window(&ctx, &id, painted) && app.app_window_fallback(&ctx) {
1554            wui.close = true;
1555            fallback = true;
1556        }
1557    }
1558    let closing = wui.close || (close_requested && !wui.keep_open);
1559    let send_title = {
1560        let mut w = app.windows_mut();
1561        let Some(e) = w.entry_mut(&id) else { return };
1562        e.content = Some(content);
1563        e.title = wui.title;
1564        let send = (e.sent_title.as_ref() != Some(&e.title)).then(|| e.title.clone());
1565        if send.is_some() {
1566            e.sent_title = send.clone();
1567        }
1568        send
1569    };
1570    if let Some(t) = send_title
1571        && own_window
1572        && !closing
1573    {
1574        ctx.send_viewport_cmd(ViewportCommand::Title(t));
1575    }
1576    if closing {
1577        let reason = if fallback {
1578            Reason::Guard
1579        } else {
1580            Reason::User
1581        };
1582        app.close_entry(&id, None, reason);
1583        // The page of this pass is the one its passes until the backend
1584        // drops it draw again (never an empty frame).
1585        crate::paint_guard::keep_last_page(&ctx, viewport);
1586    }
1587    if app.has_requests() {
1588        ctx.request_repaint_of(ViewportId::ROOT);
1589    }
1590}
1591
1592/// The application's windows, for a test or a host: whether a viewport
1593/// is one of an application's windows, so that a modal open there blocks
1594/// it alone.
1595pub(crate) fn is_app_window(app: &AppHandle, viewport: ViewportId) -> bool {
1596    viewport != ViewportId::ROOT && app.windows_ref().by_viewport(viewport).is_some()
1597}
1598
1599/// What the `app_windows` part of the `windows` collector shows.
1600pub(crate) fn describe(app: &AppHandle) -> serde_json::Value {
1601    json!(app.windows())
1602}
1603
1604/// Brings a window to the front: `{ "window": id }`, or, without one,
1605/// the next open window after the active one (cycling).
1606pub const CMD_SWITCH: egui_pop_model::ids::CommandId =
1607    egui_pop_model::ids::CommandId::from_static("window.switch");
1608/// Closes a window: `{ "window": id }`, or the active one.
1609pub const CMD_CLOSE: egui_pop_model::ids::CommandId =
1610    egui_pop_model::ids::CommandId::from_static("window.close");
1611/// A quick pick of the open windows by title, as the palette lists
1612/// commands: the one chosen comes to the front ([`CMD_SWITCH`]).
1613pub const CMD_PICK: egui_pop_model::ids::CommandId =
1614    egui_pop_model::ids::CommandId::from_static("window.pick");
1615/// The Window menu.
1616pub const MENU_WINDOW: egui_pop_model::ids::MenuId =
1617    egui_pop_model::ids::MenuId::from_static("app.menu.window");
1618/// The list of open windows, by title, in the Window menu.
1619pub const LIST_WINDOWS: &str = "app.windows";
1620
1621/// The window menu and its commands, for an application opening windows
1622/// of its own: Window lists the open windows by title (the active one
1623/// ticked) and switches to one; `window.switch` and `window.close` are
1624/// offered to agents and the palette; `window.pick` (Switch to Window…)
1625/// lists the open windows in a choice with a filter field, opened in the
1626/// window it is asked in (with the dialogs plugin).
1627#[derive(Debug, Default)]
1628pub struct WindowsPlugin;
1629
1630fn window_arg(app: &AppHandle, args: &serde_json::Value) -> Result<Option<WindowId>, String> {
1631    match args.get("window").and_then(|w| w.as_str()) {
1632        None => Ok(None),
1633        Some(w) => {
1634            let id = WindowId::new(w);
1635            // The main window's own id stays valid while another window's
1636            // content holds it: raising it brings the shell back.
1637            if app.window_viewport(&id).is_none() && id != app.main_window() {
1638                return Err(format!("no open window `{w}`"));
1639            }
1640            Ok(Some(id))
1641        }
1642    }
1643}
1644
1645impl crate::Plugin for WindowsPlugin {
1646    fn id(&self) -> egui_pop_model::ids::PluginId {
1647        egui_pop_model::ids::PluginId::from_static("egui_pop.windows")
1648    }
1649
1650    fn title(&self) -> String {
1651        "Windows".into()
1652    }
1653
1654    fn connect(&mut self, ctx: &mut crate::Ctx<'_>) -> Result<(), crate::PluginError> {
1655        use egui_pop_model::commands::CommandSpec;
1656        use egui_pop_model::menus::MenuItem;
1657        ctx.command(
1658            CommandSpec::new(CMD_SWITCH, "Switch window", "Window")
1659                .description("Brings a window to the front: the one named, or the next one.")
1660                .args(json!({ "window": "main" })),
1661            |call| {
1662                let app = call.app;
1663                let id = match window_arg(app, call.args)? {
1664                    Some(id) => id,
1665                    None => {
1666                        let open = app.windows();
1667                        let at = open.iter().position(|w| w.active).unwrap_or(0);
1668                        open[(at + 1) % open.len()].id.clone()
1669                    }
1670                };
1671                app.raise_window(&id);
1672                Ok(json!({ "window": id }))
1673            },
1674        )?
1675        .command(
1676            CommandSpec::new(CMD_CLOSE, "Close window", "Window")
1677                .description("Closes a window: the one named, or the active one.")
1678                .args(json!({ "window": "main" })),
1679            |call| {
1680                let app = call.app;
1681                let id = window_arg(app, call.args)?.unwrap_or_else(|| app.active_app_window());
1682                app.close_window(&id);
1683                Ok(json!({ "window": id }))
1684            },
1685        )?;
1686        ctx.command(
1687            CommandSpec::new(CMD_PICK, "Switch to window…", "Window")
1688                .description("Lists the open windows by title; the one chosen comes to the front."),
1689            |call| {
1690                let app = call.app;
1691                let dialogs = app
1692                    .service(&crate::dialogs::DIALOGS)
1693                    .ok_or("no dialogs plugin")?;
1694                // The others first, in their order: Enter goes to
1695                // another window; the active one last.
1696                let mut open = app.windows();
1697                open.sort_by_key(|w| w.active);
1698                let options = open
1699                    .iter()
1700                    .map(|w| crate::dialogs::ChooseOption::new(&w.title, json!(w.id)))
1701                    .collect();
1702                let id = dialogs.open(
1703                    crate::dialogs::Choose::with_options("Switch to window", options, CMD_SWITCH)
1704                        .value_key("window"),
1705                );
1706                Ok(json!({ "dialog": id, "windows": open.len() }))
1707            },
1708        )?;
1709        ctx.submenu(crate::app::MENU_MAIN, "2_window", 0, MENU_WINDOW, "Window")?;
1710        ctx.menu_item(MenuItem::command(MENU_WINDOW, "0_pick", 0, CMD_PICK))?;
1711        ctx.menu_item(MenuItem::command(MENU_WINDOW, "1_close", 0, CMD_CLOSE))?;
1712        ctx.menu_item(MenuItem::list(MENU_WINDOW, "2_windows", 0, LIST_WINDOWS))?;
1713        ctx.list_provider(LIST_WINDOWS, |app, _| {
1714            app.windows()
1715                .into_iter()
1716                .map(|w| {
1717                    crate::menus::ListItem::new(&w.title, CMD_SWITCH, json!({ "window": w.id }))
1718                        .checked(w.active)
1719                })
1720                .collect()
1721        });
1722        Ok(())
1723    }
1724}