Skip to main content

egui_pop_api/
window_invariants.rs

1//! The window invariants: the registry checked against what is on screen
2//! ([ADR 0029](https://github.com/quazardous/egui-pop/blob/main/docs/adr/0029-not-on-the-bus.md),
3//! slice 2).
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! The registry ([`AppHandle::windows_list`]) is the one list of windows
9//! and popups. Six rules say it agrees with what egui and the system
10//! show; they are checked by `pop.window.invariants`, the last listener of
11//! every window and popup point, and again at the end of every pass of
12//! the main window:
13//!
14//! 1. [`BACKEND`]: the registry's windows are the backend's viewports
15//!    (egui's `raw.viewports`), none more, none fewer, past the one pass
16//!    the backend needs to create or destroy one. Not checked while the
17//!    context embeds its viewports (one system window: kittest, the web).
18//! 2. [`PAINTS`]: a shown window painted something within the paint
19//!    guard's passes and delay ([`crate::paint_guard::DEFAULT_DELAY`]).
20//! 3. [`OWNER`]: no window or popup without an owner.
21//! 4. [`POPUP_PARENT`]: a popup's parent exists.
22//! 5. [`CHILD_ALIVE`]: a closed parent has no live child.
23//! 6. [`ON_SCREEN`]: a positioned window meets a screen: a window whose
24//!    position the system tells (not on Wayland, not minimized) overlaps
25//!    one of the screens told ([`crate::window::set_screens`]), past the
26//!    passes a move needs ([`crate::bus::ScreenRemoved`] moves those on a
27//!    screen gone). Not checked while no screen is told.
28//!
29//! [`CLOSED_LEFT`] is `pop.window.close`'s own: a window it closed is still in
30//! the registry once its listeners ran.
31//!
32//! A broken rule is a visible state, never a silent fix: one error line
33//! naming the rule, the window, its owner and its state, one
34//! `window.invariant` event on the journal (`rule`, `window`, `owner`,
35//! `state`), and an entry in [`AppHandle::broken_invariants`] (the `bus`
36//! collector of the debug bridge shows them). It is said once, until it
37//! holds again (a line says so). Containment stays the paint guard's (its
38//! fallback page, the hiding of a window that outlived its close). The
39//! test kit fails a test on one (`egui_pop_test::windows::MultiWindow`,
40//! the scenarios' `WindowInvariants`).
41
42use std::collections::{BTreeMap, BTreeSet};
43
44use egui::ViewportId;
45use serde::Serialize;
46use serde_json::json;
47
48use crate::app::AppHandle;
49use crate::bus::{WindowKind, WindowRecord};
50use crate::windows::WindowId;
51
52/// Rule 1: the registry's windows are the backend's viewports.
53pub const BACKEND: &str = "registry-is-backend";
54/// Rule 2: a shown window paints something.
55pub const PAINTS: &str = "shown-paints";
56/// Rule 3: every window and popup has an owner.
57pub const OWNER: &str = "has-owner";
58/// Rule 4: a popup's parent exists.
59pub const POPUP_PARENT: &str = "popup-has-parent";
60/// Rule 5: a closed parent has no live child.
61pub const CHILD_ALIVE: &str = "no-child-of-closed-parent";
62/// Rule 6: a positioned window meets a screen.
63pub const ON_SCREEN: &str = "positioned-meets-a-screen";
64/// `pop.window.close`'s check: the window it closed left the registry.
65pub const CLOSED_LEFT: &str = "closed-left-registry";
66
67/// The six rules, in the ADR's order.
68pub const RULES: [&str; 6] = [BACKEND, PAINTS, OWNER, POPUP_PARENT, CHILD_ALIVE, ON_SCREEN];
69
70/// The rules read from the registry alone.
71const STRUCTURE: [&str; 3] = [OWNER, POPUP_PARENT, CHILD_ALIVE];
72
73/// The main window's passes a mismatch with the backend may last: the
74/// one the backend needs to create or destroy a window.
75const BACKEND_GRACE: u32 = 1;
76
77/// The main window's passes a positioned window may stay off every
78/// screen: the system moving a window `pop.window.place` moved, or one being
79/// dragged across screens.
80const ON_SCREEN_GRACE: u32 = 3;
81
82/// How many broken invariants [`AppHandle::broken_invariants`] keeps.
83const KEPT: usize = 256;
84
85/// An invariant that did not hold.
86#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
87#[non_exhaustive]
88pub struct Broken {
89    /// The rule ([`RULES`], [`CLOSED_LEFT`]).
90    pub rule: String,
91    /// The window or popup's id; a viewport the registry does not hold
92    /// is named `viewport <id>`.
93    pub window: String,
94    /// Its owner as the registry holds it (empty when none, or unknown).
95    pub owner: String,
96    /// What is wrong, in words.
97    pub state: String,
98}
99
100impl Broken {
101    fn new(rule: &str, window: &str, owner: &str, state: impl Into<String>) -> Self {
102        Self {
103            rule: rule.to_string(),
104            window: window.to_string(),
105            owner: owner.to_string(),
106            state: state.into(),
107        }
108    }
109
110    fn key(&self) -> (String, String) {
111        (self.rule.clone(), self.window.clone())
112    }
113}
114
115/// What the checks remember between passes.
116#[derive(Debug, Default)]
117pub(crate) struct State {
118    /// Broken now, by rule and window: said once, until it holds again.
119    open: BTreeSet<(String, String)>,
120    /// The main window's passes in a row each viewport disagreed with
121    /// the backend in, and how: `true` registered without a viewport,
122    /// `false` a viewport not registered (a window closed then opened
123    /// again in the next pass is two mismatches, each with its grace).
124    mismatch: BTreeMap<(ViewportId, bool), u32>,
125    /// Every one said, oldest first, at most [`KEPT`].
126    said: Vec<Broken>,
127    /// Mismatches the next check does not count: a window whose registry
128    /// entry changed inside the main window's pass (a detached panel's,
129    /// shown inside it), which the backend lists until the next one.
130    excused: BTreeSet<(ViewportId, bool)>,
131    /// The main window's passes in a row each positioned window met no
132    /// screen in.
133    off_screen: BTreeMap<ViewportId, u32>,
134}
135
136/// The viewport a window of the registry is shown in by the backend:
137/// the main window's, an application window's deferred one, a detached
138/// panel's; none for a native window or a popup.
139pub(crate) fn viewport_of(kind: WindowKind, id: &str) -> Option<ViewportId> {
140    match kind {
141        WindowKind::Main => Some(ViewportId::ROOT),
142        WindowKind::App => Some(WindowId::new(id).deferred_viewport()),
143        WindowKind::Panel => Some(crate::workbench::panel_viewport(
144            id.strip_prefix(PANEL_PREFIX).unwrap_or(id),
145        )),
146        _ => None,
147    }
148}
149
150/// A detached panel's window id in the registry: `panel:<panel id>`.
151pub(crate) const PANEL_PREFIX: &str = "panel:";
152
153/// `pop.window.close`'s check broken: the window it closed is still held.
154pub(crate) fn closed_left(req: &crate::bus::WindowRequest) -> Broken {
155    Broken::new(
156        CLOSED_LEFT,
157        &req.window,
158        &req.owner,
159        format!("closed ({}), still in the registry", req.reason.as_str()),
160    )
161}
162
163/// Invariant 2 broken (the paint guard's watch says it).
164pub(crate) fn painted_nothing(window: &str, owner: &str, state: String) -> Broken {
165    Broken::new(PAINTS, window, owner, state)
166}
167
168/// Rules 3 to 5, read from the registry alone.
169pub(crate) fn structure(records: &[WindowRecord]) -> Vec<Broken> {
170    let held = |id: &str| records.iter().any(|r| r.id == id);
171    let mut out = Vec::new();
172    for r in records {
173        if r.owner.trim().is_empty() {
174            out.push(Broken::new(
175                OWNER,
176                &r.id,
177                "",
178                format!("{:?} without an owner", r.kind),
179            ));
180        }
181        match (r.kind, &r.parent) {
182            (WindowKind::Popup, None) => out.push(Broken::new(
183                POPUP_PARENT,
184                &r.id,
185                &r.owner,
186                "a popup without a parent",
187            )),
188            (WindowKind::Popup, Some(p)) if !held(p) => out.push(Broken::new(
189                POPUP_PARENT,
190                &r.id,
191                &r.owner,
192                format!("open, its parent `{p}` is not open"),
193            )),
194            (_, Some(p)) if !held(p) => out.push(Broken::new(
195                CHILD_ALIVE,
196                &r.id,
197                &r.owner,
198                format!("open, its parent `{p}` closed"),
199            )),
200            _ => {}
201        }
202    }
203    out
204}
205
206impl AppHandle {
207    /// Every window invariant broken since the application started,
208    /// oldest first (the last 256): the rule, the window, its owner, its
209    /// state. Empty in a healthy application.
210    ///
211    /// <div class="warning">Experimental: may change in any release
212    /// (docs/stability.md).</div>
213    pub fn broken_invariants(&self) -> Vec<Broken> {
214        egui_pop_core::lock(&self.0.bus.invariants).said.clone()
215    }
216
217    /// The invariants broken now (said and not yet holding again).
218    ///
219    /// <div class="warning">Experimental: may change in any release
220    /// (docs/stability.md).</div>
221    pub fn invariants_broken_now(&self) -> Vec<(String, String)> {
222        egui_pop_core::lock(&self.0.bus.invariants)
223            .open
224            .iter()
225            .cloned()
226            .collect()
227    }
228
229    /// One invariant does not hold: said unless already said.
230    pub(crate) fn invariant_broken(&self, b: Broken) {
231        {
232            let mut s = egui_pop_core::lock(&self.0.bus.invariants);
233            if !s.open.insert(b.key()) {
234                return;
235            }
236            if s.said.len() == KEPT {
237                s.said.remove(0);
238            }
239            s.said.push(b.clone());
240        }
241        log::error!(
242            target: "egui_pop",
243            "window invariant `{}` broken by `{}` (owner {}): {}",
244            b.rule,
245            b.window,
246            if b.owner.is_empty() { "none" } else { &b.owner },
247            b.state,
248        );
249        self.publish(
250            "egui_pop",
251            None,
252            "window.invariant",
253            json!({ "rule": b.rule, "window": b.window, "owner": b.owner, "state": b.state }),
254        );
255    }
256
257    /// An invariant broken by `window` holds again.
258    pub(crate) fn invariant_holds(&self, rule: &str, window: &str) {
259        let was = egui_pop_core::lock(&self.0.bus.invariants)
260            .open
261            .remove(&(rule.to_string(), window.to_string()));
262        if was {
263            log::info!(
264                target: "egui_pop",
265                "window invariant `{rule}` holds again for `{window}`"
266            );
267        }
268    }
269
270    /// The rules of `rules` found broken now are `found`: the new ones
271    /// said, the ones that hold again forgotten.
272    fn reconcile(&self, rules: &[&str], found: Vec<Broken>) {
273        let now: BTreeSet<(String, String)> = found.iter().map(Broken::key).collect();
274        let healed: Vec<(String, String)> = egui_pop_core::lock(&self.0.bus.invariants)
275            .open
276            .iter()
277            .filter(|(r, _)| rules.contains(&r.as_str()))
278            .filter(|k| !now.contains(*k))
279            .cloned()
280            .collect();
281        for (rule, window) in healed {
282            self.invariant_holds(&rule, &window);
283        }
284        for b in found {
285            self.invariant_broken(b);
286        }
287    }
288
289    /// A window shown inside the main window's pass (a detached panel's)
290    /// left the registry (`registered` false) or came in: the backend's
291    /// list catches up one main pass later than for a window of its own,
292    /// so the next check does not count that mismatch.
293    pub(crate) fn excuse_backend_once(&self, viewport: ViewportId, registered: bool) {
294        egui_pop_core::lock(&self.0.bus.invariants)
295            .excused
296            .insert((viewport, registered));
297    }
298
299    /// `pop.window.invariants` after a request: the rules the registry alone
300    /// answers. Whether they all hold.
301    pub(crate) fn check_invariants_after_request(&self) -> bool {
302        let records = self.windows_list();
303        let found = structure(&records);
304        let held = found.is_empty();
305        self.reconcile(&STRUCTURE, found);
306        held
307    }
308
309    /// The end of the main window's pass: every rule the registry and
310    /// the backend answer (the paint rule is the paint guard's, as it
311    /// watches each window's passes).
312    pub(crate) fn check_invariants_in_pass(&self, ctx: &egui::Context) {
313        if ctx.viewport_id() != ViewportId::ROOT {
314            return;
315        }
316        let records = self.windows_list();
317        let mut found = structure(&records);
318        found.extend(self.backend_mismatch(ctx, &records));
319        found.extend(self.off_screen(ctx, &records));
320        self.reconcile(
321            &[OWNER, POPUP_PARENT, CHILD_ALIVE, BACKEND, ON_SCREEN],
322            found,
323        );
324    }
325
326    /// Rule 6: each window whose position the system tells meets a screen
327    /// told, broken once it stayed off every screen past the grace.
328    fn off_screen(&self, ctx: &egui::Context, records: &[WindowRecord]) -> Vec<Broken> {
329        let screens = crate::window::screens();
330        let mut s = egui_pop_core::lock(&self.0.bus.invariants);
331        if screens.is_empty() || ctx.embed_viewports() {
332            s.off_screen.clear();
333            return Vec::new();
334        }
335        let previous = std::mem::take(&mut s.off_screen);
336        let mut out = Vec::new();
337        for r in records {
338            let Some(v) = viewport_of(r.kind, &r.id) else {
339                continue;
340            };
341            let Some(rect) = crate::bus::screens::positioned(ctx, v) else {
342                continue;
343            };
344            if screens.iter().any(|sc| sc.intersects(rect)) {
345                continue;
346            }
347            let passes = previous.get(&v).copied().unwrap_or(0) + 1;
348            s.off_screen.insert(v, passes);
349            if passes > ON_SCREEN_GRACE {
350                out.push(Broken::new(
351                    ON_SCREEN,
352                    &r.id,
353                    &r.owner,
354                    format!("at {rect:?}, on no screen of {screens:?}"),
355                ));
356            }
357        }
358        out
359    }
360
361    /// Rule 1: what the registry holds against the viewports the backend
362    /// lists, a mismatch broken once it lasts past the grace pass.
363    fn backend_mismatch(&self, ctx: &egui::Context, records: &[WindowRecord]) -> Vec<Broken> {
364        if ctx.embed_viewports() {
365            egui_pop_core::lock(&self.0.bus.invariants).mismatch.clear();
366            return Vec::new();
367        }
368        let expected: BTreeMap<ViewportId, &WindowRecord> = records
369            .iter()
370            .filter_map(|r| viewport_of(r.kind, &r.id).map(|v| (v, r)))
371            .collect();
372        let live: BTreeSet<ViewportId> = ctx.input(|i| i.raw.viewports.keys().copied().collect());
373        // The main window is the backend's own: always there.
374        let mut off: Vec<((ViewportId, bool), Broken)> = Vec::new();
375        for (v, r) in &expected {
376            if *v != ViewportId::ROOT && !live.contains(v) {
377                off.push((
378                    (*v, true),
379                    Broken::new(
380                        BACKEND,
381                        &r.id,
382                        &r.owner,
383                        format!("open in the registry, the backend has no viewport {v:?}"),
384                    ),
385                ));
386            }
387        }
388        for v in &live {
389            if *v != ViewportId::ROOT && !expected.contains_key(v) {
390                // An application window closed and still listed is named.
391                let window = self
392                    .windows_ref()
393                    .entries
394                    .iter()
395                    .find(|e| e.id.deferred_viewport() == *v)
396                    .map(|e| e.id.as_str().to_string())
397                    .or_else(|| self.closed_window_id(*v))
398                    .unwrap_or_else(|| format!("viewport {v:?}"));
399                off.push((
400                    (*v, false),
401                    Broken::new(
402                        BACKEND,
403                        &window,
404                        "",
405                        format!("viewport {v:?} shown by the backend, not in the registry"),
406                    ),
407                ));
408            }
409        }
410        let mut s = egui_pop_core::lock(&self.0.bus.invariants);
411        let previous = std::mem::take(&mut s.mismatch);
412        let mut out = Vec::new();
413        let excused = std::mem::take(&mut s.excused);
414        for (v, b) in off {
415            let before = previous.get(&v).copied().unwrap_or(0);
416            let passes = if excused.contains(&v) {
417                before
418            } else {
419                before + 1
420            };
421            s.mismatch.insert(v, passes);
422            if passes > BACKEND_GRACE {
423                out.push(b);
424            }
425        }
426        out
427    }
428}