Skip to main content

egui_pop_api/
paint_guard.rs

1//! The main window's paint guard: a window never stays empty without a
2//! word.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! Two holes are watched at the end of each pass of the main window:
8//!
9//! - **The focus screen without its page.** A wizard run as a focus
10//!   screen hides the shell (menus, status bar, centre) under its page;
11//!   the page is drawn by the Settings app's block. When the wizard is
12//!   stored and no page was drawn in the pass (the Settings closed under
13//!   it, its block replaced, its overlay not held), the shell is drawn
14//!   again from the next pass on, a warning says so once, and
15//!   `window.focus_hole` is published.
16//! - **A window that painted nothing.** When the shell added nothing but
17//!   backgrounds and lines under the title bar (no text, no image, no
18//!   overlay held; without a shell, in the whole pass: a window whose
19//!   decorations did not draw either, as in zen mode or under a window's
20//!   content moved into the main window) for longer than a delay ([`DEFAULT_DELAY`]), an error
21//!   says once what holds the screen (the place stack, the Settings app
22//!   and its wizard, the overlays, the layout's areas),
23//!   `window.painted_nothing` is published, and a fallback page offers to
24//!   reset the arrangement and to go back to the first place. The page
25//!   leaves as soon as the shell paints again.
26//!
27//! The cost is a counter and a scan of the pass's shapes that stops at
28//! the first text or image (the menu bar's, in a healthy window).
29
30use std::time::Duration;
31
32use egui::{Align2, Id, LayerId, Order, Shape, Ui};
33use egui_pop_core::icon::Icon;
34use egui_pop_core::kit::{Kit, State};
35use egui_pop_core::overlay;
36use egui_pop_core::placeholder::EmptyState;
37use egui_pop_core::strings;
38use egui_pop_model::context::{Envelope, Request};
39use serde_json::{Value as Json, json};
40use web_time::Instant;
41
42use crate::app::AppHandle;
43use crate::strings as txt;
44
45/// How long the main window may paint nothing before the fallback page.
46pub const DEFAULT_DELAY: Duration = Duration::from_secs(2);
47
48/// The passes a window must have painted nothing in, whatever the delay:
49/// a pass or two are empty while a place changes.
50const MIN_PASSES: u32 = 3;
51
52/// An application window's watch (its own passes, see
53/// [`AppHandle::watch_app_window`]).
54#[derive(Debug, Default)]
55pub(crate) struct WindowWatch {
56    /// Since when it paints nothing, and for how many passes.
57    empty: Option<(Instant, u32)>,
58    /// The fallback page is shown in it.
59    shown: bool,
60}
61
62/// An application window closed lately, until the backend lets its
63/// system window go.
64#[derive(Debug)]
65pub(crate) struct Closed {
66    id: String,
67    since: Instant,
68    /// The main window's passes that still saw it listed.
69    seen: u32,
70    /// Its outliving the close was said.
71    said: bool,
72}
73
74/// A window whose system window outlived it: closed, or never opened,
75/// while its viewport still runs passes or is still listed by the
76/// backend ([`orphan_pass`], [`AppHandle::watch_closed_windows`]).
77#[derive(Debug)]
78struct Orphan {
79    since: Instant,
80    passes: u32,
81    said: bool,
82}
83
84thread_local! {
85    /// The viewports whose pass found no application window, by viewport.
86    static ORPHANS: std::cell::RefCell<std::collections::BTreeMap<egui::ViewportId, Orphan>> =
87        const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
88}
89
90/// Where a window's content starts: each layer's shapes before it.
91pub(crate) struct Mark(Vec<(LayerId, usize)>);
92
93/// Marks where a window's content starts, in every layer of its pass.
94pub(crate) fn mark(ui: &Ui) -> Mark {
95    let ctx = ui.ctx();
96    let mut layers: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
97    for l in [ui.layer_id(), LayerId::background()] {
98        if !layers.contains(&l) {
99            layers.push(l);
100        }
101    }
102    Mark(layers.into_iter().map(|l| (l, shapes(ctx, l))).collect())
103}
104
105/// Whether a text, an image or a drawing was painted since `mark`, in a
106/// layer it knew or in one opened since (an area, a popup).
107pub(crate) fn painted_since(ctx: &egui::Context, mark: &Mark) -> bool {
108    let layers: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
109    let from = |l: LayerId| mark.0.iter().find(|(m, _)| *m == l).map_or(0, |(_, n)| *n);
110    mark.0
111        .iter()
112        .map(|(l, _)| *l)
113        .chain(
114            layers
115                .into_iter()
116                .filter(|l| mark.0.iter().all(|(m, _)| m != l)),
117        )
118        .any(|l| has_content(ctx, l, from(l), None, &[]))
119}
120
121/// A closed window's page, drawn by its passes until the backend drops
122/// its system window (ADR 0029: one pass of grace draws the window's last
123/// page, never nothing).
124struct LastPage {
125    title: String,
126    /// The shapes of the pass it closed in, per layer; `None` when it
127    /// closed from elsewhere (the main window's pass, a command).
128    shapes: Option<Vec<(LayerId, Vec<egui::epaint::ClippedShape>)>>,
129}
130
131thread_local! {
132    /// The application windows closed and not yet dropped, by viewport.
133    static LAST_PAGES: std::cell::RefCell<std::collections::BTreeMap<egui::ViewportId, LastPage>> =
134        const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
135}
136
137/// An application window closed (`pop.window.registry`): its passes until
138/// the main window's next one draw its last page.
139pub(crate) fn closing(viewport: egui::ViewportId, title: String) {
140    LAST_PAGES.with_borrow_mut(|p| {
141        p.insert(
142            viewport,
143            LastPage {
144                title,
145                shapes: None,
146            },
147        )
148    });
149}
150
151/// The window closed in this very pass of its own: what the pass painted
152/// is its last page.
153pub(crate) fn keep_last_page(ctx: &egui::Context, viewport: egui::ViewportId) {
154    let layers: Vec<LayerId> = ctx.memory(|m| m.layer_ids().collect());
155    let shapes: Vec<(LayerId, Vec<egui::epaint::ClippedShape>)> = ctx.graphics(|g| {
156        layers
157            .iter()
158            .filter_map(|l| {
159                let list = g.get(*l)?;
160                let shapes: Vec<_> = list.all_entries().cloned().collect();
161                (!shapes.is_empty()).then_some((*l, shapes))
162            })
163            .collect()
164    });
165    LAST_PAGES.with_borrow_mut(|p| {
166        if let Some(page) = p.get_mut(&viewport) {
167            page.shapes = Some(shapes);
168        }
169    });
170}
171
172/// The main window's pass no longer declares the window: the backend
173/// drops its system window, its last page goes.
174pub(crate) fn closed_for_good(viewport: egui::ViewportId) {
175    LAST_PAGES.with_borrow_mut(|p| p.remove(&viewport));
176}
177
178/// Draws a closed window's last page in a pass of its own: the shapes of
179/// the pass it closed in, or, closed from elsewhere, its title on the
180/// canvas. Whether it had one.
181fn draw_last_page(ui: &mut Ui, viewport: egui::ViewportId) -> bool {
182    let Some((title, shapes)) = LAST_PAGES.with_borrow(|p| {
183        p.get(&viewport)
184            .map(|l| (l.title.clone(), l.shapes.clone()))
185    }) else {
186        return false;
187    };
188    let ctx = ui.ctx().clone();
189    match shapes {
190        Some(shapes) => ctx.graphics_mut(|g| {
191            for (layer, shapes) in shapes {
192                let list = g.entry(layer);
193                for s in shapes {
194                    list.add(s.clip_rect, s.shape);
195                }
196            }
197        }),
198        None => {
199            let t = egui_pop_core::theme::Tokens::of(&ctx);
200            let rect = ui.max_rect();
201            ui.painter().rect_filled(rect, 0.0, t.surface.canvas);
202            ui.painter().text(
203                rect.center(),
204                Align2::CENTER_CENTER,
205                title,
206                egui::FontId::proportional(14.0),
207                t.text.muted,
208            );
209        }
210    }
211    true
212}
213
214/// A pass of a viewport with no application window behind it (closed, or
215/// never opened). A window closed lately draws its last page; otherwise
216/// the pass paints nothing, so its system window shows the clear colour
217/// alone. A pass or two run between a close and the main window's next
218/// pass, which drops the viewport; past the delay, an error says which
219/// window it is, once, and the main window is asked to pass (where a
220/// closed window's viewport is dropped).
221pub(crate) fn orphan_pass(ui: &mut Ui, viewport: egui::ViewportId, why: &str) {
222    let ctx = ui.ctx().clone();
223    let drawn = draw_last_page(ui, viewport);
224    let now = Instant::now();
225    let say = ORPHANS.with_borrow_mut(|o| {
226        let e = o.entry(viewport).or_insert(Orphan {
227            since: now,
228            passes: 0,
229            said: false,
230        });
231        e.passes += 1;
232        if e.passes == 1 {
233            if drawn {
234                log::debug!(
235                    target: "egui_pop",
236                    "a pass of viewport {viewport:?} after its window went ({why}): it draws \
237                     the window's last page until the backend drops it"
238                );
239            } else {
240                // Its system window shows this pass's frame: the clear
241                // colour alone, without a title bar (said, to tell a black
242                // window).
243                log::info!(
244                    target: "egui_pop",
245                    "a pass of viewport {viewport:?} after its window went ({why}): it paints \
246                     nothing, and the window is asked to hide and close"
247                );
248            }
249        }
250        let due = !e.said && e.passes >= MIN_PASSES && now.duration_since(e.since) >= DEFAULT_DELAY;
251        if due {
252            e.said = true;
253        }
254        due.then_some((e.passes, now.duration_since(e.since)))
255    });
256    if let Some((passes, since)) = say {
257        let title = ctx
258            .input(|i| i.viewport().title.clone())
259            .unwrap_or_default();
260        log::error!(
261            target: "egui_pop",
262            "the window of viewport {viewport:?} (title {title:?}) outlived its close for \
263             {passes} passes ({:.1} s): {why}; it is closed",
264            since.as_secs_f32()
265        );
266    }
267    ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
268    ctx.send_viewport_cmd(egui::ViewportCommand::Close);
269    ctx.request_repaint_of(egui::ViewportId::ROOT);
270    ctx.request_repaint_after(DEFAULT_DELAY);
271}
272
273/// A viewport has an application window again (opened): its orphan
274/// passes are forgotten.
275pub(crate) fn forget_orphan(viewport: egui::ViewportId) {
276    ORPHANS.with_borrow_mut(|o| o.remove(&viewport));
277    LAST_PAGES.with_borrow_mut(|p| p.remove(&viewport));
278}
279
280/// The guard's state, per application (the main window's).
281#[derive(Debug)]
282pub(crate) struct Guard {
283    /// A focus screen is asked and no page drew: the shell is drawn.
284    focus_hole: bool,
285    /// Where the pass starts in the window's layer: before the title
286    /// bar, or the content moved into the main window.
287    pass_start: Option<(LayerId, usize)>,
288    /// Where the shell's content starts in the window's layer: after the
289    /// title bar's shapes.
290    start: Option<(LayerId, usize)>,
291    /// The first pass was said in the log.
292    first_said: bool,
293    /// What the shell painted in this pass that says it has nothing to
294    /// show (the empty centre's "Drop a panel here"): the shapes' ranges
295    /// in their layer, not counted as content.
296    placeholders: Vec<(LayerId, std::ops::Range<usize>)>,
297    /// Since when the window paints nothing, and for how many passes.
298    empty: Option<(Instant, u32)>,
299    /// The fallback page is shown.
300    shown: bool,
301    /// `None`: the window is not watched.
302    delay: Option<Duration>,
303    /// The application windows' watches, by viewport.
304    windows: std::collections::BTreeMap<egui::ViewportId, WindowWatch>,
305    /// The application windows closed lately, by viewport.
306    closed: std::collections::BTreeMap<egui::ViewportId, Closed>,
307}
308
309impl Default for Guard {
310    fn default() -> Self {
311        Guard {
312            focus_hole: false,
313            pass_start: None,
314            start: None,
315            first_said: false,
316            placeholders: Vec::new(),
317            empty: None,
318            shown: false,
319            delay: Some(DEFAULT_DELAY),
320            windows: std::collections::BTreeMap::new(),
321            closed: std::collections::BTreeMap::new(),
322        }
323    }
324}
325
326/// Whether a shape is content: a text, an image, a drawing. Backgrounds
327/// (plain rectangles) and lines (separators, sashes, outlines) are what
328/// an empty window still paints.
329fn is_content(shape: &Shape) -> bool {
330    match shape {
331        Shape::Noop | Shape::LineSegment { .. } => false,
332        Shape::Rect(r) => r.brush.is_some(),
333        Shape::Vec(v) => v.iter().any(is_content),
334        _ => true,
335    }
336}
337
338/// How many shapes the layer holds.
339fn shapes(ctx: &egui::Context, layer: LayerId) -> usize {
340    ctx.graphics(|g| g.get(layer).map_or(0, |l| l.next_idx().0))
341}
342
343/// Whether the layer holds content from `from` up to `to` (its end
344/// without one), the shapes in `skip` (placeholders) left out.
345fn has_content(
346    ctx: &egui::Context,
347    layer: LayerId,
348    from: usize,
349    to: Option<usize>,
350    skip: &[(LayerId, std::ops::Range<usize>)],
351) -> bool {
352    let skipped = |i: usize| skip.iter().any(|(l, r)| *l == layer && r.contains(&i));
353    ctx.graphics(|g| {
354        g.get(layer).is_some_and(|l| {
355            l.all_entries()
356                .enumerate()
357                .take(to.unwrap_or(usize::MAX))
358                .skip(from)
359                .any(|(i, s)| !skipped(i) && is_content(&s.shape))
360        })
361    })
362}
363
364impl AppHandle {
365    /// How long the main window may paint nothing (no text, no image,
366    /// no overlay) before an error is logged and the fallback page
367    /// shown; `None` turns the watch off (an application whose window is
368    /// empty on purpose). [`DEFAULT_DELAY`] to start with.
369    pub fn set_empty_window_delay(&self, delay: Option<Duration>) {
370        let mut g = self.0.paint_guard.borrow_mut();
371        g.delay = delay;
372        g.empty = None;
373    }
374
375    /// Whether the main window shows the fallback page: it painted
376    /// nothing for longer than the delay.
377    pub fn empty_window(&self) -> bool {
378        self.0.paint_guard.borrow().shown
379    }
380
381    /// Whether a wizard is stored as a focus screen while no page of it
382    /// is drawn: the shell is drawn instead of hidden.
383    pub fn focus_screen_hole(&self) -> bool {
384        self.0.paint_guard.borrow().focus_hole
385    }
386
387    /// Whether the shell hides under a focus screen in this pass: one is
388    /// asked, and its page was drawn in the last pass.
389    pub(crate) fn hidden_by_focus_screen(&self) -> bool {
390        crate::admin::focus_screen(self) && !self.0.paint_guard.borrow().focus_hole
391    }
392
393    /// The main window's pass starts here in `ui`'s layer: before the
394    /// title bar, the shell, or the content moved into the main window.
395    pub(crate) fn mark_pass_start(&self, ui: &Ui) {
396        let layer = ui.layer_id();
397        let mut g = self.0.paint_guard.borrow_mut();
398        g.pass_start = Some((layer, shapes(ui.ctx(), layer)));
399        g.start = None;
400        g.placeholders.clear();
401    }
402
403    /// Draws `add`, a placeholder saying there is nothing to show (the
404    /// empty centre's "Drop a panel here"): what it paints is not content
405    /// for the guard, so a window showing only placeholders still gets
406    /// the fallback page and its way back.
407    pub(crate) fn placeholder(&self, ui: &mut Ui, add: impl FnOnce(&mut Ui)) {
408        let layer = ui.layer_id();
409        let from = shapes(ui.ctx(), layer);
410        add(ui);
411        let to = shapes(ui.ctx(), layer);
412        self.0
413            .paint_guard
414            .borrow_mut()
415            .placeholders
416            .push((layer, from..to));
417    }
418
419    /// The shell's content starts here in `ui`'s layer (what was painted
420    /// before is the title bar's).
421    pub(crate) fn mark_shell_start(&self, ui: &Ui) {
422        let layer = ui.layer_id();
423        self.0.paint_guard.borrow_mut().start = Some((layer, shapes(ui.ctx(), layer)));
424    }
425
426    /// The end of the main window's pass, once the shell and the overlay
427    /// zones are drawn.
428    pub(crate) fn end_shell_pass(&self, ui: &Ui) {
429        let ctx = ui.ctx();
430        let admin = self.service(&crate::admin::ADMIN);
431        let focus = admin.as_ref().is_some_and(|a| a.focus_screen());
432        let page = admin.as_ref().is_some_and(|a| a.take_page_drawn());
433        let hole = focus && !page;
434        let was = std::mem::replace(&mut self.0.paint_guard.borrow_mut().focus_hole, hole);
435        if hole && !was {
436            let state = self.screen_state(ctx);
437            log::warn!(
438                target: "egui_pop",
439                "a wizard holds the main window as a focus screen and no page of it was drawn: \
440                 the shell is drawn instead; {state}"
441            );
442            self.publish("egui_pop", None, "window.focus_hole", state);
443            ctx.request_repaint();
444        } else if was && !hole {
445            log::info!(target: "egui_pop", "the focus screen's hole is closed");
446        }
447        self.watch_empty(ui, page);
448        // The registry against the backend, at the end of every pass of
449        // the main window (ADR 0029, invariant 1, and 3 to 5).
450        self.check_invariants_in_pass(ctx);
451    }
452
453    fn watch_empty(&self, ui: &Ui, page: bool) {
454        let ctx = ui.ctx();
455        let (pass_start, start, delay, shown, first_said, skip) = {
456            let mut g = self.0.paint_guard.borrow_mut();
457            let first = std::mem::replace(&mut g.first_said, true);
458            let skip = std::mem::take(&mut g.placeholders);
459            (
460                g.pass_start.take(),
461                g.start.take(),
462                g.delay,
463                g.shown,
464                first,
465                skip,
466            )
467        };
468        // Without a shell (a window's content moved into the main window,
469        // a pass that stopped before its title bar), the whole pass is
470        // looked at: a window without its decorations is watched too.
471        let Some((layer, from)) = start.or(pass_start) else {
472            return;
473        };
474        // The title bar drew something: `None` when no shell was drawn.
475        let title_bar = match (pass_start, start) {
476            (Some((_, a)), Some((_, b))) => Some(has_content(ctx, layer, a, Some(b), &skip)),
477            _ => None,
478        };
479        let content = has_content(ctx, layer, from, None, &skip);
480        if !first_said {
481            log::info!(
482                target: "egui_pop",
483                "the main window's first pass: content painted: {content}, title bar painted: \
484                 {title_bar:?}, shell drawn: {}; {}",
485                start.is_some(),
486                self.screen_state(ctx)
487            );
488        }
489        let Some(delay) = delay else {
490            return;
491        };
492        let painted = page || !overlay::stack(ctx).is_empty() || content;
493        if painted {
494            let mut g = self.0.paint_guard.borrow_mut();
495            g.empty = None;
496            if shown {
497                g.shown = false;
498                drop(g);
499                log::info!(target: "egui_pop", "the main window paints again");
500                self.invariant_holds(
501                    crate::window_invariants::PAINTS,
502                    crate::windows::WindowId::MAIN,
503                );
504            }
505            return;
506        }
507        let now = Instant::now();
508        let (since, passes) = {
509            let mut g = self.0.paint_guard.borrow_mut();
510            let e = g.empty.get_or_insert((now, 0));
511            e.1 += 1;
512            *e
513        };
514        if !shown {
515            if passes < MIN_PASSES || now.duration_since(since) < delay {
516                // An idle window runs no pass: come back to look.
517                ctx.request_repaint_after(delay.max(Duration::from_millis(50)));
518                return;
519            }
520            self.0.paint_guard.borrow_mut().shown = true;
521            let mut state = self.screen_state(ctx);
522            state["title_bar_painted"] = json!(title_bar);
523            state["shell_drawn"] = json!(start.is_some());
524            log::error!(
525                target: "egui_pop",
526                "the main window painted nothing (title bar painted: {title_bar:?}, shell \
527                 drawn: {}) for {passes} passes ({:.1} s): the fallback page is shown; {state}",
528                start.is_some(),
529                now.duration_since(since).as_secs_f32()
530            );
531            self.publish("egui_pop", None, "window.painted_nothing", state);
532            self.painted_nothing(
533                crate::windows::WindowId::MAIN,
534                passes,
535                now.duration_since(since),
536            );
537        }
538        self.fallback_page(ctx);
539    }
540
541    /// What holds the screen, for the log: the place stack and the modes,
542    /// the Settings app and its wizard, the overlays held, the layout's
543    /// areas with their panels.
544    pub fn screen_state(&self, ctx: &egui::Context) -> Json {
545        let admin = self.service(&crate::admin::ADMIN);
546        let stack = crate::contexts::state(self).map(|s| {
547            json!({
548                "places": s.places.iter().map(|e| e.frame.to_string()).collect::<Vec<_>>(),
549                "modes": s.modes.iter().map(|m| m.frame.to_string()).collect::<Vec<_>>(),
550            })
551        });
552        let overlays: Vec<String> = overlay::stack(ctx)
553            .iter()
554            .map(|o| o.label.clone())
555            .collect();
556        let areas: Vec<Json> = {
557            let wb = self.workbench_mut();
558            wb.areas()
559                .into_iter()
560                .map(|a| {
561                    json!({
562                        "area": crate::workbench::area_name(a),
563                        "panels": wb.panels_in(a).iter().map(ToString::to_string).collect::<Vec<_>>(),
564                    })
565                })
566                .collect()
567        };
568        json!({
569            "contexts": stack,
570            "settings": {
571                "open": admin.as_ref().is_some_and(|a| a.is_open()),
572                "wizard": admin.as_ref().and_then(|a| a.wizard_flow()).is_some(),
573                "focus_screen": admin.as_ref().is_some_and(|a| a.focus_screen()),
574                "in_window": crate::admin::in_window(self),
575            },
576            "overlays": overlays,
577            "zen": self.zen(),
578            "own_frame": crate::frame::own_frame(self),
579            "root_has_content": self.root_has_content(),
580            "areas": areas,
581        })
582    }
583
584    /// The end of an application window's pass (a viewport of its own):
585    /// whether its content painted. A window whose passes paint nothing
586    /// (no text, no image, no overlay under its title bar) for longer
587    /// than the delay gets one error naming it and its state,
588    /// `window.painted_nothing` (with `window`), and the fallback page;
589    /// `true` while the page is to be drawn ([`AppHandle::app_window_fallback`]).
590    pub(crate) fn watch_app_window(
591        &self,
592        ctx: &egui::Context,
593        id: &crate::windows::WindowId,
594        painted: bool,
595    ) -> bool {
596        let viewport = ctx.viewport_id();
597        let delay = self.0.paint_guard.borrow().delay;
598        let Some(delay) = delay else {
599            return false;
600        };
601        let painted = painted || !overlay::stack(ctx).is_empty();
602        let now = Instant::now();
603        let (since, passes, shown) = {
604            let mut g = self.0.paint_guard.borrow_mut();
605            let w = g.windows.entry(viewport).or_default();
606            if painted {
607                let was = std::mem::take(&mut w.shown);
608                w.empty = None;
609                drop(g);
610                if was {
611                    log::info!(target: "egui_pop", "the window `{id}` paints again");
612                    self.invariant_holds(crate::window_invariants::PAINTS, id.as_str());
613                }
614                return false;
615            }
616            let e = w.empty.get_or_insert((now, 0));
617            e.1 += 1;
618            (e.0, e.1, w.shown)
619        };
620        if shown {
621            return true;
622        }
623        if passes < MIN_PASSES || now.duration_since(since) < delay {
624            // An idle window runs no pass: come back to look.
625            ctx.request_repaint_after(delay.max(Duration::from_millis(50)));
626            return false;
627        }
628        if let Some(w) = self.0.paint_guard.borrow_mut().windows.get_mut(&viewport) {
629            w.shown = true;
630        }
631        let mut state = self.screen_state(ctx);
632        let info = self.windows().into_iter().find(|w| w.viewport == viewport);
633        state["window"] = json!({
634            "id": id,
635            "viewport": format!("{viewport:?}"),
636            "title": info.as_ref().map(|w| w.title.clone()),
637            "focused": info.as_ref().and_then(|w| w.focused),
638            "geometry": info.as_ref().and_then(|w| w.geometry),
639            "minimized": ctx.input(|i| i.viewport().minimized),
640        });
641        log::error!(
642            target: "egui_pop",
643            "the window `{id}` ({viewport:?}) painted nothing for {passes} passes ({:.1} s): the \
644             fallback page is shown; {state}",
645            now.duration_since(since).as_secs_f32()
646        );
647        self.publish("egui_pop", None, "window.painted_nothing", state);
648        self.painted_nothing(id.as_str(), passes, now.duration_since(since));
649        true
650    }
651
652    /// Invariant 2 broken: a shown window painted nothing past the
653    /// guard's passes and delay.
654    fn painted_nothing(&self, window: &str, passes: u32, since: Duration) {
655        let owner = self
656            .windows_list()
657            .into_iter()
658            .find(|w| w.id == window)
659            .map(|w| w.owner)
660            .unwrap_or_default();
661        self.invariant_broken(crate::window_invariants::painted_nothing(
662            window,
663            &owner,
664            format!(
665                "shown, painted nothing for {passes} passes ({:.1} s)",
666                since.as_secs_f32()
667            ),
668        ));
669    }
670
671    /// The fallback page of an application window that painted nothing:
672    /// what happened, and a button closing the window. `true` when it is
673    /// clicked.
674    pub(crate) fn app_window_fallback(&self, ctx: &egui::Context) -> bool {
675        let mut close = false;
676        egui::Area::new(Id::unique(("egui_pop.empty_app_window", ctx.viewport_id())))
677            .order(Order::Foreground)
678            .anchor(Align2::CENTER_CENTER, egui::Vec2::ZERO)
679            .show(ctx, |ui| {
680                ui.set_max_width(420.0);
681                Kit::of(ctx)
682                    .fault_card
683                    .show(ui, State::REST, egui::Shadow::NONE, |ui| {
684                        close = EmptyState::new(
685                            Icon::Warning,
686                            strings::tr(ctx, &txt::EMPTY_WINDOW_TITLE),
687                        )
688                        .text(strings::tr(ctx, &txt::EMPTY_WINDOW_BODY))
689                        .action(strings::tr(ctx, &strings::CLOSE))
690                        .show(ui);
691                    });
692            });
693        if close {
694            log::info!(target: "egui_pop", "empty window: closed from its fallback page");
695        }
696        close
697    }
698
699    /// An application window is closed: its watch goes, and its system
700    /// window is expected gone by the delay ([`AppHandle::watch_closed_windows`]).
701    pub(crate) fn app_window_closed(&self, viewport: egui::ViewportId, id: &str) {
702        let mut g = self.0.paint_guard.borrow_mut();
703        g.windows.remove(&viewport);
704        g.closed.insert(
705            viewport,
706            Closed {
707                id: id.to_string(),
708                since: Instant::now(),
709                seen: 0,
710                said: false,
711            },
712        );
713        drop(g);
714        // Closed, it is no longer a shown window that paints nothing.
715        self.invariant_holds(crate::window_invariants::PAINTS, id);
716    }
717
718    /// The id of the application window closed lately on `viewport`,
719    /// while the backend may still list it.
720    pub(crate) fn closed_window_id(&self, viewport: egui::ViewportId) -> Option<String> {
721        self.0
722            .paint_guard
723            .borrow()
724            .closed
725            .get(&viewport)
726            .map(|c| c.id.clone())
727    }
728
729    /// An application window opens on a viewport: what was kept of an
730    /// earlier window of it goes.
731    pub(crate) fn app_window_opened(&self, viewport: egui::ViewportId) {
732        let mut g = self.0.paint_guard.borrow_mut();
733        g.windows.remove(&viewport);
734        g.closed.remove(&viewport);
735        drop(g);
736        forget_orphan(viewport);
737    }
738
739    /// From the main window's pass: a closed application window whose
740    /// system window the backend still lists past the delay outlived its
741    /// close (a window nothing draws in shows the clear colour alone: a
742    /// black window). One error names it; the viewports returned are to
743    /// be shown hidden for one pass, then dropped.
744    pub(crate) fn watch_closed_windows(&self, ctx: &egui::Context) -> Vec<egui::ViewportId> {
745        let live: Vec<egui::ViewportId> = ctx.input(|i| i.raw.viewports.keys().copied().collect());
746        let now = Instant::now();
747        let (late, waiting) = {
748            let mut g = self.0.paint_guard.borrow_mut();
749            // Gone from the backend: the close is done.
750            g.closed.retain(|v, _| live.contains(v));
751            let Some(delay) = g.delay else {
752                return Vec::new();
753            };
754            let mut late = Vec::new();
755            for (v, c) in &mut g.closed {
756                c.seen += 1;
757                // The main window's pass right after the close still sees
758                // it: the backend drops it after that pass.
759                if !c.said && c.seen >= 2 && now.duration_since(c.since) >= delay {
760                    late.push((*v, c.id.clone(), now.duration_since(c.since)));
761                    c.said = true;
762                }
763            }
764            (late, g.closed.values().any(|c| !c.said))
765        };
766        if waiting {
767            ctx.request_repaint_after(self.0.paint_guard.borrow().delay.unwrap_or(DEFAULT_DELAY));
768        }
769        late.into_iter()
770            .map(|(v, id, since)| {
771                let state = self.screen_state(ctx);
772                log::error!(
773                    target: "egui_pop",
774                    "the window `{id}` ({v:?}) is closed, yet its system window is still there \
775                     {:.1} s later: it is hidden; {state}",
776                    since.as_secs_f32()
777                );
778                self.publish(
779                    "egui_pop",
780                    None,
781                    "window.outlived",
782                    json!({ "window": id, "viewport": format!("{v:?}") }),
783                );
784                v
785            })
786            .collect()
787    }
788
789    /// The fallback page, over the empty window: what happened, and two
790    /// ways out through commands that exist.
791    fn fallback_page(&self, ctx: &egui::Context) {
792        let deep = crate::contexts::state(self).is_some_and(|s| s.depth() > 0);
793        let mut reset = false;
794        let mut back = false;
795        egui::Area::new(Id::unique("egui_pop.empty_window"))
796            .order(Order::Foreground)
797            .anchor(Align2::CENTER_CENTER, egui::Vec2::ZERO)
798            .show(ctx, |ui| {
799                ui.set_max_width(420.0);
800                Kit::of(ctx)
801                    .fault_card
802                    .show(ui, State::REST, egui::Shadow::NONE, |ui| {
803                        reset = EmptyState::new(
804                            Icon::Warning,
805                            strings::tr(ctx, &txt::EMPTY_WINDOW_TITLE),
806                        )
807                        .text(strings::tr(ctx, &txt::EMPTY_WINDOW_BODY))
808                        .action(strings::tr(ctx, &txt::EMPTY_WINDOW_RESET))
809                        .show(ui);
810                        if deep {
811                            ui.vertical_centered(|ui| {
812                                back = ui
813                                    .button(strings::tr(ctx, &txt::EMPTY_WINDOW_BACK))
814                                    .clicked();
815                            });
816                        }
817                    });
818            });
819        if reset {
820            log::info!(target: "egui_pop", "empty window: the arrangement is reset");
821            // The Settings app open with nothing drawn would keep the
822            // window: closed with it.
823            if let Some(a) = self.service(&crate::admin::ADMIN) {
824                a.close(self);
825            }
826            // Zen mode hides the bars and the title bar: left with it.
827            if self.zen() {
828                self.run(crate::workbench::CMD_LEAVE_ZEN, Json::Null);
829            }
830            self.run(crate::arrangements::CMD_RESET, Json::Null);
831        }
832        if back {
833            log::info!(target: "egui_pop", "empty window: back to the first place");
834            let _ = crate::contexts::request(
835                self,
836                Envelope::new(Request::Jump { depth: 0 }),
837                &egui_pop_model::commands::Origin::User,
838            );
839        }
840    }
841}