Skip to main content

egui_pop_api/
app.rs

1//! The application: an [`AppBuilder`] takes plugins and a theme, sorts and
2//! connects the plugins, and gives an [`App`] that draws the shell (menu
3//! bar, zones, panels, the command palette) and dispatches keys. It runs
4//! in eframe (feature `eframe`) or headless, driven by tests.
5
6use std::cell::{RefCell, RefMut};
7use std::collections::{BTreeMap, BTreeSet};
8use std::fmt;
9use std::rc::{Rc, Weak};
10use std::sync::{Arc, Mutex};
11
12use egui::{Context, Id, Ui};
13use egui_pop_core::binding::SharedStore;
14use egui_pop_core::debug::{DebugBridge, Feedback, FnCollector};
15use egui_pop_core::focus_mode::{self, FocusModes, Preference, SystemFocus};
16use egui_pop_core::keys::KeyDispatcher;
17use egui_pop_core::kit::KitSource;
18use egui_pop_core::overlay;
19use egui_pop_core::persist::{Persist, PersistError, Writer};
20use egui_pop_core::state;
21use egui_pop_core::strings;
22use egui_pop_core::theme::{self, Counterpart, ThemeSpec, Themes};
23use egui_pop_core::tokens::Color;
24use egui_pop_core::{a11y, fault, focus, lock};
25
26/// The theme was installed in this context.
27const THEME_INSTALLED: state::Slot<bool> = state::Slot::new("api.app.theme_installed");
28/// The width the top bar's blocks took after the menus, last pass.
29const TOP_BAR_RESERVE: state::Slot<f32> = state::Slot::new("api.app.top_bar_reserve");
30/// The width the top bar's end zone took last pass.
31const TOP_BAR_END_WIDTH: state::Slot<f32> = state::Slot::new("api.app.top_bar_end_width");
32use bus_contract_journal::BusJournal;
33use bus_contract_timings::BusTimings;
34use egui_pop_model::commands::{CommandSpec, Commands, Origin, Run};
35use egui_pop_model::diagnostics::{Diagnostic, Diagnostics};
36use egui_pop_model::ids::{
37    CommandId, MenuId, OwnerId, PanelId, PluginId, SettingId, StepId, StoryId, ZoneId,
38};
39use egui_pop_model::keymap::{BindOptions, Binding, Keymap, Layer, Trace};
40use egui_pop_model::menus::{Item, MenuItem, Menus, sort_items};
41use egui_pop_model::order::{Node, order};
42use egui_pop_model::panels::{Area, PanelSpec, Panels};
43use egui_pop_model::registry::{OwnedList, Registry};
44use egui_pop_model::values::{Change, Set, Store, Value, settings_schema};
45use egui_pop_model::when::WhenContext;
46use serde_json::{Value as Json, json};
47
48use crate::ctx::{Ctx, CtxError};
49use crate::hooks::{Alter, Hook, Lifecycle, LifecycleFn, On, PaletteEntry, SettingEntry};
50use crate::host::{Dispatch, Event, Host, LocalHost, Pending, Reply, Seq, Waker, source_of};
51use crate::plugin::{BuildError, Plugin, PluginError, PluginInfo};
52use crate::services::{ServiceToken, Services};
53use crate::steps::{HookFn, HookInfo, Outcome, StepHook, StepInfo, StepSpec, StepTrace};
54use crate::stories::{Story, StoryInfo};
55use crate::zones::{self, Block, DrawFn, ZoneInfo, ZoneTable, draw_chain};
56
57/// The number of the pass a viewport began last (keyed by the viewport),
58/// written by [`PassMarker`]: equal to `cumulative_pass_nr` while that
59/// pass runs, behind it once the pass has ended.
60const PASS_BEGUN: state::Slot<u64> = state::Slot::new("api.app.pass_begun");
61
62/// Marks each pass's beginning, so that [`App::logic`] tells a call
63/// inside a pass from one between passes.
64#[derive(Debug)]
65struct PassMarker;
66
67impl egui::plugin::Plugin for PassMarker {
68    fn debug_name(&self) -> &'static str {
69        "egui_pop_api::pass_marker"
70    }
71
72    fn on_begin_pass(&mut self, ui: &mut Ui) {
73        let ctx = ui.ctx();
74        PASS_BEGUN
75            .keyed(ctx.viewport_id())
76            .set(ctx, ctx.cumulative_pass_nr());
77    }
78}
79
80/// Adds [`PassMarker`] to `ctx`, once.
81fn install_pass_marker(ctx: &Context) {
82    if ctx.plugin_opt::<PassMarker>().is_none() {
83        ctx.add_plugin(PassMarker);
84    }
85}
86
87/// The viewport and the number of the pass running in `ctx`; `None`
88/// between passes (eframe's ticks of a hidden window, a test calling
89/// [`App::logic`] alone), or before the marker saw a pass begin.
90pub(crate) fn pass_in_progress(ctx: &Context) -> Option<(egui::ViewportId, u64)> {
91    let viewport = ctx.viewport_id();
92    let pass = ctx.cumulative_pass_nr();
93    (PASS_BEGUN.keyed(viewport).get(ctx) == Some(pass)).then_some((viewport, pass))
94}
95
96/// The user gives a command new keys, or none (`{ "command", "keys",
97/// "layer" }`; `keys` a shortcut, `null`, or an array of several: a
98/// pointer gesture's triggers).
99pub const STEP_REBIND: StepId = StepId::from_static("keys.rebind");
100/// A keymap document is loaded into a layer (`{ "layer", "bindings" }`).
101pub const STEP_LOAD_KEYMAP: StepId = StepId::from_static("keys.load");
102
103/// The main menu bar.
104/// The context key holding the detached panel whose window is drawn
105/// (empty in the main window): `when: "window == 'app.log'"`.
106pub const CONTEXT_WINDOW: &str = "window";
107/// The context key holding the kind of the focused panel
108/// (`PanelId::kind`): the panel's own id, or `app.gallery` while its
109/// instance `app.gallery#2` has the focus, so one clause reaches every
110/// instance: `when: "focusedPanelKind == 'app.gallery'"`.
111///
112/// Need (action): keys that work in every instance of a panel.
113pub const CONTEXT_FOCUSED_PANEL_KIND: &str = "focusedPanelKind";
114/// The context key true when, under focus routing
115/// ([`Routing::Focus`](crate::history::Routing::Focus)), Ctrl+Z goes
116/// nowhere only because no view was focused yet while a step waits
117/// somewhere ([`needs_view`](crate::history::needs_view)): Edit › Undo
118/// stays live to say why.
119pub const CONTEXT_UNDO_NEEDS_VIEW: &str = "undoNeedsView";
120/// [`CONTEXT_UNDO_NEEDS_VIEW`]'s twin for Ctrl+Shift+Z.
121pub const CONTEXT_REDO_NEEDS_VIEW: &str = "redoNeedsView";
122
123pub const MENU_MAIN: MenuId = MenuId::from_static("app.main");
124pub const MENU_FILE: MenuId = MenuId::from_static("app.menu.file");
125pub const MENU_EDIT: MenuId = MenuId::from_static("app.menu.edit");
126pub const MENU_VIEW: MenuId = MenuId::from_static("app.menu.view");
127pub const MENU_HELP: MenuId = MenuId::from_static("app.menu.help");
128/// The end of the main menu bar: its command items show there as icon
129/// buttons (`menus::bar_end`), the last at the bar's end, each pressed
130/// while its `checked` clause holds and left out where its command does
131/// not apply. Commands go there as into any menu
132/// (`CommandSpec::menu(MENU_BAR_END, group, order)`): the devtools'
133/// inspect mode does.
134pub const MENU_BAR_END: MenuId = MenuId::from_static("app.menu-bar.end");
135
136/// The framework's commands.
137pub use crate::palette::CMD_PALETTE;
138pub const CMD_QUIT: CommandId = CommandId::from_static("app.quit");
139/// Undo and redo: the keys, menu items and `when` checks are
140/// egui-pop's, what an undo does is the history owner's
141/// ([`Host::history`], ADR 0014), each run going through the
142/// [`STEP_UNDO`] and [`STEP_REDO`] steps.
143pub const CMD_UNDO: CommandId = CommandId::from_static("edit.undo");
144pub const CMD_REDO: CommandId = CommandId::from_static("edit.redo");
145/// The steps of an undo and a redo (ADR 0011): a before-hook may veto
146/// one (a gesture in progress) or redirect it (another `scope`), a
147/// run-hook does it instead of the owner, an after-hook follows. Their
148/// arguments: `label` (what it takes back, as the menu said), `origin`
149/// and `scope` (the history focus picked). Their result:
150/// `{"undone": label, "scope", "steps", "rev", "head"}` (`"redone"`), the
151/// label `null` when there was nothing. Besides the step's own signal,
152/// the journal says `edit.undone` / `edit.redone` with the label, or
153/// `edit.undo_failed` / `edit.redo_failed` with the error or the veto;
154/// and `history.changed` or `history.refused`.
155pub const STEP_UNDO: StepId = StepId::from_static("edit.undo");
156pub const STEP_REDO: StepId = StepId::from_static("edit.redo");
157
158/// Commands whose run calls the host itself: undo, redo and the agents'
159/// `history.*` call `Host::history`, the context stack's commands
160/// `Host::contexts`, the clipboard's `Host::clipboard`, which a dispatch
161/// holds. They go through the host's dispatch all the same (a guard
162/// there sees them), and their handler runs once it returns
163/// (`Dispatch::deferred`).
164const IN_INTERFACE: &[CommandId] = &[
165    CMD_UNDO,
166    CMD_REDO,
167    crate::history_view::CMD_LIST,
168    crate::history_view::CMD_READ,
169    crate::history_view::CMD_UNDO,
170    crate::history_view::CMD_REDO,
171    crate::history_view::CMD_JUMP,
172    crate::history_view::CMD_SNAPSHOT,
173    crate::history_view::CMD_RESTORE,
174    crate::history_view::CMD_DROP_SNAPSHOT,
175    crate::history_view::CMD_UNDO_STEP,
176    crate::contexts::CMD_BACK,
177    crate::contexts::CMD_UP,
178    crate::contexts::CMD_ENTER,
179    crate::contexts::CMD_READ,
180    crate::contexts::CMD_REQUEST,
181    crate::contexts::CMD_GO,
182    crate::contexts::CMD_SET_MODE,
183    crate::contexts::CMD_HOLD,
184    crate::contexts::CMD_RELEASE,
185    crate::clipboard::CMD_CUT,
186    crate::clipboard::CMD_COPY,
187    crate::clipboard::CMD_PASTE,
188    crate::clipboard::CMD_PASTE_SPECIAL,
189    crate::clipboard::CMD_CLIP_COPY,
190    crate::clipboard::CMD_CLIP_PASTE,
191    crate::clipboard::CMD_OFFERS,
192    crate::clipboard::CMD_READ,
193    crate::clipboard::CMD_WRITE,
194];
195pub const CMD_SAVE: CommandId = CommandId::from_static("app.save");
196
197/// What an overlay is, as [`AppHandle::overlay_rects`] reports it.
198#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
199#[serde(rename_all = "lowercase")]
200pub enum OverlayKind {
201    /// The dialog shown (`dialogs`).
202    Dialog,
203    /// Another modal overlay (the settings window, the palette).
204    Modal,
205    Popover,
206    /// A menu egui-pop opened as an overlay (`menus::popup_at`).
207    Menu,
208    /// The toast stack.
209    Toasts,
210    /// The workbench's drop hint, while a tab is dragged over another
211    /// area (named `drop:<panel>:<area>`).
212    DropHint,
213    /// One of egui's popups: an open menu of the menu bar, a context
214    /// menu, a combo box.
215    Popup,
216}
217
218/// An overlay on screen: what it is, a name for it (`dialog:3`, the
219/// overlay's label, `toasts`), where it was drawn last, in points.
220#[derive(Clone, Debug, PartialEq)]
221pub struct OverlayRect {
222    pub kind: OverlayKind,
223    pub id: String,
224    pub rect: egui::Rect,
225}
226
227/// The theme, as a service: read it, ask for another (installed between
228/// frames), and choose between its light and dark variants when it has
229/// a counterpart (the [`SETTING_THEME_PREFERENCE`] setting).
230pub struct ThemeService {
231    spec: Mutex<ThemeSpec>,
232    themes: Themes,
233    kits: Vec<egui_pop_core::tokens::kit::KitInfo>,
234    store: SharedStore,
235    /// Whether each theme met is a dark one, by name.
236    dark: Mutex<BTreeMap<String, bool>>,
237    /// The context the application draws in: asked to repaint when the
238    /// theme changes.
239    ctx: Mutex<Context>,
240}
241
242impl fmt::Debug for ThemeService {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_struct("ThemeService")
245            .field("spec", &self.spec)
246            .field("kits", &self.kits)
247            .finish_non_exhaustive()
248    }
249}
250
251impl ThemeService {
252    pub fn spec(&self) -> ThemeSpec {
253        lock(&self.spec).clone()
254    }
255
256    /// Asks for a theme; installed before the next frame, which it asks
257    /// for (an idle window does not wait for input to show it).
258    pub fn set(&self, spec: ThemeSpec) {
259        self.update(|s| *s = spec);
260    }
261
262    /// Changes the theme in place; installed before the next frame,
263    /// which it asks for when the spec changed.
264    pub fn update(&self, f: impl FnOnce(&mut ThemeSpec)) {
265        let changed = {
266            let mut spec = lock(&self.spec);
267            let before = spec.clone();
268            f(&mut spec);
269            *spec != before
270        };
271        if changed {
272            lock(&self.ctx).request_repaint();
273        }
274    }
275
276    /// Follows the context the application draws in.
277    fn follow(&self, ctx: &Context) {
278        let mut mine = lock(&self.ctx);
279        if *mine != *ctx {
280            *mine = ctx.clone();
281        }
282    }
283
284    pub fn themes(&self) -> &Themes {
285        &self.themes
286    }
287
288    /// The kits added (`AppBuilder::kit`, then the user's kits), each a
289    /// theme of [`ThemeService::themes`] under its name, a kit holding
290    /// both variants listed once per variant: what a theme picker lists.
291    ///
292    /// <div class="warning">Experimental: may change in any release
293    /// (docs/stability.md).</div>
294    pub fn kits(&self) -> &[egui_pop_core::tokens::kit::KitInfo] {
295        &self.kits
296    }
297
298    /// The light or dark mode asked for (the [`SETTING_THEME_PREFERENCE`]
299    /// setting): the system's by default. It chooses between the theme
300    /// and its counterpart; a theme alone keeps its own mode.
301    pub fn preference(&self) -> egui::ThemePreference {
302        lock(&self.store)
303            .get(&format!("settings/{SETTING_THEME_PREFERENCE}"))
304            .and_then(|e| e.value.as_choice().and_then(parse_preference))
305            .unwrap_or(egui::ThemePreference::System)
306    }
307
308    /// Asks for a light or dark mode, or the system's (written to the
309    /// setting); applied before the next frame.
310    pub fn set_preference(&self, preference: egui::ThemePreference) {
311        let set = Set::new(
312            &format!("settings/{SETTING_THEME_PREFERENCE}"),
313            Change::To(Value::Choice(preference_name(preference).into())),
314            Origin::User,
315        )
316        .by(&OwnerId::FRAMEWORK)
317        .untracked();
318        if let Err(e) = lock(&self.store).set(set) {
319            log::warn!(target: "egui_pop", "theme preference: {e}");
320        }
321    }
322
323    fn accent_key() -> String {
324        format!("settings/{SETTING_ACCENT_COLOR}")
325    }
326
327    /// The [`SETTING_ACCENT_COLOR`] setting's text as stored (`""`: the
328    /// theme's own accent).
329    fn accent_setting(&self) -> String {
330        lock(&self.store)
331            .get(&Self::accent_key())
332            .and_then(|e| e.value.as_text().map(str::to_string))
333            .unwrap_or_default()
334    }
335
336    /// Writes the setting's colour into the spec: a seed accent, or the
337    /// theme's own when it is empty and the accent was a seed. Text that
338    /// is not a colour is reported and changes nothing.
339    fn apply_accent_setting(&self, text: &str) {
340        let text = text.trim();
341        if text.is_empty() {
342            self.update(|spec| {
343                if spec.accent_seed().is_some() {
344                    spec.accent = None;
345                }
346            });
347            return;
348        }
349        match Color::from_hex(text) {
350            Some(seed) => self.update(|spec| *spec = spec.clone().accent_color(seed)),
351            None => log::warn!(
352                target: "egui_pop",
353                "{SETTING_ACCENT_COLOR}: `{text}` is not a #rrggbb colour, the accent is kept"
354            ),
355        }
356    }
357
358    /// The accent's seed colour, when the accent is generated from one
359    /// ([`ThemeSpec::accent_color`]): the [`SETTING_ACCENT_COLOR`]
360    /// setting, or the spec's own.
361    pub fn accent_color(&self) -> Option<Color> {
362        self.spec().accent_seed()
363    }
364
365    /// Generates the accent from a colour, for the theme and its
366    /// counterpart (each its own ramp, light or dark), or goes back to
367    /// the theme's own accent (`None`). Written to the
368    /// [`SETTING_ACCENT_COLOR`] setting and the spec; installed before
369    /// the next frame.
370    pub fn set_accent_color(&self, seed: Option<Color>) {
371        let text = seed.map_or(String::new(), |c| Color { a: 1.0, ..c }.to_hex());
372        let set = Set::new(
373            &Self::accent_key(),
374            Change::To(Value::Text(text.clone())),
375            Origin::User,
376        )
377        .by(&OwnerId::FRAMEWORK)
378        .untracked();
379        if let Err(e) = lock(&self.store).set(set) {
380            log::warn!(target: "egui_pop", "accent colour: {e}");
381        }
382        match seed {
383            Some(seed) => self.update(|spec| *spec = spec.clone().accent_color(seed)),
384            None => self.apply_accent_setting(""),
385        }
386    }
387
388    /// The theme's counterpart, its other variant, if it has one.
389    pub fn counterpart(&self) -> Option<String> {
390        self.themes.counterpart(&self.spec())
391    }
392
393    /// Whether a theme is a dark one (its panels are dark).
394    pub fn is_dark(&self, name: &str) -> bool {
395        if let Some(d) = lock(&self.dark).get(name) {
396            return *d;
397        }
398        let d = self.themes.resolve(&ThemeSpec::new(name).alone()).is_dark();
399        lock(&self.dark).insert(name.to_string(), d);
400        d
401    }
402
403    fn mode_of(&self, name: &str) -> egui::Theme {
404        if self.is_dark(name) {
405            egui::Theme::Dark
406        } else {
407            egui::Theme::Light
408        }
409    }
410
411    /// The theme shown with the preference: the spec's base, or its
412    /// counterpart when the preference (or the system's mode, with
413    /// `System`) asks for the other mode.
414    pub fn shown(&self, ctx: &Context) -> String {
415        let spec = self.spec();
416        let Some(other) = self.themes.counterpart(&spec) else {
417            return spec.base;
418        };
419        let base_mode = self.mode_of(&spec.base);
420        if self.mode_of(&other) == base_mode {
421            return spec.base;
422        }
423        let wanted = match self.preference() {
424            egui::ThemePreference::Dark => egui::Theme::Dark,
425            egui::ThemePreference::Light => egui::Theme::Light,
426            egui::ThemePreference::System => ctx.system_theme().unwrap_or(base_mode),
427        };
428        if wanted == base_mode {
429            spec.base
430        } else {
431            other
432        }
433    }
434
435    /// Picks a theme, as a theme picker does: it is shown. Its
436    /// counterpart comes from the token files; when the preference would
437    /// show the counterpart, the preference becomes the picked theme's
438    /// mode.
439    pub fn pick(&self, ctx: &Context, name: &str) {
440        self.update(|spec| {
441            spec.base = name.to_string();
442            spec.counterpart = Counterpart::Auto;
443        });
444        if self.shown(ctx) != name {
445            self.set_preference(self.mode_of(name).into());
446        }
447    }
448
449    /// Switches between the theme and its counterpart: the preference
450    /// becomes the mode of the one not shown. The mode now shown, or why
451    /// nothing changed (a theme alone).
452    pub fn toggle(&self, ctx: &Context) -> Result<egui::Theme, String> {
453        let spec = self.spec();
454        let other = self
455            .themes
456            .counterpart(&spec)
457            .filter(|o| self.mode_of(o) != self.mode_of(&spec.base))
458            .ok_or_else(|| format!("`{}` has no light or dark counterpart", spec.base))?;
459        let shown = self.shown(ctx);
460        let next = if shown == spec.base { other } else { spec.base };
461        let mode = self.mode_of(&next);
462        self.set_preference(mode.into());
463        Ok(mode)
464    }
465}
466
467/// A preference's name in the setting: `system`, `light`, `dark`.
468pub fn preference_name(p: egui::ThemePreference) -> &'static str {
469    match p {
470        egui::ThemePreference::System => "system",
471        egui::ThemePreference::Light => "light",
472        egui::ThemePreference::Dark => "dark",
473    }
474}
475
476/// A preference from its name in the setting.
477pub fn parse_preference(name: &str) -> Option<egui::ThemePreference> {
478    match name {
479        "system" => Some(egui::ThemePreference::System),
480        "light" => Some(egui::ThemePreference::Light),
481        "dark" => Some(egui::ThemePreference::Dark),
482        _ => None,
483    }
484}
485
486/// The setting choosing between a theme's light and dark variants:
487/// `system`, `light`, `dark`.
488pub const SETTING_THEME_PREFERENCE: SettingId =
489    SettingId::from_static("appearance.theme_preference");
490
491/// The setting generating the accent from a colour (`#rrggbb`), for
492/// the theme and its counterpart; empty for the theme's own accent.
493pub const SETTING_ACCENT_COLOR: SettingId = SettingId::from_static("appearance.accent_color");
494
495/// The command switching between the theme's light and dark variants.
496pub const CMD_THEME_TOGGLE: CommandId = CommandId::from_static("view.theme.toggle_light_dark");
497
498/// The theme service's token.
499pub const THEME: ServiceToken<ThemeService> = ServiceToken::new("app.theme");
500
501/// The focus mode (click or hover, the system's way and the user's
502/// choice), as a service.
503///
504/// <div class="warning">Experimental: may change in any release
505/// (docs/stability.md).</div>
506pub const FOCUS_MODE: ServiceToken<FocusModes> = ServiceToken::new("app.focus_mode");
507
508/// The setting choosing the focus mode: `system`, `click`, `hover`.
509pub const SETTING_FOCUS: SettingId = SettingId::from_static("appearance.focus");
510
511/// The section the framework's settings are shown in.
512const FRAMEWORK_SECTION: &str = "Appearance";
513
514/// What a command handler receives.
515#[derive(Debug)]
516pub struct Call<'a> {
517    pub args: &'a Json,
518    pub origin: &'a Origin,
519    pub app: &'a AppHandle,
520}
521
522impl Call<'_> {
523    /// A failure told in full ([`CommandError`]: a headline in the
524    /// user's words, a reason, a hint, details), as the handler's error:
525    /// `return Err(call.fail(CommandError::new("cloudy was not added")
526    /// .reason(..)))`. The result stays a `String` (its `Display`); a
527    /// run reported at a place ([`AppHandle::run_reported`]) shows the
528    /// whole of it.
529    ///
530    /// <div class="warning">Experimental: may change in any release
531    /// (docs/stability.md).</div>
532    ///
533    /// [`CommandError`]: egui_pop_model::commands::CommandError
534    pub fn fail(&self, err: impl Into<egui_pop_model::commands::CommandError>) -> String {
535        let err = err.into();
536        let text = err.to_string();
537        if let Some((command, _)) = self.app.running_command() {
538            self.app.keep_failure(command, err);
539        }
540        text
541    }
542}
543
544/// A command handler.
545pub type CommandFn = Rc<dyn Fn(&Call<'_>) -> Result<Json, String>>;
546
547/// Why code acting for `acting` may not run a command as `origin`: only
548/// the user's own actions run as the user, and an agent's stay an
549/// agent's (the `agent` flag is checked for them).
550fn escalation(acting: &Origin, origin: &Origin) -> Option<String> {
551    match (acting, origin) {
552        (Origin::User, _) => None,
553        (a, o) if a == o => None,
554        (Origin::Agent(_), Origin::Agent(_)) => None,
555        (a, Origin::User) => Some(format!(
556            "a command running for {} may not run another as the user; ask the user (a dialog)",
557            source_of(a)
558        )),
559        (Origin::Agent(_), o) => Some(format!(
560            "a command running for {} may not run another as {}",
561            source_of(acting),
562            source_of(o)
563        )),
564        _ => None,
565    }
566}
567
568/// While alive, the code running acts for an origin
569/// (`AppHandle::acting_origin`).
570struct ActingFor<'a>(&'a AppHandle);
571
572impl<'a> ActingFor<'a> {
573    fn new(app: &'a AppHandle, origin: &Origin) -> Self {
574        app.0.acting.borrow_mut().push(origin.clone());
575        Self(app)
576    }
577}
578
579impl Drop for ActingFor<'_> {
580    fn drop(&mut self) {
581        self.0.0.acting.borrow_mut().pop();
582    }
583}
584
585/// The registries plugins fill through `Ctx`.
586pub(crate) struct Registries {
587    /// Declarations, each with its in-process handler if it has one.
588    pub commands: Commands<Option<CommandFn>>,
589    /// Shared with the `pop.pointer.profile` listener, which loads the
590    /// profile's bindings into it.
591    pub keymap: Rc<RefCell<Keymap>>,
592    pub menus: Menus,
593    pub panels: Panels,
594    pub hooks: OwnedList<Hook>,
595    pub lifecycle: OwnedList<(On, LifecycleFn)>,
596    pub settings: Registry<SettingId, String>,
597    /// Icons set on commands another plugin may own
598    /// (`Ctx::command_icon`), applied in contribution order.
599    pub command_icons: OwnedList<CommandIcon>,
600    /// Commands the application offers to agents whatever they declare
601    /// (`AppBuilder::offer_command_to_agents`).
602    pub offered: BTreeSet<CommandId>,
603}
604
605/// An icon set on a command whoever declared it (`Ctx::command_icon`):
606/// it replaces the command's `icon` and `icon_on`.
607#[derive(Clone, Debug, PartialEq)]
608pub(crate) struct CommandIcon {
609    pub command: CommandId,
610    pub icon: String,
611    pub icon_on: Option<String>,
612}
613
614impl Registries {
615    fn new() -> Self {
616        Self {
617            commands: Commands::new(),
618            keymap: Rc::new(RefCell::new(Keymap::new())),
619            menus: Menus::new(),
620            panels: Panels::new(),
621            hooks: OwnedList::new(),
622            lifecycle: OwnedList::new(),
623            settings: Registry::new(),
624            command_icons: OwnedList::new(),
625            offered: BTreeSet::new(),
626        }
627    }
628
629    /// Removes what an owner registered; the commands removed.
630    fn remove_owner(&mut self, owner: &OwnerId) -> Vec<CommandId> {
631        let commands = self.commands.remove_owner(owner);
632        self.keymap.borrow_mut().remove_owner(owner);
633        self.menus.remove_owner(owner);
634        self.panels.remove_owner(owner);
635        self.hooks.remove_owner(owner);
636        self.lifecycle.remove_owner(owner);
637        self.settings.remove_owner(owner);
638        self.command_icons.remove_owner(owner);
639        commands
640    }
641}
642
643/// Who owns the workspace's layer of keys (`AppHandle::load_keymap`,
644/// `AppHandle::rebind_in`).
645const WORKSPACE_KEYS: OwnerId = OwnerId::from_static("workspace");
646
647/// The owner of the keys a layer loads or changes: the user's or the
648/// workspace's; `None` for the others.
649fn layer_owner(layer: Layer) -> Option<OwnerId> {
650    match layer {
651        Layer::User => Some(OwnerId::USER),
652        Layer::Workspace => Some(WORKSPACE_KEYS),
653        Layer::Suggestion | Layer::Default => None,
654    }
655}
656
657/// How the host names where a binding comes from.
658type KeySourceNames = Rc<dyn Fn(&Binding) -> Option<String>>;
659
660/// Declarations derived from the registries, after the alter hooks.
661#[derive(Clone, Debug, Default)]
662pub(crate) struct Derived {
663    pub menus: BTreeMap<MenuId, Vec<MenuItem>>,
664    pub palette: Vec<PaletteEntry>,
665    pub settings: Vec<SettingEntry>,
666    /// Each owner's section title, before the hooks (a plugin's title).
667    pub sections: BTreeMap<OwnerId, String>,
668    pub commands: Vec<(CommandSpec, OwnerId)>,
669    /// The commands whose icon a plugin other than their owner set
670    /// (`Ctx::command_icon`), with that plugin: the last one wins.
671    pub icons_set_by: BTreeMap<CommandId, OwnerId>,
672    /// Every declared panel with its owner, in declaration order.
673    pub panels: Vec<(egui_pop_model::panels::PanelSpec, OwnerId)>,
674    /// Each command's live key bindings, as shown.
675    pub keys: BTreeMap<CommandId, Vec<String>>,
676    /// Each command's live bindings, with the layer each comes from.
677    pub sources: BTreeMap<CommandId, Vec<Binding>>,
678    /// Bindings losing to another on the same keys: loser, winner.
679    pub conflicts: Vec<(Binding, Binding)>,
680    /// The live bindings of the system scope (global shortcuts).
681    pub system: Vec<Binding>,
682    /// The bindings kept dormant: their command went with a plugin.
683    pub dormant: Vec<DormantKey>,
684    /// Each layer's bindings, as saved (what `export_keymap` gives).
685    pub layers: BTreeMap<Layer, egui_pop_model::keymap::KeymapDoc>,
686    /// Commands whose keys the user changed.
687    pub rebound: BTreeSet<CommandId>,
688    /// Commands whose keys were changed for the workspace.
689    pub rebound_workspace: BTreeSet<CommandId>,
690}
691
692/// A key binding kept dormant (ADR 0028): its command went with a plugin
693/// now disconnected. It stays in its layer, saved, takes no key, and is
694/// live again when the plugin reconnects.
695#[derive(Clone, Debug, PartialEq, serde::Serialize)]
696#[non_exhaustive]
697pub struct DormantKey {
698    /// The binding: its keys, the command it runs, its layer and owner.
699    pub binding: Binding,
700    /// The disconnected plugin its command went with.
701    pub plugin: PluginId,
702    /// The plugin's title, as a shortcuts editor names it.
703    pub plugin_title: String,
704}
705
706/// What a block or a handler asks of the application, done before the
707/// next frame.
708// A declaration carries a whole `CommandSpec`; requests are few and short
709// lived, so it is not boxed (boxing would change the public variant).
710#[allow(
711    clippy::large_enum_variant,
712    reason = "a declaration carries a whole CommandSpec; requests are few and short lived, and boxing would change the public variant"
713)]
714#[derive(Clone, Debug, PartialEq)]
715pub enum Request {
716    Run {
717        command: CommandId,
718        args: Json,
719        origin: Origin,
720    },
721    /// A command run in a given context (a menu opened there).
722    RunIn {
723        command: CommandId,
724        args: Json,
725        origin: Origin,
726        context: WhenContext,
727    },
728    Enable(PluginId, bool),
729    /// Gives a command keys of its own in a layer, the user's or the
730    /// workspace's (none: no key).
731    Rebind {
732        command: CommandId,
733        keys: Option<String>,
734        layer: Layer,
735    },
736    /// Gives a command several keys at once (a pointer gesture keeping
737    /// its other triggers).
738    RebindAll {
739        command: CommandId,
740        keys: Vec<String>,
741        layer: Layer,
742    },
743    /// Takes back what a layer (the user's or the workspace's) changed
744    /// of a command's keys.
745    ResetKeys {
746        command: CommandId,
747        layer: Layer,
748    },
749    /// Declares a command after build (`AppHandle::declare`).
750    Declare {
751        owner: OwnerId,
752        spec: CommandSpec,
753    },
754    /// Removes a command declared after build.
755    Undeclare(CommandId),
756    /// Loads a keymap document into a layer.
757    LoadKeymap {
758        doc: egui_pop_model::keymap::KeymapDoc,
759        layer: Layer,
760    },
761    /// A workbench change asked for while the areas were drawn.
762    ///
763    /// <div class="warning">Experimental: may change in any release
764    /// (docs/stability.md).</div>
765    Workbench(crate::workbench::Change),
766}
767
768struct PanelView {
769    owner: OwnerId,
770    draw: Option<PanelDraw>,
771}
772
773/// How a panel is drawn: plainly, or told which instance it draws.
774pub(crate) enum PanelDraw {
775    Plain(DrawFn),
776    Instance(crate::workbench::instances::InstanceDrawFn),
777}
778
779struct StoryEntry {
780    story: Story,
781}
782
783/// An event waiting for the host: source, cause, name, data.
784type Held = (String, Option<Seq>, String, Json);
785
786pub(crate) struct Shared {
787    ctx: RefCell<Context>,
788    store: SharedStore,
789    services: RefCell<Services>,
790    zones: RefCell<ZoneTable>,
791    panels: RefCell<BTreeMap<PanelId, PanelView>>,
792    stories: RefCell<Registry<StoryId, StoryEntry>>,
793    requests: RefCell<Vec<Request>>,
794    /// The origins of the commands running now, innermost last: what a
795    /// command a handler starts inherits (`AppHandle::run`).
796    acting: RefCell<Vec<Origin>>,
797    context: RefCell<WhenContext>,
798    workbench: RefCell<crate::workbench::Workbench>,
799    /// Indicators fed by the journal, and the last event fed.
800    indicators: RefCell<OwnedList<(crate::strips::Indicator, crate::strips::IndicatorState)>>,
801    indicators_seen: std::cell::Cell<Seq>,
802    /// The areas are being drawn: workbench changes wait for the frame's
803    /// end.
804    drawing_areas: std::cell::Cell<bool>,
805    /// The centre drawn without margins.
806    edge_to_edge: std::cell::Cell<bool>,
807    /// The areas drawn without a frame (`AppBuilder::frameless`).
808    frameless: RefCell<Vec<Area>>,
809    /// The side areas whose folded strip is bare (`AppBuilder::bare_strips`).
810    bare_strips: RefCell<Vec<Area>>,
811    /// The system's text scaling (`AppBuilder::system_text_scale`).
812    system_text_scale: std::cell::Cell<crate::text::SystemTextScale>,
813    /// Whether the system always shows its scroll bars
814    /// (`AppBuilder::system_always_shows_scroll_bars`).
815    system_scroll_bars: std::cell::Cell<bool>,
816    /// The system's lines a wheel's notch (`AppBuilder::system_wheel_lines`).
817    system_wheel_lines: std::cell::Cell<u32>,
818    /// Where the toasts show by default (`AppBuilder::toast_corner`).
819    toast_corner: std::cell::Cell<crate::toasts::Corner>,
820    /// The group handles the application allows
821    /// (`AppBuilder::group_handles`).
822    pub(crate) group_handles: std::cell::Cell<crate::workbench::GroupHandles>,
823    /// The docks' controls (`AppBuilder::dock_controls`).
824    pub(crate) dock_controls: std::cell::Cell<crate::workbench::DockControls>,
825    /// The texts naming an arrangement (`AppBuilder::arrangement_strings`).
826    arrangement_strings: std::cell::Cell<crate::arrangements::ArrangementStrings>,
827    /// The layout's changes egui_stack said on the bus
828    /// (`stack.layout.changed`) and the shell has not read yet.
829    pub(crate) stack_changes: RefCell<Vec<egui_stack::bus::LayoutChange>>,
830    /// The main menu drawn as a bar under the title.
831    menu_bar: std::cell::Cell<bool>,
832    /// The application allows the system's file chooser
833    /// (`AppBuilder::system_file_chooser`).
834    system_file_chooser: std::cell::Cell<bool>,
835    /// Detached panels' windows are built transparent where the platform
836    /// gives a surface below them (`AppBuilder::transparent_panel_windows`).
837    transparent_panel_windows: std::cell::Cell<bool>,
838    /// Whether the decorated windows are built transparent for rounded
839    /// corners (`AppBuilder::rounded_windows`).
840    rounded_windows: std::cell::Cell<bool>,
841    /// The window the user worked in last (focused, clicked or typed
842    /// in): a dialog opens over it.
843    /// The shell panels' starting sizes (`AppBuilder::shell_panel_size`).
844    shell_sizes: RefCell<Vec<(PanelId, f32)>>,
845    /// The shell panels' least and largest sizes
846    /// (`AppBuilder::shell_panel_min_size`, `shell_panel_max_size`).
847    shell_bounds: RefCell<Vec<(PanelId, crate::workbench::ShellBounds)>>,
848    /// The centre's least width (`AppBuilder::centre_min_size`).
849    centre_min: std::cell::Cell<Option<crate::workbench::ShellSize>>,
850    /// The panels' commands and their shared texts, installed on each
851    /// context drawing the application.
852    pub(crate) panel_commands: RefCell<strings::PanelCommands>,
853    /// The application's name (`AppBuilder::name`).
854    name: RefCell<String>,
855    /// The application's id (`AppBuilder::app_id`).
856    app_id: RefCell<String>,
857    diagnostics: RefCell<Diagnostics>,
858    derived: RefCell<Derived>,
859    plugins: RefCell<Vec<PluginInfo>>,
860    history: RefCell<Vec<Run>>,
861    bridge: RefCell<DebugBridge>,
862    traces: RefCell<Vec<Trace>>,
863    pending_keys: RefCell<Option<String>>,
864    /// The host; out of its cell while it dispatches.
865    host: RefCell<Option<Box<dyn Host>>>,
866    /// The host's history groups (`Host::groups`) while it dispatches.
867    dispatch_groups: RefCell<Option<Rc<dyn crate::host::Groups>>>,
868    /// The commands of plugins disconnected, by the plugin that took
869    /// them away: a run of one is refused naming it, a toast's action
870    /// naming one is greyed (ADR 0028).
871    gone_commands: RefCell<BTreeMap<CommandId, PluginId>>,
872    /// Events published while the host was dispatching.
873    held: RefCell<Vec<Held>>,
874    /// The journal kept for a host that keeps none.
875    journal: RefCell<crate::host::Journal>,
876    /// egui-pop's journal is the bus's (`crate::bus::HOST_JOURNAL`): the
877    /// bus offers the journal capability and the host keeps no journal
878    /// of its own (the default host keeps none then).
879    journal_on_bus: std::cell::Cell<bool>,
880    /// Commands whose result is to come, by id: how many.
881    running: RefCell<BTreeMap<CommandId, usize>>,
882    /// When each running command's oldest run started (motion clock).
883    running_since: RefCell<BTreeMap<CommandId, f64>>,
884    /// Collectors added by plugins.
885    collectors: RefCell<Vec<(OwnerId, String)>>,
886    /// A shortcuts editor waits for keys: the dispatcher stands aside.
887    capturing: std::cell::Cell<bool>,
888    /// The main window's paint guard ([`crate::paint_guard`]).
889    pub(crate) paint_guard: RefCell<crate::paint_guard::Guard>,
890    /// The shortcuts editor offers to change keys for the workspace.
891    workspace_keys: std::cell::Cell<bool>,
892    /// How the host names where a binding comes from.
893    key_source_names: RefCell<Option<KeySourceNames>>,
894    /// Declared steps (ADR 0011), their hooks, their last runs.
895    steps: RefCell<Registry<StepId, StepSpec>>,
896    step_hooks: RefCell<OwnedList<StepHook>>,
897    step_traces: RefCell<std::collections::VecDeque<StepTrace>>,
898    /// List providers, by list name, and what each gave last.
899    lists: RefCell<OwnedList<crate::menus::Provider>>,
900    list_traces: RefCell<BTreeMap<String, crate::menus::ListTrace>>,
901    /// The menu open as a popup (`menus::popup_at`).
902    popup: RefCell<Option<crate::menus::Popup>>,
903    /// Documents written a short while after their last change, when a
904    /// persistence directory was given.
905    writer: RefCell<Option<Writer>>,
906    /// State a module keeps on the application side, by type: what is
907    /// neither `Send` nor a service (custom dialogs' bodies, the mount
908    /// registry).
909    locals: RefCell<BTreeMap<std::any::TypeId, Rc<dyn std::any::Any>>>,
910    /// The context stack's projection is writing its keys.
911    stack_writing: std::cell::Cell<bool>,
912    /// The commands running now, innermost last, with their owners.
913    running_commands: RefCell<Vec<(CommandId, Option<OwnerId>)>>,
914    /// The application windows (`AppHandle::open_window`).
915    pub(crate) windows: RefCell<crate::windows::Windows>,
916    /// The bus: the hook kernel of the requests' listeners and the window
917    /// registry (ADR 0029).
918    pub(crate) bus: crate::bus::Bus,
919    /// The keymap as last rebuilt, for the windows dispatching their keys
920    /// in their own pass.
921    keymap: RefCell<Rc<Keymap>>,
922}
923
924/// Marks a command as running while it lives (what reports name, as
925/// the context stack's hand writes).
926struct RunningCommand(AppHandle);
927
928impl RunningCommand {
929    fn new(app: &AppHandle, command: &CommandId, owner: Option<&OwnerId>) -> Self {
930        app.0
931            .running_commands
932            .borrow_mut()
933            .push((command.clone(), owner.cloned()));
934        RunningCommand(app.clone())
935    }
936}
937
938impl Drop for RunningCommand {
939    fn drop(&mut self) {
940        self.0.0.running_commands.borrow_mut().pop();
941    }
942}
943
944/// The application at run time, cheap to clone: blocks, panels, stories
945/// and command handlers reach services, the store and the command runner
946/// through it.
947#[derive(Clone)]
948pub struct AppHandle(pub(crate) Rc<Shared>);
949
950impl fmt::Debug for AppHandle {
951    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
952        f.debug_struct("AppHandle").finish_non_exhaustive()
953    }
954}
955
956/// A handle that does not keep the application alive (for collectors).
957#[derive(Clone)]
958pub(crate) struct WeakApp(Weak<Shared>);
959
960impl WeakApp {
961    pub(crate) fn get(&self) -> Result<AppHandle, String> {
962        self.0
963            .upgrade()
964            .map(AppHandle)
965            .ok_or_else(|| "the application is gone".to_string())
966    }
967}
968
969impl AppHandle {
970    pub(crate) fn downgrade(&self) -> WeakApp {
971        WeakApp(self.weak())
972    }
973
974    fn new(
975        ctx: &Context,
976        host: Box<dyn Host>,
977        default_host: bool,
978        bus: Option<Arc<dyn crate::bus::bus_contract::Bus>>,
979    ) -> Self {
980        let store = host.store();
981        let keeps_journal = !default_host && host.last_seq().is_some();
982        let handle = AppHandle(Rc::new(Shared {
983            ctx: RefCell::new(ctx.clone()),
984            store,
985            services: RefCell::new(Services::default()),
986            zones: RefCell::new(ZoneTable::default()),
987            panels: RefCell::new(BTreeMap::new()),
988            stories: RefCell::new(Registry::new()),
989            requests: RefCell::new(Vec::new()),
990            acting: RefCell::new(Vec::new()),
991            context: RefCell::new(WhenContext::new()),
992            workbench: RefCell::new(crate::workbench::Workbench::default()),
993            indicators: RefCell::new(OwnedList::new()),
994            indicators_seen: std::cell::Cell::new(0),
995            drawing_areas: std::cell::Cell::new(false),
996            edge_to_edge: std::cell::Cell::new(false),
997            frameless: RefCell::new(Vec::new()),
998            bare_strips: RefCell::new(Vec::new()),
999            system_text_scale: std::cell::Cell::default(),
1000            system_scroll_bars: std::cell::Cell::default(),
1001            system_wheel_lines: std::cell::Cell::new(crate::pointer::SYSTEM_WHEEL_LINES),
1002            toast_corner: std::cell::Cell::default(),
1003            group_handles: std::cell::Cell::new(crate::workbench::DEFAULT_GROUP_HANDLES),
1004            dock_controls: std::cell::Cell::default(),
1005            arrangement_strings: std::cell::Cell::default(),
1006            stack_changes: RefCell::new(Vec::new()),
1007            menu_bar: std::cell::Cell::new(true),
1008            system_file_chooser: std::cell::Cell::new(false),
1009            transparent_panel_windows: std::cell::Cell::new(false),
1010            rounded_windows: std::cell::Cell::new(false),
1011            shell_sizes: RefCell::default(),
1012            shell_bounds: RefCell::default(),
1013            centre_min: std::cell::Cell::new(None),
1014            panel_commands: RefCell::default(),
1015            name: RefCell::default(),
1016            app_id: RefCell::default(),
1017            diagnostics: RefCell::new(Diagnostics::new()),
1018            derived: RefCell::new(Derived::default()),
1019            plugins: RefCell::new(Vec::new()),
1020            history: RefCell::new(Vec::new()),
1021            bridge: RefCell::new(DebugBridge::with_core_collectors()),
1022            traces: RefCell::new(Vec::new()),
1023            pending_keys: RefCell::new(None),
1024            host: RefCell::new(Some(host)),
1025            dispatch_groups: RefCell::new(None),
1026            gone_commands: RefCell::new(BTreeMap::new()),
1027            held: RefCell::new(Vec::new()),
1028            journal: RefCell::new(crate::host::Journal::default()),
1029            journal_on_bus: std::cell::Cell::new(false),
1030            running: RefCell::new(BTreeMap::new()),
1031            running_since: RefCell::new(BTreeMap::new()),
1032            collectors: RefCell::new(Vec::new()),
1033            capturing: std::cell::Cell::new(false),
1034            paint_guard: RefCell::default(),
1035            workspace_keys: std::cell::Cell::new(false),
1036            key_source_names: RefCell::new(None),
1037            steps: RefCell::new(Registry::new()),
1038            step_hooks: RefCell::new(OwnedList::new()),
1039            step_traces: RefCell::new(std::collections::VecDeque::new()),
1040            lists: RefCell::new(OwnedList::new()),
1041            list_traces: RefCell::new(BTreeMap::new()),
1042            popup: RefCell::new(None),
1043            writer: RefCell::new(None),
1044            locals: RefCell::new(BTreeMap::new()),
1045            stack_writing: std::cell::Cell::new(false),
1046            running_commands: RefCell::new(Vec::new()),
1047            windows: RefCell::default(),
1048            bus: crate::bus::Bus::new(bus),
1049            keymap: RefCell::default(),
1050        }));
1051        // One journal per process: the bus's, when it offers one and the
1052        // host keeps none of its own.
1053        let kernel = &handle.0.bus.kernel;
1054        if kernel.journal().is_some() && !keeps_journal {
1055            match crate::bus::bus_contract::declare_all(&**kernel, &[crate::bus::HOST_JOURNAL])
1056                .into_iter()
1057                .next()
1058            {
1059                None => handle.0.journal_on_bus.set(true),
1060                Some(refused) => {
1061                    log::error!(target: "egui_pop", "{refused}: egui-pop keeps its own journal");
1062                }
1063            }
1064        }
1065        // The host says its jobs on `pop.job.event`.
1066        if let Some(h) = handle.0.host.borrow_mut().as_mut() {
1067            h.set_job_publisher(handle.0.bus.jobs.clone());
1068        }
1069        // Every setting changed is said once on the bus.
1070        crate::bus::settings::hear(&mut lock(&handle.0.store), &handle.0.bus.settings_heard);
1071        handle
1072    }
1073
1074    /// The state of type `T` kept on the application side, made on first
1075    /// use: one value per type and per application, shared by its windows
1076    /// and gone with it. A plugin or a host keeps its own state there
1077    /// under a type of its own (a private type keeps others out).
1078    pub fn local<T: Default + 'static>(&self) -> Rc<T> {
1079        let id = std::any::TypeId::of::<T>();
1080        let any = self
1081            .0
1082            .locals
1083            .borrow_mut()
1084            .entry(id)
1085            .or_insert_with(|| Rc::new(T::default()) as Rc<dyn std::any::Any>)
1086            .clone();
1087        any.downcast::<T>()
1088            .unwrap_or_else(|_| unreachable!("kept under its own type"))
1089    }
1090
1091    /// Records a diagnostic found at run time (ADR 0003).
1092    pub(crate) fn report_diagnostic(&self, d: Diagnostic) {
1093        self.0.diagnostics.borrow_mut().push(d);
1094    }
1095
1096    fn weak(&self) -> Weak<Shared> {
1097        Rc::downgrade(&self.0)
1098    }
1099
1100    /// The debug bridge's collectors, their descriptions and actions.
1101    pub fn debug_describe(&self) -> Json {
1102        self.0.bridge.borrow().describe()
1103    }
1104
1105    /// Every capability an agent may name, as one list of
1106    /// [`PROTOCOL`](egui_pop_core::debug::PROTOCOL) 1:
1107    /// `{ "protocol", "capabilities": [..] }`. The collectors' actions
1108    /// (`kind: "action"`, see `DebugBridge::capabilities`), then every
1109    /// command (`kind: "command"`, `name` its id, called through
1110    /// `commands.run` with `{ "id", "args" }`): `description`,
1111    /// `mutates` (not read-only), `agent`, `args` (a JSON Schema, or
1112    /// `null`), `example` (its free description of the arguments when
1113    /// not a schema), `result` (`null`) and `call`. `bridge.describe`
1114    /// answers it to an agent.
1115    pub fn debug_capabilities(&self) -> Json {
1116        use egui_pop_core::debug::{PROTOCOL, is_schema};
1117        let mut caps = self.0.bridge.borrow().capabilities();
1118        for (s, _) in self.commands() {
1119            let (args, example) = if is_schema(&s.args) {
1120                (s.args.clone(), Json::Null)
1121            } else {
1122                (Json::Null, s.args.clone())
1123            };
1124            caps.push(json!({
1125                "kind": "command",
1126                "name": s.id,
1127                "title": s.title,
1128                "description": s.description,
1129                "mutates": !s.read_only,
1130                "agent": s.agent,
1131                "destructive": s.destructive,
1132                // The calls destructive by their arguments, when the
1133                // command is not destructive whole.
1134                "destructive_if": s.destructive_if,
1135                "private": s.private,
1136                "args": args,
1137                "example": example,
1138                "result": Json::Null,
1139                "call": { "collector": "commands", "action": "run", "id": s.id },
1140            }));
1141        }
1142        // The windows an agent may name (`window` on `call` and
1143        // `snapshot`), the main one first.
1144        let windows: Vec<Json> = self
1145            .windows()
1146            .into_iter()
1147            .map(|w| json!({ "id": w.id, "title": w.title, "main": w.main, "active": w.active }))
1148            .collect();
1149        json!({ "protocol": PROTOCOL, "capabilities": caps, "windows": windows })
1150    }
1151
1152    /// A bridge call, outside any step. `bridge.describe` lists the
1153    /// bridge itself, so it is answered here, the bridge not borrowed.
1154    fn bridge_call_as(
1155        &self,
1156        collector: &str,
1157        action: &str,
1158        args: &Json,
1159        origin: &Origin,
1160    ) -> Feedback {
1161        if collector == BRIDGE && action == "describe" {
1162            let refused = self
1163                .0
1164                .bridge
1165                .borrow()
1166                .refusal(collector, action, args, origin);
1167            if refused.is_none() {
1168                let f = Feedback {
1169                    ok: true,
1170                    collector: collector.into(),
1171                    action: action.into(),
1172                    mutates: false,
1173                    message: format!("`{collector}.{action}` read"),
1174                    data: self.debug_capabilities(),
1175                };
1176                self.0.bridge.borrow_mut().record(f.clone());
1177                return f;
1178            }
1179        }
1180        self.0
1181            .bridge
1182            .borrow_mut()
1183            .call_as(&self.egui(), collector, action, args, origin)
1184    }
1185
1186    /// The number of requests queued for the next frame (commands to
1187    /// run, plugins to connect...).
1188    pub(crate) fn queued_requests(&self) -> usize {
1189        self.0.requests.borrow().len()
1190    }
1191
1192    /// The debug bridge's mode now ([`AppBuilder::debug_bridge`]): what
1193    /// it lets anyone but the user do. A transport out of the process
1194    /// (`egui-pop-agent`) reads it to refuse snapshots when it is `Off`.
1195    pub fn debug_bridge_mode(&self) -> egui_pop_core::debug::BridgeMode {
1196        self.0.bridge.borrow().mode()
1197    }
1198
1199    /// Every collector's snapshot.
1200    pub fn debug_snapshot(&self) -> Json {
1201        self.0.bridge.borrow().snapshot(&self.egui())
1202    }
1203
1204    /// The window group an agent's call names (an application window's
1205    /// id, `main` for the main window), or the active window's without
1206    /// one (ADR 0025).
1207    pub fn window_group_named(&self, window: Option<&str>) -> Result<egui::ViewportId, String> {
1208        match window {
1209            None => Ok(self.window_group(self.active_window())),
1210            Some(w) => {
1211                let id = crate::windows::WindowId::new(w);
1212                let viewport = if w == crate::windows::WindowId::MAIN {
1213                    Some(egui::ViewportId::ROOT)
1214                } else {
1215                    self.window_viewport(&id)
1216                };
1217                viewport
1218                    .map(|v| self.window_group(v))
1219                    .ok_or_else(|| format!("no open window `{w}`"))
1220            }
1221        }
1222    }
1223
1224    /// Why `args` may not run `command`: they do not match its JSON
1225    /// Schema (`CommandSpec::schema`), as `refused by
1226    /// `pop.command.args`: ...`. `None` when they match, when its
1227    /// arguments are only described, or for a command that is not there.
1228    /// Every run is checked so before its handler; this asks before (the
1229    /// bridge's `commands.run`, to answer an agent at once).
1230    pub fn command_args_refusal(&self, command: &CommandId, args: &Json) -> Option<String> {
1231        let commands = self.commands();
1232        let (spec, _) = commands.iter().find(|(s, _)| &s.id == command)?;
1233        crate::bus::args_refusal(spec, args)
1234            .map(|r| format!("refused by `{}`: {r}", crate::bus::ARGS_VALIDATOR))
1235    }
1236
1237    /// Whether this bridge call destroys or discards what cannot easily
1238    /// be had back: an action declared so, `commands.run` of a
1239    /// destructive command (`CommandSpec::destructive`) or of a call its
1240    /// arguments make destructive (`CommandSpec::destructive_if`). The agent
1241    /// socket asks the user before it runs such a call for an agent.
1242    pub fn debug_destructive(&self, collector: &str, action: &str, args: &Json) -> bool {
1243        self.0.bridge.borrow().destructive(collector, action, args)
1244    }
1245
1246    /// Whether this bridge call changes the application (its collector
1247    /// says so for these arguments); `true` for an action the bridge
1248    /// does not know, as a call treats it. The agent socket's grants
1249    /// hold a read-only agent to the calls that do not.
1250    pub fn debug_mutates(&self, collector: &str, action: &str, args: &Json) -> bool {
1251        self.0
1252            .bridge
1253            .borrow()
1254            .mutates(collector, action, args)
1255            .unwrap_or(true)
1256    }
1257
1258    /// Why `origin` may not make this bridge call (its mode, the
1259    /// action's `agent` flag), `None` when it may or when there is no
1260    /// such action. The call itself is refused the same way; this asks
1261    /// before (the agent socket, before asking the user to confirm).
1262    pub fn debug_refusal(
1263        &self,
1264        collector: &str,
1265        action: &str,
1266        args: &Json,
1267        origin: &Origin,
1268    ) -> Option<String> {
1269        self.0
1270            .bridge
1271            .borrow()
1272            .refusal(collector, action, args, origin)
1273    }
1274
1275    /// Every collector's snapshot, seen from a window (an application
1276    /// window's id; the active window without one): the dialog shown
1277    /// there, the context its commands run in.
1278    pub fn debug_snapshot_in(&self, window: Option<&str>) -> Result<Json, String> {
1279        let group = self.window_group_named(window)?;
1280        let _group = crate::windows::enter_group(Some(group));
1281        Ok(self.debug_snapshot())
1282    }
1283
1284    /// Calls a collector's action for `origin` in a window (an
1285    /// application window's id; the active window without one): a
1286    /// command runs in that window's context (`appWindow`, `modalOpen`),
1287    /// and what it opens (a dialog, a toast, the palette) shows there;
1288    /// `dialogs.answer` answers the dialog shown there.
1289    pub fn debug_call_in(
1290        &self,
1291        window: Option<&str>,
1292        collector: &str,
1293        action: &str,
1294        args: &Json,
1295        origin: Origin,
1296    ) -> Feedback {
1297        let group = match self.window_group_named(window) {
1298            Ok(g) => g,
1299            Err(e) => {
1300                return Feedback {
1301                    ok: false,
1302                    collector: collector.into(),
1303                    action: action.into(),
1304                    mutates: false,
1305                    message: e,
1306                    data: Json::Null,
1307                };
1308            }
1309        };
1310        let _group = crate::windows::enter_group(Some(group));
1311        self.debug_call_as(collector, action, args, origin)
1312    }
1313
1314    /// Calls a collector's action as the agent
1315    /// (`Origin::Agent("debug-bridge")`); always returns a feedback
1316    /// block. An action not offered to agents is refused, and every
1317    /// call goes through the [`STEP_DEBUG_CALL`] step (see
1318    /// [`AppHandle::debug_call_as`]). `commands.run` is queued here (the
1319    /// App runs it before the next frame); `App::debug_call` runs it at
1320    /// once.
1321    pub fn debug_call(&self, collector: &str, action: &str, args: &Json) -> Feedback {
1322        self.debug_call_as(collector, action, args, egui_pop_core::debug::agent())
1323    }
1324
1325    /// Calls a collector's action for `origin`: the agent's calls go
1326    /// through [`AppHandle::debug_call`], the user's (the devtools
1327    /// panel, a debug page) come here with `Origin::User`. Only the user
1328    /// may call an action not offered to agents: for anyone else it is
1329    /// refused, in the bridge's log and on the journal
1330    /// (`debug.call.refused`, from the caller). Every other call runs
1331    /// through the [`STEP_DEBUG_CALL`] step, which a plugin may veto
1332    /// (`debug.call.vetoed` on the journal).
1333    pub fn debug_call_as(
1334        &self,
1335        collector: &str,
1336        action: &str,
1337        args: &Json,
1338        origin: Origin,
1339    ) -> Feedback {
1340        let (spec, refusal, mutates) = {
1341            let b = self.0.bridge.borrow();
1342            (
1343                b.action(collector, action),
1344                b.refusal(collector, action, args, &origin),
1345                b.mutates(collector, action, args).unwrap_or(true),
1346            )
1347        };
1348        if spec.is_none() {
1349            // No such action: the bridge's answer lists what exists.
1350            return self.0.bridge.borrow_mut().call_as(
1351                &self.egui(),
1352                collector,
1353                action,
1354                args,
1355                &origin,
1356            );
1357        }
1358        let source = source_of(&origin);
1359        // A private command's arguments are private data: its call's
1360        // events and trace are marked so, as the command's own are, and
1361        // readers that do not read private data get them redacted
1362        // (`host::redact_private`).
1363        let private = self.call_is_private(collector, action, args);
1364        if let Some(reason) = refusal {
1365            let feedback =
1366                self.0
1367                    .bridge
1368                    .borrow_mut()
1369                    .call_as(&self.egui(), collector, action, args, &origin);
1370            let mut refused =
1371                json!({ "collector": collector, "action": action, "args": args, "reason": reason });
1372            if private {
1373                refused[crate::steps::PRIVATE] = Json::Bool(true);
1374            }
1375            self.publish(&source, None, "debug.call.refused", refused);
1376            return feedback;
1377        }
1378        let mut ran: Option<Feedback> = None;
1379        let mut asked =
1380            json!({ "collector": collector, "action": action, "args": args, "origin": source });
1381        if private {
1382            asked[crate::steps::PRIVATE] = Json::Bool(true);
1383        }
1384        // A call that only reads is not published nor traced when it runs
1385        // (an agent polling would fill both); its veto and its failure
1386        // are.
1387        let out = self.step_with(&STEP_DEBUG_CALL, asked, !mutates, |app, a| {
1388            let f = app.bridge_call_as(
1389                a["collector"].as_str().unwrap_or_default(),
1390                a["action"].as_str().unwrap_or_default(),
1391                &a["args"],
1392                // The caller stays who it is, whatever a redirection says.
1393                &origin,
1394            );
1395            // Only the message: the data may be large (the journal's own
1396            // events, for `journal.since`).
1397            let result = if f.ok {
1398                Ok(json!({ "message": f.message }))
1399            } else {
1400                Err(f.message.clone())
1401            };
1402            ran = Some(f);
1403            result
1404        });
1405        let feedback = |ok: bool, message: String, data: Json| Feedback {
1406            ok,
1407            collector: collector.into(),
1408            action: action.into(),
1409            mutates,
1410            message,
1411            data,
1412        };
1413        let feedback = match out {
1414            Outcome::Done(result) => match ran {
1415                Some(f) => return f,
1416                // A plugin's run-hook did it instead.
1417                None => match result {
1418                    Ok(data) => feedback(
1419                        true,
1420                        format!("`{collector}.{action}` done by a plugin"),
1421                        data,
1422                    ),
1423                    Err(e) => feedback(
1424                        false,
1425                        format!("`{collector}.{action}` failed: {e}"),
1426                        Json::Null,
1427                    ),
1428                },
1429            },
1430            Outcome::Vetoed { by, reason } => feedback(
1431                false,
1432                format!("`{collector}.{action}` vetoed by {by}: {reason}"),
1433                Json::Null,
1434            ),
1435        };
1436        self.0.bridge.borrow_mut().record(feedback.clone());
1437        feedback
1438    }
1439
1440    /// Whether a bridge call carries a private command's arguments:
1441    /// `commands.run` of a command declared private, or of one no longer
1442    /// declared (as the `commands` collector's history counts it).
1443    fn call_is_private(&self, collector: &str, action: &str, args: &Json) -> bool {
1444        if (collector, action) != ("commands", "run") {
1445            return false;
1446        }
1447        args.get("id")
1448            .and_then(Json::as_str)
1449            .and_then(|id| CommandId::new(id).ok())
1450            .is_none_or(|id| self.command(&id).is_none_or(|s| s.private))
1451    }
1452
1453    /// The feedback blocks of the last bridge calls.
1454    pub fn debug_log(&self) -> Vec<Feedback> {
1455        self.0.bridge.borrow().log().cloned().collect()
1456    }
1457
1458    /// The last key resolutions, oldest first.
1459    pub fn key_traces(&self) -> Vec<Trace> {
1460        self.0.traces.borrow().clone()
1461    }
1462
1463    /// The chords of a shortcut in progress.
1464    pub fn pending_keys(&self) -> Option<String> {
1465        self.0.pending_keys.borrow().clone()
1466    }
1467
1468    /// The egui context the application draws in.
1469    pub fn egui(&self) -> Context {
1470        self.0.ctx.borrow().clone()
1471    }
1472
1473    /// Records commands derived from a panel (see
1474    /// `strings::PanelCommand`), installed on the current context now and
1475    /// on each context the application is drawn in.
1476    pub(crate) fn add_panel_commands(
1477        &self,
1478        entries: impl IntoIterator<Item = (String, strings::PanelCommand)>,
1479    ) {
1480        let mut all = self.0.panel_commands.borrow_mut();
1481        Arc::make_mut(&mut all).extend(entries);
1482        strings::set_panel_commands(&self.egui(), all.clone());
1483    }
1484
1485    /// The texts naming an arrangement of the panels, the application's
1486    /// (`AppBuilder::arrangement_strings`) or egui-pop's.
1487    ///
1488    /// <div class="warning">Experimental: may change in any release
1489    /// (docs/stability.md).</div>
1490    pub fn arrangement_strings(&self) -> crate::arrangements::ArrangementStrings {
1491        self.0.arrangement_strings.get()
1492    }
1493
1494    /// The application's name (`AppBuilder::name`); empty when none was
1495    /// given.
1496    pub fn name(&self) -> String {
1497        self.0.name.borrow().clone()
1498    }
1499
1500    /// The application's id (`AppBuilder::app_id`), reverse-DNS
1501    /// (`org.example.App`); empty when none was given.
1502    pub fn app_id(&self) -> String {
1503        self.0.app_id.borrow().clone()
1504    }
1505
1506    /// The value store.
1507    pub fn store(&self) -> SharedStore {
1508        self.0.store.clone()
1509    }
1510
1511    /// The value at `path` in the store, as `T` (`None`: not declared,
1512    /// or not a `T`): `app.value::<f64>("swatch/hue")`.
1513    pub fn value<T: egui_pop_core::binding::Bindable>(&self, path: &str) -> Option<T> {
1514        egui_pop_core::binding::read(&self.0.store, path)
1515    }
1516
1517    /// A setting's value, as `T` (`None`: not declared, or not a `T`):
1518    /// `app.setting::<bool>(&SHOW_CODE)`, read at `settings/<id>`.
1519    pub fn setting<T: egui_pop_core::binding::Bindable>(&self, id: &SettingId) -> Option<T> {
1520        self.value(&id.path())
1521    }
1522
1523    /// The persistence directory (`AppBuilder::persist`), if one was
1524    /// given.
1525    pub fn persist(&self) -> Option<Persist> {
1526        self.0.writer.borrow().as_ref().map(|w| w.persist().clone())
1527    }
1528
1529    /// Writes a document under the persistence directory about a second
1530    /// after its last change (the debounced writer of
1531    /// `egui_pop_core::persist`): offering the same text again does
1532    /// nothing, a new one moves the deadline. `false` without a
1533    /// directory. Pending documents are written at the deadline, by
1534    /// [`AppHandle::flush_documents`] and by `App::save`.
1535    pub fn save_later(&self, name: &str, text: String) -> bool {
1536        let ctx = self.egui();
1537        let now = egui_pop_core::motion::now(&ctx);
1538        let mut w = self.0.writer.borrow_mut();
1539        let Some(w) = w.as_mut() else {
1540            return false;
1541        };
1542        if w.offer(name, text, now) {
1543            ctx.request_repaint_after(std::time::Duration::from_secs_f64(
1544                egui_pop_core::persist::DEBOUNCE,
1545            ));
1546        }
1547        true
1548    }
1549
1550    /// Records that a document's text is on disk (just loaded):
1551    /// [`AppHandle::save_later`] writes it again only once it changes.
1552    pub fn saved_already(&self, name: &str, text: &str) {
1553        if let Some(w) = self.0.writer.borrow_mut().as_mut() {
1554            w.written(name, text);
1555        }
1556    }
1557
1558    /// Writes every document waiting in the debounced writer now; what
1559    /// was written and how it went.
1560    pub fn flush_documents(&self) -> Vec<(String, Result<(), PersistError>)> {
1561        self.0
1562            .writer
1563            .borrow_mut()
1564            .as_mut()
1565            .map(Writer::flush)
1566            .unwrap_or_default()
1567    }
1568
1569    /// The documents waiting in the debounced writer.
1570    pub fn pending_documents(&self) -> Vec<String> {
1571        self.0
1572            .writer
1573            .borrow()
1574            .as_ref()
1575            .map(|w| w.pending().into_iter().map(str::to_string).collect())
1576            .unwrap_or_default()
1577    }
1578
1579    /// Appends an event to the host's journal (held until the host is
1580    /// free when published from a command it is running).
1581    ///
1582    /// <div class="warning">Experimental: may change in any release
1583    /// (docs/stability.md).</div>
1584    pub fn publish(&self, source: &str, cause: Option<Seq>, name: &str, data: Json) {
1585        match self.0.host.borrow_mut().as_mut() {
1586            Some(h) => {
1587                self.publish_to(h.as_mut(), source, cause, name, data);
1588            }
1589            None => self
1590                .0
1591                .held
1592                .borrow_mut()
1593                .push((source.into(), cause, name.into(), data)),
1594        }
1595    }
1596
1597    /// Publishes on the host's journal, or on egui-pop's when the host
1598    /// keeps none.
1599    fn publish_to(
1600        &self,
1601        h: &mut dyn Host,
1602        source: &str,
1603        cause: Option<Seq>,
1604        name: &str,
1605        data: Json,
1606    ) -> Seq {
1607        if let Some(journal) = self.bus_journal() {
1608            match crate::bus::journal::publish(journal, source, cause, name, data) {
1609                Ok(seq) => return seq,
1610                Err(refused) => {
1611                    log::error!(target: "egui_pop", "`{name}` not journaled: {refused}");
1612                    return journal.last_seq();
1613                }
1614            }
1615        }
1616        // The data goes to whichever keeps it: a host keeping no journal
1617        // gets it back unused, so it is cloned only for the fallback.
1618        match h.publish(source, cause, name, data.clone()) {
1619            Some(seq) => seq,
1620            None => self
1621                .0
1622                .journal
1623                .borrow_mut()
1624                .publish(source, cause, name, data),
1625        }
1626    }
1627
1628    /// The journal's events after `seq` (empty while the host is
1629    /// dispatching), read through the host.
1630    ///
1631    /// <div class="warning">Experimental: may change in any release
1632    /// (docs/stability.md).</div>
1633    pub fn events_since(&self, seq: Seq) -> Vec<Event> {
1634        if let Some(journal) = self.bus_journal() {
1635            return journal
1636                .since(seq, usize::MAX)
1637                .entries
1638                .iter()
1639                .map(crate::bus::journal::event_of)
1640                .collect();
1641        }
1642        self.0
1643            .host
1644            .borrow()
1645            .as_ref()
1646            .map(|h| {
1647                h.since(seq)
1648                    .unwrap_or_else(|| self.0.journal.borrow().since(seq))
1649            })
1650            .unwrap_or_default()
1651    }
1652
1653    /// The bus's journal, when it is egui-pop's (`crate::bus::HOST_JOURNAL`).
1654    fn bus_journal(&self) -> Option<&dyn crate::bus::bus_contract_journal::Journal> {
1655        if self.0.journal_on_bus.get() {
1656            self.0.bus.kernel.journal()
1657        } else {
1658            None
1659        }
1660    }
1661
1662    /// Reads the host (`None` while it dispatches a command).
1663    fn with_host<R>(&self, f: impl FnOnce(&dyn Host) -> R) -> Option<R> {
1664        self.0.host.borrow().as_deref().map(f)
1665    }
1666
1667    /// The host's history groups while it dispatches a command.
1668    pub(crate) fn dispatch_groups(&self) -> Option<Rc<dyn crate::host::Groups>> {
1669        self.0.dispatch_groups.borrow().clone()
1670    }
1671
1672    /// Changes the host (`None` while it dispatches a command).
1673    pub(crate) fn with_host_mut<R>(
1674        &self,
1675        f: impl FnOnce(&mut (dyn Host + 'static)) -> R,
1676    ) -> Option<R> {
1677        let mut host = self.0.host.borrow_mut();
1678        host.as_mut().map(|h| f(h.as_mut()))
1679    }
1680
1681    /// Whether Ctrl+Z would undo something now, in the history focus
1682    /// picks (`crate::history::target`; `false` while the host dispatches
1683    /// a command).
1684    pub fn can_undo(&self) -> bool {
1685        crate::history::can_undo(self)
1686    }
1687
1688    /// Whether Ctrl+Shift+Z would redo something now.
1689    pub fn can_redo(&self) -> bool {
1690        crate::history::can_redo(self)
1691    }
1692
1693    /// What an undo would take back ("exposure change").
1694    pub fn undo_label(&self) -> Option<String> {
1695        crate::history::undo_label(self)
1696    }
1697
1698    /// What a redo would do again.
1699    pub fn redo_label(&self) -> Option<String> {
1700        crate::history::redo_label(self)
1701    }
1702
1703    /// A command's title as menus show it now, in the interface's
1704    /// language: the application's live title when it gives one on
1705    /// `pop.command.label` ([`command_text`](Self::command_text)); else
1706    /// the declared title, undo and redo naming what they would do
1707    /// ("Undo exposure change").
1708    pub fn command_title(&self, spec: &CommandSpec) -> String {
1709        if let Some(t) = self.command_text(&spec.id).title {
1710            return t;
1711        }
1712        let ctx = self.egui();
1713        let title = strings::command_title(&ctx, spec.id.as_str(), &spec.title);
1714        let label = if spec.id == CMD_UNDO {
1715            self.undo_label()
1716        } else if spec.id == CMD_REDO {
1717            self.redo_label()
1718        } else {
1719            None
1720        };
1721        match label.filter(|l| !l.is_empty()) {
1722            Some(l) => strings::tr_args(
1723                &ctx,
1724                &crate::strings::COMMAND_WITH_CHANGE,
1725                &[("title", &title), ("change", &l)],
1726            ),
1727            None => title,
1728        }
1729    }
1730
1731    /// A command's tooltip as menus show it now: the application's live
1732    /// tooltip when it gives one on `pop.command.label`
1733    /// ([`command_text`](Self::command_text)), else the declared
1734    /// description, translated (empty stays empty).
1735    pub fn command_tooltip(&self, spec: &CommandSpec) -> String {
1736        match self.command_text(&spec.id).tooltip {
1737            Some(t) => t,
1738            None => strings::command_description(&self.egui(), spec.id.as_str(), &spec.description),
1739        }
1740    }
1741
1742    /// A command's title as a menu, a toolbar or the tray shows it: its
1743    /// [`command_title`](Self::command_title) without the trailing hint of
1744    /// its arguments, which the palette keeps
1745    /// ([`strings::without_argument_hint`]).
1746    pub fn command_menu_title(&self, spec: &CommandSpec) -> String {
1747        strings::without_argument_hint(&self.command_title(spec)).to_string()
1748    }
1749
1750    /// A settings section's title as shown: the owner's plugin title
1751    /// translated (`plugin-<id>.title`), or the section as a hook named
1752    /// it.
1753    pub(crate) fn section_title(&self, ctx: &Context, owner: &OwnerId, section: &str) -> String {
1754        let derived = self.0.derived.borrow();
1755        match derived.sections.get(owner) {
1756            Some(title) if title == section => strings::plugin_title(ctx, owner.as_str(), section),
1757            _ => section.to_string(),
1758        }
1759    }
1760
1761    /// A panel's title as shown (its id when it is not declared).
1762    /// A panel's declared kind: a view when it is not declared.
1763    pub(crate) fn panel_kind(&self, id: &PanelId) -> egui_pop_model::panels::PanelKind {
1764        self.workbench_mut()
1765            .spec(id)
1766            .map(|s| s.kind)
1767            .unwrap_or_default()
1768    }
1769
1770    pub(crate) fn panel_title(&self, ctx: &Context, id: &PanelId) -> String {
1771        // An instance not renamed: its kind's title (translated) and its
1772        // number.
1773        if id.is_instance() {
1774            let renamed = self
1775                .workbench_mut()
1776                .layout
1777                .instance(id)
1778                .and_then(|i| i.title.clone());
1779            if let Some(t) = renamed {
1780                return t;
1781            }
1782            if self.workbench_mut().spec(id).is_some() {
1783                let kind = self.panel_title(ctx, &id.kind());
1784                return format!("{kind} {}", id.instance_number());
1785            }
1786        }
1787        let title = self.workbench_mut().spec(id).map(|s| s.title.clone());
1788        match title {
1789            Some(t) => strings::panel_title(ctx, id.as_str(), &t),
1790            None => id.to_string(),
1791        }
1792    }
1793
1794    /// Undoes through the [`STEP_UNDO`] step, in the history focus
1795    /// picks (`crate::history::undo`): its hooks, then (unless a run-hook
1796    /// replaces it) the owner's undo; the journal says how it went. What
1797    /// `edit.undo` runs.
1798    pub fn undo(&self, origin: &Origin) -> Outcome {
1799        crate::history::undo(self, origin)
1800    }
1801
1802    /// Redoes through the [`STEP_REDO`] step.
1803    pub fn redo(&self, origin: &Origin) -> Outcome {
1804        crate::history::redo(self, origin)
1805    }
1806
1807    /// Every overlay on screen, bottom first, with where it was drawn
1808    /// last: dialogs, modals, popovers and menus of the overlay stack,
1809    /// the toast stack, then egui's popups. What an application keeps
1810    /// its own hit-testing and pictures right with, without egui-pop's
1811    /// internal ids. They are the window's being drawn (the main window
1812    /// outside a pass): each window has its own overlays.
1813    pub fn overlay_rects(&self) -> Vec<OverlayRect> {
1814        let ctx = self.egui();
1815        let dialog = self
1816            .service(&crate::dialogs::DIALOGS)
1817            .and_then(|d| d.current_in(self.window_group(ctx.viewport_id())))
1818            .map(|(id, _)| id);
1819        let mut known: Vec<Id> = Vec::new();
1820        let mut out: Vec<OverlayRect> = overlay::rects(&ctx)
1821            .into_iter()
1822            .map(|(spec, rect)| {
1823                known.push(spec.id);
1824                let (kind, id) = match dialog {
1825                    Some(n) if spec.id == crate::dialogs::overlay_id(n) => {
1826                        (OverlayKind::Dialog, format!("dialog:{n}"))
1827                    }
1828                    _ => (
1829                        match spec.kind {
1830                            overlay::Kind::Modal => OverlayKind::Modal,
1831                            overlay::Kind::Popover => OverlayKind::Popover,
1832                            overlay::Kind::Menu => OverlayKind::Menu,
1833                        },
1834                        spec.label.clone(),
1835                    ),
1836                };
1837                OverlayRect { kind, id, rect }
1838            })
1839            .collect();
1840        // A drop hint not armed is not drawn.
1841        if let Some(hint) = self.drop_hint().filter(|h| h.armed) {
1842            out.push(OverlayRect {
1843                kind: OverlayKind::DropHint,
1844                id: hint.name(),
1845                rect: hint.rect,
1846            });
1847        }
1848        let toasts = crate::toasts::area_id();
1849        known.push(toasts);
1850        // The toasts are drawn in the active window only.
1851        if self.active_window() == ctx.viewport_id()
1852            && self
1853                .service(&crate::toasts::TOASTS)
1854                .is_some_and(|t| !t.shown().is_empty())
1855            && let Some(rect) = ctx.memory(|m| m.area_rect(toasts))
1856        {
1857            out.push(OverlayRect {
1858                kind: OverlayKind::Toasts,
1859                id: "toasts".into(),
1860                rect,
1861            });
1862        }
1863        let mut popups: Vec<(Id, egui::Rect)> = ctx.memory(|m| {
1864            m.areas()
1865                .visible_layer_ids()
1866                .into_iter()
1867                .filter(|l| l.order == egui::Order::Foreground && !known.contains(&l.id))
1868                .filter_map(|l| m.area_rect(l.id).map(|r| (l.id, r)))
1869                .collect()
1870        });
1871        popups.sort_by_key(|a| a.0.value());
1872        let menu = self.popup().map(|p| p.menu);
1873        out.extend(popups.into_iter().map(|(id, rect)| match &menu {
1874            Some(m) if id == crate::menus::popup_id() => OverlayRect {
1875                kind: OverlayKind::Menu,
1876                id: m.to_string(),
1877                rect,
1878            },
1879            _ => OverlayRect {
1880                kind: OverlayKind::Popup,
1881                id: format!("popup:{}", id.short_debug_format()),
1882                rect,
1883            },
1884        }));
1885        out
1886    }
1887
1888    /// The journal's last sequence number, as the host says.
1889    ///
1890    /// <div class="warning">Experimental: may change in any release
1891    /// (docs/stability.md).</div>
1892    pub fn last_event(&self) -> Seq {
1893        if let Some(journal) = self.bus_journal() {
1894            return journal.last_seq();
1895        }
1896        self.0.host.borrow().as_ref().map_or(0, |h| {
1897            h.last_seq()
1898                .unwrap_or_else(|| self.0.journal.borrow().last())
1899        })
1900    }
1901
1902    pub(crate) fn add_collector(&self, owner: &OwnerId, c: FnCollector) -> Result<(), CtxError> {
1903        let name = egui_pop_core::debug::Collector::name(&c).to_string();
1904        self.0
1905            .bridge
1906            .borrow_mut()
1907            .register(c)
1908            .map_err(CtxError::Collector)?;
1909        self.0.collectors.borrow_mut().push((owner.clone(), name));
1910        Ok(())
1911    }
1912
1913    /// Runs a step (ADR 0011): its before-hooks (veto, redirect), its
1914    /// run-hook or `default`, its after-hooks; publishes the step on the
1915    /// journal and keeps a trace. Hooks run without any registry
1916    /// borrowed: they may run other steps or ask for commands.
1917    pub fn step(
1918        &self,
1919        step: &StepId,
1920        args: Json,
1921        default: impl FnOnce(&AppHandle, &Json) -> Result<Json, String>,
1922    ) -> Outcome {
1923        self.step_with(step, args, false, default)
1924    }
1925
1926    /// As [`AppHandle::step`]; `quiet`, a run that succeeds is neither
1927    /// published nor traced (a veto or a failure is).
1928    pub(crate) fn step_with(
1929        &self,
1930        step: &StepId,
1931        args: Json,
1932        quiet: bool,
1933        default: impl FnOnce(&AppHandle, &Json) -> Result<Json, String>,
1934    ) -> Outcome {
1935        let hooks: Vec<(OwnerId, HookFn)> = self
1936            .0
1937            .step_hooks
1938            .borrow()
1939            .iter()
1940            .filter(|s| s.item.step == *step)
1941            .map(|s| (s.owner.clone(), s.item.f.clone()))
1942            .collect();
1943        let declared = self.0.steps.borrow().contains(step);
1944        let (outcome, trace) = crate::steps::run(self, step, args, hooks, declared, quiet, default);
1945        if quiet && outcome.ok() {
1946            return outcome;
1947        }
1948        let mut traces = self.0.step_traces.borrow_mut();
1949        traces.push_back(trace);
1950        while traces.len() > crate::steps::TRACES {
1951            traces.pop_front();
1952        }
1953        outcome
1954    }
1955
1956    /// The declared steps, with their hooks (owner, kind), in
1957    /// declaration order.
1958    pub fn steps(&self) -> Vec<StepInfo> {
1959        let hooks = self.0.step_hooks.borrow();
1960        self.0
1961            .steps
1962            .borrow()
1963            .in_order()
1964            .into_iter()
1965            .map(|(id, slot)| StepInfo {
1966                spec: slot.item.clone(),
1967                owner: slot.owner.clone(),
1968                hooks: hooks
1969                    .iter()
1970                    .filter(|h| h.item.step == *id)
1971                    .map(|h| HookInfo {
1972                        owner: h.owner.clone(),
1973                        kind: h.item.f.kind(),
1974                    })
1975                    .collect(),
1976            })
1977            .collect()
1978    }
1979
1980    /// The last runs of steps, oldest first.
1981    pub fn step_traces(&self) -> Vec<StepTrace> {
1982        self.0.step_traces.borrow().iter().cloned().collect()
1983    }
1984
1985    pub(crate) fn declare_step(&self, owner: &OwnerId, spec: StepSpec) -> Result<(), CtxError> {
1986        let id = spec.id.clone();
1987        self.0
1988            .steps
1989            .borrow_mut()
1990            .insert(owner, id, spec)
1991            .map_err(|t| CtxError::Step {
1992                id: t.id.to_string(),
1993                by: t.by,
1994            })
1995    }
1996
1997    pub(crate) fn add_step_hook(&self, owner: &OwnerId, step: StepId, f: HookFn) {
1998        self.0
1999            .step_hooks
2000            .borrow_mut()
2001            .push(owner, StepHook { step, f });
2002    }
2003
2004    pub(crate) fn add_list_provider(&self, owner: &OwnerId, provider: crate::menus::Provider) {
2005        self.0.lists.borrow_mut().push(owner, provider);
2006    }
2007
2008    /// The entries of a list (`MenuItem::list`), asked of its provider (the
2009    /// last registered for the name) in a context; empty without one.
2010    /// Menus ask when they open; what it gave is kept for the `lists`
2011    /// collector.
2012    pub fn list_items(&self, name: &str, cx: &WhenContext) -> Vec<crate::menus::ListItem> {
2013        let provider = self
2014            .0
2015            .lists
2016            .borrow()
2017            .iter()
2018            .filter(|s| s.item.name == name)
2019            .last()
2020            .map(|s| (s.owner.clone(), s.item.f.clone()));
2021        let Some((owner, f)) = provider else {
2022            return Vec::new();
2023        };
2024        let items = f(self, cx);
2025        self.0.list_traces.borrow_mut().insert(
2026            name.to_string(),
2027            crate::menus::ListTrace {
2028                name: name.to_string(),
2029                owner,
2030                items: items.clone(),
2031            },
2032        );
2033        items
2034    }
2035
2036    /// The list providers (name, owner) and what each gave last.
2037    pub fn lists(&self) -> Json {
2038        let traces = self.0.list_traces.borrow();
2039        json!(
2040            self.0
2041                .lists
2042                .borrow()
2043                .iter()
2044                .map(|s| json!({
2045                    "name": s.item.name,
2046                    "owner": s.owner,
2047                    "last": traces.get(&s.item.name).map(|t| &t.items),
2048                }))
2049                .collect::<Vec<_>>()
2050        )
2051    }
2052
2053    pub(crate) fn popup(&self) -> Option<crate::menus::Popup> {
2054        self.0.popup.borrow().clone()
2055    }
2056
2057    pub(crate) fn set_popup(&self, popup: Option<crate::menus::Popup>) {
2058        *self.0.popup.borrow_mut() = popup;
2059    }
2060
2061    /// Whether a run of this command waits for its result.
2062    pub fn running(&self, id: &CommandId) -> bool {
2063        self.0.running.borrow().get(id).is_some_and(|n| *n > 0)
2064    }
2065
2066    /// When the command's waiting runs started, by the motion clock
2067    /// (`egui_pop_core::motion::now`): what a busy indicator's delay
2068    /// counts from. `None` when no run waits.
2069    pub fn running_since(&self, id: &CommandId) -> Option<f64> {
2070        self.0.running_since.borrow().get(id).copied()
2071    }
2072
2073    /// Whether the host is in its cell (not lent to a dispatch).
2074    pub(crate) fn host_free(&self) -> bool {
2075        self.0.host.try_borrow().is_ok_and(|h| h.is_some())
2076    }
2077
2078    pub(crate) fn publish_now(
2079        &self,
2080        source: &str,
2081        cause: Option<Seq>,
2082        name: &str,
2083        data: Json,
2084    ) -> Seq {
2085        let mut host = self.0.host.borrow_mut();
2086        let h = host.as_mut().expect("the host is free outside a dispatch");
2087        for (s, c, n, d) in self.0.held.borrow_mut().drain(..) {
2088            self.publish_to(h.as_mut(), &s, c, &n, d);
2089        }
2090        self.publish_to(h.as_mut(), source, cause, name, data)
2091    }
2092
2093    /// A service, typed.
2094    pub fn service<T: Send + Sync + 'static>(&self, token: &ServiceToken<T>) -> Option<Arc<T>> {
2095        self.0.services.borrow().get(token)
2096    }
2097
2098    /// The theme service.
2099    pub fn theme(&self) -> Arc<ThemeService> {
2100        self.service(&THEME)
2101            .expect("the framework provides the theme")
2102    }
2103
2104    /// Asks for a command, run before the next frame for whoever the
2105    /// code asking acts for ([`AppHandle::acting_origin`]): the user, or
2106    /// the origin of the command whose handler asks. A command an agent
2107    /// started runs the commands it starts as that agent.
2108    pub fn run(&self, command: CommandId, args: Json) {
2109        self.run_as(command, args, self.acting_origin());
2110    }
2111
2112    /// Asks for a command with an origin. While a command runs for
2113    /// anyone but the user, its handler may not claim the user's origin,
2114    /// and one running for an agent may not claim any other than an
2115    /// agent's: such a request is refused, on the journal
2116    /// (`command.refused`, from the origin acting) and in the log. To act
2117    /// for the user, ask the user (a dialog: the user's answer runs its
2118    /// command as the user).
2119    pub fn run_as(&self, command: CommandId, args: Json, origin: Origin) {
2120        let acting = self.acting_origin();
2121        if let Some(reason) = escalation(&acting, &origin) {
2122            log::warn!(target: "egui_pop", "command `{command}`: {reason}");
2123            self.publish(
2124                &source_of(&acting),
2125                None,
2126                "command.refused",
2127                json!({ "command": command, "origin": source_of(&origin), "reason": reason }),
2128            );
2129            return;
2130        }
2131        // Asked from an application window (its content, a command run
2132        // there): it runs in that window's context.
2133        let group = crate::windows::current_group().map(|g| self.window_group(g));
2134        if group.is_some_and(|g| g != egui::ViewportId::ROOT) {
2135            let context = self.when_context();
2136            self.push_request(Request::RunIn {
2137                command,
2138                args,
2139                origin,
2140                context,
2141            });
2142            return;
2143        }
2144        self.push_request(Request::Run {
2145            command,
2146            args,
2147            origin,
2148        });
2149    }
2150
2151    /// Who the code running now acts for: the origin of the innermost
2152    /// command whose handler (or host dispatch) is running, else the
2153    /// user. A command's handler gets it as `Call::origin` too.
2154    pub fn acting_origin(&self) -> Origin {
2155        self.0
2156            .acting
2157            .borrow()
2158            .last()
2159            .cloned()
2160            .unwrap_or(Origin::User)
2161    }
2162
2163    /// Asks for a plugin to be connected or disconnected before the next
2164    /// frame.
2165    pub fn set_plugin_enabled(&self, plugin: PluginId, enabled: bool) {
2166        self.push_request(Request::Enable(plugin, enabled));
2167    }
2168
2169    pub(crate) fn push_request(&self, r: Request) {
2170        self.0.requests.borrow_mut().push(r);
2171        self.egui().request_repaint();
2172    }
2173
2174    /// Asks for a command from the user, run before the main window's
2175    /// next pass in a given context (a window's keys).
2176    pub(crate) fn run_in_context(&self, command: CommandId, args: Json, context: WhenContext) {
2177        self.push_request(Request::RunIn {
2178            command,
2179            args,
2180            origin: Origin::User,
2181            context,
2182        });
2183        self.egui().request_repaint_of(egui::ViewportId::ROOT);
2184    }
2185
2186    /// Whether requests wait for the main window's next pass.
2187    pub(crate) fn has_requests(&self) -> bool {
2188        !self.0.requests.borrow().is_empty()
2189    }
2190
2191    /// The keymap as last rebuilt.
2192    pub(crate) fn shared_keymap(&self) -> Rc<Keymap> {
2193        self.0.keymap.borrow().clone()
2194    }
2195
2196    /// A shortcuts editor waits for keys.
2197    pub(crate) fn capturing_keys(&self) -> bool {
2198        self.0.capturing.get()
2199    }
2200
2201    /// Sets an application-wide context key (depth 0), for `when`
2202    /// clauses. The context stack's own keys (`place`, `placeDepth`,
2203    /// `modePushed`, `mode.*`) are its projection's: a plugin setting one
2204    /// by hand is reported (`contexts::hand_writes`, a diagnostic) while
2205    /// the stack is connected.
2206    pub fn set_context(&self, key: &str, value: &str) {
2207        if !self.0.stack_writing.get() && crate::contexts::is_stack_key(key) {
2208            crate::contexts::written_by_hand(self, key, value);
2209        }
2210        self.0.context.borrow_mut().set(key, value);
2211    }
2212
2213    /// Sets a context key as the context stack's projection.
2214    pub(crate) fn set_stack_context(&self, key: &str, value: &str) {
2215        self.0.stack_writing.set(true);
2216        self.0.context.borrow_mut().set(key, value);
2217        self.0.stack_writing.set(false);
2218    }
2219
2220    /// The command running now (the innermost), with its owner.
2221    pub(crate) fn running_command(&self) -> Option<(CommandId, Option<OwnerId>)> {
2222        self.0.running_commands.borrow().last().cloned()
2223    }
2224
2225    /// Records a warning among the diagnostics (logged).
2226    pub(crate) fn warn(
2227        &self,
2228        code: &'static str,
2229        owner: Option<&OwnerId>,
2230        subject: &str,
2231        message: String,
2232    ) {
2233        self.0
2234            .diagnostics
2235            .borrow_mut()
2236            .warn(code, owner, subject, message);
2237    }
2238
2239    /// The application-wide context keys.
2240    pub fn context(&self) -> WhenContext {
2241        self.0.context.borrow().clone()
2242    }
2243
2244    /// The context keys at this moment: application-wide, then the focus
2245    /// chain's, the overlays'. They are the window's being drawn: in a
2246    /// detached panel's window, its focus chain and its overlays, and
2247    /// `window` holds the panel's id (empty in the main window);
2248    /// `appWindow` names the application window (ADR 0025);
2249    /// `focusedPanel` is the window group's own: the workbench's focused
2250    /// panel in the main window and its detached panels, an application
2251    /// window's last focused panel in it (empty when none);
2252    /// `focusedPanelKind`, that panel's kind (`PanelId::kind`: the
2253    /// panel's own id, or `app.gallery` for its instance `app.gallery#2`);
2254    /// `modalOpen` says whether a modal is open in the window's group
2255    /// (an application window's own, or the main window's with its
2256    /// detached panels: a modal in one application window does not make
2257    /// `!modalOpen` refuse in another). Asked for another window group
2258    /// than the one being drawn (a command a window's content asked for,
2259    /// an agent's call naming a window), `appWindow`, `window` and
2260    /// `modalOpen` are that group's; the focus chain's keys stay the
2261    /// window being drawn's;
2262    /// `overlayOpen`, whether egui-pop's overlay stack holds anything or
2263    /// an egui popup (a menu, a combo box's list) is open.
2264    pub fn when_context(&self) -> WhenContext {
2265        let mut base = self.context();
2266        let ctx = &self.egui();
2267        let flag = |on: bool| if on { "true" } else { "false" };
2268        let overlay_open = !overlay::stack(ctx).is_empty() || egui::Popup::is_any_open(ctx);
2269        base.set("overlayOpen", flag(overlay_open));
2270        let here = ctx.viewport_id();
2271        let group = self.current_window_group_or(here);
2272        // The window the keys are for: the one drawn, or the one of the
2273        // group asked for.
2274        let view = if group == self.window_group(here) {
2275            here
2276        } else {
2277            self.shown_in(group)
2278        };
2279        base.set("modalOpen", flag(overlay::modal_open_in(ctx, group)));
2280        base.set("canUndo", flag(self.can_undo()));
2281        base.set("canRedo", flag(self.can_redo()));
2282        base.set(
2283            CONTEXT_UNDO_NEEDS_VIEW,
2284            flag(crate::history::needs_view(self, false)),
2285        );
2286        base.set(
2287            CONTEXT_REDO_NEEDS_VIEW,
2288            flag(crate::history::needs_view(self, true)),
2289        );
2290        // Each window's own: the workbench's for the main window's group
2291        // (its detached panels' windows share it), an application window's
2292        // own for it ("" while none of its panels was focused), so a
2293        // panel's keys never fire from another window.
2294        // `focusedPanelKind` beside it: the kind of an instance
2295        // (`app.gallery` for `app.gallery#2`), so a kind's keys reach
2296        // every instance.
2297        let focused = if self.window_group(view) != egui::ViewportId::ROOT {
2298            Some(self.window_focused_panel(view))
2299        } else {
2300            self.try_workbench().map(|wb| wb.focused.clone())
2301        };
2302        if let Some(panel) = focused {
2303            base.set("focusedPanel", panel.as_ref().map_or("", PanelId::as_str));
2304            let kind = panel.as_ref().map(PanelId::kind);
2305            base.set(
2306                CONTEXT_FOCUSED_PANEL_KIND,
2307                kind.as_ref().map_or("", PanelId::as_str),
2308            );
2309        }
2310        if let Some(panel) = self.window_panel(view) {
2311            base.set(CONTEXT_WINDOW, panel.as_str());
2312        }
2313        let app_window = match self.window_at(view) {
2314            Some(id) => id,
2315            // A detached panel's window belongs to the main window.
2316            None => self.windows_ref().root.id.clone(),
2317        };
2318        base.set(crate::windows::CONTEXT_APP_WINDOW, app_window.as_str());
2319        for (key, on) in crate::clipboard::keys(self).into_iter().flatten() {
2320            base.set(key, flag(on));
2321        }
2322        for (key, on) in crate::layout_controls::keys(self) {
2323            base.set(key, flag(on));
2324        }
2325        base.set(
2326            "canvasActive",
2327            flag(egui_pop_core::canvas::active(ctx).is_some()),
2328        );
2329        focus::when_context(ctx, &base)
2330    }
2331
2332    /// A window's name for agents: `main`, or its detached panel's id.
2333    pub fn window_name(&self, window: egui::ViewportId) -> String {
2334        if let Some(p) = self.window_panel(window) {
2335            return p.to_string();
2336        }
2337        if window != egui::ViewportId::ROOT
2338            && let Some(id) = self.window_at(window)
2339        {
2340            return id.to_string();
2341        }
2342        "main".to_string()
2343    }
2344
2345    /// What the `windows` collector shows: the active window, each
2346    /// window's overlays, where the palette and the popup menu are.
2347    pub fn describe_windows(&self) -> Json {
2348        let ctx = self.egui();
2349        let modal = overlay::modal_windows(&ctx);
2350        let mut windows = vec![egui::ViewportId::ROOT];
2351        if let Ok(wb) = self.0.workbench.try_borrow() {
2352            windows.extend(
2353                wb.layout
2354                    .auxiliary
2355                    .iter()
2356                    .map(|a| crate::workbench::window_id(&a.panel)),
2357            );
2358        }
2359        windows.extend(self.windows().iter().skip(1).map(|w| w.viewport));
2360        let stacks = overlay::stacks(&ctx);
2361        // Each window group has its own palette: the active one's first.
2362        let palettes: Vec<String> = self
2363            .service(&crate::palette::PALETTE)
2364            .map(|p| {
2365                let active = self.window_group(self.active_window());
2366                let mut groups = p.open_groups();
2367                groups.sort_by_key(|g| *g != active);
2368                groups
2369                    .into_iter()
2370                    .filter_map(|g| p.window_in(g))
2371                    .map(|w| self.window_name(self.still_open(w)))
2372                    .collect()
2373            })
2374            .unwrap_or_default();
2375        let palette = palettes.first().cloned();
2376        json!({
2377            "active": self.window_name(self.active_window()),
2378            "windows": windows.iter().map(|v| json!({
2379                "window": self.window_name(*v),
2380                "overlays": stacks
2381                    .iter()
2382                    .find(|(w, _)| w == v)
2383                    .map(|(_, specs)| specs.iter().map(|o| o.label.clone()).collect::<Vec<_>>())
2384                    .unwrap_or_default(),
2385                "modal": modal.contains(v),
2386            })).collect::<Vec<_>>(),
2387            "palette": palette,
2388            "palettes": palettes,
2389            "popup_menu": crate::menus::popup_window(self).map(|w| self.window_name(w)),
2390            "app_windows": crate::windows::describe(self),
2391        })
2392    }
2393
2394    /// The panel a window shows: the detached panel of a detached
2395    /// panel's window (`workbench::window_id`); `None` for the main
2396    /// window, or a window that is no longer open.
2397    pub fn window_panel(&self, window: egui::ViewportId) -> Option<PanelId> {
2398        if window == egui::ViewportId::ROOT {
2399            return None;
2400        }
2401        let wb = self.0.workbench.try_borrow().ok()?;
2402        wb.layout
2403            .auxiliary
2404            .iter()
2405            .find(|a| crate::workbench::window_id(&a.panel) == window)
2406            .map(|a| a.panel.clone())
2407    }
2408
2409    /// The window the user worked in last (focused, clicked or typed
2410    /// in), still open: the main window (`ViewportId::ROOT`), a detached
2411    /// panel's or an application window's. A dialog opens over it. The
2412    /// registry holds it (`pop.window.activate`, [`AppHandle::active_window_id`]).
2413    pub fn active_window(&self) -> egui::ViewportId {
2414        let (id, kind) = self.active_window_record();
2415        self.still_open(
2416            crate::window_invariants::viewport_of(kind, &id).unwrap_or(egui::ViewportId::ROOT),
2417        )
2418    }
2419
2420    /// A window if it is still open, else the main window.
2421    pub(crate) fn still_open(&self, window: egui::ViewportId) -> egui::ViewportId {
2422        if self.window_panel(window).is_some() || crate::windows::is_app_window(self, window) {
2423            window
2424        } else {
2425            egui::ViewportId::ROOT
2426        }
2427    }
2428
2429    /// The diagnostics collected (registration, zones, hooks), then the
2430    /// store's (writes from plugins that are not a path's writers).
2431    pub fn diagnostics(&self) -> Vec<Diagnostic> {
2432        let mut all = self.0.diagnostics.borrow().all().to_vec();
2433        all.extend_from_slice(lock(&self.0.store).diagnostics().all());
2434        all
2435    }
2436
2437    /// The menus declared, by id.
2438    pub fn menu_ids(&self) -> Vec<MenuId> {
2439        self.0.derived.borrow().menus.keys().cloned().collect()
2440    }
2441
2442    /// A menu's items after the hooks.
2443    pub fn menu(&self, menu: &MenuId) -> Vec<MenuItem> {
2444        self.0
2445            .derived
2446            .borrow()
2447            .menus
2448            .get(menu)
2449            .cloned()
2450            .unwrap_or_default()
2451    }
2452
2453    /// The palette's entries after the hooks.
2454    pub fn palette(&self) -> Vec<PaletteEntry> {
2455        self.0.derived.borrow().palette.clone()
2456    }
2457
2458    /// What the command palette lists for `query`, best first: the
2459    /// entries that apply now, matched on their label in the interface's
2460    /// language (`Category: Title`), the recent ones winning ties, as
2461    /// the palette ranks them (`palette::rank_with`).
2462    pub fn palette_search(&self, query: &str) -> Vec<crate::palette::Ranked> {
2463        crate::palette::search(self, query)
2464    }
2465
2466    /// The settings form's entries after the hooks.
2467    pub fn settings(&self) -> Vec<SettingEntry> {
2468        self.0.derived.borrow().settings.clone()
2469    }
2470
2471    /// The plugin a command went with, when it was declared by a plugin
2472    /// now disconnected (ADR 0028): what a toast's greyed action and a
2473    /// refused run name.
2474    pub fn command_gone_with(&self, id: &CommandId) -> Option<PluginId> {
2475        self.0.gone_commands.borrow().get(id).cloned()
2476    }
2477
2478    /// The key bindings kept dormant (ADR 0028): those of the user, the
2479    /// workspace or another plugin whose command went with a plugin now
2480    /// disconnected, each with that plugin. They take no key (it goes to
2481    /// the next binding of it) and are live again when the plugin
2482    /// reconnects; a shortcuts editor lists them apart.
2483    pub fn dormant_keys(&self) -> Vec<DormantKey> {
2484        self.0.derived.borrow().dormant.clone()
2485    }
2486
2487    /// A command's declaration.
2488    pub fn command(&self, id: &CommandId) -> Option<CommandSpec> {
2489        self.0
2490            .derived
2491            .borrow()
2492            .commands
2493            .iter()
2494            .find(|(s, _)| s.id == *id)
2495            .map(|(s, _)| s.clone())
2496    }
2497
2498    /// The plugin that set a command's icon over its declaration
2499    /// (`Ctx::command_icon`), if one did.
2500    pub fn icon_set_by(&self, id: &CommandId) -> Option<OwnerId> {
2501        self.0.derived.borrow().icons_set_by.get(id).cloned()
2502    }
2503
2504    /// Asks for a command's keys to be the user's own (`None`: no key),
2505    /// saved in the user's keymap; applied before the next frame.
2506    pub fn rebind(&self, command: CommandId, keys: Option<String>) {
2507        self.rebind_in(Layer::User, command, keys);
2508    }
2509
2510    /// Asks for a command's keys in `layer`: the user's (saved in the
2511    /// user's keymap) or the workspace's (kept by the application, which
2512    /// reads it back with [`AppHandle::export_keymap`]); applied before
2513    /// the next frame, through the `keys.rebind` step. Another layer is
2514    /// refused there.
2515    pub fn rebind_in(&self, layer: Layer, command: CommandId, keys: Option<String>) {
2516        self.push_request(Request::Rebind {
2517            command,
2518            keys,
2519            layer,
2520        });
2521    }
2522
2523    /// Asks for a command's keys in `layer`, several at once (a pointer
2524    /// gesture's triggers: `Wheel`, `Ctrl+Scroll`, `Pinch`; none: no
2525    /// key), through the `keys.rebind` step (`keys` an array).
2526    pub fn rebind_gestures(&self, layer: Layer, command: CommandId, keys: &[&str]) {
2527        self.push_request(Request::RebindAll {
2528            command,
2529            keys: keys.iter().map(|k| (*k).to_string()).collect(),
2530            layer,
2531        });
2532    }
2533
2534    /// Asks for a command's default keys back.
2535    pub fn reset_keys(&self, command: CommandId) {
2536        self.reset_keys_in(Layer::User, command);
2537    }
2538
2539    /// Takes back what `layer` (the user's or the workspace's) changed
2540    /// of a command's keys, before the next frame.
2541    pub fn reset_keys_in(&self, layer: Layer, command: CommandId) {
2542        self.push_request(Request::ResetKeys { command, layer });
2543    }
2544
2545    /// Whether `layer` (the user's or the workspace's) changed a
2546    /// command's keys.
2547    pub fn rebound_in(&self, layer: Layer, id: &CommandId) -> bool {
2548        let d = self.0.derived.borrow();
2549        match layer {
2550            Layer::User => d.rebound.contains(id),
2551            Layer::Workspace => d.rebound_workspace.contains(id),
2552            _ => false,
2553        }
2554    }
2555
2556    /// A command's live bindings, each with the layer it comes from.
2557    pub fn key_sources(&self, id: &CommandId) -> Vec<Binding> {
2558        self.0
2559            .derived
2560            .borrow()
2561            .sources
2562            .get(id)
2563            .cloned()
2564            .unwrap_or_default()
2565    }
2566
2567    /// Whether the shortcuts editor offers to change keys for the
2568    /// workspace as well as for the user (off by default: an application
2569    /// with workspaces turns it on, and keeps the workspace's layer).
2570    pub fn offer_workspace_keys(&self, on: bool) {
2571        self.0.workspace_keys.set(on);
2572    }
2573
2574    /// Whether the shortcuts editor offers the workspace's keys.
2575    pub fn workspace_keys_offered(&self) -> bool {
2576        self.0.workspace_keys.get()
2577    }
2578
2579    /// How the shortcuts editor names where a binding comes from: `f`
2580    /// gives a name, in the interface's language, or `None` for the
2581    /// default one ([`AppHandle::key_source_name`]).
2582    pub fn name_key_sources(&self, f: impl Fn(&Binding) -> Option<String> + 'static) {
2583        *self.0.key_source_names.borrow_mut() = Some(Rc::new(f));
2584    }
2585
2586    /// Where a binding comes from, as the shortcuts editor says it after
2587    /// its keys: the host's name for it, else `workspace` or `user`;
2588    /// nothing for the application's defaults.
2589    pub fn key_source_name(&self, ctx: &Context, binding: &Binding) -> Option<String> {
2590        let named = self.0.key_source_names.borrow().clone();
2591        if let Some(name) = named.and_then(|f| f(binding)) {
2592            return Some(name);
2593        }
2594        let key = match binding.layer {
2595            Layer::Suggestion | Layer::Default => return None,
2596            Layer::Workspace => &crate::strings::SHORTCUTS_FROM_WORKSPACE,
2597            Layer::User => &crate::strings::SHORTCUTS_FROM_USER,
2598        };
2599        Some(strings::tr(ctx, key))
2600    }
2601
2602    /// While on, key presses reach the interface instead of the key
2603    /// dispatcher (a shortcuts editor capturing new keys).
2604    pub fn capture_keys(&self, on: bool) {
2605        self.0.capturing.set(on);
2606    }
2607
2608    /// Whether a shortcuts editor captures the keys ([`Self::capture_keys`]).
2609    pub fn keys_captured(&self) -> bool {
2610        self.0.capturing.get()
2611    }
2612
2613    /// [`AppHandle::key_conflicts`] by scope (`global`, `surface:<name>`).
2614    pub fn key_conflicts_by_scope(&self) -> BTreeMap<String, Vec<(Binding, Binding)>> {
2615        let mut out: BTreeMap<String, Vec<(Binding, Binding)>> = BTreeMap::new();
2616        for (lose, win) in self.key_conflicts() {
2617            out.entry(lose.options.scope.to_string())
2618                .or_default()
2619                .push((lose, win));
2620        }
2621        out
2622    }
2623
2624    /// Declares a command after build, owned by `owner` (a host's own
2625    /// registry changing at run time), with the rules and traces of
2626    /// `Ctx::declare`: its keys, menus and palette entry follow before the
2627    /// next frame, with no plugin reconnected. A refusal is logged and
2628    /// published (`command.declare_failed`).
2629    pub fn declare(&self, owner: &OwnerId, spec: CommandSpec) {
2630        self.push_request(Request::Declare {
2631            owner: owner.clone(),
2632            spec,
2633        });
2634    }
2635
2636    /// Removes a command declared after build, with its keys and menu
2637    /// items, before the next frame.
2638    pub fn undeclare(&self, id: &CommandId) {
2639        self.push_request(Request::Undeclare(id.clone()));
2640    }
2641
2642    /// A layer's bindings, whoever declared them, as a keymap document
2643    /// (scopes, `when` clauses, every key): a profile to save.
2644    pub fn export_keymap(&self, layer: Layer) -> egui_pop_model::keymap::KeymapDoc {
2645        self.0
2646            .derived
2647            .borrow()
2648            .layers
2649            .get(&layer)
2650            .cloned()
2651            .unwrap_or_default()
2652    }
2653
2654    /// Loads a keymap document into the user's (or the workspace's)
2655    /// layer, replacing what was loaded there, before the next frame
2656    /// (the `keys.load` step). Returns what it will change against the
2657    /// layer as it stands; conflicts are published once applied
2658    /// (`keys.conflict`). `App::load_keymap` does it at once.
2659    pub fn load_keymap(
2660        &self,
2661        doc: egui_pop_model::keymap::KeymapDoc,
2662        layer: Layer,
2663    ) -> egui_pop_model::keymap::KeymapDiff {
2664        let diff = egui_pop_model::keymap::KeymapDiff::between(&self.export_keymap(layer), &doc);
2665        self.push_request(Request::LoadKeymap { doc, layer });
2666        diff
2667    }
2668
2669    /// Bindings losing to another on the same keys (loser, winner): what
2670    /// a shortcuts editor shows as conflicts.
2671    pub fn key_conflicts(&self) -> Vec<(Binding, Binding)> {
2672        self.0.derived.borrow().conflicts.clone()
2673    }
2674
2675    /// Whether the user changed a command's keys.
2676    pub fn rebound(&self, id: &CommandId) -> bool {
2677        self.0.derived.borrow().rebound.contains(id)
2678    }
2679
2680    /// Whether a command applies in a context (its `when` clause holds).
2681    pub fn applies(&self, id: &CommandId, cx: &WhenContext) -> bool {
2682        self.0
2683            .derived
2684            .borrow()
2685            .commands
2686            .iter()
2687            .find(|(s, _)| s.id == *id)
2688            .is_some_and(|(s, _)| {
2689                s.when.is_empty()
2690                    || egui_pop_model::when::When::parse(&s.when).is_ok_and(|w| w.eval(cx))
2691            })
2692    }
2693
2694    /// A command's live key bindings, as shown (`Ctrl+K Ctrl+S`).
2695    pub fn keys_for(&self, id: &CommandId) -> Vec<String> {
2696        self.0
2697            .derived
2698            .borrow()
2699            .keys
2700            .get(id)
2701            .cloned()
2702            .unwrap_or_default()
2703    }
2704
2705    /// The live key bindings of the system scope (`BindOptions::system()`):
2706    /// what a plugin registers with the desktop as global shortcuts,
2707    /// current after each rebuild (`On::Rebuilt`).
2708    pub fn system_bindings(&self) -> Vec<Binding> {
2709        self.0.derived.borrow().system.clone()
2710    }
2711
2712    /// Every command (spec and owner).
2713    pub fn commands(&self) -> Vec<(CommandSpec, OwnerId)> {
2714        self.0.derived.borrow().commands.clone()
2715    }
2716
2717    /// The last command runs, oldest first.
2718    pub fn history(&self) -> Vec<Run> {
2719        self.0.history.borrow().clone()
2720    }
2721
2722    /// The plugins, in connection order.
2723    pub fn plugins(&self) -> Vec<PluginInfo> {
2724        self.0.plugins.borrow().clone()
2725    }
2726
2727    /// The zones with their resolved blocks.
2728    pub fn zones(&self) -> Vec<ZoneInfo> {
2729        self.0.zones.borrow().infos()
2730    }
2731
2732    /// The services: id, owner, type.
2733    pub fn services(&self) -> Vec<(String, OwnerId, &'static str)> {
2734        self.0
2735            .services
2736            .borrow()
2737            .list()
2738            .into_iter()
2739            .map(|(i, o, t)| (i.to_string(), o, t))
2740            .collect()
2741    }
2742
2743    pub(crate) fn zones_mut(&self) -> RefMut<'_, ZoneTable> {
2744        self.0.zones.borrow_mut()
2745    }
2746
2747    pub(crate) fn services_mut(&self) -> RefMut<'_, Services> {
2748        self.0.services.borrow_mut()
2749    }
2750
2751    pub(crate) fn add_panel_view(&self, owner: &OwnerId, id: PanelId, draw: PanelDraw) {
2752        self.0.panels.borrow_mut().insert(
2753            id,
2754            PanelView {
2755                owner: owner.clone(),
2756                draw: Some(draw),
2757            },
2758        );
2759    }
2760
2761    pub(crate) fn add_story(&self, owner: &OwnerId, story: Story) -> Result<(), CtxError> {
2762        let id = story.id.clone();
2763        self.0
2764            .stories
2765            .borrow_mut()
2766            .insert(owner, id, StoryEntry { story })
2767            .map_err(|t| CtxError::Story {
2768                id: t.id.to_string(),
2769                by: t.by,
2770            })
2771    }
2772
2773    /// Whether a zone has blocks to draw.
2774    pub fn zone_has_blocks(&self, zone: &ZoneId) -> bool {
2775        self.0
2776            .zones
2777            .borrow()
2778            .resolved
2779            .get(zone)
2780            .is_some_and(|b| !b.is_empty())
2781    }
2782
2783    /// Draws a zone's blocks, each in a fault boundary. A zone nobody
2784    /// declared draws nothing (and was reported when zones were
2785    /// resolved).
2786    pub fn show_zone(&self, ui: &mut Ui, zone: &ZoneId) {
2787        let plan: Vec<(usize, Vec<usize>, String, OwnerId)> =
2788            match self.0.zones.borrow().resolved.get(zone) {
2789                Some(blocks) => blocks
2790                    .iter()
2791                    .map(|r| (r.draw, r.wraps.clone(), r.id.to_string(), r.owner.clone()))
2792                    .collect(),
2793                None => return,
2794            };
2795        for (draw, wraps, id, owner) in plan {
2796            let taken = {
2797                let mut z = self.0.zones.borrow_mut();
2798                let base = z.contributions.get_mut(draw).and_then(|c| c.block.take());
2799                let ws: Vec<(usize, Option<Block>)> = wraps
2800                    .iter()
2801                    .map(|&w| (w, z.contributions.get_mut(w).and_then(|c| c.block.take())))
2802                    .collect();
2803                (base, ws)
2804            };
2805            let (Some(mut base), ws) = taken else {
2806                continue;
2807            };
2808            let mut wrap_blocks: Vec<(usize, Block)> = ws
2809                .into_iter()
2810                .filter_map(|(i, b)| b.map(|b| (i, b)))
2811                .collect();
2812            ui.push_id(("egui_pop_block", &id), |ui| {
2813                fault::boundary(ui, "block", &id, |ui| {
2814                    let draw_fn: &mut DrawFn = match &mut base {
2815                        Block::Add { draw, .. }
2816                        | Block::Replace { draw, .. }
2817                        | Block::Extend { draw, .. } => draw,
2818                        Block::Wrap { .. } => return,
2819                    };
2820                    let mut wrap_fns: Vec<zones::WrapFn> = Vec::new();
2821                    // Move the wrappers out of their blocks for the call,
2822                    // then put them back.
2823                    for (_, b) in &mut wrap_blocks {
2824                        if let Block::Wrap { wrap, .. } = b {
2825                            wrap_fns.push(std::mem::replace(wrap, Box::new(|_, _, _| {})));
2826                        }
2827                    }
2828                    draw_chain(ui, self, draw_fn, &mut wrap_fns);
2829                    // What the inspect mode names the block by.
2830                    egui_pop_core::inspect::region(
2831                        ui,
2832                        "block",
2833                        &id,
2834                        Some(zone.as_str()),
2835                        owner.as_str(),
2836                    );
2837                    let mut back = wrap_fns.into_iter();
2838                    for (_, b) in &mut wrap_blocks {
2839                        if let Block::Wrap { wrap, .. } = b
2840                            && let Some(f) = back.next()
2841                        {
2842                            *wrap = f;
2843                        }
2844                    }
2845                });
2846            });
2847            let mut z = self.0.zones.borrow_mut();
2848            if let Some(c) = z.contributions.get_mut(draw) {
2849                c.block = Some(base);
2850            }
2851            for (i, b) in wrap_blocks {
2852                if let Some(c) = z.contributions.get_mut(i) {
2853                    c.block = Some(b);
2854                }
2855            }
2856        }
2857    }
2858
2859    /// The stories, by group then weight.
2860    pub fn stories(&self) -> Vec<StoryInfo> {
2861        let mut v: Vec<StoryInfo> = self
2862            .0
2863            .stories
2864            .borrow()
2865            .iter()
2866            .map(|(_, s)| StoryInfo {
2867                id: s.item.story.id.clone(),
2868                title: s.item.story.title.clone(),
2869                description: s.item.story.description.clone(),
2870                group: s.item.story.group.clone(),
2871                weight: s.item.story.weight,
2872                has_playground: s.item.story.playground.is_some(),
2873                owner: s.owner.clone(),
2874            })
2875            .collect();
2876        v.sort_by(|a, b| (&a.group, a.weight, &a.title).cmp(&(&b.group, b.weight, &b.title)));
2877        v
2878    }
2879
2880    fn with_story(&self, id: &StoryId, playground: bool, ui: &mut Ui) -> bool {
2881        let taken = {
2882            let mut s = self.0.stories.borrow_mut();
2883            s.get_mut(id).and_then(|e| {
2884                if playground {
2885                    e.story.playground.take()
2886                } else {
2887                    Some(std::mem::replace(&mut e.story.show, Box::new(|_, _| {})))
2888                }
2889            })
2890        };
2891        let Some(mut f) = taken else {
2892            return false;
2893        };
2894        let title = id.to_string();
2895        ui.push_id(("egui_pop_story", id.as_str(), playground), |ui| {
2896            fault::boundary(ui, "story", &title, |ui| f(ui, self));
2897        });
2898        if let Some(e) = self.0.stories.borrow_mut().get_mut(id) {
2899            if playground {
2900                e.story.playground = Some(f);
2901            } else {
2902                e.story.show = f;
2903            }
2904        }
2905        true
2906    }
2907
2908    /// Draws a story; `false` when there is no such story.
2909    pub fn show_story(&self, ui: &mut Ui, id: &StoryId) -> bool {
2910        self.with_story(id, false, ui)
2911    }
2912
2913    /// Draws a story's playground; `false` when it has none.
2914    pub fn show_playground(&self, ui: &mut Ui, id: &StoryId) -> bool {
2915        self.with_story(id, true, ui)
2916    }
2917
2918    /// Draws a panel's content, in its focus scope and fault boundary.
2919    pub(crate) fn show_panel(&self, ui: &mut Ui, id: &PanelId) {
2920        let title = self.panel_title(ui.ctx(), id);
2921        let title = title.as_str();
2922        // An instance (`<kind>#<n>`) is drawn by its kind's function.
2923        let key = if id.is_instance() && !self.0.panels.borrow().contains_key(id) {
2924            id.kind()
2925        } else {
2926            id.clone()
2927        };
2928        let taken = self
2929            .0
2930            .panels
2931            .borrow_mut()
2932            .get_mut(&key)
2933            .and_then(|p| Some((p.draw.take()?, p.owner.clone())));
2934        let Some((mut draw, owner)) = taken else {
2935            return;
2936        };
2937        let instance = crate::workbench::instances::Instance::of(id, title);
2938        let scope = scope_name(id.as_str());
2939        let region = ui.max_rect().intersect(ui.clip_rect());
2940        ui.push_id(("egui_pop_panel", id.as_str()), |ui| {
2941            focus::scope(ui, &scope, &[], |ui| {
2942                let taking = self.takes_the_focus(ui.ctx(), id, &scope);
2943                self.panel_stop(ui, id, title, taking);
2944                let failed = |fault: &fault::Fault| {
2945                    log::error!(
2946                        target: "egui_pop",
2947                        "panel `{id}` (of `{owner}`) panicked while drawing: {}; \
2948                         its region shows the fault, the rest of the window is drawn",
2949                        fault.message
2950                    );
2951                    self.publish(
2952                        "egui_pop",
2953                        None,
2954                        "panel.fault",
2955                        json!({ "panel": id.as_str(), "owner": owner.as_str(), "message": fault.message }),
2956                    );
2957                };
2958                // Its edit areas are inert while what it shows is not
2959                // current (`pop.panel.state` stale, updating or failed).
2960                let inert = self.panel_state(id.as_str()) != crate::bus::PanelState::Ready;
2961                // The window of the layout holding it, for the drawing scope.
2962                let window = self
2963                    .try_workbench()
2964                    .and_then(|w| w.layout.window_of(id).map(|a| a.panel.clone()));
2965                egui_pop_core::areas::scope(ui, id.as_str(), inert, |ui| {
2966                    // What runs while it draws knows it (`bus::drawing_panel`).
2967                    let _drawing =
2968                        crate::bus::drawing::Drawing::enter(self, id, window, ui.ctx().viewport_id());
2969                    fault::boundary_reporting(
2970                        ui,
2971                        "panel",
2972                        title,
2973                        |ui| match &mut draw {
2974                            PanelDraw::Plain(f) => f(ui, self),
2975                            PanelDraw::Instance(f) => f(ui, self, &instance),
2976                        },
2977                        failed,
2978                    );
2979                });
2980                // Its state (`pop.panel.state`), drawn by the chrome over what
2981                // the panel drew.
2982                crate::bus::panel_state::paint_content(
2983                    &self.0.bus.panel_states,
2984                    ui,
2985                    id.as_str(),
2986                    region,
2987                );
2988                // What the inspect mode names the panel by.
2989                egui_pop_core::inspect::region(ui, "panel", id.as_str(), None, owner.as_str());
2990                if taking {
2991                    settle_panel_focus(ui);
2992                }
2993            });
2994        });
2995        if let Some(p) = self.0.panels.borrow_mut().get_mut(&key) {
2996            p.draw = Some(draw);
2997        }
2998    }
2999
3000    /// Whether a panel about to be drawn is to take the widget focus now.
3001    fn takes_the_focus(&self, ctx: &Context, id: &PanelId, scope: &str) -> bool {
3002        if !self.workbench_mut().take_focus_request(id) {
3003            return false;
3004        }
3005        ctx.request_repaint();
3006        // Its own window comes forward, if another has the system's focus.
3007        if ctx.input(|i| i.viewport().focused) == Some(false) {
3008            self.raise_viewport(ctx.viewport_id(), "egui_pop.workbench");
3009        }
3010        // Egui would take the focus straight off a widget under a modal.
3011        if overlay::modal_open(ctx) {
3012            return false;
3013        }
3014        let inside =
3015            focus::focused(ctx).is_some() && focus::chain(ctx).iter().any(|r| r.name == scope);
3016        !inside
3017    }
3018
3019    /// The panel's own stop: it holds the focus a panel takes (unless the
3020    /// panel prefers a widget), and Tab goes on from it into the panel's
3021    /// widgets. It shows nothing and is not a Tab stop otherwise.
3022    fn panel_stop(&self, ui: &mut Ui, id: &PanelId, title: &str, taking: bool) {
3023        let stop = Id::unique(("egui_pop.panel_stop", id.as_str()));
3024        if taking {
3025            ui.memory_mut(|m| m.request_focus(stop));
3026        }
3027        if taking || ui.memory(|m| m.has_focus(stop)) {
3028            let r = ui.interact(ui.max_rect(), stop, egui::Sense::focusable_noninteractive());
3029            a11y::name(&r, egui::Role::Pane, title);
3030        }
3031    }
3032
3033    /// Keeps `focused` up with where the focus went, and starts a pass for a
3034    /// panel waiting for the widget focus.
3035    fn follow_focus(&self, ctx: &Context) {
3036        if ctx.viewport_id() == egui::ViewportId::ROOT {
3037            self.workbench_mut().age_focus_request();
3038        }
3039        if let Some(moved) = focus::take_moved(ctx)
3040            && self.workbench_mut().follow_focus(moved)
3041        {
3042            self.publish_focused();
3043        }
3044    }
3045
3046    fn publish_focused(&self) {
3047        let panel = self.focused_panel();
3048        self.publish(
3049            "egui_pop",
3050            None,
3051            "workbench.focused",
3052            json!({ "panel": panel }),
3053        );
3054    }
3055
3056    pub(crate) fn workbench_mut(&self) -> RefMut<'_, crate::workbench::Workbench> {
3057        self.0.workbench.borrow_mut()
3058    }
3059
3060    /// The workbench, unless something holds it now.
3061    pub(crate) fn try_workbench(&self) -> Option<RefMut<'_, crate::workbench::Workbench>> {
3062        self.0.workbench.try_borrow_mut().ok()
3063    }
3064
3065    /// Whether the centre is drawn edge to edge.
3066    pub fn edge_to_edge(&self) -> bool {
3067        self.0.edge_to_edge.get()
3068    }
3069
3070    /// Whether an area is drawn without a frame
3071    /// ([`AppBuilder::frameless`]): no margin around it, its panels'
3072    /// bodies without margin, border or rounded corners.
3073    pub fn frameless(&self, area: Area) -> bool {
3074        self.0.frameless.borrow().contains(&area)
3075    }
3076
3077    /// Whether a side area's folded strip is bare
3078    /// ([`AppBuilder::bare_strips`]): its grip alone, no icon per panel.
3079    pub fn bare_strip(&self, area: Area) -> bool {
3080        self.0.bare_strips.borrow().contains(&area)
3081    }
3082
3083    /// The shell panels' least and largest sizes the application set.
3084    pub(crate) fn shell_bounds(&self) -> Vec<(PanelId, crate::workbench::ShellBounds)> {
3085        self.0.shell_bounds.borrow().clone()
3086    }
3087
3088    /// Sets a shell panel's least size across its area while the
3089    /// application runs, as [`AppBuilder::shell_panel_min_size`] does at
3090    /// build time: a size its content needs, measured with the fonts and
3091    /// the text size of the moment (a header's row of buttons), set each
3092    /// frame or when it changes. The area widens to it on the next pass,
3093    /// in the main window or in the application window that holds the
3094    /// panel; the user's drag stops there. `None` puts back the panel's own
3095    /// least (`PanelSpec::min_size`, or egui-pop's).
3096    ///
3097    /// ```
3098    /// use egui_pop_api::App;
3099    /// use egui_pop_api::workbench::PANEL_SIDE_BAR;
3100    ///
3101    /// let app = App::builder().build(&egui::Context::default()).unwrap();
3102    /// let handle = app.handle();
3103    /// handle.set_shell_panel_min_size(PANEL_SIDE_BAR, Some(341.0.into()));
3104    /// assert_eq!(handle.shell_panel_min_size(&PANEL_SIDE_BAR), Some(341.0.into()));
3105    /// handle.set_shell_panel_min_size(PANEL_SIDE_BAR, None);
3106    /// assert_eq!(handle.shell_panel_min_size(&PANEL_SIDE_BAR), None);
3107    /// ```
3108    ///
3109    /// <div class="warning">Experimental: may change in any release
3110    /// (docs/stability.md).</div>
3111    pub fn set_shell_panel_min_size(
3112        &self,
3113        panel: PanelId,
3114        size: Option<crate::workbench::ShellSize>,
3115    ) {
3116        if self.shell_panel_min_size(&panel) == size {
3117            return;
3118        }
3119        self.with_bounds(panel, |b| b.min = size);
3120    }
3121
3122    /// Sets a shell panel's largest size across its area while the
3123    /// application runs, as [`AppBuilder::shell_panel_max_size`] does at
3124    /// build time; `None`: no largest size.
3125    ///
3126    /// <div class="warning">Experimental: may change in any release
3127    /// (docs/stability.md).</div>
3128    pub fn set_shell_panel_max_size(
3129        &self,
3130        panel: PanelId,
3131        size: Option<crate::workbench::ShellSize>,
3132    ) {
3133        if self.shell_panel_max_size(&panel) == size {
3134            return;
3135        }
3136        self.with_bounds(panel, |b| b.max = size);
3137    }
3138
3139    /// A shell panel's least size the application set, at build time or
3140    /// since; `None` when it set none.
3141    ///
3142    /// <div class="warning">Experimental: may change in any release
3143    /// (docs/stability.md).</div>
3144    pub fn shell_panel_min_size(&self, panel: &PanelId) -> Option<crate::workbench::ShellSize> {
3145        let bounds = self.0.shell_bounds.borrow();
3146        bounds
3147            .iter()
3148            .find(|(p, _)| p == panel)
3149            .and_then(|(_, b)| b.min)
3150    }
3151
3152    /// A shell panel's largest size the application set, at build time
3153    /// or since; `None` when it set none.
3154    ///
3155    /// <div class="warning">Experimental: may change in any release
3156    /// (docs/stability.md).</div>
3157    pub fn shell_panel_max_size(&self, panel: &PanelId) -> Option<crate::workbench::ShellSize> {
3158        let bounds = self.0.shell_bounds.borrow();
3159        bounds
3160            .iter()
3161            .find(|(p, _)| p == panel)
3162            .and_then(|(_, b)| b.max)
3163    }
3164
3165    fn with_bounds(&self, panel: PanelId, f: impl FnOnce(&mut crate::workbench::ShellBounds)) {
3166        {
3167            let mut bounds = self.0.shell_bounds.borrow_mut();
3168            let at = match bounds.iter().position(|(p, _)| *p == panel) {
3169                Some(at) => at,
3170                None => {
3171                    bounds.push((panel, Default::default()));
3172                    bounds.len() - 1
3173                }
3174            };
3175            f(&mut bounds[at].1);
3176        }
3177        self.egui().request_repaint();
3178    }
3179
3180    /// The centre's least width the application set
3181    /// ([`AppBuilder::centre_min_size`]).
3182    ///
3183    /// <div class="warning">Experimental: may change in any release
3184    /// (docs/stability.md).</div>
3185    pub fn centre_min_size(&self) -> Option<crate::workbench::ShellSize> {
3186        self.0.centre_min.get()
3187    }
3188
3189    /// The system's text scaling the text size was seeded from
3190    /// (`AppBuilder::system_text_scale`; 1 when none was given).
3191    pub fn system_text_scale(&self) -> crate::text::SystemTextScale {
3192        self.0.system_text_scale.get()
3193    }
3194
3195    /// Whether the system always shows its scroll bars
3196    /// (`AppBuilder::system_always_shows_scroll_bars`).
3197    pub fn system_always_shows_scroll_bars(&self) -> bool {
3198        self.0.system_scroll_bars.get()
3199    }
3200
3201    /// The system's lines a wheel's notch (`AppBuilder::system_wheel_lines`; 3 when
3202    /// none was given).
3203    pub fn system_wheel_lines(&self) -> u32 {
3204        self.0.system_wheel_lines.get()
3205    }
3206
3207    /// Whether the main menu is drawn as a bar under the title
3208    /// (`AppBuilder::menu_bar`).
3209    pub fn menu_bar(&self) -> bool {
3210        self.0.menu_bar.get()
3211    }
3212
3213    /// Whether the application allows the system's file chooser
3214    /// (`AppBuilder::system_file_chooser`): off by default.
3215    pub fn system_file_chooser(&self) -> bool {
3216        self.0.system_file_chooser.get()
3217    }
3218
3219    /// Whether detached panels' windows are built transparent where the
3220    /// platform gives a surface below them
3221    /// (`AppBuilder::transparent_panel_windows`): off by default.
3222    pub fn transparent_panel_windows(&self) -> bool {
3223        self.0.transparent_panel_windows.get()
3224    }
3225
3226    /// Whether the windows the application decorates are built
3227    /// transparent for rounded corners (`AppBuilder::rounded_windows`).
3228    pub fn rounded_windows(&self) -> bool {
3229        self.0.rounded_windows.get()
3230    }
3231
3232    pub(crate) fn set_drawing_areas(&self, on: bool) {
3233        self.0.drawing_areas.set(on);
3234    }
3235
3236    /// Whether the workbench's areas are being drawn (their layout must
3237    /// not change under them).
3238    pub(crate) fn drawing_areas(&self) -> bool {
3239        self.0.drawing_areas.get()
3240    }
3241
3242    /// Whether a panel is shown (docked or detached, not closed).
3243    pub fn panel_visible(&self, id: &PanelId) -> bool {
3244        self.workbench_mut().shows(id)
3245    }
3246
3247    /// Shows or closes a panel (the `workbench.show` and `workbench.hide`
3248    /// steps; a palette opens through `palette.open`).
3249    pub fn set_panel_visible(&self, id: &PanelId, visible: bool) {
3250        let palette = self.workbench_mut().spec(id).is_some_and(|s| s.palette);
3251        let change = if visible && palette {
3252            // A palette opens through its own step, floating.
3253            crate::workbench::Change::OpenPalette(id.clone())
3254        } else if visible {
3255            crate::workbench::Change::Show(id.clone())
3256        } else {
3257            crate::workbench::Change::Hide(id.clone())
3258        };
3259        self.change_workbench(change);
3260    }
3261
3262    /// The workbench's layout as it stands: areas, tabs and splits,
3263    /// detached panels, closed panels.
3264    pub fn layout(&self) -> egui_pop_model::layout::Layout {
3265        self.workbench_mut().layout()
3266    }
3267
3268    /// The layout as saved: [`AppHandle::layout`] and the places kept for
3269    /// panels no longer declared, which go back there when declared again
3270    /// (ADR 0028).
3271    pub fn saved_layout(&self) -> egui_pop_model::layout::SavedLayout {
3272        let mut wb = self.workbench_mut();
3273        egui_pop_model::layout::SavedLayout {
3274            layout: wb.layout(),
3275            dormant: wb.dormant.clone(),
3276        }
3277    }
3278
3279    /// Puts in a layout (loaded, or an arrangement), repaired against
3280    /// today's panels and screens; says what the repair changed.
3281    pub fn set_layout(&self, layout: egui_pop_model::layout::Layout) -> Vec<String> {
3282        let before = self.workbench_mut().layout.auxiliary.clone();
3283        let names = self.layout_screens();
3284        let screens: Vec<&str> = names.iter().map(String::as_str).collect();
3285        let instances = crate::workbench::instances::open_ids(self);
3286        let notes = self.workbench_mut().set_layout(layout, &screens);
3287        self.sync_panel_windows(&before);
3288        crate::workbench::instances::say(self, &instances);
3289        self.note_layout("layout.set");
3290        notes
3291    }
3292
3293    /// The declared panels.
3294    pub fn panels(&self) -> Vec<egui_pop_model::panels::PanelSpec> {
3295        self.workbench_mut().specs.clone()
3296    }
3297
3298    /// Every declared panel with the plugin that declared it (its
3299    /// [`OwnerId`]), in declaration order: the application's panels and
3300    /// those of the plugins it connected, egui-pop's among them (the
3301    /// jobs centre, `egui_pop.jobs`; the devtools). A host that checks
3302    /// layouts or templates against its own panels accepts these too, so
3303    /// a template may place a plugin's panel. Unlike [`Self::panels`], a
3304    /// zone shown as a panel is listed even while it has no blocks.
3305    pub fn declared_panels(&self) -> Vec<(egui_pop_model::panels::PanelSpec, OwnerId)> {
3306        self.0.derived.borrow().panels.clone()
3307    }
3308
3309    /// The drop hint on screen, while a tab is dragged (where it would
3310    /// land, in its area or another) or a palette over an area it docks
3311    /// in.
3312    ///
3313    /// <div class="warning">Experimental: may change in any release
3314    /// (docs/stability.md).</div>
3315    pub fn drop_hint(&self) -> Option<crate::workbench::DropHint> {
3316        self.workbench_mut().hint.clone()
3317    }
3318
3319    /// The detached window under a dragged tab, where letting it go
3320    /// moves it (as a tab), found in the last pass: `None` while no tab
3321    /// is dragged over one.
3322    ///
3323    /// <div class="warning">Experimental: may change in any release
3324    /// (docs/stability.md).</div>
3325    pub fn window_drop(&self) -> Option<crate::workbench::WindowDrop> {
3326        self.workbench_mut().window_drop.clone()
3327    }
3328
3329    /// The detached windows outlined in the last pass: a tab is dragged out
3330    /// of the main window, where the system hides window positions
3331    /// (Wayland), and these windows may take it, though none can tell the
3332    /// pointer is over it until it is let go.
3333    ///
3334    /// <div class="warning">Experimental: may change in any release
3335    /// (docs/stability.md).</div>
3336    pub fn window_outlines(&self) -> Vec<PanelId> {
3337        self.workbench_mut().window_outlines().to_vec()
3338    }
3339
3340    /// The panel the keys obey, the context key `focusedPanel`: the last that
3341    /// held the widget focus, had the pointer pressed in it or was given the
3342    /// keyboard (`crate::workbench`'s "The focused panel").
3343    pub fn focused_panel(&self) -> Option<PanelId> {
3344        self.workbench_mut().focused.clone()
3345    }
3346
3347    /// Changes the workbench through its step (ADR 0011): `None` when
3348    /// asked while the areas are drawn (it is done at the frame's end).
3349    ///
3350    /// <div class="warning">Experimental: may change in any release
3351    /// (docs/stability.md).</div>
3352    pub fn change_workbench(&self, change: crate::workbench::Change) -> Option<Outcome> {
3353        self.change_workbench_from(change, None)
3354    }
3355
3356    /// [`AppHandle::change_workbench`], asked from a window (`origin`) and
3357    /// sent to the window the application chose (`home`), both in the
3358    /// step's arguments: a panel opening goes there (rule A,
3359    /// [`crate::workbench::window_areas`]). Without them, the window the
3360    /// change is asked in.
3361    pub(crate) fn change_workbench_from(
3362        &self,
3363        change: crate::workbench::Change,
3364        from: Option<crate::workbench::window_areas::OpenFrom>,
3365    ) -> Option<Outcome> {
3366        if self.0.drawing_areas.get() {
3367            self.push_request(Request::Workbench(change));
3368            return None;
3369        }
3370        let (step, mut args) = change.step();
3371        if let Some(from) = from {
3372            if let Some(origin) = from.origin {
3373                args["origin"] = Json::String(origin);
3374            }
3375            if let Some(home) = from.home {
3376                args["home"] = Json::String(home);
3377            }
3378            if let Some(area) = from.area {
3379                args["home_area"] = Json::String(crate::workbench::area_name(area).into());
3380            }
3381        }
3382        let id = step.clone();
3383        let focused = self.focused_panel();
3384        let instances = crate::workbench::instances::open_ids(self);
3385        let out = self.step(&step, args, move |app, args| {
3386            let c = crate::workbench::Change::from_args(&id, args)?;
3387            // Zen mode on one panel (`panel`, as a plugin may have
3388            // redirected it): a draw override, the layout untouched.
3389            if let crate::workbench::Change::Zen(on) = c {
3390                let panel = match args.get("panel").and_then(Json::as_str) {
3391                    Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
3392                    None => None,
3393                };
3394                return app.workbench_mut().apply_zen(on, panel);
3395            }
3396            // A detached panel's window opened, docked back or closed is
3397            // its request on the bus, whose workbench listener changes the
3398            // layout; any other window the change made or ended is asked
3399            // once it is done.
3400            let before = app.workbench_mut().layout.auxiliary.clone();
3401            // Which panels may float, as the user's setting says now.
3402            let scope = crate::workbench::float_scope(app);
3403            app.workbench_mut().float_scope = scope;
3404            // Where it was asked from, and the windows shown now: where a
3405            // panel opening may go.
3406            let from = crate::workbench::window_areas::OpenFrom::of(app, args);
3407            let shown = app.shown_window_ids();
3408            {
3409                let mut wb = app.workbench_mut();
3410                wb.open_from = Some(from);
3411                wb.open_windows = shown;
3412            }
3413            let done = match crate::bus::panels::ask(app, &c) {
3414                Some(done) => done,
3415                None => app.workbench_mut().apply(&c),
3416            };
3417            app.workbench_mut().open_from = None;
3418            app.sync_panel_windows(&before);
3419            done
3420        });
3421        if self.focused_panel() != focused {
3422            self.publish_focused();
3423        }
3424        crate::workbench::instances::say(self, &instances);
3425        // Said on the bus once its gesture ended (`pop.layout.changed`).
3426        if matches!(out, Outcome::Done(Ok(_))) {
3427            self.note_layout(step.as_str());
3428        }
3429        // A palette's change, once done, is news.
3430        if let (Some(event), Outcome::Done(Ok(result))) = (change.event(), &out) {
3431            self.publish("egui_pop", None, event, result.clone());
3432        }
3433        if matches!(change, crate::workbench::Change::Zen(_)) {
3434            self.follow_zen();
3435        }
3436        self.egui().request_repaint();
3437        Some(out)
3438    }
3439
3440    /// Starts zen mode (only the centre is shown) or ends it
3441    /// (`workbench.zen`).
3442    pub fn set_zen(&self, on: bool) -> Option<Outcome> {
3443        self.change_workbench(crate::workbench::Change::Zen(on))
3444    }
3445
3446    /// Starts zen mode on one panel (`workbench.zen` with `panel`): the
3447    /// panel alone, full size, in the window holding it, a detached
3448    /// window's included; the layout is left as it is, so leaving zen
3449    /// mode ([`Self::set_zen`] with `false`) draws it unchanged. A panel
3450    /// that is not open is refused. `None` when asked while the areas
3451    /// are drawn: it runs at the frame's end.
3452    ///
3453    /// <div class="warning">Experimental: may change in any release
3454    /// (docs/stability.md).</div>
3455    pub fn set_zen_panel(&self, panel: &PanelId) -> Option<Outcome> {
3456        let args = json!({ "zen": true, "panel": panel });
3457        if self.0.drawing_areas.get() {
3458            self.push_request(Request::Run {
3459                command: crate::workbench::CMD_ZEN,
3460                args: json!({ "panel": panel }),
3461                origin: Origin::User,
3462            });
3463            return None;
3464        }
3465        let step = crate::workbench::STEP_ZEN;
3466        let id = step.clone();
3467        let out = self.step(&step, args, move |app, args| {
3468            let c = crate::workbench::Change::from_args(&id, args)?;
3469            let crate::workbench::Change::Zen(on) = c else {
3470                return Err("not a zen mode change".into());
3471            };
3472            let panel = match args.get("panel").and_then(Json::as_str) {
3473                Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
3474                None => None,
3475            };
3476            app.workbench_mut().apply_zen(on, panel)
3477        });
3478        self.follow_zen();
3479        self.egui().request_repaint();
3480        Some(out)
3481    }
3482
3483    /// Whether zen mode is on.
3484    pub fn zen(&self) -> bool {
3485        self.workbench_mut().zen
3486    }
3487
3488    /// The panel zen mode shows alone, while it shows one (none: off, or
3489    /// the centre whole).
3490    ///
3491    /// <div class="warning">Experimental: may change in any release
3492    /// (docs/stability.md).</div>
3493    pub fn zen_panel(&self) -> Option<PanelId> {
3494        let wb = self.workbench_mut();
3495        wb.zen_panel.clone().filter(|_| wb.zen)
3496    }
3497
3498    /// Whether `panel` is the one panel docked in the centre.
3499    pub(crate) fn centre_holds_only(&self, panel: &PanelId) -> bool {
3500        let wb = self.workbench_mut();
3501        let centre = wb.panels_in(Area::Center);
3502        centre.len() == 1 && centre[0] == *panel
3503    }
3504
3505    /// Whether zen mode changes what the main window draws (on, and not
3506    /// on a detached window's panel).
3507    pub(crate) fn main_zen(&self) -> bool {
3508        self.workbench_mut().main_zen()
3509    }
3510
3511    /// The panel zen mode would show now, without one named: the focused
3512    /// panel when it is a view or mixed one, else the application's
3513    /// choice (`pop.zen.panel`), else the centre's active tab; each one
3514    /// open. `None`: the centre whole.
3515    ///
3516    /// <div class="warning">Experimental: may change in any release
3517    /// (docs/stability.md).</div>
3518    pub fn zen_target(&self) -> Option<PanelId> {
3519        use egui_pop_model::panels::PanelKind;
3520        let shows = |p: &PanelId| self.workbench_mut().layout.shows(p);
3521        if let Some(p) = self.focused_panel().filter(|p| {
3522            shows(p) && matches!(self.panel_kind(p), PanelKind::View | PanelKind::Mixed)
3523        }) {
3524            return Some(p);
3525        }
3526        if let Some(p) = self
3527            .zen_choice()
3528            .and_then(|p| PanelId::new(&p).ok())
3529            .filter(|p| shows(p))
3530        {
3531            return Some(p);
3532        }
3533        let wb = self.workbench_mut();
3534        wb.layout
3535            .active_in(egui_pop_model::panels::Area::Center)
3536            .first()
3537            .map(|p| (*p).clone())
3538    }
3539
3540    /// Keeps the `workbenchZen` context key in line with zen mode.
3541    pub(crate) fn follow_zen(&self) {
3542        let on = self.zen();
3543        self.set_context("workbenchZen", if on { "true" } else { "false" });
3544    }
3545
3546    /// Where an area was drawn in the last pass (none while it is not
3547    /// shown, folded included).
3548    pub fn area_rect(&self, area: Area) -> Option<egui::Rect> {
3549        self.workbench_mut().rects.get(&area).copied()
3550    }
3551
3552    /// Lays out the row, column or grid holding a panel's group again
3553    /// (`workbench.arrange`; refused for a group alone in its area).
3554    ///
3555    /// <div class="warning">Experimental: may change in any release
3556    /// (docs/stability.md).</div>
3557    pub fn arrange(&self, panel: &PanelId, how: crate::workbench::Arrangement) -> Option<Outcome> {
3558        self.change_workbench(crate::workbench::Change::Arrange(panel.clone(), how))
3559    }
3560
3561    /// Folds an area to its strip, or unfolds it (`workbench.fold`).
3562    pub fn fold_area(&self, area: Area, folded: bool) -> Option<Outcome> {
3563        self.change_workbench(crate::workbench::Change::Fold(area, folded))
3564    }
3565
3566    /// Folds an application window's area to its strip, or unfolds it
3567    /// (`workbench.fold` with `window`): a side area keeps a strip with
3568    /// its panels' icons, each opening its panel as a flyout; the bottom
3569    /// goes out of sight. Refused for a window without areas and for the
3570    /// centre; `window` the main window's id folds the main window's.
3571    ///
3572    /// <div class="warning">Experimental: may change in any release
3573    /// (docs/stability.md).</div>
3574    pub fn fold_window_area(&self, window: &str, area: Area, folded: bool) -> Option<Outcome> {
3575        let change = if window == crate::windows::WindowId::MAIN {
3576            crate::workbench::Change::Fold(area, folded)
3577        } else {
3578            crate::workbench::Change::FoldWindow(window.to_string(), area, folded)
3579        };
3580        self.change_workbench(change)
3581    }
3582
3583    /// Opens a folded side area's panel alone over the centre, as a
3584    /// click on its strip icon does, or closes it (`workbench.flyout`;
3585    /// refused for a panel not in a folded side area).
3586    pub fn open_flyout(&self, panel: &PanelId, open: bool) -> Option<Outcome> {
3587        self.change_workbench(crate::workbench::Change::Flyout(panel.clone(), open))
3588    }
3589
3590    /// The panel shown as a flyout, and where it was drawn in the last
3591    /// pass (none before it is drawn).
3592    pub fn flyout(&self) -> Option<(PanelId, Option<egui::Rect>)> {
3593        let wb = self.workbench_mut();
3594        wb.flyout.clone().map(|p| (p, wb.flyout_rect))
3595    }
3596
3597    /// Lays a side area beside the centre or over it (`workbench.place`;
3598    /// refused for the centre and the bottom area).
3599    pub fn place_area(
3600        &self,
3601        area: Area,
3602        placement: egui_pop_model::layout::Placement,
3603    ) -> Option<Outcome> {
3604        self.change_workbench(crate::workbench::Change::Place(area, placement))
3605    }
3606
3607    /// Where a side area lies now (beside the centre, or over it).
3608    pub fn area_placement(&self, area: Area) -> egui_pop_model::layout::Placement {
3609        self.workbench_mut().layout.placement(area)
3610    }
3611
3612    /// The indicators and their states, lightest first.
3613    ///
3614    /// <div class="warning">Experimental: may change in any release
3615    /// (docs/stability.md).</div>
3616    pub fn indicators(&self) -> Vec<(crate::strips::Indicator, crate::strips::IndicatorState)> {
3617        let mut v: Vec<_> = self
3618            .0
3619            .indicators
3620            .borrow()
3621            .iter()
3622            .map(|s| s.item.clone())
3623            .collect();
3624        v.sort_by_key(|(i, _)| i.weight);
3625        v
3626    }
3627
3628    pub(crate) fn add_indicator(&self, owner: &OwnerId, ind: crate::strips::Indicator) {
3629        let state = ind.initial.clone();
3630        self.0.indicators.borrow_mut().push(owner, (ind, state));
3631    }
3632
3633    /// Feeds the journal's new events to the indicators.
3634    pub(crate) fn feed_indicators(&self) {
3635        let seen = self.0.indicators_seen.get();
3636        let last = self.last_event();
3637        if last <= seen {
3638            return;
3639        }
3640        let events = self.events_since(seen);
3641        let mut list = self.0.indicators.borrow_mut();
3642        let mut items: Vec<_> = list.iter_mut().map(|s| &mut s.item).collect();
3643        for e in &events {
3644            for (ind, state) in items.iter_mut().map(|x| (&x.0, &mut x.1)) {
3645                if e.name.starts_with(&ind.prefix) {
3646                    (ind.reduce)(state, e);
3647                    state.seq = e.seq;
3648                }
3649            }
3650        }
3651        self.0.indicators_seen.set(last);
3652    }
3653
3654    /// Moves a panel to an area (`workbench.move`); refused when its
3655    /// rules keep it out.
3656    pub fn move_panel(&self, panel: &PanelId, area: Area) -> Option<Outcome> {
3657        self.change_workbench(crate::workbench::Change::Move(panel.clone(), area))
3658    }
3659
3660    /// Moves a panel into the detached window holding `window` (a panel
3661    /// of it), as a tab (`workbench.join_window`).
3662    pub fn move_to_window(&self, panel: &PanelId, window: &PanelId) -> Option<Outcome> {
3663        self.change_workbench(crate::workbench::Change::JoinWindow(
3664            panel.clone(),
3665            window.clone(),
3666        ))
3667    }
3668
3669    /// Moves a panel to a window of its own (`workbench.detach`).
3670    pub fn detach_panel(&self, panel: &PanelId) -> Option<Outcome> {
3671        self.change_workbench(crate::workbench::Change::Detach(panel.clone()))
3672    }
3673
3674    /// Docks a detached panel back in its area (`workbench.attach`).
3675    pub fn attach_panel(&self, panel: &PanelId) -> Option<Outcome> {
3676        self.change_workbench(crate::workbench::Change::Attach(panel.clone()))
3677    }
3678
3679    /// Shows a panel and gives it the keyboard (`workbench.focus`): it is the
3680    /// focused panel at once, and in the next pass the panel itself holds the
3681    /// focus (its own stop, from which Tab enters its widgets), or the widget
3682    /// it named with `focus::prefer` (`crate::workbench`'s "The focused
3683    /// panel").
3684    pub fn focus_panel(&self, panel: &PanelId) -> Option<Outcome> {
3685        self.change_workbench(crate::workbench::Change::Focus(panel.clone()))
3686    }
3687
3688    /// A change the workbench refused: on the journal, and in a toast when
3689    /// toasts are there.
3690    pub(crate) fn workbench_refused(&self, what: &str, why: &str) {
3691        self.publish(
3692            "egui_pop",
3693            None,
3694            "workbench.refused",
3695            json!({ "change": what, "reason": why }),
3696        );
3697        if let Some(t) = self.service(&crate::toasts::TOASTS) {
3698            t.notify(crate::toasts::Toast::warning(why));
3699        }
3700    }
3701}
3702
3703/// A step's outcome as a command's result.
3704fn outcome_result(outcome: Outcome) -> Result<Json, String> {
3705    match outcome {
3706        Outcome::Done(r) => r,
3707        Outcome::Vetoed { by, reason } => Err(format!("stopped by `{by}`: {reason}")),
3708    }
3709}
3710
3711/// A zen mode command's result: the step's, or the change asked for when
3712/// it runs after the areas are drawn.
3713fn zen_result(outcome: Option<Outcome>, on: bool) -> Result<Json, String> {
3714    match outcome {
3715        Some(o) => outcome_result(o),
3716        None => Ok(json!({ "zen": on })),
3717    }
3718}
3719
3720/// After a panel asked for the focus and drew its content: the widget it
3721/// prefers (`focus::prefer`) takes it, else the panel's own stop keeps it.
3722/// Never its first focusable widget: a slider focused that way would take
3723/// the wheel meant to scroll the panel; Tab goes on from the stop.
3724fn settle_panel_focus(ui: &mut Ui) {
3725    if let Some(preferred) = focus::preferred(ui.ctx()) {
3726        ui.memory_mut(|m| m.request_focus(preferred));
3727    }
3728}
3729
3730/// Whether a focus target (a surface's name, a panel's id, or a panel
3731/// kind's) names the focus surface `surface`: the surface itself, the
3732/// panel's surface (its id as a scope name), or, for a kind, the surface
3733/// of each of its instances (`app.gallery` names `app.gallery#2`'s,
3734/// `app.gallery_2`). A target naming an instance (`app.gallery#2`) names
3735/// that instance only.
3736pub(crate) fn names_surface(target: &str, surface: &str) -> bool {
3737    if target == surface {
3738        return true;
3739    }
3740    let own = scope_name(target);
3741    if own == surface {
3742        return true;
3743    }
3744    !target.contains('#')
3745        && surface
3746            .strip_prefix(own.as_str())
3747            .and_then(|rest| rest.strip_prefix('_'))
3748            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
3749}
3750
3751/// A focus scope name from an id: letters, digits, `_` and `.` only.
3752pub(crate) fn scope_name(id: &str) -> String {
3753    id.chars()
3754        .map(|c| {
3755            if c.is_ascii_alphanumeric() || c == '.' {
3756                c
3757            } else {
3758                '_'
3759            }
3760        })
3761        .collect()
3762}
3763
3764struct Slot {
3765    plugin: Box<dyn Plugin>,
3766    id: PluginId,
3767    owner: OwnerId,
3768    connected: bool,
3769    reason: Option<String>,
3770}
3771
3772/// Builds an application.
3773pub struct AppBuilder {
3774    plugins: Vec<Box<dyn Plugin>>,
3775    /// The ids of the plugins a group added: one added on its own with
3776    /// the same id takes its place.
3777    grouped: Vec<PluginId>,
3778    theme: ThemeSpec,
3779    themes: Themes,
3780    persist: Option<Persist>,
3781    store: Option<SharedStore>,
3782    host: Option<Box<dyn Host>>,
3783    /// The bus the application supplies (`AppBuilder::bus`).
3784    bus: Option<Arc<dyn crate::bus::bus_contract::Bus>>,
3785    system_focus: Option<SystemFocus>,
3786    /// The application opens windows of its own (`AppBuilder::multi_window`).
3787    multi_window: bool,
3788    system_text_scale: crate::text::SystemTextScale,
3789    system_scroll_bars: bool,
3790    system_wheel_lines: u32,
3791    edge_to_edge: bool,
3792    frameless: Vec<Area>,
3793    bare_strips: Vec<Area>,
3794    layout: Option<egui_pop_model::layout::Layout>,
3795    menu_bar: bool,
3796    system_file_chooser: bool,
3797    transparent_panel_windows: bool,
3798    rounded_windows: Option<bool>,
3799    shell_sizes: Vec<(PanelId, f32)>,
3800    shell_bounds: Vec<(PanelId, crate::workbench::ShellBounds)>,
3801    centre_min: Option<crate::workbench::ShellSize>,
3802    folded: Vec<Area>,
3803    over: Vec<Area>,
3804    wrap: Option<WrapUi>,
3805    on_exit: Vec<ExitFn>,
3806    name: Option<String>,
3807    app_id: Option<String>,
3808    panel_alignment: crate::workbench::PanelAlignment,
3809    toast_corner: crate::toasts::Corner,
3810    group_handles: crate::workbench::GroupHandles,
3811    dock_controls: crate::workbench::DockControls,
3812    arrangement_strings: crate::arrangements::ArrangementStrings,
3813    pointer_profile: String,
3814    dock_drag: Option<egui_pop_model::pointer::DockDrag>,
3815    kits: Vec<KitSource>,
3816    user_kits: bool,
3817    cache: Option<egui_pop_core::tokens::cache::Cache>,
3818    writer_check: Option<egui_pop_model::values::WriterCheck>,
3819    offered: Vec<String>,
3820    offered_commands: Vec<CommandId>,
3821    bridge_mode: Option<egui_pop_core::debug::BridgeMode>,
3822}
3823
3824/// Draws around the whole application (`AppBuilder::wrap`): gets the
3825/// `Ui`, the handle, and the application's drawing to call where it
3826/// likes.
3827pub type WrapUi = Box<dyn FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui))>;
3828/// Runs when the application closes (`AppBuilder::on_exit`), before the
3829/// `app.exit` step.
3830pub type ExitFn = Box<dyn FnMut(&AppHandle)>;
3831
3832/// The application closes: its default writes what is still waiting
3833/// (the settings, the keymap, the layout and the documents plugins
3834/// offered, when a directory was given). A plugin replaces it to save
3835/// elsewhere, or follows it; a veto writes nothing more. Saving does not
3836/// wait for the exit: what changes is written about a second later
3837/// (`AppHandle::save_later`).
3838pub const STEP_EXIT: StepId = StepId::from_static("app.exit");
3839/// A debug collector's action is called (`{ "collector", "action",
3840/// "args", "origin" }`, the origin as the journal's sources write it:
3841/// `agent:debug-bridge`, `user`): by an agent through the bridge
3842/// (`AppHandle::debug_call`) or by the user (`AppHandle::debug_call_as`,
3843/// the devtools panel). A before-hook may veto it, for every caller (a
3844/// kiosk build); the caller is not redirected. A call that only reads (a
3845/// read-only command's `commands.run` included) is published and traced
3846/// only when vetoed or failed. A call the bridge's mode or the action's
3847/// `agent` flag refuses never reaches the step: it is refused first
3848/// (`debug.call.refused`).
3849pub const STEP_DEBUG_CALL: StepId = StepId::from_static("debug.call");
3850
3851/// The bridge's own collector: `bridge.describe`, `bridge.wait`.
3852pub const BRIDGE: &str = "bridge";
3853/// The workbench's layout is loaded (`{ "document" }`, from
3854/// `Host::layout_document`): at the start, and on `App::load_layout`. A
3855/// before-hook may redirect the document or veto; a run-hook loads it
3856/// from elsewhere (and calls `AppHandle::set_layout`).
3857pub const STEP_LAYOUT_LOAD: StepId = StepId::from_static("layout.load");
3858/// The workbench's layout is saved (`{ "document" }`): by `App::save`
3859/// (so at exit) and `App::save_layout`. A before-hook may redirect or
3860/// veto; a run-hook saves it elsewhere (`AppHandle::layout`).
3861pub const STEP_LAYOUT_SAVE: StepId = StepId::from_static("layout.save");
3862
3863impl fmt::Debug for AppBuilder {
3864    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3865        f.debug_struct("AppBuilder")
3866            .field(
3867                "plugins",
3868                &self.plugins.iter().map(|p| p.id()).collect::<Vec<_>>(),
3869            )
3870            .field("theme", &self.theme)
3871            .finish()
3872    }
3873}
3874
3875impl Default for AppBuilder {
3876    fn default() -> Self {
3877        Self::new()
3878    }
3879}
3880
3881impl AppBuilder {
3882    pub fn new() -> Self {
3883        Self {
3884            plugins: Vec::new(),
3885            grouped: Vec::new(),
3886            theme: ThemeSpec::default(),
3887            themes: Themes::default(),
3888            persist: None,
3889            store: None,
3890            writer_check: None,
3891            offered: Vec::new(),
3892            offered_commands: Vec::new(),
3893            bridge_mode: None,
3894            host: None,
3895            bus: None,
3896            system_focus: None,
3897            multi_window: false,
3898            system_text_scale: crate::text::SystemTextScale::default(),
3899            system_scroll_bars: false,
3900            system_wheel_lines: crate::pointer::SYSTEM_WHEEL_LINES,
3901            edge_to_edge: false,
3902            frameless: Vec::new(),
3903            bare_strips: Vec::new(),
3904            layout: None,
3905            menu_bar: true,
3906            system_file_chooser: false,
3907            transparent_panel_windows: false,
3908            rounded_windows: None,
3909            shell_sizes: Vec::new(),
3910            shell_bounds: Vec::new(),
3911            centre_min: None,
3912            folded: Vec::new(),
3913            over: Vec::new(),
3914            wrap: None,
3915            on_exit: Vec::new(),
3916            name: None,
3917            app_id: None,
3918            panel_alignment: crate::workbench::PanelAlignment::Center,
3919            toast_corner: crate::toasts::Corner::default(),
3920            group_handles: crate::workbench::DEFAULT_GROUP_HANDLES,
3921            dock_controls: crate::workbench::DockControls::default(),
3922            arrangement_strings: crate::arrangements::ArrangementStrings::default(),
3923            pointer_profile: egui_pop_model::pointer::DEFAULT_PROFILE.into(),
3924            dock_drag: None,
3925            kits: Vec::new(),
3926            user_kits: false,
3927            cache: None,
3928        }
3929    }
3930
3931    /// The bottom panel's alignment by default (the
3932    /// `workbench.panel_alignment` setting's default; `Center`, under
3933    /// the editors between the side bars as VS Code has it, unless
3934    /// given).
3935    ///
3936    /// <div class="warning">Experimental: may change in any release
3937    /// (docs/stability.md).</div>
3938    pub fn panel_alignment(mut self, alignment: crate::workbench::PanelAlignment) -> Self {
3939        self.panel_alignment = alignment;
3940        self
3941    }
3942
3943    /// Where the toasts show by default (the `appearance.toast_corner`
3944    /// setting's default; the bottom-right corner unless given).
3945    pub fn toast_corner(mut self, corner: crate::toasts::Corner) -> Self {
3946        self.toast_corner = corner;
3947        self
3948    }
3949
3950    /// The handles that may move a whole tab group, and a floating
3951    /// window's move handle (`MOVE_WINDOW`): the user turns off any of
3952    /// them in the settings, never on one left out here. By default
3953    /// [`DEFAULT_GROUP_HANDLES`](crate::workbench::DEFAULT_GROUP_HANDLES),
3954    /// every handle.
3955    ///
3956    /// <div class="warning">Experimental: may change in any release
3957    /// (docs/stability.md).</div>
3958    pub fn group_handles(mut self, allowed: crate::workbench::GroupHandles) -> Self {
3959        self.group_handles = allowed;
3960        self
3961    }
3962
3963    /// The controls the workbench's docks show beyond their tabs: an
3964    /// "Eject group" button on the tab bars, the groups' menus, what
3965    /// drags a floating window
3966    /// ([`DockControls`](crate::workbench::DockControls)). By default
3967    /// egui_stack's: no eject button, the group menus on, a floating
3968    /// window moved by its bar.
3969    ///
3970    /// <div class="warning">Experimental: may change in any release
3971    /// (docs/stability.md).</div>
3972    pub fn dock_controls(mut self, controls: crate::workbench::DockControls) -> Self {
3973        self.dock_controls = controls;
3974        self
3975    }
3976
3977    /// The application's own texts naming an arrangement of the panels
3978    /// ([`ArrangementStrings`](crate::arrangements::ArrangementStrings)):
3979    /// the layout menu's "Save the current arrangement as…", the save
3980    /// dialog's title and button, the name it suggests. Whole strings
3981    /// under the application's keys, translated by its catalogues; by
3982    /// default egui-pop's.
3983    ///
3984    /// <div class="warning">Experimental: may change in any release
3985    /// (docs/stability.md).</div>
3986    pub fn arrangement_strings(mut self, words: crate::arrangements::ArrangementStrings) -> Self {
3987        self.arrangement_strings = words;
3988        self
3989    }
3990
3991    /// The pointer profile by default (the `input.pointer_profile`
3992    /// setting's default: `document` unless given; `darktable`,
3993    /// `photoshop`, `lightroom`, `blender`, `trackpad`; the retired
3994    /// `adobe` gives `lightroom`). An id no profile has is reported and
3995    /// the default kept.
3996    pub fn pointer_profile(mut self, id: &str) -> Self {
3997        self.pointer_profile = id.into();
3998        self
3999    }
4000
4001    /// What a plain drag of a floating palette does by default (the
4002    /// `input.dock_drag` setting's default; the pointer profile's unless
4003    /// given, which is [`DockDrag::ModifierDocks`] but for Photoshop's):
4004    /// a Visual Studio-like application picks
4005    /// [`DockDrag::ModifierFloats`], a touch-first one [`DockDrag::Dwell`].
4006    /// The user changes it in the settings.
4007    ///
4008    /// <div class="warning">Experimental: may change in any release
4009    /// (docs/stability.md).</div>
4010    ///
4011    /// [`DockDrag::ModifierDocks`]: egui_pop_model::pointer::DockDrag::ModifierDocks
4012    /// [`DockDrag::ModifierFloats`]: egui_pop_model::pointer::DockDrag::ModifierFloats
4013    /// [`DockDrag::Dwell`]: egui_pop_model::pointer::DockDrag::Dwell
4014    pub fn dock_drag(mut self, mode: egui_pop_model::pointer::DockDrag) -> Self {
4015        self.dock_drag = Some(mode);
4016        self
4017    }
4018
4019    /// The application's name ("Helios"), apart from its window's title
4020    /// ("photo.raw — Helios"): a detached panel's window says it
4021    /// (`{ $application }`), and the frame shows it when `FramePlugin`
4022    /// has no name of its own. `run_native` takes its `app_name` when
4023    /// none is given.
4024    pub fn name(mut self, name: &str) -> Self {
4025        self.name = Some(name.into());
4026        self
4027    }
4028
4029    /// The application's id, reverse-DNS (`org.example.App`): the one its
4030    /// desktop file, its store listing and its window (eframe's
4031    /// `ViewportBuilder::with_app_id`) carry. What identifies the
4032    /// application to others reads it (`AppHandle::app_id`): the viewer's
4033    /// YouTube player sends it. `run_native` takes the window's when none
4034    /// is given.
4035    pub fn app_id(mut self, id: &str) -> Self {
4036        self.app_id = Some(id.into());
4037        self
4038    }
4039
4040    /// Draws the main area edge to edge: no margin around the centre's
4041    /// panels (an image viewer, a canvas). Their bodies keep their own
4042    /// frame; [`AppBuilder::frameless`] takes that away too.
4043    ///
4044    /// <div class="warning">Experimental: may change in any release
4045    /// (docs/stability.md).</div>
4046    pub fn main_edge_to_edge(mut self, on: bool) -> Self {
4047        self.edge_to_edge = on;
4048        self
4049    }
4050
4051    /// Areas drawn without a frame: no margin around the area, and its
4052    /// panels' bodies without margin, border or rounded corners, so that
4053    /// they run to the window's edges and are set apart by the splitter's
4054    /// line only (a viewer whose views draw to their edges). A panel then
4055    /// gives itself the margin it wants. Any area: the side areas, the
4056    /// bottom one, the centre (which `main_edge_to_edge` leaves framed
4057    /// inside).
4058    ///
4059    /// ```
4060    /// use egui_pop_api::App;
4061    /// use egui_pop_model::panels::Area;
4062    ///
4063    /// let app = App::builder()
4064    ///     .frameless(&[Area::StartSide, Area::Bottom])
4065    ///     .build(&egui::Context::default())
4066    ///     .unwrap();
4067    /// assert!(app.handle().frameless(Area::Bottom));
4068    /// assert!(!app.handle().frameless(Area::EndSide));
4069    /// ```
4070    ///
4071    /// <div class="warning">Experimental: may change in any release
4072    /// (docs/stability.md).</div>
4073    pub fn frameless(mut self, areas: &[Area]) -> Self {
4074        self.frameless = areas.to_vec();
4075        self
4076    }
4077
4078    /// Side areas whose folded strip stays bare: its grip glyph alone,
4079    /// `area-strip.width` wide, without an icon (or a title's first
4080    /// letter) per panel; a click on it unfolds the area, and no panel
4081    /// opens as a flyout from it. For an application whose folded area is
4082    /// a plain handle. The centre and the bottom area have no strip and
4083    /// are ignored.
4084    ///
4085    /// ```
4086    /// use egui_pop_api::App;
4087    /// use egui_pop_model::panels::Area;
4088    ///
4089    /// let app = App::builder()
4090    ///     .bare_strips(&[Area::StartSide])
4091    ///     .build(&egui::Context::default())
4092    ///     .unwrap();
4093    /// assert!(app.handle().bare_strip(Area::StartSide));
4094    /// assert!(!app.handle().bare_strip(Area::EndSide));
4095    /// ```
4096    pub fn bare_strips(mut self, areas: &[Area]) -> Self {
4097        self.bare_strips = areas
4098            .iter()
4099            .copied()
4100            .filter(|a| matches!(a, Area::StartSide | Area::EndSide))
4101            .collect();
4102        self
4103    }
4104
4105    /// The layout the application starts with when none was saved, and
4106    /// the one the `Default` arrangement resets to: its panels in their
4107    /// areas, its closed panels (`Layout::hidden`), its folded and lying
4108    /// areas. Not given, every panel starts in its default area. The
4109    /// shell's zone panels (`workbench::PANEL_SIDE_BAR`, `PANEL_MAIN`,
4110    /// `PANEL_INSPECTOR`) show as soon as their zones have blocks, a
4111    /// default plugin's included: listing them in `hidden` leaves them
4112    /// out. A panel the layout does
4113    /// not place goes to its default area; one it places where its rules
4114    /// forbid, or that no plugin declares, is repaired as a saved layout
4115    /// is (the repair is logged). `folded` and `over`, given too, add
4116    /// their areas.
4117    ///
4118    /// ```
4119    /// use egui_pop_api::App;
4120    /// use egui_pop_api::workbench::{PANEL_INSPECTOR, PANEL_SIDE_BAR};
4121    /// use egui_pop_model::layout::Layout;
4122    ///
4123    /// let app = App::builder()
4124    ///     .layout(Layout {
4125    ///         hidden: vec![PANEL_SIDE_BAR, PANEL_INSPECTOR],
4126    ///         ..Layout::default()
4127    ///     })
4128    ///     .build(&egui::Context::default())
4129    ///     .unwrap();
4130    /// assert!(!app.handle().panel_visible(&PANEL_SIDE_BAR));
4131    /// ```
4132    ///
4133    /// <div class="warning">Experimental: may change in any release
4134    /// (docs/stability.md).</div>
4135    pub fn layout(mut self, layout: egui_pop_model::layout::Layout) -> Self {
4136        self.layout = Some(layout);
4137        self
4138    }
4139
4140    /// Draws the main menu as a bar under the title (the default), or
4141    /// not at all: its commands stay in the palette, under their keys and
4142    /// in any menu the application opens itself (`menus::popup_at`). The
4143    /// top bar's zone is then drawn only when it has blocks.
4144    pub fn menu_bar(mut self, on: bool) -> Self {
4145        self.menu_bar = on;
4146        self
4147    }
4148
4149    /// Allows the system's file chooser (`files`, feature `native-dialogs`):
4150    /// a fallback, off by default, for an application that cannot do with
4151    /// egui-pop's in-app picker. On, the files plugin uses the system's
4152    /// chooser when the feature is compiled in, a portal answers and the
4153    /// person's `files.native` setting is on; never under tests
4154    /// (`files::system_chooser_refused`). Off, or without the feature, the
4155    /// in-app picker always answers.
4156    pub fn system_file_chooser(mut self, on: bool) -> Self {
4157        self.system_file_chooser = on;
4158        self
4159    }
4160
4161    /// Builds detached panels' windows transparent where the platform
4162    /// gives a surface below a window (Wayland, where the image viewport's
4163    /// image surface is a subsurface), so that surface shows through; off
4164    /// by default. Elsewhere, and off, they stay opaque. Either way each
4165    /// window says how it was built and why
4166    /// (`egui_pop_core::window_surface::transparency`, `windows.list`). The
4167    /// panel's content fills the window: eframe clears an immediate
4168    /// window to transparent, so a panel that leaves part of it unpainted
4169    /// shows the desktop there.
4170    pub fn transparent_panel_windows(mut self, on: bool) -> Self {
4171        self.transparent_panel_windows = on;
4172        self
4173    }
4174
4175    /// Whether the windows the application decorates (its own frame:
4176    /// the main window, detached panels' and application windows) get
4177    /// rounded corners while they float free (the kit's `window.radius`;
4178    /// square when maximized, in full screen or against a screen's
4179    /// edge). A rounded corner needs a transparent window, so they are
4180    /// built transparent: by default on Wayland only; `true` allows X11
4181    /// too (a compositing window manager is needed there), `false` keeps
4182    /// them square and opaque. Windows and macOS round their windows
4183    /// themselves (`window.corners`), the web has no window: never there.
4184    pub fn rounded_windows(mut self, on: bool) -> Self {
4185        self.rounded_windows = Some(on);
4186        self
4187    }
4188
4189    /// The size a shell panel starts at (`workbench::PANEL_SIDE_BAR`,
4190    /// `PANEL_INSPECTOR`: their width), instead of egui-pop's; its
4191    /// smallest size follows when it is larger. The user's resizing and a
4192    /// saved layout still win.
4193    pub fn shell_panel_size(mut self, panel: PanelId, size: f32) -> Self {
4194        self.shell_sizes.retain(|(p, _)| *p != panel);
4195        self.shell_sizes.push((panel, size));
4196        self
4197    }
4198
4199    /// The least size of a panel across its area (`workbench::PANEL_SIDE_BAR`,
4200    /// `PANEL_INSPECTOR`: their width), in points or as a share of the
4201    /// window ([`ShellSize`](crate::workbench::ShellSize)), instead of
4202    /// egui-pop's (120 points for the side bar, 160 for the inspector) or
4203    /// the panel's own `PanelSpec::min_size`. Dragging stops there, in
4204    /// the main window and in an application window's side areas alike. A
4205    /// least size measured from the panel's content, while running:
4206    /// [`AppHandle::set_shell_panel_min_size`].
4207    ///
4208    /// ```
4209    /// use egui_pop_api::App;
4210    /// use egui_pop_api::workbench::{PANEL_SIDE_BAR, ShellSize};
4211    ///
4212    /// let app = App::builder()
4213    ///     .shell_panel_min_size(PANEL_SIDE_BAR, 230.0)
4214    ///     .shell_panel_max_size(PANEL_SIDE_BAR, ShellSize::Share(0.6))
4215    ///     .build(&egui::Context::default())
4216    ///     .unwrap();
4217    /// # let _ = app;
4218    /// ```
4219    ///
4220    /// <div class="warning">Experimental: may change in any release
4221    /// (docs/stability.md).</div>
4222    pub fn shell_panel_min_size(
4223        mut self,
4224        panel: PanelId,
4225        size: impl Into<crate::workbench::ShellSize>,
4226    ) -> Self {
4227        self.bounds_of(panel).min = Some(size.into());
4228        self
4229    }
4230
4231    /// The largest size of a panel across its area, in points or as a
4232    /// share of the window; none by default. Dragging stops there; a
4233    /// least size larger wins.
4234    ///
4235    /// <div class="warning">Experimental: may change in any release
4236    /// (docs/stability.md).</div>
4237    pub fn shell_panel_max_size(
4238        mut self,
4239        panel: PanelId,
4240        size: impl Into<crate::workbench::ShellSize>,
4241    ) -> Self {
4242        self.bounds_of(panel).max = Some(size.into());
4243        self
4244    }
4245
4246    /// The centre's least width, in points or as a share of the window:
4247    /// the side areas give way to it, each down to its own least width
4248    /// (a window too narrow for all of them squeezes the centre). None by
4249    /// default.
4250    ///
4251    /// <div class="warning">Experimental: may change in any release
4252    /// (docs/stability.md).</div>
4253    pub fn centre_min_size(mut self, size: impl Into<crate::workbench::ShellSize>) -> Self {
4254        self.centre_min = Some(size.into());
4255        self
4256    }
4257
4258    fn bounds_of(&mut self, panel: PanelId) -> &mut crate::workbench::ShellBounds {
4259        let at = match self.shell_bounds.iter().position(|(p, _)| *p == panel) {
4260            Some(at) => at,
4261            None => {
4262                self.shell_bounds.push((panel, Default::default()));
4263                self.shell_bounds.len() - 1
4264            }
4265        };
4266        &mut self.shell_bounds[at].1
4267    }
4268
4269    /// Areas folded to their strip when the application starts with no
4270    /// saved layout (a saved one, the user's choice, wins).
4271    pub fn folded(mut self, areas: &[Area]) -> Self {
4272        self.folded = areas.to_vec();
4273        self
4274    }
4275
4276    /// Side areas lying over the centre when the application starts with
4277    /// no saved layout (`workbench.place`; a saved one wins): their
4278    /// folded strip keeps the room, the centre its width. The centre and
4279    /// the bottom area always lie beside.
4280    pub fn over(mut self, areas: &[Area]) -> Self {
4281        self.over = areas
4282            .iter()
4283            .copied()
4284            .filter(|a| matches!(a, Area::StartSide | Area::EndSide))
4285            .collect();
4286        self
4287    }
4288
4289    /// Draws around the whole application every frame (a custom frame,
4290    /// a backdrop): `f` gets the `Ui`, the handle and the application's
4291    /// drawing, to call where it likes.
4292    ///
4293    /// <div class="warning">Experimental: may change in any release
4294    /// (docs/stability.md).</div>
4295    pub fn wrap(
4296        mut self,
4297        f: impl FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui)) + 'static,
4298    ) -> Self {
4299        self.wrap = Some(Box::new(f));
4300        self
4301    }
4302
4303    /// Runs `f` when the application closes, before the `app.exit` step
4304    /// (which saves).
4305    ///
4306    /// <div class="warning">Experimental: may change in any release
4307    /// (docs/stability.md).</div>
4308    pub fn on_exit(mut self, f: impl FnMut(&AppHandle) + 'static) -> Self {
4309        self.on_exit.push(Box::new(f));
4310        self
4311    }
4312
4313    /// Adds a plugin; one a group added with the same id gives it its
4314    /// place.
4315    pub fn plugin(self, plugin: impl Plugin) -> Self {
4316        self.boxed(Box::new(plugin))
4317    }
4318
4319    /// Adds a group of plugins (`DefaultPlugins`, `MinimalPlugins`),
4320    /// less those whose id is already added.
4321    pub fn plugins(mut self, group: impl crate::PluginGroup) -> Self {
4322        for p in group.plugins() {
4323            let id = p.id();
4324            if self.plugins.iter().any(|q| q.id() == id) {
4325                continue;
4326            }
4327            self.grouped.push(id);
4328            self.plugins.push(p);
4329        }
4330        self
4331    }
4332
4333    /// Adds a boxed plugin; one a group added with the same id gives it
4334    /// its place.
4335    pub fn boxed(mut self, plugin: Box<dyn Plugin>) -> Self {
4336        let id = plugin.id();
4337        if let Some(i) = self.grouped.iter().position(|g| *g == id) {
4338            self.grouped.remove(i);
4339            self.plugins.retain(|p| p.id() != id);
4340        }
4341        self.plugins.push(plugin);
4342        self
4343    }
4344
4345    /// The theme at start-up.
4346    pub fn theme(mut self, spec: ThemeSpec) -> Self {
4347        self.theme = spec;
4348        self
4349    }
4350
4351    /// The themes to pick from (the built-in ones by default).
4352    pub fn themes(mut self, themes: Themes) -> Self {
4353        self.themes = themes;
4354        self
4355    }
4356
4357    /// Adds a kit (`docs/kit-packages.md`): its theme joins the themes to
4358    /// pick from, under the kit's name, and its faces and handlers are
4359    /// registered when the application is built. A folder read at run
4360    /// time, a `kit!` or a kit crate's `kit()`:
4361    ///
4362    /// ```
4363    /// use egui_pop_api::App;
4364    /// use egui_pop_core::kit::Kit;
4365    /// use egui_pop_core::theme::ThemeSpec;
4366    /// use egui_pop_core::tokens::kit::KitData;
4367    ///
4368    /// let kit = KitData::from_text(
4369    ///     "underline",
4370    ///     r#"
4371    ///     tab:
4372    ///       shape: {$type: "string", $value: "underline"}
4373    ///     "#,
4374    /// );
4375    /// let ctx = egui::Context::default();
4376    /// let app = App::builder()
4377    ///     .kit(kit)
4378    ///     .theme(ThemeSpec::new("underline"))
4379    ///     .build(&ctx)
4380    ///     .unwrap();
4381    /// assert_eq!(Kit::of(&ctx).tab.shape, "underline");
4382    /// assert_eq!(app.handle().theme().kits()[0].name, "underline");
4383    /// ```
4384    ///
4385    /// What is wrong with a kit is logged and in the diagnostics
4386    /// (`kit-problem`); the kit is added anyway, with fallbacks.
4387    ///
4388    /// <div class="warning">Experimental: may change in any release
4389    /// (docs/stability.md).</div>
4390    pub fn kit(mut self, kit: impl Into<KitSource>) -> Self {
4391        self.kits.push(kit.into());
4392        self
4393    }
4394
4395    /// Adds the user's kits too: the data-only kit folders under
4396    /// `<persist directory>/kits` (`egui_pop_tokens::kit::discover`), read
4397    /// when the application is built, after the application's own (a
4398    /// user kit of the same name replaces it), their YAML through the
4399    /// cache (`AppBuilder::cache`). Without a persistence directory there
4400    /// are none.
4401    pub fn user_kits(mut self, on: bool) -> Self {
4402        self.user_kits = on;
4403        self
4404    }
4405
4406    /// Where the files read at run time (the user's kits) are kept
4407    /// compiled (`egui_pop_tokens::cache`): `Cache::for_app(id)` for the
4408    /// platform's cache directory under the application's id,
4409    /// `Cache::at(dir)` elsewhere, `Cache::off()` for none. Not given,
4410    /// it is the process's default (`cache::set_default`), off until the
4411    /// application sets one.
4412    pub fn cache(mut self, cache: egui_pop_core::tokens::cache::Cache) -> Self {
4413        self.cache = Some(cache);
4414        self
4415    }
4416
4417    /// Where settings and the user's keymap are saved.
4418    pub fn persist(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
4419        self.persist = Some(Persist::new(dir));
4420        self
4421    }
4422
4423    /// Saves the settings, the layout and the window's place in the
4424    /// user's configuration folder, in a folder named `app`
4425    /// ([`crate::dirs::config_dir`]: `~/.config/<app>` on Linux), or in
4426    /// the temporary folder when the environment names no configuration
4427    /// folder. `persist_in_config(env!("CARGO_PKG_NAME"))` names it after
4428    /// the crate.
4429    pub fn persist_in_config(self, app: &str) -> Self {
4430        let dir = crate::dirs::config_dir(app).unwrap_or_else(|| {
4431            // The web has no temporary folder (`temp_dir` panics there).
4432            let temp = if cfg!(target_arch = "wasm32") {
4433                std::path::PathBuf::new()
4434            } else {
4435                std::env::temp_dir()
4436            };
4437            temp.join(app)
4438        });
4439        self.persist(dir)
4440    }
4441
4442    /// The application's kernel: runs the commands, keeps the journal
4443    /// and the store (`LocalHost` by default, see `host`).
4444    ///
4445    /// <div class="warning">Experimental: may change in any release
4446    /// (docs/stability.md).</div>
4447    pub fn host(mut self, host: impl Host + 'static) -> Self {
4448        self.host = Some(Box::new(host));
4449        self
4450    }
4451
4452    /// The bus egui-pop publishes on and listens to (ADR 0030): the
4453    /// application's, shared with its other libraries if it chooses one
4454    /// bus, or one of several. egui-pop declares its points on it
4455    /// ([`crate::bus::CONTRACT`]) and registers its listeners; it never
4456    /// constructs a bus when one is given. Without it, the default: an
4457    /// `bus_kernel::Kernel` of its own.
4458    ///
4459    /// One egui-pop application per bus: its listeners hold that
4460    /// application's window registry, and a second application on the
4461    /// same bus finds its points declared (logged as an error).
4462    ///
4463    /// <div class="warning">Experimental: may change in any release
4464    /// (docs/stability.md).</div>
4465    pub fn bus(mut self, bus: Arc<dyn crate::bus::bus_contract::Bus>) -> Self {
4466        self.bus = Some(bus);
4467        self
4468    }
4469
4470    /// Shares an existing store instead of a new one (with the default
4471    /// host; a host given to `host` brings its own).
4472    pub fn store(mut self, store: SharedStore) -> Self {
4473        self.store = Some(store);
4474        self
4475    }
4476
4477    /// What a write from a plugin that is not one of a path's writers
4478    /// gets: refused (the default) or applied with a warning, to migrate
4479    /// plugins written before the check
4480    /// (`egui_pop_model::values::WriterCheck`). Either way it is in the
4481    /// diagnostics.
4482    pub fn writer_check(mut self, check: egui_pop_model::values::WriterCheck) -> Self {
4483        self.writer_check = Some(check);
4484        self
4485    }
4486
4487    /// Offers a debug collector's action to agents (`dialogs.answer`):
4488    /// the bridge's agent (`AppHandle::debug_call`) may then call it,
4489    /// whatever the action declares. An action that writes is for the
4490    /// user only by default; offer one only to agents the application
4491    /// trusts with it (a test harness, its own automation). A name that
4492    /// matches no action once the plugins are connected is reported
4493    /// (`agent-offer-unknown`).
4494    pub fn offer_to_agents(mut self, action: &str) -> Self {
4495        self.offered.push(action.into());
4496        self
4497    }
4498
4499    /// What the debug bridge lets anyone but the user do: `On` (the
4500    /// default: every action and command offered to agents), `ReadOnly`
4501    /// (only calls that change nothing: actions with `mutates: false` and
4502    /// `commands.run` of a command declared `read_only`), or `Off` (no
4503    /// call). The user's calls (the devtools panel, `debug_call_as` with
4504    /// `Origin::User`) are never refused by it; snapshots stay readable
4505    /// by code in the process.
4506    pub fn debug_bridge(mut self, mode: egui_pop_core::debug::BridgeMode) -> Self {
4507        self.bridge_mode = Some(mode);
4508        self
4509    }
4510
4511    /// The debug bridge's mode the application chose
4512    /// ([`AppBuilder::debug_bridge`]), `None` when it chose none (the
4513    /// bridge is then `On`). A transport the application turns on
4514    /// (`egui-pop-agent`) reads it to default to `ReadOnly`.
4515    pub fn chosen_debug_bridge(&self) -> Option<egui_pop_core::debug::BridgeMode> {
4516        self.bridge_mode
4517    }
4518
4519    /// Offers a command to agents whatever it declares
4520    /// (`CommandSpec::no_agent`): `terminal.send`, for an agent the
4521    /// application trusts to type into its terminals. The agent then runs
4522    /// it through the bridge (`commands.run`) and the commands a handler
4523    /// starts for it, as the user would. A command kept from agents
4524    /// usually reaches the system or acts for the person: offer one only
4525    /// knowing what it does. A command that is not declared once the
4526    /// plugins are connected is reported (`agent-offer-unknown`).
4527    pub fn offer_command_to_agents(mut self, command: CommandId) -> Self {
4528        self.offered_commands.push(command);
4529        self
4530    }
4531
4532    /// The application opens windows of its own
4533    /// ([`AppHandle::open_window`]): `run_native` then sets wgpu's present
4534    /// mode for several windows (`windows::present_mode`: `AutoNoVsync`
4535    /// on Wayland, where a FIFO present can stall every window), unless
4536    /// the options chose a mode other than eframe's default.
4537    pub fn multi_window(mut self, on: bool) -> Self {
4538        self.multi_window = on;
4539        self
4540    }
4541
4542    /// The window manager's focus mode (`focus_mode::read_system()`
4543    /// reads it). Not given, it is read by `run_native` and taken as
4544    /// click elsewhere (tests stay the same on every desktop).
4545    ///
4546    /// <div class="warning">Experimental: may change in any release
4547    /// (docs/stability.md).</div>
4548    pub fn system_focus(mut self, system: SystemFocus) -> Self {
4549        self.system_focus = Some(system);
4550        self
4551    }
4552
4553    /// The system's text scaling (`egui_pop_platform::text_scale::read`
4554    /// reads it in-process): the default of the text size setting, rounded
4555    /// to a step, until the user chooses one. Not given, the default is
4556    /// 100 %; egui-pop reads nothing itself.
4557    pub fn system_text_scale(mut self, system: crate::text::SystemTextScale) -> Self {
4558        self.system_text_scale = system;
4559        self
4560    }
4561
4562    /// Whether the system was asked always to show its scroll bars: `true`
4563    /// makes the `auto` of the `appearance.scroll_bars` setting show full
4564    /// bars. One way only, so there is no value for a system that hides them:
4565    /// that is most systems' default, and nobody chose it. Not given, `false`;
4566    /// egui-pop reads nothing itself.
4567    pub fn system_always_shows_scroll_bars(mut self, always: bool) -> Self {
4568        self.system_scroll_bars = always;
4569        self
4570    }
4571
4572    /// The lines a notch of the wheel moves on the system
4573    /// (`egui_pop_platform::wheel_lines::read` reads it): the default of the
4574    /// `input.wheel_speed` setting, 3 lines being 1, until the user chooses one.
4575    /// Not given, 3; egui-pop reads nothing itself.
4576    pub fn system_wheel_lines(mut self, lines: u32) -> Self {
4577        self.system_wheel_lines = lines;
4578        self
4579    }
4580
4581    /// Sorts the plugins, connects them, installs the theme and resolves
4582    /// the declarations, on a context.
4583    pub fn build(self, ctx: &Context) -> Result<App, BuildError> {
4584        if let Some(bus) = &self.bus {
4585            let declared = bus.points();
4586            if let Some(taken) = crate::bus::CONTRACT
4587                .iter()
4588                .find(|d| declared.iter().any(|p| p.id == d.id && p.declared))
4589            {
4590                return Err(BuildError::Bus(
4591                    crate::bus::bus_contract::Refused::AlreadyDeclared {
4592                        point: taken.id.as_str(),
4593                    },
4594                ));
4595            }
4596        }
4597        let nodes: Vec<Node> = self
4598            .plugins
4599            .iter()
4600            .map(|p| Node {
4601                id: p.id(),
4602                requires: p.requires(),
4603                priority: p.priority(),
4604            })
4605            .collect();
4606        let sorted = order(&nodes)?;
4607        let mut plugins: Vec<Option<Box<dyn Plugin>>> =
4608            self.plugins.into_iter().map(Some).collect();
4609        let slots: Vec<Slot> = sorted
4610            .into_iter()
4611            .map(|i| {
4612                let plugin = plugins[i].take().expect("each plugin once");
4613                let id = plugin.id();
4614                Slot {
4615                    owner: OwnerId::from(&id),
4616                    id,
4617                    plugin,
4618                    connected: false,
4619                    reason: None,
4620                }
4621            })
4622            .collect();
4623        let default_host = self.host.is_none();
4624        let host = self.host.unwrap_or_else(|| {
4625            Box::new(LocalHost::new(
4626                self.store
4627                    .unwrap_or_else(|| Arc::new(Mutex::new(Store::new()))),
4628            ))
4629        });
4630        let handle = AppHandle::new(ctx, host, default_host, self.bus);
4631        if let Some(check) = self.writer_check {
4632            lock(&handle.store()).set_writer_check(check);
4633        }
4634        let modes = FocusModes::new(self.system_focus.unwrap_or_default());
4635        let mut app = App {
4636            handle,
4637            plugins: slots,
4638            reg: Registries::new(),
4639            keys: WindowKeys::default(),
4640            panel_keys: BTreeMap::new(),
4641            dirty: true,
4642            started: false,
4643            theme: Rc::default(),
4644            persist: self.persist,
4645            kits: Vec::new(),
4646            in_flight: Vec::new(),
4647            waking: None,
4648            wrap: self.wrap,
4649            on_exit: self.on_exit,
4650            autosave: AutoSave::default(),
4651            rebuilds: 0,
4652            pointer: Rc::default(),
4653            keymap_changed: Rc::default(),
4654            logic_pass: None,
4655        };
4656        install_pass_marker(ctx);
4657        *app.handle.0.writer.borrow_mut() = app
4658            .persist
4659            .clone()
4660            .map(|p| Writer::new(p, egui_pop_core::persist::DEBOUNCE));
4661        app.handle.0.edge_to_edge.set(self.edge_to_edge);
4662        *app.handle.0.frameless.borrow_mut() = self.frameless;
4663        *app.handle.0.bare_strips.borrow_mut() = self.bare_strips;
4664        app.handle.0.system_text_scale.set(self.system_text_scale);
4665        app.handle.0.system_scroll_bars.set(self.system_scroll_bars);
4666        app.handle.0.system_wheel_lines.set(self.system_wheel_lines);
4667        app.handle.0.toast_corner.set(self.toast_corner);
4668        app.handle.0.group_handles.set(self.group_handles);
4669        app.handle.0.dock_controls.set(self.dock_controls);
4670        app.handle
4671            .0
4672            .arrangement_strings
4673            .set(self.arrangement_strings);
4674        app.handle.0.menu_bar.set(self.menu_bar);
4675        app.handle
4676            .0
4677            .system_file_chooser
4678            .set(self.system_file_chooser);
4679        app.handle
4680            .0
4681            .transparent_panel_windows
4682            .set(self.transparent_panel_windows);
4683        let rounded =
4684            crate::window::rounded_windows(self.rounded_windows, crate::window::windowing());
4685        app.handle.0.rounded_windows.set(rounded);
4686        egui_pop_core::frame::set_rounding(ctx, rounded);
4687        *app.handle.0.shell_sizes.borrow_mut() = self.shell_sizes;
4688        *app.handle.0.shell_bounds.borrow_mut() = self.shell_bounds;
4689        app.handle.0.centre_min.set(self.centre_min);
4690        {
4691            let mut wb = app.handle.workbench_mut();
4692            let given = self.layout.is_some();
4693            let mut start = self.layout.unwrap_or_default();
4694            for a in self.folded {
4695                if !start.folded.contains(&a) {
4696                    start.folded.push(a);
4697                }
4698            }
4699            for a in self.over {
4700                if !start.over.contains(&a) {
4701                    start.over.push(a);
4702                }
4703            }
4704            if given {
4705                // What the `Default` arrangement resets to.
4706                wb.templates.push((
4707                    OwnerId::FRAMEWORK,
4708                    crate::arrangements::DEFAULT.to_string(),
4709                    start.clone(),
4710                ));
4711            }
4712            wb.layout = start;
4713        }
4714        *app.handle.0.name.borrow_mut() = self.name.unwrap_or_default();
4715        *app.handle.0.app_id.borrow_mut() = self.app_id.unwrap_or_default();
4716        strings::set_application(ctx, &app.handle.name());
4717        let mut themes = self.themes;
4718        let mut kits = self.kits;
4719        if self.user_kits
4720            && let Some(p) = &app.persist
4721        {
4722            let dir = p.dir().join(egui_pop_core::tokens::kit::USER_KITS_DIR);
4723            let cache = self
4724                .cache
4725                .unwrap_or_else(egui_pop_core::tokens::cache::default);
4726            kits.extend(
4727                egui_pop_core::tokens::kit::discover_with(&dir, &cache)
4728                    .into_iter()
4729                    .map(KitSource::new),
4730            );
4731        }
4732        // A kit of the same name as an earlier one replaces it.
4733        let mut seen = std::collections::BTreeSet::new();
4734        kits.reverse();
4735        kits.retain(|k| seen.insert(k.name().to_string()));
4736        kits.reverse();
4737        {
4738            let mut d = app.handle.0.diagnostics.borrow_mut();
4739            for kit in &kits {
4740                themes.add_kit(&kit.data);
4741                for p in kit.problems() {
4742                    d.warn("kit-problem", None, kit.name(), p);
4743                }
4744            }
4745        }
4746        let infos = kits.iter().flat_map(|k| k.data.infos()).collect();
4747        app.kits = kits;
4748        app.reg.offered = self.offered_commands.iter().cloned().collect();
4749        app.framework(
4750            self.theme,
4751            themes,
4752            infos,
4753            modes,
4754            self.panel_alignment,
4755            (&self.pointer_profile, self.dock_drag),
4756        )
4757        .expect("the framework's registrations are valid");
4758        app.install_collectors();
4759        app.handle
4760            .0
4761            .bridge
4762            .borrow_mut()
4763            .set_mode(self.bridge_mode.unwrap_or_default());
4764        for a in &self.offered {
4765            app.handle.0.bridge.borrow_mut().offer_to_agents(a);
4766        }
4767        for i in 0..app.plugins.len() {
4768            if let Err(error) = app.connect_slot(i) {
4769                let plugin = app.plugins[i].id.clone();
4770                return Err(BuildError::Connect { plugin, error });
4771            }
4772        }
4773        for c in &self.offered_commands {
4774            if app.reg.commands.spec(c).is_none() {
4775                app.handle.0.diagnostics.borrow_mut().warn(
4776                    "agent-offer-unknown",
4777                    None,
4778                    c.to_string(),
4779                    "`AppBuilder::offer_command_to_agents` names no declared command; nothing is offered",
4780                );
4781            }
4782        }
4783        for a in &self.offered {
4784            let known = a
4785                .split_once('.')
4786                .and_then(|(c, n)| app.handle.0.bridge.borrow().action(c, n))
4787                .is_some();
4788            if !known {
4789                app.handle.0.diagnostics.borrow_mut().warn(
4790                    "agent-offer-unknown",
4791                    None,
4792                    a.clone(),
4793                    "`AppBuilder::offer_to_agents` names no debug collector's action (`collector.action`); nothing is offered",
4794                );
4795            }
4796        }
4797        app.load_documents();
4798        app.rebuild();
4799        app.autosave_baseline();
4800        app.listen_settings();
4801        app.listen_layout();
4802        crate::workbench::listen_stack(&app.handle);
4803        app.install_theme();
4804        app.emit(&Lifecycle::Started);
4805        app.started = true;
4806        Ok(app)
4807    }
4808
4809    /// Builds and runs the application in a native window. With the
4810    /// `create-native` feature (default), eframe runs on an event loop
4811    /// egui-pop owns ([`crate::runner`]): the screens are known before the
4812    /// main window is placed, and every window's handles once painted.
4813    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
4814    pub fn run_native(mut self, title: &str, mut options: eframe::NativeOptions) -> eframe::Result {
4815        self.system_focus
4816            .get_or_insert_with(egui_pop_core::focus_mode::read_system);
4817        self.name.get_or_insert_with(|| title.to_string());
4818        if self.app_id.is_none() {
4819            self.app_id.clone_from(&options.viewport.app_id);
4820        }
4821        // The window's place from the last run, bounded here; with the
4822        // `create-native` feature, repaired against the screens the event
4823        // loop reads before the window exists (`runner`).
4824        if let Some(p) = &self.persist {
4825            crate::window::restore(p.dir(), &mut options);
4826        }
4827        if self.multi_window {
4828            crate::windows::present_mode(&mut options);
4829        }
4830        crate::window::transparent_for_corners(&mut options, self.rounded_windows);
4831        let keymap_shortcuts = self.clipboard_shortcuts(&mut options);
4832        crate::runner::run(
4833            title,
4834            options,
4835            Box::new(move |cc| {
4836                crate::frame::record_native_window(cc);
4837                let app = self
4838                    .build(&cc.egui_ctx)
4839                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
4840                crate::clipboard::set_keymap_shortcuts(app.handle(), keymap_shortcuts);
4841                Ok(Box::new(app))
4842            }),
4843        )
4844    }
4845
4846    /// As [`AppBuilder::run_native`], the built application handed to
4847    /// `make`, which gives eframe the `eframe::App` to run: one of the
4848    /// application's own around egui-pop's (it calls `App::logic`,
4849    /// `App::show_wrapped` and `App::exit` from its own). `make` may fail
4850    /// (its kernel does not start, a file is missing): the error is
4851    /// logged, published on the journal as `app.make_failed` and returned
4852    /// as eframe's `Error::AppCreation`.
4853    ///
4854    /// <div class="warning">Experimental: may change in any release
4855    /// (docs/stability.md).</div>
4856    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
4857    pub fn run_native_with(
4858        mut self,
4859        title: &str,
4860        mut options: eframe::NativeOptions,
4861        make: impl FnOnce(App, &eframe::CreationContext<'_>) -> Result<Box<dyn eframe::App>, MakeError>
4862        + 'static,
4863    ) -> eframe::Result {
4864        self.system_focus
4865            .get_or_insert_with(egui_pop_core::focus_mode::read_system);
4866        self.name.get_or_insert_with(|| title.to_string());
4867        if self.app_id.is_none() {
4868            self.app_id.clone_from(&options.viewport.app_id);
4869        }
4870        if let Some(p) = &self.persist {
4871            crate::window::restore(p.dir(), &mut options);
4872        }
4873        if self.multi_window {
4874            crate::windows::present_mode(&mut options);
4875        }
4876        crate::window::transparent_for_corners(&mut options, self.rounded_windows);
4877        let keymap_shortcuts = self.clipboard_shortcuts(&mut options);
4878        crate::runner::run(
4879            title,
4880            options,
4881            Box::new(move |cc| {
4882                crate::frame::record_native_window(cc);
4883                let app = self
4884                    .build(&cc.egui_ctx)
4885                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
4886                crate::clipboard::set_keymap_shortcuts(app.handle(), keymap_shortcuts);
4887                let handle = app.handle().clone();
4888                make(app, cc).inspect_err(|e| report_make_error(&handle, e.as_ref()))
4889            }),
4890        )
4891    }
4892}
4893
4894impl AppBuilder {
4895    /// Whether the keymap runs the copy, cut and paste chords: eframe's
4896    /// clipboard shortcuts turned off when a plugin reading the system
4897    /// clipboard is added ([`crate::clipboard::SYSTEM_PLUGIN`]); kept
4898    /// off when the application's options already have them off.
4899    /// Otherwise egui-winit keeps making events of the chords, which
4900    /// text fields read themselves.
4901    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
4902    fn clipboard_shortcuts(&self, options: &mut eframe::NativeOptions) -> bool {
4903        if self
4904            .plugins
4905            .iter()
4906            .any(|p| p.id() == crate::clipboard::SYSTEM_PLUGIN)
4907        {
4908            options.clipboard_shortcuts = false;
4909        }
4910        !options.clipboard_shortcuts
4911    }
4912}
4913
4914/// Why `make` (of `AppBuilder::run_native_with`) gave no application.
4915pub type MakeError = Box<dyn std::error::Error + Send + Sync>;
4916
4917/// Says why `make` failed: in the log and on the journal
4918/// (`app.make_failed`, with the error).
4919#[cfg(any(test, all(feature = "eframe", not(target_arch = "wasm32"))))]
4920pub(crate) fn report_make_error(app: &AppHandle, e: &(dyn std::error::Error + Send + Sync)) {
4921    log::error!(target: "egui_pop", "the application could not be made: {e}");
4922    app.publish(
4923        "egui_pop",
4924        None,
4925        "app.make_failed",
4926        json!({ "error": e.to_string() }),
4927    );
4928}
4929
4930/// Loads the pointer profile the setting asks for into the keymap's
4931/// default layer; after a change (not the first load), asks about the
4932/// user's changes. The keymap is rebuilt with the next requests.
4933fn load_pointer_profile(
4934    app: &AppHandle,
4935    keymap: &RefCell<Keymap>,
4936    sync: &RefCell<crate::pointer::Sync>,
4937    changed: &std::cell::Cell<bool>,
4938) {
4939    let id = crate::pointer::profile_id(app);
4940    let first = {
4941        let mut sync = sync.borrow_mut();
4942        if sync.loaded.as_deref() == Some(id.as_str()) {
4943            return;
4944        }
4945        let first = sync.loaded.is_none();
4946        sync.loaded = Some(id.clone());
4947        first
4948    };
4949    let loaded = crate::pointer::load_profile(&mut keymap.borrow_mut(), &id);
4950    match loaded {
4951        Some(profile) => {
4952            changed.set(true);
4953            if !first {
4954                crate::pointer::ask_about_overrides(app, profile);
4955            }
4956        }
4957        None => app.0.diagnostics.borrow_mut().warn(
4958            "unknown-pointer-profile",
4959            None,
4960            &id,
4961            format!(
4962                "`{id}` is not a pointer profile: `{}` stays in force",
4963                egui_pop_model::pointer::DEFAULT_PROFILE
4964            ),
4965        ),
4966    }
4967}
4968
4969/// The settings the theme follows (`pop.theme.install`).
4970const THEME_SETTINGS: [SettingId; 6] = [
4971    SETTING_ACCENT_COLOR,
4972    SETTING_THEME_PREFERENCE,
4973    crate::text::SETTING_TEXT_SIZE,
4974    crate::text::SETTING_FONT_UI,
4975    crate::text::SETTING_FONT_MONO,
4976    crate::scroll_bars::SETTING_SCROLL_BARS,
4977];
4978
4979/// The theme installed and the settings it follows, shared by the
4980/// application and its `pop.theme.install` listener.
4981#[derive(Default)]
4982struct ThemeFollow {
4983    /// The settings were read once.
4984    read: bool,
4985    /// The spec last installed.
4986    installed: Option<ThemeSpec>,
4987    /// The accent colour setting as last read (it changes the spec's
4988    /// accent when it changes).
4989    accent_setting: Option<String>,
4990    /// The text settings as last read.
4991    text_seen: crate::text::Seen,
4992    /// What the scroll bars' setting asked for when last read.
4993    scroll_bars_seen: Option<theme::ScrollBars>,
4994    /// The light or dark preference applied since the last install.
4995    preference: Option<egui::ThemePreference>,
4996}
4997
4998impl ThemeFollow {
4999    /// Writes the settings into the theme service's spec. Read for the
5000    /// first time, a setting at its default leaves the application's spec
5001    /// alone.
5002    fn read_settings(&mut self, app: &AppHandle) {
5003        self.read = true;
5004        let service = app.theme();
5005        let accent = service.accent_setting();
5006        if self.accent_setting.as_ref() != Some(&accent) {
5007            if self.accent_setting.is_some() || !accent.trim().is_empty() {
5008                service.apply_accent_setting(&accent);
5009            }
5010            self.accent_setting = Some(accent);
5011        }
5012        let mut wanted = service.spec();
5013        let text = crate::text::apply(app, &mut self.text_seen, &mut wanted);
5014        let bars = crate::scroll_bars::apply(app, &mut self.scroll_bars_seen, &mut wanted);
5015        if text || bars {
5016            service.set(wanted);
5017        }
5018    }
5019
5020    /// Installs the theme service's spec when it is not the one installed
5021    /// (or `force`), its light or dark preference with it.
5022    fn install(&mut self, app: &AppHandle, force: bool) {
5023        let service = app.theme();
5024        let mut spec = service.spec();
5025        if !force && self.installed.as_ref() == Some(&spec) {
5026            return;
5027        }
5028        if self.installed.is_some() {
5029            // A spec set since (a theme chosen, the application's own):
5030            // the settings the person chose go over it again, as read for
5031            // the first time.
5032            self.accent_setting = None;
5033            self.text_seen = crate::text::Seen::default();
5034            self.scroll_bars_seen = None;
5035            self.read_settings(app);
5036            spec = service.spec();
5037        }
5038        let ctx = app.egui();
5039        theme::install_with(&ctx, service.themes(), &spec);
5040        THEME_INSTALLED.set(&ctx, true);
5041        self.installed = Some(spec);
5042        // The install forces the theme's own mode.
5043        self.preference = None;
5044        let paired = theme::is_paired(&ctx);
5045        app.set_context("themePaired", if paired { "true" } else { "false" });
5046        self.follow_preference(app);
5047    }
5048
5049    /// Applies the light or dark preference the setting asks for.
5050    fn follow_preference(&mut self, app: &AppHandle) {
5051        let preference = app.theme().preference();
5052        if self.preference != Some(preference) {
5053            theme::set_preference(&app.egui(), preference);
5054            self.preference = Some(preference);
5055        }
5056    }
5057}
5058
5059/// A window's key dispatcher, and the count of active-window changes it
5060/// last saw ([`crate::bus::KEYS`]).
5061#[derive(Debug, Default)]
5062pub(crate) struct WindowKeys {
5063    dispatcher: KeyDispatcher,
5064    seen: u64,
5065}
5066
5067impl WindowKeys {
5068    /// The dispatcher, its shortcut in progress dropped when the active
5069    /// window changed since it last keyed.
5070    pub(crate) fn dispatcher(&mut self, app: &AppHandle) -> &mut KeyDispatcher {
5071        let epoch = app.0.bus.keys_epoch.get();
5072        if epoch != self.seen {
5073            self.seen = epoch;
5074            self.dispatcher.cancel_pending();
5075        }
5076        &mut self.dispatcher
5077    }
5078}
5079
5080/// A built application.
5081pub struct App {
5082    handle: AppHandle,
5083    plugins: Vec<Slot>,
5084    reg: Registries,
5085    /// The main window's key dispatcher.
5086    keys: WindowKeys,
5087    /// Each detached panel's window's own key dispatcher, by viewport:
5088    /// a chord begun in one window is never finished in another.
5089    panel_keys: BTreeMap<egui::ViewportId, WindowKeys>,
5090    dirty: bool,
5091    started: bool,
5092    /// The theme installed and the settings it follows, shared with its
5093    /// listener on `pop.settings.changed` ([`crate::bus::THEME_INSTALL`]).
5094    theme: Rc<RefCell<ThemeFollow>>,
5095    persist: Option<Persist>,
5096    /// The kits added: their faces and handlers are registered in each
5097    /// context the theme is installed in.
5098    kits: Vec<KitSource>,
5099    /// Results to come.
5100    in_flight: Vec<InFlight>,
5101    /// The context the host's waker wakes.
5102    waking: Option<Context>,
5103    wrap: Option<WrapUi>,
5104    on_exit: Vec<ExitFn>,
5105    /// What the debounced saving last saw and wrote.
5106    autosave: AutoSave,
5107    /// Rebuilds so far (the keymap may have changed).
5108    rebuilds: u64,
5109    /// The pointer profile loaded and the map published, shared with the
5110    /// `pop.pointer.profile` listener.
5111    pointer: Rc<RefCell<crate::pointer::Sync>>,
5112    /// The `pop.pointer.profile` listener changed the keymap: rebuilt with
5113    /// the application's next requests.
5114    keymap_changed: Rc<std::cell::Cell<bool>>,
5115    /// The pass the logic last ran in (`App::logic`).
5116    logic_pass: Option<(egui::ViewportId, u64)>,
5117}
5118
5119/// What went with an owner (`App::remove_owner`).
5120struct Removed {
5121    commands: Vec<CommandId>,
5122    panels: usize,
5123    /// Components and host offers it declared, and the mounts that went
5124    /// with it (ADR 0013).
5125    mounts: crate::mounts::RemovedMounts,
5126    undo: Vec<egui_pop_model::values::DroppedSteps>,
5127}
5128
5129/// The document the notices are saved in, under the persistence
5130/// directory.
5131pub(crate) const NOTICES_DOC: &str = "notices";
5132
5133/// What the debounced saving of the settings and the keymap last saw
5134/// (the layout is saved on `pop.layout.changed`).
5135#[derive(Debug, Default)]
5136struct AutoSave {
5137    /// The store's sequence number last offered.
5138    store_seq: std::cell::Cell<Option<u64>>,
5139    /// The rebuild count when the keymap was last offered.
5140    rebuilds: std::cell::Cell<Option<u64>>,
5141    /// The notice store's revision last offered.
5142    notices_rev: std::cell::Cell<Option<u64>>,
5143}
5144
5145/// Saves the layout to the document the host names now, through the
5146/// `layout.save` step; `None` when the host keeps the layout. Done, the
5147/// layout as it stands is the one said (`pop.layout.changed`).
5148fn save_layout(handle: &AppHandle, persist: Option<Persist>) -> Option<Outcome> {
5149    let document = handle.with_host(|h| h.layout_document()).flatten()?;
5150    let out = handle.step(
5151        &STEP_LAYOUT_SAVE,
5152        json!({ "document": document }),
5153        move |app, args| {
5154            let document = args["document"].as_str().ok_or("`document` is missing")?;
5155            let Some(p) = persist else {
5156                return Ok(json!({ "document": document, "saved": false }));
5157            };
5158            p.save(
5159                document,
5160                &egui_pop_model::layout::schema(),
5161                &app.saved_layout(),
5162            )
5163            .map_err(|e| e.to_string())?;
5164            Ok(json!({ "document": document, "saved": true }))
5165        },
5166    );
5167    if out.ok() {
5168        handle.layout_said_now();
5169    }
5170    Some(out)
5171}
5172
5173/// A run waiting for its result.
5174struct InFlight {
5175    command: CommandId,
5176    args: Json,
5177    origin: Origin,
5178    seq: Seq,
5179    pending: Pending,
5180}
5181
5182impl fmt::Debug for App {
5183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5184        f.debug_struct("App")
5185            .field(
5186                "plugins",
5187                &self
5188                    .plugins
5189                    .iter()
5190                    .map(|p| (&p.id, p.connected))
5191                    .collect::<Vec<_>>(),
5192            )
5193            .finish_non_exhaustive()
5194    }
5195}
5196
5197impl App {
5198    /// Starts building an application.
5199    pub fn builder() -> AppBuilder {
5200        AppBuilder::new()
5201    }
5202
5203    /// The application handle.
5204    pub fn handle(&self) -> &AppHandle {
5205        &self.handle
5206    }
5207
5208    /// How many things each registry holds: what removal tests compare.
5209    pub fn census(&self) -> BTreeMap<&'static str, usize> {
5210        let h = &self.handle.0;
5211        let store = lock(&h.store);
5212        BTreeMap::from([
5213            ("commands", self.reg.commands.len()),
5214            ("bindings", self.reg.keymap.borrow().all().count()),
5215            ("menu items", self.reg.menus.len()),
5216            ("panels", self.reg.panels.all().len()),
5217            ("panel views", h.panels.borrow().len()),
5218            ("hooks", self.reg.hooks.len()),
5219            ("lifecycle handlers", self.reg.lifecycle.len()),
5220            ("settings", self.reg.settings.len()),
5221            ("zones", h.zones.borrow().zones.len()),
5222            ("blocks", h.zones.borrow().contributions.len()),
5223            ("services", h.services.borrow().list().len()),
5224            ("stories", h.stories.borrow().len()),
5225            ("steps", h.steps.borrow().len()),
5226            ("step hooks", h.step_hooks.borrow().len()),
5227            ("list providers", h.lists.borrow().len()),
5228            ("indicators", h.indicators.borrow().len()),
5229            ("store paths", store.list("").len()),
5230            ("store listeners", store.listeners().len()),
5231        ])
5232    }
5233
5234    /// The key dispatcher (its traces, a shortcut in progress).
5235    pub fn dispatcher(&self) -> &KeyDispatcher {
5236        &self.keys.dispatcher
5237    }
5238
5239    /// The keymap.
5240    pub fn keymap(&self) -> std::cell::Ref<'_, Keymap> {
5241        self.reg.keymap.borrow()
5242    }
5243
5244    /// The framework's own registrations (the pointer profile and the palette
5245    /// drag mode by default, as the builder has them).
5246    fn framework(
5247        &mut self,
5248        theme: ThemeSpec,
5249        themes: Themes,
5250        kits: Vec<egui_pop_core::tokens::kit::KitInfo>,
5251        modes: FocusModes,
5252        panel_alignment: crate::workbench::PanelAlignment,
5253        (pointer_profile, dock_drag): (&str, Option<egui_pop_model::pointer::DockDrag>),
5254    ) -> Result<(), CtxError> {
5255        let owner = OwnerId::FRAMEWORK;
5256        let handle = self.handle.clone();
5257        let connected: Vec<PluginId> = Vec::new();
5258        let mut ctx = Ctx {
5259            owner: owner.clone(),
5260            plugin: PluginId::from_static("framework"),
5261            rank: 0,
5262            reg: &mut self.reg,
5263            app: &handle,
5264            connected: &connected,
5265        };
5266        ctx.step(
5267            StepSpec::new(
5268                crate::menus::STEP_OPEN,
5269                "A menu opens as a popup or a context menu; a veto keeps it closed, a redirect changes its arguments.",
5270            )
5271            .args(json!({ "menu": "app.menu.edit", "args": { "path": "node/exposure" }, "how": "context" })),
5272        )?;
5273        for (zone, title) in zones::SHELL.iter().zip([
5274            "Title",
5275            "Top bar",
5276            "Activity bar",
5277            "Side bar",
5278            "Main",
5279            "Inspector",
5280            "Status bar",
5281            "Overlays",
5282        ]) {
5283            ctx.zone(zone.clone(), title)?;
5284        }
5285        ctx.zone(zones::TOP_BAR_END, "Top bar end")?;
5286        ctx.zone(zones::WINDOW_OVERLAYS, "Window overlays")?;
5287        for (spec, zone, scope) in [
5288            (
5289                PanelSpec::new(
5290                    crate::workbench::PANEL_SIDE_BAR,
5291                    "Side bar",
5292                    Area::StartSide,
5293                )
5294                .min_size(120.0)
5295                .default_size(170.0),
5296                zones::SIDE_BAR,
5297                "sideBar",
5298            ),
5299            (
5300                PanelSpec::new(crate::workbench::PANEL_MAIN, "Main", Area::Center),
5301                zones::MAIN,
5302                "main",
5303            ),
5304            (
5305                PanelSpec::new(
5306                    crate::workbench::PANEL_INSPECTOR,
5307                    "Inspector",
5308                    Area::EndSide,
5309                )
5310                .min_size(160.0)
5311                .default_size(240.0),
5312                zones::INSPECTOR,
5313                "inspector",
5314            ),
5315        ] {
5316            let size = handle
5317                .0
5318                .shell_sizes
5319                .borrow()
5320                .iter()
5321                .find(|(p, _)| *p == spec.id)
5322                .map(|(_, s)| *s);
5323            let spec = match size {
5324                Some(s) => {
5325                    let min = spec.min_size.min(s);
5326                    spec.min_size(min).default_size(s)
5327                }
5328                None => spec,
5329            };
5330            ctx.zone_panel(spec, zone, scope)?;
5331        }
5332        for spec in crate::workbench::steps() {
5333            ctx.step(spec)?;
5334        }
5335        // Zen mode: Shift+F11 toggles it (Sublime Text's distraction
5336        // free mode; VS Code's Ctrl+K Z would make Ctrl+K a prefix
5337        // everywhere, and it deletes to the line's end in a text field).
5338        // Escape leaves it, unless an overlay or a pushed mode wants it.
5339        ctx.command(
5340            CommandSpec::new(crate::workbench::CMD_ZEN, "Zen mode", "View")
5341                .description("Shows one panel alone, full size, in its window: `panel`, else the focused panel when it is a view, else the application's choice, else the centre's active tab. No title, menu or status bar, no other panel. Escape leaves it, and the layout is as it was.")
5342                .key("Shift+F11")
5343                .checked("workbenchZen")
5344                .menu(MENU_VIEW, "9_window", 2)
5345                .args(json!({ "panel": "app.viewer" })),
5346            |call| {
5347                let named = match call.args.get("panel").and_then(Json::as_str) {
5348                    Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
5349                    None => None,
5350                };
5351                // A toggle; a panel named while another is zenned moves
5352                // zen mode to it.
5353                let current = call.app.zen_panel();
5354                if call.app.zen() && (named.is_none() || named == current) {
5355                    return zen_result(call.app.set_zen(false), false);
5356                }
5357                match named.or_else(|| call.app.zen_target()) {
5358                    // The centre's only panel: the centre whole shows it
5359                    // alone already, drawn where it was, so the widget
5360                    // holding the keyboard keeps it.
5361                    Some(p) if call.app.centre_holds_only(&p) => {
5362                        zen_result(call.app.set_zen(true), true)
5363                    }
5364                    Some(p) => zen_result(call.app.set_zen_panel(&p), true),
5365                    None => zen_result(call.app.set_zen(true), true),
5366                }
5367            },
5368        )?
5369        .command(
5370            CommandSpec::new(crate::workbench::CMD_LEAVE_ZEN, "Leave zen mode", "View")
5371                .description("Shows the whole workbench again.")
5372                .when("workbenchZen"),
5373            |call| zen_result(call.app.set_zen(false), false),
5374        )?;
5375        ctx.keybinding(
5376            "Escape",
5377            crate::workbench::CMD_LEAVE_ZEN,
5378            "workbenchZen && !modePushed && !overlayOpen && !textInputFocus",
5379            Layer::Default,
5380        )?;
5381        // The navigation commands of every canvas (the node graph, the
5382        // image viewport, plots; docs/design/navigation.md): they go to
5383        // the canvas under the pointer or with the keyboard. Their keys
5384        // are the pointer profile's (`Profile::view_keys`), loaded with
5385        // its gestures.
5386        let views: [(&str, &str, &str); 10] = [
5387            (
5388                "view.fit",
5389                "Fit the view",
5390                "Frames all the content of the canvas in use.",
5391            ),
5392            (
5393                "view.frame_selection",
5394                "Frame the selection",
5395                "Frames the selection of the canvas in use (all its content when nothing is selected).",
5396            ),
5397            (
5398                "view.zoom_in",
5399                "Zoom in",
5400                "Zooms the canvas in use in, around its centre.",
5401            ),
5402            (
5403                "view.zoom_out",
5404                "Zoom out",
5405                "Zooms the canvas in use out, around its centre.",
5406            ),
5407            (
5408                "view.zoom_100",
5409                "Zoom to 100 %",
5410                "Shows the canvas in use at 100 % (one unit, or one pixel, to a point).",
5411            ),
5412            (
5413                "view.pan_left",
5414                "Pan left",
5415                "Moves the view of the canvas in use left.",
5416            ),
5417            (
5418                "view.pan_right",
5419                "Pan right",
5420                "Moves the view of the canvas in use right.",
5421            ),
5422            (
5423                "view.pan_up",
5424                "Pan up",
5425                "Moves the view of the canvas in use up.",
5426            ),
5427            (
5428                "view.pan_down",
5429                "Pan down",
5430                "Moves the view of the canvas in use down.",
5431            ),
5432            (
5433                "view.hand",
5434                "Hand mode",
5435                "Toggles hand mode: a primary drag pans the canvases (for a pen, a touch screen or a mouse without a middle button). Space held does the same for a moment.",
5436            ),
5437        ];
5438        for (id, title, description) in views {
5439            let spec = CommandSpec::new(CommandId::from_static(id), title, "View")
5440                .description(description)
5441                .when(egui_pop_model::pointer::VIEW_KEYS_WHEN);
5442            ctx.command(spec, move |call| {
5443                if egui_pop_core::canvas::request(&call.app.egui(), id) {
5444                    Ok(json!({ "queued": id }))
5445                } else {
5446                    Err("no canvas has been shown".into())
5447                }
5448            })?;
5449        }
5450        // F6, as VS Code, GTK and the ARIA splitter pattern have it.
5451        ctx.command(
5452            CommandSpec::new(crate::workbench::CMD_NEXT_REGION, "Go to the next region", "View")
5453                .description("Moves the keyboard to the next part of the window: the activity bar, a side or bottom area, the centre, a palette, the flyout, the status bar.")
5454                .when("!modalOpen")
5455                .key("F6"),
5456            |call| crate::workbench::go_to_region(call.app, call.origin, false),
5457        )?
5458        .command(
5459            CommandSpec::new(crate::workbench::CMD_PREVIOUS_REGION, "Go to the previous region", "View")
5460                .description("Moves the keyboard to the previous part of the window.")
5461                .when("!modalOpen")
5462                .key("Shift+F6"),
5463            |call| crate::workbench::go_to_region(call.app, call.origin, true),
5464        )?
5465        // Ctrl+Page Down and Up, as VS Code and browsers have them.
5466        .command(
5467            CommandSpec::new(crate::workbench::CMD_NEXT_TAB, "Go to the next tab", "View")
5468                .description("Shows and focuses the next tab of the focused panel's group.")
5469                .when("!modalOpen")
5470                .key("Ctrl+PageDown"),
5471            |call| crate::workbench::go_to_tab(call.app, false),
5472        )?
5473        .command(
5474            CommandSpec::new(crate::workbench::CMD_PREVIOUS_TAB, "Go to the previous tab", "View")
5475                .description("Shows and focuses the previous tab of the focused panel's group.")
5476                .when("!modalOpen")
5477                .key("Ctrl+PageUp"),
5478            |call| crate::workbench::go_to_tab(call.app, true),
5479        )?
5480        // The row, column or grid around the focused panel's group, laid
5481        // out again (`workbench.arrange`); `panel` names another group.
5482        .command(
5483            CommandSpec::new(crate::workbench::CMD_ARRANGE_GRID, "Arrange as grid", "View")
5484                .description("Lays out the focused panel's group and the groups beside it in rows and columns.")
5485                .when("!modalOpen")
5486                .args(json!({ "panel": "app.inspector", "columns": 2 })),
5487            |call| crate::workbench::arrange_command(call.app, call.args, "grid"),
5488        )?
5489        .command(
5490            CommandSpec::new(crate::workbench::CMD_ARRANGE_ROW, "Arrange as row", "View")
5491                .description("Lays out the focused panel's group and the groups beside it side by side.")
5492                .when("!modalOpen")
5493                .args(json!({ "panel": "app.inspector" })),
5494            |call| crate::workbench::arrange_command(call.app, call.args, "row"),
5495        )?
5496        .command(
5497            CommandSpec::new(crate::workbench::CMD_ARRANGE_COLUMN, "Arrange as column", "View")
5498                .description("Lays out the focused panel's group and the groups beside it one above the other.")
5499                .when("!modalOpen")
5500                .args(json!({ "panel": "app.inspector" })),
5501            |call| crate::workbench::arrange_command(call.app, call.args, "column"),
5502        )?
5503        .command(
5504            CommandSpec::new(crate::workbench::CMD_MOVE_TO_WINDOW, "Move to window", "View")
5505                .description("Moves the focused panel, or `panel`, into the detached window holding `window`, as a tab.")
5506                .when("!modalOpen")
5507                .args(json!({ "panel": "app.outline", "window": "app.inspector" })),
5508            |call| crate::workbench::move_to_window_command(call.app, call.args),
5509        )?;
5510        crate::palettes::declare(&mut ctx)?;
5511        crate::workbench::panel_menu::declare(&mut ctx)?;
5512        for (i, (menu, label)) in [
5513            (MENU_FILE, "File"),
5514            (MENU_EDIT, "Edit"),
5515            (MENU_VIEW, "View"),
5516            (MENU_HELP, "Help"),
5517        ]
5518        .into_iter()
5519        .enumerate()
5520        {
5521            ctx.submenu(MENU_MAIN, &format!("{i}"), 0, menu, label)?;
5522        }
5523        ctx.service(
5524            &THEME,
5525            ThemeService {
5526                spec: Mutex::new(theme),
5527                themes,
5528                kits,
5529                store: handle.store(),
5530                dark: Mutex::new(BTreeMap::new()),
5531                ctx: Mutex::new(handle.egui()),
5532            },
5533        )?;
5534        ctx.setting(
5535            SETTING_THEME_PREFERENCE,
5536            egui_pop_model::values::Descriptor::choice(
5537                "Light or dark",
5538                &["system", "light", "dark"],
5539                "system",
5540            )
5541            .description(
5542                "Which variant of a theme with a light and a dark one is shown: the system's, or always the light or the dark one. A theme without a counterpart keeps its own.",
5543            ),
5544        )?;
5545        ctx.setting(
5546            SETTING_ACCENT_COLOR,
5547            egui_pop_model::values::Descriptor::text("Accent colour", "").description(
5548                "A colour (#rrggbb) the accent is generated from, light and dark: twelve steps whose text and contrast read in the theme. Empty keeps the theme's own accent.",
5549            ),
5550        )?;
5551        ctx.command(
5552            CommandSpec::new(CMD_THEME_TOGGLE, "Toggle light and dark theme", "View")
5553                .icon("theme")
5554                .description("Shows the other variant of the theme, light or dark, when it has one.")
5555                .when("themePaired")
5556                .menu(MENU_VIEW, "6_theme", 9),
5557            |call| {
5558                let mode = call.app.theme().toggle(&call.app.egui())?;
5559                Ok(json!({ "theme": call.app.theme().shown(&call.app.egui()), "dark": mode == egui::Theme::Dark }))
5560            },
5561        )?;
5562        let mut focus = egui_pop_model::values::Descriptor::choice(
5563            "Keyboard focus",
5564            &Preference::CHOICES,
5565            Preference::System.as_str(),
5566        );
5567        focus.description = format!(
5568            "Whether moving the mouse over a panel or a field gives it the keyboard \
5569             (hover), or only a click does (click). {}.",
5570            modes.system_said()
5571        );
5572        ctx.setting(SETTING_FOCUS, focus)?;
5573        crate::zoom::register(&mut ctx)?;
5574        crate::text::register(&mut ctx, handle.system_text_scale())?;
5575        crate::scroll_bars::register(&mut ctx)?;
5576        crate::toasts::register(&mut ctx, handle.0.toast_corner.get())?;
5577        crate::sliders::register(&mut ctx)?;
5578        crate::pointer::register(
5579            &mut ctx,
5580            pointer_profile,
5581            handle.system_wheel_lines(),
5582            dock_drag,
5583        )?;
5584        ctx.setting(
5585            crate::workbench::SETTING_PANEL_ALIGNMENT,
5586            egui_pop_model::values::Descriptor::choice(
5587                "Panel alignment",
5588                &crate::workbench::PanelAlignment::CHOICES,
5589                panel_alignment.as_str(),
5590            )
5591            .description(
5592                "How the bottom panel lines up with the side bars: the whole width (justify), between them (center), under the start one (start) or under the end one (end).",
5593            ),
5594        )?;
5595        crate::workbench::register_group_settings(&mut ctx, handle.0.group_handles.get())?;
5596        ctx.setting(
5597            crate::menus::SETTING_ICONS,
5598            egui_pop_model::values::Descriptor::choice(
5599                "Menu icons",
5600                &crate::menus::MenuIcons::CHOICES,
5601                crate::menus::MenuIcons::default().as_str(),
5602            )
5603            .description(
5604                "Whether menus show the commands' icons in a column on their left (on), none (off), or follow the desktop (platform: off on GNOME, as KDE Plasma says, on elsewhere).",
5605            ),
5606        )?;
5607        crate::layout_controls::declare(&mut ctx)?;
5608        crate::bus::declare(&mut ctx)?;
5609        ctx.service(&FOCUS_MODE, modes)?;
5610        ctx.step(
5611            crate::steps::StepSpec::new(
5612                STEP_DEBUG_CALL,
5613                "A debug collector's action is called (`collector`, `action`, `args`), by an agent or the user (`origin`).",
5614            )
5615            .args(json!({ "collector": "store", "action": "get", "args": { "path": "settings/x" }, "origin": "agent:debug-bridge" })),
5616        )?;
5617        ctx.step(
5618            crate::steps::StepSpec::new(
5619                STEP_EXIT,
5620                "The application closes; the default saves the settings, keymap and layout.",
5621            )
5622            .args(json!({})),
5623        )?;
5624        ctx.step(
5625            crate::steps::StepSpec::new(
5626                STEP_LAYOUT_LOAD,
5627                "The workbench's layout is loaded from a document (`document`, as the host names it).",
5628            )
5629            .args(json!({ "document": crate::host::LAYOUT_DOCUMENT })),
5630        )?
5631        .step(
5632            crate::steps::StepSpec::new(
5633                STEP_LAYOUT_SAVE,
5634                "The workbench's layout is saved to a document (`document`, as the host names it).",
5635            )
5636            .args(json!({ "document": crate::host::LAYOUT_DOCUMENT })),
5637        )?;
5638        ctx.step(
5639            crate::steps::StepSpec::new(
5640                STEP_REBIND,
5641                "The user gives a command new keys (`command`, `keys`; null: no key).",
5642            )
5643            .args(json!({ "command": "app.quit", "keys": "Ctrl+Q" })),
5644        )?
5645        .step(
5646            crate::steps::StepSpec::new(
5647                STEP_LOAD_KEYMAP,
5648                "A keymap document is loaded into the user's or the workspace's layer.",
5649            )
5650            .args(json!({ "layer": "user", "bindings": 3 })),
5651        )?;
5652        ctx.step(
5653            StepSpec::new(
5654                STEP_UNDO,
5655                "Undoes the last change in the history focus picks: the history owner's undo by default.",
5656            )
5657            .args(json!({ "label": "exposure change", "origin": "user", "scope": "app" })),
5658        )?;
5659        ctx.step(
5660            StepSpec::new(
5661                STEP_REDO,
5662                "Redoes the last undone change: the history owner's redo by default.",
5663            )
5664            .args(json!({ "label": "exposure change", "origin": "user", "scope": "app" })),
5665        )?;
5666        ctx.step(
5667            StepSpec::new(
5668                crate::history::STEP_TARGET,
5669                "Picks the history Ctrl+Z and Ctrl+Shift+Z go to (`scope`, `redo`, `rule`: focus, last_focused, none (focus routing, no view focused yet: `scope` null) or newest); a before-hook names another scope, or null for none. Run quietly whenever the target is read.",
5670            )
5671            .args(json!({ "scope": "app", "redo": false, "rule": "newest" })),
5672        )?;
5673        ctx.step(
5674            StepSpec::new(
5675                crate::history::STEP_JUMP,
5676                "Brings a history to one of its steps (`to`, 0: the start) by undos or redos, all or nothing.",
5677            )
5678            .args(json!({ "scope": "app", "to": 3, "origin": "user" })),
5679        )?;
5680        ctx.step(
5681            StepSpec::new(
5682                crate::history::STEP_RESTORE,
5683                "Brings a history back to one of its snapshots (`snapshot`), as a new step.",
5684            )
5685            .args(json!({ "scope": "app", "snapshot": 1, "origin": "user" })),
5686        )?;
5687        ctx.step(
5688            StepSpec::new(
5689                crate::history::STEP_UNDO_STEP,
5690                "Undoes one step of a history (`step`) out of order, when its owner allows it.",
5691            )
5692            .args(json!({ "scope": "app", "step": 3, "origin": "user" })),
5693        )?;
5694        ctx.on(crate::hooks::On::Pass, |app, _| crate::history::pass(app));
5695        ctx.command(
5696            CommandSpec::new(CMD_UNDO, "Undo", "Edit")
5697                .icon("undo")
5698                .description("Undo the last change.")
5699                .key_with("Ctrl+Z", BindOptions::global().through_modal())
5700                .when("!textInputFocus && (canUndo || undoNeedsView)")
5701                .menu(MENU_EDIT, "0_undo", 0),
5702            |call| outcome_result(call.app.undo(call.origin)),
5703        )?;
5704        ctx.command(
5705            CommandSpec::new(CMD_REDO, "Redo", "Edit")
5706                .icon("redo")
5707                .description("Redo the last undone change.")
5708                .key_with("Ctrl+Shift+Z", BindOptions::global().through_modal())
5709                .key_with("Ctrl+Y", BindOptions::global().through_modal())
5710                .when("!textInputFocus && (canRedo || redoNeedsView)")
5711                .menu(MENU_EDIT, "0_undo", 1),
5712            |call| outcome_result(call.app.redo(call.origin)),
5713        )?;
5714        ctx.command(
5715            CommandSpec::new(CMD_QUIT, "Quit", "File")
5716                .description("Close the application.")
5717                .key("Ctrl+Q")
5718                .menu(MENU_FILE, "9_quit", 0)
5719                .no_agent(),
5720            |call| {
5721                call.app.quit();
5722                Ok(Json::Null)
5723            },
5724        )?;
5725        let store = self.handle.store();
5726        egui_pop_model::values::register_with(&mut self.reg.commands, &owner, store, |h| {
5727            let f: CommandFn = Rc::new(move |call: &Call<'_>| h(call.args, call.origin));
5728            Some(f)
5729        })
5730        .ok();
5731        Ok(())
5732    }
5733
5734    /// The api's collectors: commands, keys, zones, plugins, services,
5735    /// diagnostics, the store.
5736    fn install_collectors(&mut self) {
5737        let h = &self.handle;
5738        let up = |w: &Weak<Shared>| {
5739            w.upgrade()
5740                .map(AppHandle)
5741                .ok_or_else(|| "the application is gone".to_string())
5742        };
5743        let mut b = h.0.bridge.borrow_mut();
5744        let (w1, w2, w3, w4) = (h.weak(), h.weak(), h.weak(), h.weak());
5745        b.register(
5746            FnCollector::new("commands", "Every command: id, title, keys, where it applies, its icon and \"on\" icon by name (with the names that do not resolve), owner; the last runs.")
5747                .snapshot(move |_| {
5748                    let Ok(app) = up(&w1) else { return Json::Null };
5749                    let cx = app.when_context();
5750                    let palette = app.palette();
5751                    json!({
5752                        "commands": app.commands().iter().map(|(s, owner)| json!({
5753                            "id": s.id,
5754                            "title": s.title,
5755                            "category": s.category,
5756                            "description": s.description,
5757                            "when": s.when,
5758                            "keys": palette.iter().find(|e| e.command == s.id).map(|e| e.keys.clone()).unwrap_or_default(),
5759                            "agent": s.agent,
5760                            "read_only": s.read_only,
5761                            "destructive": s.destructive,
5762                            "destructive_if": s.destructive_if,
5763                            "private": s.private,
5764                            "args": s.args,
5765                            "running": app.running(&s.id),
5766                            "owner": owner,
5767                            "icon": s.icon,
5768                            "icon_on": s.icon_on,
5769                            "unknown_icons": unknown_icons(s),
5770                            "icon_set_by": app.icon_set_by(&s.id),
5771                        })).collect::<Vec<_>>(),
5772                        "context": cx.iter().map(|(k, v, d)| json!({"key": k, "value": v, "depth": d})).collect::<Vec<_>>(),
5773                        // Each run says whether its command is private
5774                        // (one no longer declared counts as private), so
5775                        // a reader is given it redacted
5776                        // (`host::redact_private`).
5777                        "history": app.history().iter().map(|r| {
5778                            let mut run = json!(r);
5779                            if app.command(&r.id).is_none_or(|s| s.private) {
5780                                run["private"] = Json::Bool(true);
5781                            }
5782                            run
5783                        }).collect::<Vec<_>>(),
5784                    })
5785                })
5786                .action_as("run", "Runs a command (`id`, `args`) as its caller: anyone but the user only a command offered to agents.", true, move |_, args, origin| {
5787                    let app = up(&w2)?;
5788                    let id = args.get("id").and_then(Json::as_str).ok_or("`id` is missing")?;
5789                    let id = CommandId::new(id).map_err(|e| e.to_string())?;
5790                    let known = app.commands().iter().find(|(s, _)| s.id == id).map(|(s, _)| s.agent);
5791                    match known {
5792                        None => return Err(format!("`{id}` is not offered to agents")),
5793                        Some(false) if *origin != Origin::User => {
5794                            return Err(format!("`{id}` is not offered to agents"));
5795                        }
5796                        Some(_) => {}
5797                    }
5798                    let run_args = args.get("args").cloned().unwrap_or(Json::Null);
5799                    // Arguments its schema refuses are refused now, on
5800                    // the journal as the run itself would be, rather than
5801                    // queued to fail later.
5802                    if let Some(msg) = app.command_args_refusal(&id, &run_args) {
5803                        app.publish(
5804                            &source_of(origin),
5805                            None,
5806                            "command.refused",
5807                            json!({
5808                                "command": id,
5809                                "origin": source_of(origin),
5810                                "reason": msg,
5811                                "by": crate::bus::ARGS_VALIDATOR,
5812                                "failed": false,
5813                            }),
5814                        );
5815                        return Err(msg);
5816                    }
5817                    app.run_as(id, run_args, origin.clone());
5818                    Ok(json!({ "queued": true }))
5819                })
5820                // The command's own `agent` flag is checked.
5821                .agent(true)
5822                // Running a read-only command changes nothing.
5823                .mutates_when(move |args| {
5824                    let Ok(app) = up(&w3) else { return true };
5825                    let Some(id) = args.get("id").and_then(Json::as_str) else { return true };
5826                    !app.commands().iter().any(|(s, _)| s.id.as_str() == id && s.read_only)
5827                })
5828                // Destructive when its command is, whole or by these
5829                // arguments (`CommandSpec::destructive_if`): an agent's run waits
5830                // for the user's confirmation. A command kept from agents
5831                // is refused to them without asking.
5832                .destructive_when(move |args| {
5833                    let Ok(app) = up(&w4) else { return false };
5834                    let Some(id) = args.get("id").and_then(Json::as_str) else { return false };
5835                    // A run its schema refuses is refused at once, not
5836                    // asked about.
5837                    let run_args = args.get("args").cloned().unwrap_or(Json::Null);
5838                    app.commands().iter().any(|(s, _)| {
5839                        s.id.as_str() == id
5840                            && s.is_destructive(&run_args)
5841                            && s.agent
5842                            && crate::bus::args_refusal(s, &run_args).is_none()
5843                    })
5844                })
5845                .args(json!({ "id": "app.palette", "args": null })),
5846        )
5847        .expect("distinct names");
5848        let (w1, w2) = (h.weak(), h.weak());
5849        b.register(
5850            FnCollector::new(
5851                "icons",
5852                "The icon vocabulary (egui-pop's names, the Phosphor set's `phosphor:<name>` when built in, the registered ones with their owner and paint), every icon a command, panel or frame declares and whether it resolves, the unknown names with who asked for them, and the icons drawn by name in the last pass (tree rows, inputs, crumbs).",
5853            )
5854            .snapshot(move |ctx| {
5855                use egui_pop_core::icon::registry;
5856                let Ok(app) = up(&w1) else { return Json::Null };
5857                let declared = declared_icons(&app);
5858                let mut unknown: Vec<Json> = registry::unknown()
5859                    .into_iter()
5860                    .map(|u| json!(u))
5861                    .collect();
5862                for d in declared.iter().filter(|d| !d.resolves) {
5863                    unknown.push(json!({
5864                        "name": d.name,
5865                        "surfaces": [format!("{} {}", d.surface, d.subject)],
5866                        "owner": d.owner,
5867                        "hint": registry::hint(&d.name),
5868                    }));
5869                }
5870                json!({
5871                    "builtin": registry::builtin_names().collect::<Vec<_>>(),
5872                    "phosphor": {
5873                        "available": registry::phosphor_available(),
5874                        "prefix": registry::PHOSPHOR_PREFIX,
5875                        "count": registry::phosphor_names().len(),
5876                    },
5877                    "registered": egui_pop_core::icon_set::registered().iter().map(|r| json!({
5878                        "name": r.name,
5879                        "owner": r.owner,
5880                        "paint": match r.paint {
5881                            egui_pop_core::icon_set::Paint::Mono => "single-colour",
5882                            egui_pop_core::icon_set::Paint::Colour => "full-colour",
5883                        },
5884                    })).collect::<Vec<_>>(),
5885                    "declared": declared,
5886                    "unknown": unknown,
5887                    "drawn": registry::drawn(ctx),
5888                })
5889            })
5890            .action(
5891                "search",
5892                "The names of the vocabulary containing `query` (at most `limit`, 50 by default), Phosphor's included.",
5893                false,
5894                move |_, args| {
5895                    let _ = up(&w2)?;
5896                    let query = args.get("query").and_then(Json::as_str).ok_or("`query` is missing")?;
5897                    let limit = args.get("limit").and_then(Json::as_u64).unwrap_or(50) as usize;
5898                    Ok(json!(egui_pop_core::icon::registry::search(query, limit)))
5899                },
5900            )
5901            .args(json!({ "query": "grid", "limit": 20 })),
5902        )
5903        .expect("distinct names");
5904        let (w1, w2) = (h.weak(), h.weak());
5905        b.register(
5906            FnCollector::new(
5907                "journal",
5908                "The host's event journal (sequence, source, cause, name, data): the last 64, or since a sequence number.",
5909            )
5910            .snapshot(move |_| {
5911                let Ok(app) = up(&w1) else { return Json::Null };
5912                let last = app.last_event();
5913                json!({ "last": last, "events": app.events_since(last.saturating_sub(64)) })
5914            })
5915            .action("since", "The events after `seq`.", false, move |_, args| {
5916                let app = up(&w2)?;
5917                let seq = args.get("seq").and_then(Json::as_u64).unwrap_or(0);
5918                Ok(json!(app.events_since(seq)))
5919            })
5920            .args(json!({ "seq": 0 })),
5921        )
5922        .expect("distinct names");
5923        let w = h.weak();
5924        b.register(
5925            FnCollector::new(
5926                BRIDGE,
5927                "The bridge itself, for agents: every capability as one list (`describe`), and a wait on the journal or for the application to settle (`wait`).",
5928            )
5929            .action(
5930                "describe",
5931                "Every capability: the collectors' actions and the commands, with their JSON Schemas when given (`AppHandle::debug_capabilities`).",
5932                false,
5933                |_, _| Err("answered by the application (`AppHandle::debug_capabilities`)".into()),
5934            )
5935            .agent(true)
5936            .args(Json::Null)
5937            .result_schema(json!({
5938                "type": "object",
5939                "required": ["protocol", "capabilities"],
5940                "properties": {
5941                    "protocol": { "type": "integer" },
5942                    "capabilities": { "type": "array", "items": { "type": "object" } }
5943                }
5944            }))
5945            .action(
5946                "wait",
5947                "Whether a journal event after `since` matches (`event`, `cause`), the application is settled (`settled: true`), or the first of several (`any`); in-process it answers at once, a transport holds it until met or `deadline_ms`.",
5948                false,
5949                move |_, args| up(&w)?.wait_answer(args),
5950            )
5951            .agent(true)
5952            .args(json!({ "event": "command.done", "since": 0 }))
5953            .schema(crate::wait::args_schema())
5954            .result_schema(crate::wait::result_schema()),
5955        )
5956        .expect("distinct names");
5957        let w = h.weak();
5958        b.register(
5959            FnCollector::new(
5960                "keys",
5961                "The keymap's last resolutions, each binding considered and why it won or lost; `dormant` lists the bindings whose command went with a disconnected plugin.",
5962            )
5963            .snapshot(move |_| {
5964                let Ok(app) = up(&w) else { return Json::Null };
5965                json!({ "pending": app.pending_keys(), "traces": app.key_traces(), "dormant": app.dormant_keys() })
5966            }),
5967        )
5968        .expect("distinct names");
5969        let w = h.weak();
5970        b.register(
5971            FnCollector::new(
5972                "zones",
5973                "Every zone and its resolved blocks: owner, weight, what replaced or wrapped them.",
5974            )
5975            .snapshot(move |_| {
5976                let Ok(app) = up(&w) else { return Json::Null };
5977                json!(app.zones())
5978            }),
5979        )
5980        .expect("distinct names");
5981        let (w1, w2) = (h.weak(), h.weak());
5982        b.register(
5983            FnCollector::new("plugins", "The plugins in connection order, connected or why not; the services.")
5984                .snapshot(move |_| {
5985                    let Ok(app) = up(&w1) else { return Json::Null };
5986                    json!({
5987                        "plugins": app.plugins(),
5988                        "services": app.services().iter().map(|(i, o, t)| json!({"id": i, "owner": o, "type": t})).collect::<Vec<_>>(),
5989                    })
5990                })
5991                .action("set_enabled", "Connects or disconnects a plugin (`id`, `enabled`), before the next frame.", true, move |_, args| {
5992                    let app = up(&w2)?;
5993                    let id = args.get("id").and_then(Json::as_str).ok_or("`id` is missing")?;
5994                    let id = PluginId::new(id).map_err(|e| e.to_string())?;
5995                    if !app.plugins().iter().any(|p| p.id == id) {
5996                        return Err(format!("no plugin `{id}`"));
5997                    }
5998                    let enabled = args.get("enabled").and_then(Json::as_bool).ok_or("`enabled` is missing")?;
5999                    app.set_plugin_enabled(id, enabled);
6000                    Ok(json!({ "queued": true }))
6001                })
6002                .args(json!({ "id": "plugin.id", "enabled": false })),
6003        )
6004        .expect("distinct names");
6005        let w = h.weak();
6006        b.register(
6007            FnCollector::new(
6008                "diagnostics",
6009                "What registration ignored or changed, and what happens instead.",
6010            )
6011            .snapshot(move |_| {
6012                let Ok(app) = up(&w) else { return Json::Null };
6013                json!(app.diagnostics())
6014            }),
6015        )
6016        .expect("distinct names");
6017        let w = h.weak();
6018        b.register(
6019            FnCollector::new(
6020                "steps",
6021                "Every declared step with its hooks (before, replace, after), and the last runs: who redirected, vetoed, ran and followed.",
6022            )
6023            .snapshot(move |_| {
6024                let Ok(app) = up(&w) else { return Json::Null };
6025                json!({ "steps": app.steps(), "runs": app.step_traces() })
6026            }),
6027        )
6028        .expect("distinct names");
6029        let w = h.weak();
6030        b.register(
6031            FnCollector::new(
6032                "bus",
6033                "The bus (ADR 0029): every point on it, egui-pop's and the application's (`by`), with its kind, deadline and budget, whether it is journaled or relayable, and its listeners in the order they run (owner, after, before, priority, deadline, threaded, local, missing targets, runs, failures), the ordering constraints naming a listener not there, the order as text, the window registry (`windows.list`), and the window invariants broken now and said. The capabilities the bus offers (`capabilities`: defer, timings, journal, relay) and, with a journal, its last number (`journal_seq`). When the bus offers timings: each point's passes (`timing`: count, p50, p95, max in µs, passes over budget) and each listener's runs, and `slowest`: every listener timed, the slowest first by p95.",
6034            )
6035            .snapshot(move |_| {
6036                let Ok(app) = up(&w) else { return Json::Null };
6037                let kernel = app.bus();
6038                let infos = kernel.points();
6039                let ids: Vec<&str> = infos.iter().map(|p| p.id).collect();
6040                let timings: Vec<crate::bus::bus_contract_timings::PointTimings> =
6041                    kernel.timings().map(|t| t.points()).unwrap_or_default();
6042                let points: Vec<Json> = infos
6043                    .iter()
6044                    .map(|p| {
6045                        let timed = timings.iter().find(|t| t.point == p.id);
6046                        let listeners: Vec<Json> = p
6047                            .listeners
6048                            .iter()
6049                            .map(|l| {
6050                                let timing = timed
6051                                    .and_then(|t| t.listeners.iter().find(|x| x.id == l.id))
6052                                    .map(|x| crate::bus::budget::stats(&x.stats));
6053                                json!({
6054                                    "id": l.id,
6055                                    "owner": l.owner,
6056                                    "after": l.after,
6057                                    "before": l.before,
6058                                    "priority": l.priority,
6059                                    "deadline_ms": l.deadline.as_millis(),
6060                                    "threaded": l.threaded,
6061                                    "local": l.local,
6062                                    "missing": l.missing,
6063                                    "runs": l.runs,
6064                                    "failures": l.failures,
6065                                    "last_failure": l.last_failure,
6066                                    "timing": timing,
6067                                })
6068                            })
6069                            .collect();
6070                        let by = if crate::bus::CONTRACT.iter().any(|d| d.id == p.id) {
6071                            "egui_pop"
6072                        } else {
6073                            "application"
6074                        };
6075                        let timing = timed.map(|t| {
6076                            let mut j = crate::bus::budget::stats(&t.passes);
6077                            j["over_budget"] = json!(t.over_budget);
6078                            j
6079                        });
6080                        json!({
6081                            "point": p.id,
6082                            "kind": p.kind.as_str(),
6083                            "by": by,
6084                            "declared": p.declared,
6085                            "description": p.description,
6086                            "deadline_ms": p.deadline.as_millis(),
6087                            "budget_us": p.budget.map(crate::bus::budget::us),
6088                            "journaled": crate::bus::bus_contract_journal::is_journaled(&p.facets),
6089                            "relayable": crate::bus::bus_contract_crossing::codec(&p.facets).is_some(),
6090                            "timing": timing,
6091                            "listeners": listeners,
6092                        })
6093                    })
6094                    .collect();
6095                let offers = |c| crate::bus::bus_contract::offers(&*kernel, c);
6096                json!({
6097                    "capabilities": {
6098                        "defer": offers(&crate::bus::bus_contract_defer::CONTRACT),
6099                        "timings": offers(&crate::bus::bus_contract_timings::CONTRACT),
6100                        "journal": offers(&crate::bus::bus_contract_journal::CONTRACT),
6101                        "relay": offers(&crate::bus::bus_contract_crossing::CONTRACT),
6102                    },
6103                    "journal_seq": kernel.journal().map(|j| j.last_seq()),
6104                    "points": points,
6105                    "slowest": crate::bus::budget::slowest(&timings),
6106                    "missing_targets": crate::bus::missing_targets(&*kernel, &ids),
6107                    "order": app.bus_order_of(&ids),
6108                    "windows": app.windows_list(),
6109                    "invariants": { "broken_now": app.invariants_broken_now(), "said": app.broken_invariants() },
6110                })
6111            }),
6112        )
6113        .expect("distinct names");
6114        let w = h.weak();
6115        b.register(
6116            FnCollector::new(
6117                "lists",
6118                "The menus' list providers (name, owner) and the entries each gave when its menu last opened.",
6119            )
6120            .snapshot(move |_| {
6121                let Ok(app) = up(&w) else { return Json::Null };
6122                app.lists()
6123            }),
6124        )
6125        .expect("distinct names");
6126        let w = h.weak();
6127        b.register(
6128            FnCollector::new(
6129                "menu_bar",
6130                "Each menu drawn as a bar (the shell's `app.main`): the menus in the bar, those moved into its \"…\" menu, whether it collapsed into one entry, and each menu's access key.",
6131            )
6132            .snapshot(move |_| {
6133                let Ok(app) = up(&w) else { return Json::Null };
6134                json!(crate::menus::bar_layouts(&app))
6135            }),
6136        )
6137        .expect("distinct names");
6138        let w = h.weak();
6139        b.register(
6140            FnCollector::new(
6141                "toolbars",
6142                "Each toolbar drawn last (`toolbars::Toolbar`), by menu id: its orientation and labels, every tool in order (a command with its arguments, a submenu or a separator; its title, icon name, key, whether it is enabled and why not, checked, busy) and which went into its \"More tools\" menu.",
6143            )
6144            .snapshot(move |_| {
6145                let Ok(app) = up(&w) else { return Json::Null };
6146                json!(crate::toolbars::layouts(&app))
6147            }),
6148        )
6149        .expect("distinct names");
6150        let w = h.weak();
6151        b.register(
6152            FnCollector::new(
6153                "text_scale",
6154                "The text size: the factor in use, the setting's default (the system's step), whether the user chose it, and the system's text scaling (factor, step, where it was read).",
6155            )
6156            .snapshot(move |_| {
6157                let Ok(app) = up(&w) else { return Json::Null };
6158                crate::text::describe(&app)
6159            }),
6160        )
6161        .expect("distinct names");
6162        let w = h.weak();
6163        b.register(
6164            FnCollector::new(
6165                "history",
6166                "The histories (ADR 0014): each scope, whether it is active, where Edit > Undo and Redo go and what they would do (the runs are in the `steps` collector).",
6167            )
6168            .snapshot(move |_| {
6169                let Ok(app) = up(&w) else { return Json::Null };
6170                crate::history::snapshot(&app)
6171            }),
6172        )
6173        .expect("distinct names");
6174        let w = h.weak();
6175        b.register(
6176            FnCollector::new(
6177                "overlay_rects",
6178                "Every overlay on screen with where it was drawn last (points): dialogs, modals, popovers, menus, the toasts, egui's popups.",
6179            )
6180            .snapshot(move |_| {
6181                let Ok(app) = up(&w) else { return Json::Null };
6182                json!(
6183                    app.overlay_rects()
6184                        .iter()
6185                        .map(|o| json!({
6186                            "kind": o.kind,
6187                            "id": o.id,
6188                            "rect": [o.rect.min.x, o.rect.min.y, o.rect.max.x, o.rect.max.y],
6189                        }))
6190                        .collect::<Vec<_>>()
6191                )
6192            }),
6193        )
6194        .expect("distinct names");
6195        let w = h.weak();
6196        b.register(
6197            FnCollector::new(
6198                "windows",
6199                "The application's windows (`main`, or a detached panel's id): the active one (where dialogs, the palette and menus open, and toasts show), each window's open overlays (bottom first) and whether a modal blocks the others, and the windows the palette and the popup menu are shown in.",
6200            )
6201            .snapshot(move |_| {
6202                let Ok(app) = up(&w) else { return Json::Null };
6203                app.describe_windows()
6204            }),
6205        )
6206        .expect("distinct names");
6207        let w = h.weak();
6208        b.register(
6209            FnCollector::new(
6210                "workbench",
6211                "The workbench: the layout (areas, folded, closed and detached panels, flyout widths), where each area was drawn (points), the focused panel, the side areas' strip icons (`strips`: each panel's title, icon, key, whether it shows, and its indicator with `marked` when the icon shows it), the flyout open (its panel and rect), the tab being dragged and the drop hint (its rect, name, refusal, zone and index among the tabs it joins).",
6212            )
6213            .snapshot(move |_| {
6214                let Ok(app) = up(&w) else { return Json::Null };
6215                let layout = app.layout();
6216                let strips = crate::workbench::strip(&app);
6217                let wb = app.workbench_mut();
6218                json!({
6219                    "layout": layout,
6220                    "strips": strips,
6221                    "flyout": wb.flyout.as_ref().map(|p| json!({
6222                        "panel": p,
6223                        "rect": wb.flyout_rect.map(|r| [r.min.x, r.min.y, r.max.x, r.max.y]),
6224                    })),
6225                    "rects": wb.rects.iter().map(|(a, r)| (
6226                        crate::workbench::area_name(*a),
6227                        [r.min.x, r.min.y, r.max.x, r.max.y],
6228                    )).collect::<BTreeMap<_, _>>(),
6229                    "focused": wb.focused,
6230                    "zen": wb.zen,
6231                    "dragging": wb.dragging.as_ref().map(|(d, a, _)| json!({
6232                        "panel": d.lead(),
6233                        "group": d.is_group().then(|| d.panels()),
6234                        "from": crate::workbench::area_name(*a),
6235                    })),
6236                    "window_outlines": wb.window_outlines(),
6237                    "window_drop": wb.window_drop.as_ref().map(|d| json!({
6238                        "panel": d.panel,
6239                        "window": d.window,
6240                        "zone": format!("{:?}", d.zone).to_lowercase(),
6241                        "refusal": d.refusal,
6242                    })),
6243                    "drop_hint": wb.hint.as_ref().map(|h| json!({
6244                        "name": h.name(),
6245                        "panel": h.panel,
6246                        "area": h.area,
6247                        "rect": [h.rect.min.x, h.rect.min.y, h.rect.max.x, h.rect.max.y],
6248                        "refusal": h.refusal,
6249                        "zone": format!("{:?}", h.zone).to_lowercase(),
6250                        "index": h.index,
6251                        "armed": h.armed,
6252                        "preview": h.preview.as_ref().map(|p| json!({
6253                            "area": p.area,
6254                            "index": p.index,
6255                            "rect": [p.rect.min.x, p.rect.min.y, p.rect.max.x, p.rect.max.y],
6256                        })),
6257                    })),
6258                })
6259            }),
6260        )
6261        .expect("distinct names");
6262        b.register(egui_pop_core::debug::store_collector(h.store()))
6263            .expect("distinct names");
6264        b.register(crate::mounts::collector(h.downgrade()))
6265            .expect("distinct names");
6266    }
6267
6268    /// Calls the debug bridge as the agent (`AppHandle::debug_call`);
6269    /// `commands.run` runs at once and its result is in the feedback.
6270    pub fn debug_call(&mut self, collector: &str, action: &str, args: &Json) -> Feedback {
6271        self.debug_call_as(collector, action, args, egui_pop_core::debug::agent())
6272    }
6273
6274    /// Calls the debug bridge for `origin` (`AppHandle::debug_call_as`);
6275    /// `commands.run` runs at once and its result is in the feedback.
6276    pub fn debug_call_as(
6277        &mut self,
6278        collector: &str,
6279        action: &str,
6280        args: &Json,
6281        origin: Origin,
6282    ) -> Feedback {
6283        let feedback = self
6284            .handle
6285            .debug_call_as(collector, action, args, origin.clone());
6286        if collector == "commands"
6287            && action == "run"
6288            && feedback.ok
6289            && feedback.data == json!({ "queued": true })
6290        {
6291            let queued = self.handle.0.requests.borrow_mut().pop();
6292            let id = args
6293                .get("id")
6294                .and_then(Json::as_str)
6295                .and_then(|i| CommandId::new(i).ok());
6296            if let Some(id) = id {
6297                let a = args.get("args").cloned().unwrap_or(Json::Null);
6298                let reply = match queued {
6299                    Some(Request::RunIn { context, .. }) => self.run_in(&id, a, origin, &context),
6300                    _ => self.run(&id, a, origin),
6301                };
6302                let Some(result) = reply.now() else {
6303                    return Feedback {
6304                        message: format!("`{id}` is running; its result goes to the journal"),
6305                        data: json!({ "pending": true }),
6306                        ..feedback
6307                    };
6308                };
6309                return Feedback {
6310                    ok: result.is_ok(),
6311                    message: match &result {
6312                        Ok(_) => format!("`{id}` ran; the application may have changed"),
6313                        Err(e) => format!("`{id}` failed: {e}"),
6314                    },
6315                    data: result.unwrap_or(Json::Null),
6316                    ..feedback
6317                };
6318            }
6319        }
6320        if feedback.ok && feedback.mutates {
6321            self.process_requests();
6322        }
6323        feedback
6324    }
6325
6326    fn connected_ids(&self) -> Vec<PluginId> {
6327        self.plugins
6328            .iter()
6329            .filter(|p| p.connected)
6330            .map(|p| p.id.clone())
6331            .collect()
6332    }
6333
6334    /// Connects one plugin (its requirements must be connected). A
6335    /// failure removes what it registered.
6336    fn connect_slot(&mut self, i: usize) -> Result<(), PluginError> {
6337        let connected = self.connected_ids();
6338        let slot = &self.plugins[i];
6339        if let Some(missing) = slot
6340            .plugin
6341            .requires()
6342            .into_iter()
6343            .find(|r| !connected.contains(r))
6344        {
6345            let reason = format!("its requirement `{missing}` is not connected");
6346            self.handle.0.diagnostics.borrow_mut().warn(
6347                "plugin-skipped",
6348                Some(&slot.owner),
6349                slot.id.as_str(),
6350                format!("{reason}: it is not connected"),
6351            );
6352            self.plugins[i].reason = Some(reason);
6353            self.update_plugin_infos();
6354            return Ok(());
6355        }
6356        let handle = self.handle.clone();
6357        let owner = slot.owner.clone();
6358        let id = slot.id.clone();
6359        let mut ctx = Ctx {
6360            owner: owner.clone(),
6361            plugin: id.clone(),
6362            rank: i + 1,
6363            reg: &mut self.reg,
6364            app: &handle,
6365            connected: &connected,
6366        };
6367        let slot = &mut self.plugins[i];
6368        // What it writes while connecting is written as the plugin.
6369        let _scope = egui_pop_model::values::enter_scope(&owner);
6370        if !slot.plugin.enabled(&ctx) {
6371            slot.reason = Some("it is disabled".into());
6372            self.update_plugin_infos();
6373            return Ok(());
6374        }
6375        match slot.plugin.connect(&mut ctx) {
6376            Ok(()) => {
6377                slot.connected = true;
6378                slot.reason = None;
6379                self.handle
6380                    .0
6381                    .gone_commands
6382                    .borrow_mut()
6383                    .retain(|_, p| *p != id);
6384                self.handle.zones_mut().set_rank(&owner, i + 1);
6385                self.dirty = true;
6386                self.update_plugin_infos();
6387                if self.started {
6388                    // Its listeners take back what it had left (ADR 0029).
6389                    self.handle.plugin_connected(crate::bus::PluginChange::new(
6390                        id.as_str(),
6391                        owner.as_str(),
6392                        "connected",
6393                    ));
6394                    self.emit(&Lifecycle::Connected(id));
6395                }
6396                Ok(())
6397            }
6398            Err(e) => {
6399                let removed = self.remove_owner(&owner);
6400                self.said_gone(&id, &owner, "failed connect", removed);
6401                let slot = &mut self.plugins[i];
6402                slot.reason = Some(format!("it failed to connect: {e}"));
6403                self.handle.0.diagnostics.borrow_mut().error(
6404                    "connect-failed",
6405                    Some(&owner),
6406                    id.as_str(),
6407                    format!("{e}: what it registered is removed"),
6408                );
6409                self.update_plugin_infos();
6410                Err(e)
6411            }
6412        }
6413    }
6414
6415    fn remove_owner(&mut self, owner: &OwnerId) -> Removed {
6416        let commands = self.reg.remove_owner(owner);
6417        let h = &self.handle.0;
6418        h.zones.borrow_mut().remove_owner(owner);
6419        let panels = {
6420            let mut panels = h.panels.borrow_mut();
6421            let n = panels.len();
6422            panels.retain(|_, p| p.owner != *owner);
6423            n - panels.len()
6424        };
6425        h.stories.borrow_mut().remove_owner(owner);
6426        h.steps.borrow_mut().remove_owner(owner);
6427        h.step_hooks.borrow_mut().remove_owner(owner);
6428        h.lists.borrow_mut().remove_owner(owner);
6429        h.list_traces.borrow_mut().retain(|_, t| t.owner != *owner);
6430        h.indicators.borrow_mut().remove_owner(owner);
6431        h.workbench.borrow_mut().templates.retain(|t| t.0 != *owner);
6432        h.services.borrow_mut().remove_owner(owner);
6433        // Its listeners on the bus go with it (ADR 0029).
6434        h.bus.kernel.forget(owner.as_str());
6435        let mounts = crate::mounts::remove_owner(&self.handle, owner);
6436        let undo = lock(&h.store).remove_owner_report(owner).dropped;
6437        crate::history::remove_owner(&self.handle, owner);
6438        h.diagnostics.borrow_mut().remove_owner(owner);
6439        egui_pop_core::icon_set::unregister_owner(owner.as_str());
6440        h.collectors.borrow_mut().retain(|(o, name)| {
6441            if o == owner {
6442                h.bridge.borrow_mut().unregister(name);
6443            }
6444            o != owner
6445        });
6446        self.dirty = true;
6447        Removed {
6448            commands,
6449            panels,
6450            mounts,
6451            undo,
6452        }
6453    }
6454
6455    /// Says that a plugin went (ADR 0028): a `plugin.disconnected` event
6456    /// on the journal, with why and what went by kind, and an info line.
6457    /// Its commands are kept as gone, so a run of one is refused naming
6458    /// it.
6459    fn said_gone(&mut self, plugin: &PluginId, owner: &OwnerId, reason: &str, removed: Removed) {
6460        let steps: usize = removed.undo.iter().map(|d| d.steps).sum();
6461        let mixed: usize = removed.undo.iter().map(|d| d.mixed).sum();
6462        // The bus is asked first: its listeners close or mark what the
6463        // plugin leaves (its jobs), each counting what it did, before the
6464        // event that counts them (ADR 0029).
6465        let did = self.handle.plugin_disconnected(
6466            crate::bus::PluginChange::new(plugin.as_str(), owner.as_str(), reason).commands(
6467                removed
6468                    .commands
6469                    .iter()
6470                    .map(|c| c.as_str().to_string())
6471                    .collect(),
6472            ),
6473        );
6474        let count = |key: &str| did.get(key).and_then(Json::as_u64).unwrap_or(0);
6475        let (jobs_cancelled, jobs_orphaned) = (count("jobs_cancelled"), count("jobs_orphaned"));
6476        log::info!(
6477            target: "egui_pop",
6478            "plugin `{plugin}` disconnected ({reason}): {} command(s), {} panel(s), {} component(s), {} host(s), {} mount(s), {steps} undo step(s) ({mixed} mixed) removed; {jobs_cancelled} job(s) to cancel, {jobs_orphaned} orphaned",
6479            removed.commands.len(),
6480            removed.panels,
6481            removed.mounts.components,
6482            removed.mounts.hosts,
6483            removed.mounts.mounts,
6484        );
6485        let undo: Vec<Json> = removed
6486            .undo
6487            .iter()
6488            .map(|d| json!({ "history": d.history, "steps": d.steps, "mixed": d.mixed }))
6489            .collect();
6490        let mut counted = json!({
6491            "commands": removed.commands.len(),
6492            "panels": removed.panels,
6493            "components": removed.mounts.components,
6494            "hosts": removed.mounts.hosts,
6495            "mounts": removed.mounts.mounts,
6496            "undo_steps": steps,
6497            "mixed_undo_steps": mixed,
6498            // Said without the jobs plugin too: the event keeps its shape.
6499            "jobs_cancelled": jobs_cancelled,
6500            "jobs_orphaned": jobs_orphaned,
6501        });
6502        for (key, value) in did {
6503            counted[key] = value;
6504        }
6505        self.handle.publish(
6506            "egui_pop",
6507            None,
6508            "plugin.disconnected",
6509            json!({
6510                "plugin": plugin,
6511                "owner": owner,
6512                "reason": reason,
6513                "removed": counted,
6514                "undo": undo,
6515            }),
6516        );
6517        // What it left open is closed, saying why (ADR 0028): its
6518        // dialogs are cancelled; its commands are kept as gone, so a run
6519        // of one is refused naming it and a toast's action greyed.
6520        crate::dialogs::owner_gone(&self.handle, plugin, owner, &removed.commands);
6521        let mut gone = self.handle.0.gone_commands.borrow_mut();
6522        for c in removed.commands {
6523            gone.insert(c, plugin.clone());
6524        }
6525    }
6526
6527    fn update_plugin_infos(&self) {
6528        *self.handle.0.plugins.borrow_mut() = self
6529            .plugins
6530            .iter()
6531            .map(|s| PluginInfo {
6532                id: s.id.clone(),
6533                title: s.plugin.title(),
6534                requires: s.plugin.requires(),
6535                priority: s.plugin.priority(),
6536                connected: s.connected,
6537                reason: s.reason.clone(),
6538            })
6539            .collect();
6540    }
6541
6542    /// Disconnects a plugin and those requiring it (dependents first);
6543    /// everything they registered is removed. Returns the plugins
6544    /// disconnected. Each leaves a `plugin.disconnected` event on the
6545    /// journal (ADR 0028).
6546    pub fn disconnect(&mut self, plugin: &PluginId) -> Vec<PluginId> {
6547        self.disconnect_because(plugin, "removed")
6548    }
6549
6550    /// [`App::disconnect`], saying why on the journal: `removed`,
6551    /// `disabled`; its dependents say `requirement gone`.
6552    fn disconnect_because(&mut self, plugin: &PluginId, reason: &str) -> Vec<PluginId> {
6553        let mut out = Vec::new();
6554        let Some(i) = self.plugins.iter().position(|p| p.id == *plugin) else {
6555            return out;
6556        };
6557        if !self.plugins[i].connected {
6558            return out;
6559        }
6560        // Dependents first, latest first.
6561        for j in (i + 1..self.plugins.len()).rev() {
6562            if self.plugins[j].connected && self.plugins[j].plugin.requires().contains(plugin) {
6563                let dep = self.plugins[j].id.clone();
6564                out.extend(self.disconnect_because(&dep, "requirement gone"));
6565            }
6566        }
6567        let handle = self.handle.clone();
6568        let connected = self.connected_ids();
6569        let slot = &mut self.plugins[i];
6570        let owner = slot.owner.clone();
6571        let mut ctx = Ctx {
6572            owner: owner.clone(),
6573            plugin: slot.id.clone(),
6574            rank: i + 1,
6575            reg: &mut self.reg,
6576            app: &handle,
6577            connected: &connected,
6578        };
6579        slot.plugin.disconnect(&mut ctx);
6580        slot.connected = false;
6581        slot.reason = Some("it was disconnected".into());
6582        let removed = self.remove_owner(&owner);
6583        self.said_gone(plugin, &owner, reason, removed);
6584        self.update_plugin_infos();
6585        self.emit(&Lifecycle::Disconnected(plugin.clone()));
6586        out.push(plugin.clone());
6587        out
6588    }
6589
6590    /// Connects a plugin that is not (its requirements first).
6591    pub fn connect(&mut self, plugin: &PluginId) -> Result<(), PluginError> {
6592        let Some(i) = self.plugins.iter().position(|p| p.id == *plugin) else {
6593            return Err(PluginError::Failed(format!("no plugin `{plugin}`")));
6594        };
6595        if self.plugins[i].connected {
6596            return Ok(());
6597        }
6598        for r in self.plugins[i].plugin.requires() {
6599            self.connect(&r)?;
6600        }
6601        self.connect_slot(i)
6602    }
6603
6604    fn emit(&mut self, event: &Lifecycle) {
6605        let handle = self.handle.clone();
6606        // Handlers get the handle, not `Ctx`: the list cannot change
6607        // while they run.
6608        for slot in self.reg.lifecycle.iter_mut() {
6609            let (on, f) = &mut slot.item;
6610            if on.matches(event) {
6611                let _scope = egui_pop_model::values::enter_scope(&slot.owner);
6612                f(&handle, event);
6613            }
6614        }
6615    }
6616
6617    /// Rebuilds the derived declarations: menus, palette and settings
6618    /// through their hooks, and the zones. Runs after plugins come or go,
6619    /// never per frame.
6620    pub fn rebuild(&mut self) {
6621        let mut d = Diagnostics::new();
6622        // Keys bound to a command that went with its plugin are dormant
6623        // while it is off (ADR 0028): they stay, and take no key.
6624        let gone: BTreeMap<CommandId, PluginId> = self
6625            .handle
6626            .0
6627            .gone_commands
6628            .borrow()
6629            .iter()
6630            .filter(|(c, _)| self.reg.commands.spec(c).is_none())
6631            .map(|(c, p)| (c.clone(), p.clone()))
6632            .collect();
6633        self.reg
6634            .keymap
6635            .borrow_mut()
6636            .set_dormant(gone.keys().cloned());
6637        let reg = &self.reg;
6638        // Hooks in order: `after` constraints, then priority.
6639        let hooks: Vec<&Hook> = reg.hooks.iter().map(|s| &s.item).collect();
6640        let nodes: Vec<Node> = hooks
6641            .iter()
6642            .map(|h| {
6643                let id = egui_pop_model::ids::PluginId::new(h.id.as_str()).expect("same syntax");
6644                let after = h
6645                    .after
6646                    .iter()
6647                    .filter(|a| {
6648                        let known = hooks.iter().any(|o| o.id == **a);
6649                        if !known {
6650                            d.warn(
6651                                "dangling-after",
6652                                None,
6653                                h.id.as_str(),
6654                                format!("hook `{}` runs after `{a}`, which is not registered: it runs by priority alone", h.id),
6655                            );
6656                        }
6657                        known
6658                    })
6659                    .map(|a| PluginId::new(a.as_str()).expect("same syntax"))
6660                    .collect();
6661                Node {
6662                    id,
6663                    requires: after,
6664                    priority: h.priority,
6665                }
6666            })
6667            .collect();
6668        let hook_order: Vec<usize> = match order(&nodes) {
6669            Ok(o) => o,
6670            Err(e) => {
6671                d.error(
6672                    "hook-order",
6673                    None,
6674                    "hooks",
6675                    format!("{e}: hooks run in registration order"),
6676                );
6677                (0..hooks.len()).collect()
6678            }
6679        };
6680        let mut derived = Derived::default();
6681        for id in reg.menus.ids() {
6682            let mut items = reg.menus.items(&id);
6683            sort_items(&mut items);
6684            derived.menus.insert(id, items);
6685        }
6686        derived.palette = reg
6687            .commands
6688            .specs()
6689            .filter(|s| s.palette)
6690            .map(|s| PaletteEntry {
6691                command: s.id.clone(),
6692                title: s.title.clone(),
6693                category: s.category.clone(),
6694                keys: reg
6695                    .keymap
6696                    .borrow()
6697                    .keys_for(&s.id)
6698                    .iter()
6699                    .map(|k| k.to_string())
6700                    .collect(),
6701            })
6702            .collect();
6703        derived
6704            .palette
6705            .sort_by(|a, b| (&a.category, &a.title).cmp(&(&b.category, &b.title)));
6706        let titles: BTreeMap<OwnerId, String> = self
6707            .plugins
6708            .iter()
6709            .map(|s| (s.owner.clone(), s.plugin.title()))
6710            .chain([(OwnerId::FRAMEWORK, FRAMEWORK_SECTION.to_string())])
6711            .collect();
6712        let store = lock(&self.handle.0.store);
6713        derived.sections.clone_from(&titles);
6714        derived.settings = reg
6715            .settings
6716            .in_order()
6717            .into_iter()
6718            .filter_map(|(id, slot)| {
6719                store.get(&slot.item).map(|e| SettingEntry {
6720                    id: id.clone(),
6721                    path: slot.item.clone(),
6722                    owner: slot.owner.clone(),
6723                    // The text settings have their page, under Appearance.
6724                    section: if slot.owner == OwnerId::FRAMEWORK
6725                        && crate::text::FONT_SETTINGS.contains(id)
6726                    {
6727                        crate::settings_window::FONTS.to_string()
6728                    } else {
6729                        titles
6730                            .get(&slot.owner)
6731                            .cloned()
6732                            .unwrap_or_else(|| slot.owner.to_string())
6733                    },
6734                    descriptor: e.descriptor.clone(),
6735                })
6736            })
6737            .collect();
6738        drop(store);
6739        for &i in &hook_order {
6740            match &hooks[i].alter {
6741                Alter::Menu(menu, f) => {
6742                    if let Some(items) = derived.menus.get_mut(menu) {
6743                        f(items);
6744                    } else {
6745                        let mut items = Vec::new();
6746                        f(&mut items);
6747                        derived.menus.insert(menu.clone(), items);
6748                    }
6749                }
6750                Alter::Palette(f) => f(&mut derived.palette),
6751                Alter::Settings(f) => f(&mut derived.settings),
6752            }
6753        }
6754        derived.commands = reg
6755            .commands
6756            .specs()
6757            .map(|s| {
6758                (
6759                    s.clone(),
6760                    reg.commands
6761                        .owner(&s.id)
6762                        .cloned()
6763                        .unwrap_or(OwnerId::FRAMEWORK),
6764                )
6765            })
6766            .collect();
6767        // Icons set by another plugin replace the declared ones, the last
6768        // contribution winning.
6769        for slot in reg.command_icons.iter() {
6770            let set = &slot.item;
6771            match derived.commands.iter_mut().find(|(s, _)| s.id == set.command) {
6772                Some((spec, _)) => {
6773                    spec.icon = Some(set.icon.clone());
6774                    spec.icon_on.clone_from(&set.icon_on);
6775                    derived
6776                        .icons_set_by
6777                        .insert(set.command.clone(), slot.owner.clone());
6778                }
6779                None => d.warn(
6780                    "unknown-command",
6781                    Some(&slot.owner),
6782                    set.command.as_str(),
6783                    format!(
6784                        "`{}` sets the icon of command `{}`, which is not declared: nothing shows it",
6785                        slot.owner, set.command
6786                    ),
6787                ),
6788            }
6789        }
6790        derived.keys = reg
6791            .commands
6792            .specs()
6793            .map(|s| {
6794                let keys = reg.keymap.borrow().keys_for(&s.id);
6795                (s.id.clone(), keys.iter().map(|k| k.to_string()).collect())
6796            })
6797            .collect();
6798        derived.sources = reg
6799            .commands
6800            .specs()
6801            .map(|s| (s.id.clone(), reg.keymap.borrow().sources_for(&s.id)))
6802            .filter(|(_, b)| !b.is_empty())
6803            .collect();
6804        derived.panels = reg
6805            .panels
6806            .owned()
6807            .into_iter()
6808            .map(|(spec, owner)| (spec.clone(), owner.clone()))
6809            .collect();
6810        derived.conflicts = reg.keymap.borrow().conflicts();
6811        derived.system = reg.keymap.borrow().system_bindings();
6812        derived.dormant = reg
6813            .keymap
6814            .borrow()
6815            .dormant()
6816            .into_iter()
6817            .filter_map(|binding| {
6818                let plugin = match &binding.action {
6819                    egui_pop_model::keymap::Action::Run(c) => gone.get(c)?.clone(),
6820                    _ => return None,
6821                };
6822                let plugin_title = self
6823                    .plugins
6824                    .iter()
6825                    .find(|s| s.id == plugin)
6826                    .map_or_else(|| plugin.to_string(), |s| s.plugin.title());
6827                Some(DormantKey {
6828                    binding,
6829                    plugin,
6830                    plugin_title,
6831                })
6832            })
6833            .collect();
6834        // Each is said once, when it falls asleep.
6835        let asleep = self.handle.0.derived.borrow().dormant.clone();
6836        for k in &derived.dormant {
6837            if !asleep.contains(k) {
6838                log::info!(
6839                    target: "egui_pop",
6840                    "keys: `{}` ({:?} layer) is dormant: its command `{}` went with plugin `{}`",
6841                    k.binding.keys,
6842                    k.binding.layer,
6843                    k.binding.action,
6844                    k.plugin
6845                );
6846            }
6847        }
6848        derived.layers = [
6849            Layer::Suggestion,
6850            Layer::Default,
6851            Layer::Workspace,
6852            Layer::User,
6853        ]
6854        .into_iter()
6855        .map(|l| (l, reg.keymap.borrow().export_layer(l)))
6856        .collect();
6857        // New conflicts are signalled once.
6858        let before: Vec<String> = self
6859            .handle
6860            .0
6861            .derived
6862            .borrow()
6863            .conflicts
6864            .iter()
6865            .map(|(l, w)| format!("{} {} {}", l.keys, l.action, w.action))
6866            .collect();
6867        for (lose, win) in &derived.conflicts {
6868            let key = format!("{} {} {}", lose.keys, lose.action, win.action);
6869            if self.started && !before.contains(&key) {
6870                self.handle.publish(
6871                    "egui_pop",
6872                    None,
6873                    "keys.conflict",
6874                    json!({
6875                        "keys": lose.keys.to_string(),
6876                        "scope": lose.options.scope.to_string(),
6877                        "loses": lose.action.to_string(),
6878                        "wins": win.action.to_string(),
6879                    }),
6880                );
6881            }
6882        }
6883        derived.rebound = reg
6884            .commands
6885            .specs()
6886            .filter(|s| {
6887                reg.keymap
6888                    .borrow()
6889                    .rebound(&OwnerId::USER, Layer::User, &s.id)
6890            })
6891            .map(|s| s.id.clone())
6892            .collect();
6893        derived.rebound_workspace = reg
6894            .commands
6895            .specs()
6896            .filter(|s| {
6897                reg.keymap
6898                    .borrow()
6899                    .rebound(&WORKSPACE_KEYS, Layer::Workspace, &s.id)
6900            })
6901            .map(|s| s.id.clone())
6902            .collect();
6903        // Menu items naming unknown commands are reported.
6904        for (menu, items) in &derived.menus {
6905            for it in items {
6906                if let Item::Command { id, .. } = &it.item
6907                    && reg.commands.spec(id).is_none()
6908                {
6909                    d.warn(
6910                        "unknown-command",
6911                        None,
6912                        id.as_str(),
6913                        format!("menu `{menu}` names command `{id}`, which is not declared: the item is shown greyed"),
6914                    );
6915                }
6916            }
6917        }
6918        *self.handle.0.derived.borrow_mut() = derived;
6919        self.check_steps(&mut d);
6920        self.check_icons(&mut d);
6921        self.handle.zones_mut().resolve(&mut d);
6922        // The panels, but a zone shown as a panel only when it has blocks.
6923        let zone_of = self.handle.workbench_mut().zone_of.clone();
6924        let specs: Vec<egui_pop_model::panels::PanelSpec> = self
6925            .reg
6926            .panels
6927            .all()
6928            .into_iter()
6929            .filter(|p| {
6930                zone_of
6931                    .get(&p.id)
6932                    .is_none_or(|z| self.handle.zone_has_blocks(z))
6933            })
6934            .cloned()
6935            .collect();
6936        let before = self.handle.workbench_mut().layout.auxiliary.clone();
6937        let names = self.handle.layout_screens();
6938        let screens: Vec<&str> = names.iter().map(String::as_str).collect();
6939        let notes = self.handle.workbench_mut().refresh(specs, &screens);
6940        self.handle.note_layout("layout.repair");
6941        for note in notes {
6942            log::info!(target: "egui_pop", "layout: {note}");
6943        }
6944        self.handle.sync_panel_windows(&before);
6945        let mut all = self.handle.0.diagnostics.borrow_mut();
6946        // Resolution diagnostics are recomputed each rebuild.
6947        let kept: Vec<Diagnostic> = all
6948            .take()
6949            .into_iter()
6950            .filter(|x| !RESOLUTION_CODES.contains(&x.code))
6951            .collect();
6952        for x in kept {
6953            all.push_quiet(x);
6954        }
6955        all.extend(d.take());
6956        drop(all);
6957        self.dirty = false;
6958        self.rebuilds += 1;
6959        *self.handle.0.keymap.borrow_mut() = Rc::new(self.reg.keymap.borrow().clone());
6960        if self.started {
6961            self.emit(&Lifecycle::Rebuilt);
6962        }
6963    }
6964
6965    /// Every icon name a command or a panel declares is checked against
6966    /// the icon vocabulary (`unknown-icon`): an unknown one is drawn as a
6967    /// placeholder (a panel's title letter), never dropped silently.
6968    fn check_icons(&self, d: &mut Diagnostics) {
6969        for icon in declared_icons(&self.handle) {
6970            if !icon.resolves {
6971                d.warn(
6972                    "unknown-icon",
6973                    icon.owner.as_ref(),
6974                    icon.subject.as_str(),
6975                    format!(
6976                        "{} `{}` declares the icon `{}`: {}; a placeholder is drawn",
6977                        icon.surface,
6978                        icon.subject,
6979                        icon.name,
6980                        egui_pop_core::icon::registry::hint(&icon.name)
6981                    ),
6982                );
6983            }
6984        }
6985    }
6986
6987    /// Hooks on steps nobody declared never run; two run-hooks on one
6988    /// step: the last wins.
6989    fn check_steps(&self, d: &mut Diagnostics) {
6990        let steps = self.handle.0.steps.borrow();
6991        let hooks = self.handle.0.step_hooks.borrow();
6992        let mut replaced: BTreeMap<StepId, Vec<OwnerId>> = BTreeMap::new();
6993        for h in hooks.iter() {
6994            if !steps.contains(&h.item.step) {
6995                d.warn(
6996                    "unknown-step",
6997                    Some(&h.owner),
6998                    h.item.step.as_str(),
6999                    format!(
7000                        "a {} hook on step `{}`, which nobody declares: it never runs",
7001                        h.item.f.kind(),
7002                        h.item.step
7003                    ),
7004                );
7005            }
7006            if matches!(h.item.f, HookFn::Run(_)) {
7007                replaced
7008                    .entry(h.item.step.clone())
7009                    .or_default()
7010                    .push(h.owner.clone());
7011            }
7012        }
7013        for (step, owners) in replaced {
7014            if owners.len() > 1 {
7015                let last = owners.last().expect("two or more");
7016                d.warn(
7017                    "step-replaced-twice",
7018                    Some(last),
7019                    step.as_str(),
7020                    format!(
7021                        "step `{step}` is replaced by {}: `{last}` (the last) runs it",
7022                        owners
7023                            .iter()
7024                            .map(|o| format!("`{o}`"))
7025                            .collect::<Vec<_>>()
7026                            .join(", ")
7027                    ),
7028                );
7029            }
7030        }
7031    }
7032
7033    fn load_documents(&mut self) {
7034        if self.persist.is_none() {
7035            return;
7036        }
7037        if let Some(Outcome::Done(Err(e))) = self.load_layout() {
7038            self.handle.0.diagnostics.borrow_mut().error(
7039                "layout-unreadable",
7040                None,
7041                "layout",
7042                format!("{e}: the default layout is used"),
7043            );
7044        }
7045        let Some(p) = &self.persist else { return };
7046        match p.load::<egui_pop_model::values::SettingsDoc>("settings", &settings_schema()) {
7047            Ok(Some(read)) => {
7048                let d = lock(&self.handle.0.store).import(&read.value, &Origin::User);
7049                self.handle
7050                    .0
7051                    .diagnostics
7052                    .borrow_mut()
7053                    .extend(d.all().iter().cloned());
7054            }
7055            Ok(None) => {}
7056            Err(e) => self.handle.0.diagnostics.borrow_mut().error(
7057                "settings-unreadable",
7058                None,
7059                "settings",
7060                format!("{e}: the defaults are used"),
7061            ),
7062        }
7063        match p
7064            .load::<egui_pop_model::keymap::KeymapDoc>("keymap", &egui_pop_model::keymap_schema())
7065        {
7066            Ok(Some(read)) => {
7067                let d = self
7068                    .reg
7069                    .keymap
7070                    .borrow_mut()
7071                    .load(&OwnerId::USER, Layer::User, &read.value);
7072                self.handle
7073                    .0
7074                    .diagnostics
7075                    .borrow_mut()
7076                    .extend(d.all().iter().cloned());
7077            }
7078            Ok(None) => {}
7079            Err(e) => self.handle.0.diagnostics.borrow_mut().error(
7080                "keymap-unreadable",
7081                None,
7082                "keymap",
7083                format!("{e}: the default keys are used"),
7084            ),
7085        }
7086        // The notices kept by the last session (docs/notices.md,
7087        // "Persistence"): a missing file is a first start, an unreadable
7088        // one is left for the next save to replace.
7089        match p.load::<egui_pop_model::notice::NoticesDoc>(
7090            NOTICES_DOC,
7091            &egui_pop_model::notice::notices_schema(),
7092        ) {
7093            Ok(Some(read)) => self.handle.0.bus.notices.restore(&read.value),
7094            Ok(None) => {}
7095            Err(e) => {
7096                log::warn!(target: "egui_pop", "the notices could not be read: {e}");
7097            }
7098        }
7099    }
7100
7101    /// Saves now the settings, the user's keymap (when a directory was
7102    /// given), the layout ([`App::save_layout`]) and every document
7103    /// waiting in the debounced writer.
7104    pub fn save(&self) -> Result<(), egui_pop_core::persist::PersistError> {
7105        let Some(p) = &self.persist else {
7106            return Ok(());
7107        };
7108        let (settings, keymap) = self.document_texts()?;
7109        p.save_text("settings", &settings)?;
7110        self.handle.saved_already("settings", &settings);
7111        p.save_text("keymap", &keymap)?;
7112        self.handle.saved_already("keymap", &keymap);
7113        let layout = match self.save_layout() {
7114            Some(Outcome::Done(Err(e))) => Err(egui_pop_core::persist::PersistError::Io {
7115                path: p.dir().to_path_buf(),
7116                error: std::io::Error::other(e),
7117            }),
7118            _ => Ok(()),
7119        };
7120        self.offer_notices();
7121        let mut flushed = Ok(());
7122        for (_, r) in self.handle.flush_documents() {
7123            if let Err(e) = r {
7124                flushed = Err(e);
7125            }
7126        }
7127        layout.and(flushed)
7128    }
7129
7130    /// The settings' and the user keymap's documents as they stand.
7131    fn document_texts(&self) -> Result<(String, String), PersistError> {
7132        let doc_error = |name: &str, error| PersistError::Doc {
7133            path: std::path::PathBuf::from(name),
7134            error,
7135            backup: None,
7136        };
7137        let mut doc = lock(&self.handle.0.store).export("settings/");
7138        // A value a library or workspace layer holds is saved as the
7139        // user's own (the `app` layer's), not as shown.
7140        if let Some(admin) = self.handle.service(&crate::admin::ADMIN) {
7141            admin.app_doc(&self.handle, &mut doc.values);
7142        }
7143        let settings = settings_schema()
7144            .save(&doc)
7145            .map_err(|e| doc_error("settings", e))?;
7146        let keymap = self.reg.keymap.borrow().export(&OwnerId::USER, Layer::User);
7147        let keymap = egui_pop_model::keymap_schema()
7148            .save(&keymap)
7149            .map_err(|e| doc_error("keymap", e))?;
7150        Ok((settings, keymap))
7151    }
7152
7153    /// What was loaded is what is on disk: the debounced saving writes
7154    /// only what changes from now on.
7155    fn autosave_baseline(&mut self) {
7156        if self.persist.is_none() {
7157            return;
7158        }
7159        if let Ok((settings, keymap)) = self.document_texts() {
7160            self.handle.saved_already("settings", &settings);
7161            self.handle.saved_already("keymap", &keymap);
7162        }
7163        self.autosave
7164            .store_seq
7165            .set(Some(lock(&self.handle.0.store).seq()));
7166        self.autosave.rebuilds.set(Some(self.rebuilds));
7167        let notices = &self.handle.0.bus.notices;
7168        if let Some(text) = notices.doc_text() {
7169            self.handle.saved_already(NOTICES_DOC, &text);
7170        }
7171        self.autosave.notices_rev.set(Some(notices.rev()));
7172        self.layout_baseline();
7173    }
7174
7175    /// Offers the notices to the debounced writer when they changed.
7176    fn offer_notices(&self) {
7177        let notices = &self.handle.0.bus.notices;
7178        let rev = notices.rev();
7179        if self.autosave.notices_rev.get() != Some(rev) {
7180            self.autosave.notices_rev.set(Some(rev));
7181            if let Some(text) = notices.doc_text() {
7182                self.handle.save_later(NOTICES_DOC, text);
7183            }
7184        }
7185    }
7186
7187    /// The layout as it stands is the one on disk (just loaded or saved).
7188    fn layout_baseline(&self) {
7189        self.handle.layout_said_now();
7190    }
7191
7192    /// Saves what changed a short while after it changed: the settings,
7193    /// the user's keymap and the documents plugins offered. Saving never
7194    /// waits for the exit, so a crash loses at most the last second. The
7195    /// layout is saved when it changed, by the `pop.layout.save` listener of
7196    /// `pop.layout.changed` (`crate::bus::layout`).
7197    fn autosave(&mut self, ctx: &Context) {
7198        if self.persist.is_none() {
7199            return;
7200        }
7201        let now = egui_pop_core::motion::now(ctx);
7202        let seq = lock(&self.handle.0.store).seq();
7203        let keymap_may_change = self.autosave.rebuilds.get() != Some(self.rebuilds);
7204        if self.autosave.store_seq.get() != Some(seq) || keymap_may_change {
7205            self.autosave.store_seq.set(Some(seq));
7206            self.autosave.rebuilds.set(Some(self.rebuilds));
7207            if let Ok((settings, keymap)) = self.document_texts() {
7208                self.handle.save_later("settings", settings);
7209                self.handle.save_later("keymap", keymap);
7210            }
7211        }
7212        self.offer_notices();
7213        let due = {
7214            let mut w = self.handle.0.writer.borrow_mut();
7215            match w.as_mut() {
7216                Some(w) => {
7217                    for (name, r) in w.tick(now) {
7218                        if let Err(e) = r {
7219                            log::warn!(target: "egui_pop", "saving `{name}`: {e}");
7220                        }
7221                    }
7222                    w.next_due()
7223                }
7224                None => None,
7225            }
7226        };
7227        for d in due.into_iter() {
7228            if d > now {
7229                ctx.request_repaint_after(std::time::Duration::from_secs_f64((d - now).max(0.05)));
7230            }
7231        }
7232    }
7233
7234    /// The document the layout is kept in now, as the host says
7235    /// (`Host::layout_document`); `None`: the host keeps it.
7236    pub fn layout_document(&self) -> Option<String> {
7237        self.handle.with_host(|h| h.layout_document()).flatten()
7238    }
7239
7240    /// Loads the layout from the host's document, through the
7241    /// `layout.load` step (an application switching workspaces calls it
7242    /// once its host names the new one). `None` when the host keeps the
7243    /// layout; a document not written yet keeps the layout as it is.
7244    pub fn load_layout(&mut self) -> Option<Outcome> {
7245        let document = self.layout_document()?;
7246        let persist = self.persist.clone();
7247        let started = self.started;
7248        Some(self.handle.step(
7249            &STEP_LAYOUT_LOAD,
7250            json!({ "document": document }),
7251            move |app, args| {
7252                let document = args["document"].as_str().ok_or("`document` is missing")?;
7253                let Some(p) = persist else {
7254                    return Ok(json!({ "document": document, "loaded": false }));
7255                };
7256                let read = p
7257                    .load::<egui_pop_model::layout::SavedLayout>(
7258                        document,
7259                        &egui_pop_model::layout::schema(),
7260                    )
7261                    .map_err(|e| e.to_string())?;
7262                let Some(read) = read else {
7263                    return Ok(json!({ "document": document, "loaded": false }));
7264                };
7265                // The places kept in it replace those kept so far.
7266                app.workbench_mut().dormant = read.value.dormant;
7267                let notes = if started {
7268                    app.set_layout(read.value.layout)
7269                } else {
7270                    // Repaired against the panels when the application is
7271                    // first resolved.
7272                    app.workbench_mut().layout = read.value.layout;
7273                    Vec::new()
7274                };
7275                Ok(json!({ "document": document, "loaded": true, "repaired": notes }))
7276            },
7277        ))
7278        .inspect(|o| {
7279            if o.ok() && self.started {
7280                self.layout_baseline();
7281            }
7282        })
7283    }
7284
7285    /// Saves the layout to the host's document, through the
7286    /// `layout.save` step. `None` when the host keeps the layout.
7287    pub fn save_layout(&self) -> Option<Outcome> {
7288        save_layout(&self.handle, self.persist.clone())
7289    }
7290
7291    /// Registers egui-pop's listener of `pop.layout.changed`, local to the
7292    /// interface's thread: the layout saved to the host's document
7293    /// ([`crate::bus::LAYOUT_SAVE`]).
7294    fn listen_layout(&mut self) {
7295        use crate::bus::{LAYOUT_SAVE, LayoutChanged, OWNER, asking};
7296        let persist = self.persist.clone();
7297        let listened = self.handle.bus().listen_local::<LayoutChanged>(
7298            LAYOUT_SAVE,
7299            bus_contract::ListenOpts::new().owner(OWNER),
7300            move |_, ()| {
7301                // Without persistence, nothing is saved (as the autosave
7302                // of the settings).
7303                if persist.is_none() {
7304                    return Ok(());
7305                }
7306                let Some(app) = asking() else { return Ok(()) };
7307                match save_layout(&app, persist.clone()) {
7308                    Some(Outcome::Done(Err(e))) => Err(format!("saving the layout: {e}").into()),
7309                    _ => Ok(()),
7310                }
7311            },
7312        );
7313        if let Err(e) = listened {
7314            log::error!(target: "egui_pop", "{LAYOUT_SAVE}: {e}");
7315        }
7316    }
7317
7318    /// Declares a command now (see `AppHandle::declare`).
7319    pub fn declare(&mut self, owner: &OwnerId, spec: CommandSpec) -> Result<(), CtxError> {
7320        let id = spec.id.clone();
7321        match crate::ctx::add_command(&mut self.reg, owner, spec, None) {
7322            Ok(()) => {
7323                self.rebuild();
7324                Ok(())
7325            }
7326            Err(e) => {
7327                self.handle.publish(
7328                    "egui_pop",
7329                    None,
7330                    "command.declare_failed",
7331                    json!({ "command": id, "owner": owner, "error": e.to_string() }),
7332                );
7333                Err(e)
7334            }
7335        }
7336    }
7337
7338    /// Removes a command, its owner's keys and menu items for it; whether
7339    /// it was declared.
7340    pub fn undeclare(&mut self, id: &CommandId) -> bool {
7341        let Some(owner) = self.reg.commands.remove(id) else {
7342            return false;
7343        };
7344        self.reg.keymap.borrow_mut().remove_command(&owner, id);
7345        self.reg.menus.remove_command(&owner, id);
7346        self.rebuild();
7347        true
7348    }
7349
7350    /// Loads a keymap document into the user's or the workspace's layer
7351    /// now, through the `keys.load` step: what changed, what was skipped,
7352    /// the conflicts after it.
7353    pub fn load_keymap(
7354        &mut self,
7355        doc: &egui_pop_model::keymap::KeymapDoc,
7356        layer: Layer,
7357    ) -> Result<egui_pop_model::keymap::KeymapDiff, String> {
7358        let owner = layer_owner(layer).ok_or("only the user's and the workspace's layers load")?;
7359        let handle = self.handle.clone();
7360        let mut keymap = self.reg.keymap.borrow_mut();
7361        let mut diff = None;
7362        let out = handle.step(
7363            &STEP_LOAD_KEYMAP,
7364            json!({ "layer": layer, "bindings": doc.bindings.len() }),
7365            |_, _| {
7366                let before = keymap.export(&owner, layer);
7367                let d = keymap.load(&owner, layer, doc);
7368                let mut diff_now = egui_pop_model::keymap::KeymapDiff::between(
7369                    &before,
7370                    &keymap.export(&owner, layer),
7371                );
7372                diff_now.skipped = d.all().iter().map(|x| x.message.clone()).collect();
7373                diff_now.conflicts = keymap
7374                    .conflicts()
7375                    .iter()
7376                    .map(|(l, w)| {
7377                        format!(
7378                            "{} ({}): {} loses to {}",
7379                            l.keys, l.options.scope, l.action, w.action
7380                        )
7381                    })
7382                    .collect();
7383                let summary = json!({
7384                    "added": diff_now.added.len(),
7385                    "removed": diff_now.removed.len(),
7386                    "changed": diff_now.changed.len(),
7387                    "skipped": diff_now.skipped,
7388                    "conflicts": diff_now.conflicts,
7389                });
7390                diff = Some(diff_now);
7391                Ok(summary)
7392            },
7393        );
7394        drop(keymap);
7395        self.rebuild();
7396        match out {
7397            Outcome::Done(Ok(_)) => Ok(diff.unwrap_or_default()),
7398            Outcome::Done(Err(e)) => Err(e),
7399            Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
7400        }
7401    }
7402
7403    /// The application closes: the requests still asked for after the
7404    /// drawing heard ([`AppHandle::drain_asks`]), the `on_exit`
7405    /// functions, then the `app.exit` step, whose default writes what is still waiting
7406    /// (`App::save`). A vetoed exit writes nothing more: what changed was
7407    /// written already, a second after it changed.
7408    pub fn exit(&mut self) -> Outcome {
7409        let handle = self.handle.clone();
7410        // No request asked for after the drawing is lost on the way out:
7411        // those waiting are heard before the `on_exit` functions, and
7412        // those they ask after them.
7413        handle.drain_asks();
7414        for f in &mut self.on_exit {
7415            f(&handle);
7416        }
7417        drain_before_exit(&handle);
7418        let this: &App = self;
7419        handle.step(&STEP_EXIT, json!({}), |_, _| {
7420            this.save()
7421                .map(|()| json!({ "saved": true }))
7422                .map_err(|e| e.to_string())
7423        })
7424    }
7425
7426    /// Draws the application, through the `wrap` given to the builder
7427    /// when there is one.
7428    pub fn show_wrapped(&mut self, ui: &mut Ui) {
7429        match self.wrap.take() {
7430            Some(mut wrap) => {
7431                let handle = self.handle.clone();
7432                wrap(ui, &handle, &mut |ui| self.show(ui));
7433                self.wrap = Some(wrap);
7434            }
7435            None => self.show(ui),
7436        }
7437    }
7438
7439    /// Installs the theme where it is not yet (the kits' faces with it),
7440    /// or again when the theme service's spec changed; the settings are
7441    /// read once here, then followed by the `pop.theme.install` listener.
7442    fn install_theme(&mut self) {
7443        let ctx = self.handle.egui();
7444        let here = THEME_INSTALLED.get(&ctx).unwrap_or(false);
7445        if !here {
7446            for kit in &self.kits {
7447                kit.register(&ctx);
7448            }
7449        }
7450        let mut follow = self.theme.borrow_mut();
7451        if !follow.read {
7452            follow.read_settings(&self.handle);
7453        }
7454        follow.install(&self.handle, !here);
7455    }
7456
7457    /// Registers egui-pop's listeners of `pop.settings.changed`, local to the
7458    /// interface's thread: the theme, the pointer profile, the main
7459    /// window's frame.
7460    fn listen_settings(&mut self) {
7461        use crate::bus::{OWNER, SettingsChanged, THEME_INSTALL, asking};
7462        let bus = self.handle.bus();
7463        let follow = self.theme.clone();
7464        let listened = bus.listen_local::<SettingsChanged>(
7465            THEME_INSTALL,
7466            bus_contract::ListenOpts::new().owner(OWNER),
7467            move |change, ()| {
7468                if !change.is_any(&THEME_SETTINGS) {
7469                    return Ok(());
7470                }
7471                let Some(app) = asking() else { return Ok(()) };
7472                let Ok(mut follow) = follow.try_borrow_mut() else {
7473                    return Err("the theme is being installed".into());
7474                };
7475                follow.read_settings(&app);
7476                if THEME_INSTALLED.get(&app.egui()).unwrap_or(false) {
7477                    follow.install(&app, false);
7478                    follow.follow_preference(&app);
7479                }
7480                Ok(())
7481            },
7482        );
7483        if let Err(e) = listened {
7484            log::error!(target: "egui_pop", "{THEME_INSTALL}: {e}");
7485        }
7486        let keymap = self.reg.keymap.clone();
7487        let sync = self.pointer.clone();
7488        let changed = self.keymap_changed.clone();
7489        let listened = bus.listen_local::<SettingsChanged>(
7490            crate::bus::POINTER_PROFILE,
7491            bus_contract::ListenOpts::new().owner(OWNER),
7492            move |change, ()| {
7493                if change.id() != crate::pointer::SETTING_PROFILE.as_str() {
7494                    return Ok(());
7495                }
7496                let Some(app) = asking() else { return Ok(()) };
7497                load_pointer_profile(&app, &keymap, &sync, &changed);
7498                Ok(())
7499            },
7500        );
7501        if let Err(e) = listened {
7502            log::error!(target: "egui_pop", "{}: {e}", crate::bus::POINTER_PROFILE);
7503        }
7504        crate::frame::listen(&self.handle);
7505    }
7506
7507    /// Draws in this context from now on (an application built on one
7508    /// context and shown in another, as test harnesses do).
7509    fn attach(&mut self, ctx: &Context) {
7510        *self.handle.0.ctx.borrow_mut() = ctx.clone();
7511        install_pass_marker(ctx);
7512        let commands = self.handle.0.panel_commands.borrow().clone();
7513        if !strings::panel_commands(ctx).is_some_and(|c| Arc::ptr_eq(&c, &commands)) {
7514            strings::set_panel_commands(ctx, commands);
7515        }
7516        strings::set_application(ctx, &self.handle.0.name.borrow());
7517        focus::install(ctx);
7518        // The foreground's ranks, before this pass shows any layer.
7519        egui_pop_core::layers::install(ctx);
7520        // egui-pop's interface zoom replaces egui's keys (`zoom`).
7521        egui_pop_core::scale::disable_keyboard_zoom(ctx);
7522        let zoom = crate::zoom::current(&self.handle);
7523        if (ctx.zoom_factor() - zoom).abs() > 1e-3 {
7524            ctx.set_zoom_factor(zoom);
7525        }
7526        if self.waking.as_ref() != Some(ctx) {
7527            self.waking = Some(ctx.clone());
7528            self.handle.theme().follow(ctx);
7529            self.handle.0.bus.wake_with(ctx);
7530            crate::bus::overlays::watch(ctx, &self.handle);
7531            let c = ctx.clone();
7532            if let Some(h) = self.handle.0.host.borrow_mut().as_mut() {
7533                h.set_waker(Waker::new(move || c.request_repaint()));
7534            }
7535        }
7536        if let Some(modes) = self.handle.service(&FOCUS_MODE) {
7537            let preference = lock(&self.handle.store())
7538                .get(&format!("settings/{SETTING_FOCUS}"))
7539                .and_then(|e| e.value.as_choice().and_then(Preference::parse))
7540                .unwrap_or_default();
7541            modes.set_preference(preference);
7542            focus_mode::set(ctx, &modes);
7543        }
7544    }
7545
7546    /// Runs a command now, in the current context: its result, or a
7547    /// result to come (`Reply::Later`, kept until it arrives).
7548    ///
7549    /// <div class="warning">Experimental: may change in any release
7550    /// (docs/stability.md).</div>
7551    pub fn run(&mut self, command: &CommandId, args: Json, origin: Origin) -> Reply {
7552        let cx = self.handle.when_context();
7553        self.run_in(command, args, origin, &cx)
7554    }
7555
7556    /// Runs a command now, in a given context, through the host.
7557    ///
7558    /// <div class="warning">Experimental: may change in any release
7559    /// (docs/stability.md).</div>
7560    pub fn run_in(
7561        &mut self,
7562        command: &CommandId,
7563        args: Json,
7564        origin: Origin,
7565        cx: &WhenContext,
7566    ) -> Reply {
7567        // What it opens (a dialog, a toast, the palette) belongs to the
7568        // window it was asked in.
7569        let window = cx.get(crate::windows::CONTEXT_APP_WINDOW);
7570        let group = (!window.is_empty())
7571            .then(|| {
7572                self.handle
7573                    .window_viewport(&crate::windows::WindowId::new(window))
7574            })
7575            .flatten();
7576        let _group = crate::windows::enter_group(group);
7577        // A command kept from agents does not run for one, whoever asks.
7578        if matches!(origin, Origin::Agent(_))
7579            && self.reg.commands.spec(command).is_some_and(|s| !s.agent)
7580        {
7581            let msg = format!("`{command}` is not offered to agents");
7582            self.handle.publish(
7583                &source_of(&origin),
7584                None,
7585                "command.refused",
7586                json!({ "command": command, "origin": source_of(&origin), "reason": msg }),
7587            );
7588            self.record(command, &args, &origin, Err(msg.clone()));
7589            return Reply::Done(Err(msg));
7590        }
7591        let handler = match self.reg.commands.prepare(command, cx) {
7592            Ok(h) => h.clone(),
7593            Err(e) => {
7594                let msg = e.to_string();
7595                if matches!(e, egui_pop_model::commands::RunRefused::Unknown { .. }) {
7596                    // A run of a command no longer there (queued, a menu,
7597                    // a toast's or a job's action, an accepted dialog):
7598                    // refused on the journal, naming the plugin that
7599                    // took it away (ADR 0028).
7600                    let reason = match self.handle.command_gone_with(command) {
7601                        Some(p) => format!("its plugin `{p}` is disconnected"),
7602                        None => msg.clone(),
7603                    };
7604                    self.handle.publish(
7605                        &source_of(&origin),
7606                        None,
7607                        "command.refused",
7608                        json!({ "command": command, "origin": source_of(&origin), "reason": reason }),
7609                    );
7610                    self.handle
7611                        .settle_reported(command, &args, &Err(reason.clone()));
7612                    return Reply::Done(Err(reason));
7613                }
7614                self.record(command, &args, &origin, Err(msg.clone()));
7615                return Reply::Done(Err(msg));
7616            }
7617        };
7618        // Arguments that do not match the command's JSON Schema are
7619        // refused before anything else hears of the run, whoever asks it
7620        // (`pop.command.args`). A command whose arguments are only
7621        // described (an example, a text) is not checked.
7622        if let Some(reason) = self
7623            .reg
7624            .commands
7625            .spec(command)
7626            .and_then(|s| crate::bus::args_refusal(s, &args))
7627        {
7628            let msg = format!("refused by `{}`: {reason}", crate::bus::ARGS_VALIDATOR);
7629            self.handle.publish(
7630                &source_of(&origin),
7631                None,
7632                "command.refused",
7633                json!({
7634                    "command": command,
7635                    "origin": source_of(&origin),
7636                    "reason": msg,
7637                    "by": crate::bus::ARGS_VALIDATOR,
7638                    "failed": false,
7639                }),
7640            );
7641            self.record(command, &args, &origin, Err(msg.clone()));
7642            return Reply::Done(Err(msg));
7643        }
7644        // Its listeners on the bus (`pop.command.run`), in their order, before
7645        // the handler: one may refuse it, and a failing one refuses it
7646        // (fail-closed). Nobody listening, it goes on as before.
7647        let mut ask = crate::bus::CommandAsk::new(command.clone(), args.clone(), origin.clone());
7648        if !window.is_empty() {
7649            ask = ask.window(window);
7650        }
7651        if let Some(refused) = crate::bus::ask_command_run(&self.handle, ask) {
7652            let msg = crate::bus::command_refusal(&refused);
7653            self.handle.publish(
7654                &source_of(&origin),
7655                None,
7656                "command.refused",
7657                json!({
7658                    "command": command,
7659                    "origin": source_of(&origin),
7660                    "reason": msg,
7661                    "by": refused.listener,
7662                    "failed": refused.failed,
7663                }),
7664            );
7665            self.record(command, &args, &origin, Err(msg.clone()));
7666            return Reply::Done(Err(msg));
7667        }
7668        let source = source_of(&origin);
7669        let _running = RunningCommand::new(&self.handle, command, self.reg.commands.owner(command));
7670        // A private command's events keep their data, marked: readers
7671        // that do not read private data get it redacted
7672        // (`host::redact_private`).
7673        let mut dispatched = json!({ "command": command, "args": args });
7674        if self.is_private(command) {
7675            dispatched["private"] = Json::Bool(true);
7676        }
7677        let seq = self
7678            .handle
7679            .publish_now(&source, None, "command.dispatched", dispatched);
7680        if crate::jobs::is_job_command(command) {
7681            self.handle
7682                .tag_job_event(seq, egui_pop_model::jobs::JobEventKind::CommandDispatched);
7683        }
7684        let owner = self.reg.commands.owner(command).cloned();
7685        // A command whose run calls the host itself (undo, `history.*`,
7686        // the context stack's and the clipboard's commands) still goes
7687        // through the host's dispatch, so a guard there sees it; its
7688        // handler cannot run inside the dispatch, which holds the host.
7689        // The dispatch gets a stand-in that approves it (`run_local`
7690        // answers `null` at once, `Dispatch::deferred` says so), and the
7691        // handler runs once the host is back.
7692        let deferred = IN_INTERFACE.contains(command);
7693        let approved = Rc::new(std::cell::Cell::new(false));
7694        let stand_in: Option<CommandFn> = (deferred && handler.is_some()).then(|| {
7695            let approved = approved.clone();
7696            Rc::new(move |_: &Call<'_>| {
7697                approved.set(true);
7698                Ok(Json::Null)
7699            }) as CommandFn
7700        });
7701        let local = if deferred {
7702            stand_in.as_ref()
7703        } else {
7704            handler.as_ref()
7705        };
7706        let mut host = self
7707            .handle
7708            .0
7709            .host
7710            .borrow_mut()
7711            .take()
7712            .expect("a command dispatched from inside a dispatch is queued (AppHandle::run)");
7713        let acting = ActingFor::new(&self.handle, &origin);
7714        // A group the handler opens (`Call::group`) reaches the host's
7715        // history through its groups while the host is out of its cell.
7716        let groups = self.handle.0.dispatch_groups.replace(host.groups());
7717        let reply = host.dispatch(
7718            &Dispatch::new(command, &args, &origin, cx, seq, &self.handle, local)
7719                .owned_by(owner.as_ref())
7720                .deferring(deferred),
7721        );
7722        *self.handle.0.dispatch_groups.borrow_mut() = groups;
7723        drop(acting);
7724        *self.handle.0.host.borrow_mut() = Some(host);
7725        if deferred && approved.get() {
7726            // The host let it run in the interface: its handler now.
7727            let result = match &handler {
7728                Some(h) => {
7729                    let _scope = owner.as_ref().map(egui_pop_model::values::enter_scope);
7730                    let _acting = ActingFor::new(&self.handle, &origin);
7731                    h(&Call {
7732                        args: &args,
7733                        origin: &origin,
7734                        app: &self.handle,
7735                    })
7736                }
7737                None => Err(format!("no handler for `{command}`")),
7738            };
7739            self.finish(command, &args, &origin, seq, result.clone());
7740            return Reply::Done(result);
7741        }
7742        match reply {
7743            Reply::Done(result) => {
7744                self.finish(command, &args, &origin, seq, result.clone());
7745                Reply::Done(result)
7746            }
7747            Reply::Later(pending) => {
7748                let waiting = {
7749                    let mut running = self.handle.0.running.borrow_mut();
7750                    let n = running.entry(command.clone()).or_default();
7751                    *n += 1;
7752                    *n
7753                };
7754                if waiting == 1 {
7755                    let now = egui_pop_core::motion::now(&self.handle.egui());
7756                    self.handle
7757                        .0
7758                        .running_since
7759                        .borrow_mut()
7760                        .insert(command.clone(), now);
7761                }
7762                self.in_flight.push(InFlight {
7763                    command: command.clone(),
7764                    args,
7765                    origin,
7766                    seq,
7767                    pending: pending.clone(),
7768                });
7769                Reply::Later(pending)
7770            }
7771        }
7772    }
7773
7774    /// Whether `command` is declared private (`CommandSpec::private`).
7775    fn is_private(&self, command: &CommandId) -> bool {
7776        self.reg.commands.spec(command).is_some_and(|s| s.private)
7777    }
7778
7779    /// A result arrived: the history and the journal keep it.
7780    fn finish(
7781        &mut self,
7782        command: &CommandId,
7783        args: &Json,
7784        origin: &Origin,
7785        seq: Seq,
7786        result: Result<Json, String>,
7787    ) {
7788        use egui_pop_model::jobs::JobEventKind;
7789        let (kind, mut data) = match &result {
7790            Ok(v) => (
7791                JobEventKind::CommandDone,
7792                json!({ "command": command, "result": v }),
7793            ),
7794            Err(e) => (
7795                JobEventKind::CommandFailed,
7796                json!({ "command": command, "error": e }),
7797            ),
7798        };
7799        if self.is_private(command) {
7800            data["private"] = Json::Bool(true);
7801        }
7802        let done = self
7803            .handle
7804            .publish_now(&source_of(origin), Some(seq), kind.name(), data);
7805        if crate::jobs::is_job_command(command) {
7806            self.handle.tag_job_event(done, kind);
7807        }
7808        self.record(command, args, origin, result);
7809    }
7810
7811    /// Takes the results that arrived (each frame does it before
7812    /// drawing); returns how many.
7813    pub fn settle(&mut self) -> usize {
7814        profiling::scope!("pop.app.settle");
7815        let mut arrived = Vec::new();
7816        self.in_flight.retain(|f| match f.pending.take() {
7817            Some(r) => {
7818                arrived.push((
7819                    f.command.clone(),
7820                    f.args.clone(),
7821                    f.origin.clone(),
7822                    f.seq,
7823                    r,
7824                ));
7825                false
7826            }
7827            None => true,
7828        });
7829        let n = arrived.len();
7830        for (command, args, origin, seq, result) in arrived {
7831            if let Some(c) = self.handle.0.running.borrow_mut().get_mut(&command) {
7832                *c = c.saturating_sub(1);
7833                if *c == 0 {
7834                    self.handle.0.running_since.borrow_mut().remove(&command);
7835                }
7836            }
7837            if let Err(e) = &result {
7838                log::warn!(target: "egui_pop", "command `{command}`: {e}");
7839            }
7840            self.finish(&command, &args, &origin, seq, result);
7841        }
7842        n
7843    }
7844
7845    fn record(
7846        &mut self,
7847        command: &CommandId,
7848        args: &Json,
7849        origin: &Origin,
7850        result: Result<Json, String>,
7851    ) {
7852        self.handle.settle_reported(command, args, &result);
7853        let run = Run {
7854            id: command.clone(),
7855            args: args.clone(),
7856            origin: origin.clone(),
7857            result,
7858        };
7859        self.reg.commands.record(run.clone());
7860        let mut h = self.handle.0.history.borrow_mut();
7861        h.push(run);
7862        let len = h.len();
7863        if len > 64 {
7864            h.drain(..len - 64);
7865        }
7866    }
7867
7868    /// Changes a command's keys through the `keys.rebind` step: `keys`
7869    /// a text (one shortcut), `null` (none) or an array (several).
7870    fn rebind_step(&mut self, command: &CommandId, args: Json) {
7871        let handle = self.handle.clone();
7872        let mut keymap = self.reg.keymap.borrow_mut();
7873        let mut changed = false;
7874        let out = handle.step(&STEP_REBIND, args, |_, args| {
7875            let command = args
7876                .get("command")
7877                .and_then(Json::as_str)
7878                .and_then(|c| CommandId::new(c).ok())
7879                .ok_or("`command` is missing")?;
7880            let layer: Layer = args
7881                .get("layer")
7882                .cloned()
7883                .map_or(Ok(Layer::User), serde_json::from_value)
7884                .map_err(|e| format!("`layer`: {e}"))?;
7885            let owner = layer_owner(layer)
7886                .ok_or("keys change in the user's or the workspace's layer only")?;
7887            match args.get("keys") {
7888                Some(Json::Array(list)) => {
7889                    let keys: Vec<&str> = list.iter().filter_map(Json::as_str).collect();
7890                    keymap.rebind_all(&owner, layer, &command, &keys)?;
7891                }
7892                other => {
7893                    let keys = other.and_then(Json::as_str);
7894                    keymap.rebind(&owner, layer, &command, keys)?;
7895                }
7896            }
7897            changed = true;
7898            Ok(json!({ "command": command, "keys": args.get("keys"), "layer": layer }))
7899        });
7900        if changed {
7901            self.dirty = true;
7902        }
7903        if let Outcome::Done(Err(e)) = out {
7904            log::warn!(target: "egui_pop", "keys for `{command}`: {e}");
7905        }
7906    }
7907
7908    /// Does what blocks and handlers asked for.
7909    pub fn process_requests(&mut self) {
7910        profiling::scope!("pop.app.requests");
7911        loop {
7912            let requests: Vec<Request> = std::mem::take(&mut *self.handle.0.requests.borrow_mut());
7913            if requests.is_empty() {
7914                break;
7915            }
7916            for r in requests {
7917                match r {
7918                    Request::Run {
7919                        command,
7920                        args,
7921                        origin,
7922                    } => {
7923                        if let Reply::Done(Err(e)) = self.run(&command, args, origin) {
7924                            log::warn!(target: "egui_pop", "command `{command}`: {e}");
7925                        }
7926                    }
7927                    Request::RunIn {
7928                        command,
7929                        args,
7930                        origin,
7931                        context,
7932                    } => {
7933                        if let Reply::Done(Err(e)) = self.run_in(&command, args, origin, &context) {
7934                            log::warn!(target: "egui_pop", "command `{command}`: {e}");
7935                        }
7936                    }
7937                    Request::Enable(p, true) => {
7938                        if let Err(e) = self.connect(&p) {
7939                            log::warn!(target: "egui_pop", "plugin `{p}`: {e}");
7940                        }
7941                    }
7942                    Request::Enable(p, false) => {
7943                        self.disconnect_because(&p, "disabled");
7944                    }
7945                    Request::Rebind {
7946                        command,
7947                        keys,
7948                        layer,
7949                    } => {
7950                        let args = json!({ "command": command, "keys": keys, "layer": layer });
7951                        self.rebind_step(&command, args);
7952                    }
7953                    Request::RebindAll {
7954                        command,
7955                        keys,
7956                        layer,
7957                    } => {
7958                        let args = json!({ "command": command, "keys": keys, "layer": layer });
7959                        self.rebind_step(&command, args);
7960                    }
7961                    Request::Declare { owner, spec } => {
7962                        let id = spec.id.clone();
7963                        if let Err(e) = self.declare(&owner, spec) {
7964                            log::warn!(target: "egui_pop", "declaring `{id}`: {e}");
7965                        }
7966                    }
7967                    Request::Undeclare(id) => {
7968                        self.undeclare(&id);
7969                    }
7970                    Request::LoadKeymap { doc, layer } => {
7971                        if let Err(e) = self.load_keymap(&doc, layer) {
7972                            log::warn!(target: "egui_pop", "loading a keymap: {e}");
7973                        }
7974                    }
7975                    Request::ResetKeys { command, layer } => {
7976                        if let Some(owner) = layer_owner(layer) {
7977                            self.reg.keymap.borrow_mut().reset(&owner, layer, &command);
7978                            self.dirty = true;
7979                        }
7980                    }
7981                    Request::Workbench(change) => {
7982                        let what = format!("{change:?}");
7983                        if let Some(Outcome::Done(Err(e))) = self.handle.change_workbench(change) {
7984                            self.handle.workbench_refused(&what, &e);
7985                        }
7986                    }
7987                }
7988            }
7989        }
7990        if self.keymap_changed.take() {
7991            self.dirty = true;
7992        }
7993        if self.dirty {
7994            self.rebuild();
7995        }
7996    }
7997
7998    /// Between frames: the theme asked for, requests, declarations, and
7999    /// the `On::Pass` handlers.
8000    ///
8001    /// The `On::Pass` handlers run once per pass: a second call inside
8002    /// the same egui pass (the same viewport and
8003    /// `Context::cumulative_pass_nr`) settles again (the theme asked
8004    /// for, requests, declarations) but does not run them. eframe calls
8005    /// it from its `logic` hook and [`App::show`] calls it again, so that
8006    /// an integration without that hook (plain egui, kittest's
8007    /// `build_ui`) still runs it; a host may also call it a second time
8008    /// after changing something (a theme, a request) so the change is in
8009    /// place before the pass draws. Calls between passes always run the
8010    /// handlers: eframe ticks the logic alone while the window is
8011    /// hidden, and those ticks share one pass number.
8012    pub fn logic(&mut self, ctx: &Context) {
8013        let mut again = false;
8014        if let Some(pass) = pass_in_progress(ctx) {
8015            again = self.logic_pass == Some(pass);
8016            self.logic_pass = Some(pass);
8017        }
8018        profiling::scope!("pop.app.logic");
8019        self.attach(ctx);
8020        // The settings changed since the last pass, said on the bus: the
8021        // theme, the pointer profile and the frame follow there.
8022        self.handle.deliver_settings();
8023        self.install_theme();
8024        self.settle();
8025        self.handle.feed_indicators();
8026        // The journal's new events to their listeners on the bus, before
8027        // the pass's handlers read what follows them.
8028        self.handle.deliver_events();
8029        if !again {
8030            // Local listeners queued by emits on other threads, in their
8031            // order, before the pass's handlers.
8032            self.handle.run_pending();
8033            // Passes over a point's budget since the last pass, said.
8034            self.handle.say_over_budget();
8035            self.emit(&Lifecycle::Pass);
8036        }
8037        if self.pointer.borrow().loaded.is_none() {
8038            // Read once; then followed by `pop.pointer.profile`.
8039            load_pointer_profile(
8040                &self.handle,
8041                &self.reg.keymap,
8042                &self.pointer,
8043                &self.keymap_changed,
8044            );
8045        }
8046        self.process_requests();
8047        // What the requests changed, followed before the pass draws.
8048        self.handle.deliver_settings();
8049        if self.keymap_changed.get() {
8050            self.process_requests();
8051        }
8052        self.publish_pointer(ctx);
8053        // The layout's changes noted since, said once (`pop.layout.changed`).
8054        self.handle.settle_layout(ctx);
8055        self.autosave(ctx);
8056    }
8057
8058    /// Publishes the pointer gestures in force to the context, when the
8059    /// keymap or the settings changed, or the context lacks them.
8060    fn publish_pointer(&mut self, ctx: &Context) {
8061        let print = crate::pointer::settings_print(&self.handle);
8062        let fresh = match &self.pointer.borrow().published {
8063            Some((map, rebuilds, p)) => {
8064                *rebuilds == self.rebuilds
8065                    && *p == print
8066                    && egui_pop_core::pointer::published(ctx).is_some_and(|m| Arc::ptr_eq(&m, map))
8067            }
8068            None => false,
8069        };
8070        if fresh {
8071            return;
8072        }
8073        let map = Arc::new(crate::pointer::map(&self.handle, &self.reg.keymap.borrow()));
8074        egui_pop_core::pointer::set_shared_map(ctx, map.clone());
8075        self.pointer.borrow_mut().published = Some((map, self.rebuilds, print));
8076    }
8077
8078    /// Draws the whole application in a `Ui` covering the window, after
8079    /// dispatching this frame's keys.
8080    ///
8081    /// Runs [`App::logic`] first, which does nothing when the host
8082    /// already ran it in this pass (eframe's `logic` hook).
8083    pub fn show(&mut self, ui: &mut Ui) {
8084        profiling::scope!("pop.app.show");
8085        let ctx = ui.ctx().clone();
8086        // What opens while the main window draws belongs to its group.
8087        let _group = crate::windows::enter_group(Some(egui::ViewportId::ROOT));
8088        // The style `ui` was made with: a theme installed or a light or
8089        // dark switch below comes after it.
8090        let before = ctx.global_style();
8091        self.logic(&ctx);
8092        if let Some((from, to)) = egui_pop_core::scale::changed(&ctx) {
8093            self.handle.publish(
8094                "egui_pop",
8095                None,
8096                "scale.changed",
8097                json!({ "viewport": "root", "from": from, "to": to }),
8098            );
8099            // Strokes are snapped for the scale: install the theme again.
8100            self.theme.borrow_mut().installed = None;
8101            self.install_theme();
8102        }
8103        // Drawn with the theme of this pass, as `Kit::of` and
8104        // `Tokens::of` are: else this pass mixes the variants, and what a
8105        // cache keeps from it stays drawn in the other one. A style the
8106        // host set on `ui` itself is kept.
8107        let now = ctx.global_style();
8108        if !Arc::ptr_eq(&before, &now) && Arc::ptr_eq(ui.style(), &before) {
8109            ui.set_style(now);
8110        }
8111        self.handle.note_window(&ctx);
8112        // The screens told since the last pass: `pop.screen.added`,
8113        // `pop.screen.removed`, the windows on a screen gone moved or docked.
8114        self.handle.follow_screens(&ctx);
8115        // The files the system says over the main window, read once.
8116        crate::bus::files::begin_pass(&ctx, crate::windows::WindowId::MAIN);
8117        // A drag begun here followed; let go, delivered (`bus::drag`).
8118        crate::bus::drag::begin_pass(&ctx, crate::windows::WindowId::MAIN);
8119        crate::workbench::forget_closed_windows(&self.handle, &ctx);
8120        // The system asks the main window's close: a `pop.window.close` of
8121        // the main window (another window moving into it when one is
8122        // open, ADR 0025), unless one already ran.
8123        if ctx.viewport_id() == egui::ViewportId::ROOT {
8124            self.handle.main_close_seen(&ctx);
8125        }
8126        // A dialog open in a detached panel's window blocks this one; one
8127        // in an application window does not.
8128        let app = self.handle.clone();
8129        app.block_window(&ctx, &|v| !crate::windows::is_app_window(&app, v));
8130        overlay::begin_pass(&ctx);
8131        self.dispatch_keys(&ctx);
8132        self.process_requests();
8133        // The main window asked to the front while a window's content
8134        // was drawn in it: that content goes back to a window of its own.
8135        self.handle.ask_home();
8136        self.handle.declare_windows(&ctx);
8137        self.handle.mark_pass_start(ui);
8138        if !self.handle.root_pass(ui) {
8139            self.outlined(ui);
8140        }
8141        let name = self.handle.name();
8142        let name = if name.is_empty() {
8143            ctx.input(|i| i.viewport().title.clone())
8144                .unwrap_or_default()
8145        } else {
8146            name
8147        };
8148        let handle = self.handle.clone();
8149        // The detached panels belong to the shell: not drawn while a
8150        // window's content moved into the main window.
8151        let mut drawn = Vec::new();
8152        if !handle.root_has_content() {
8153            crate::workbench::windows(&handle, &ctx, &name, &mut |c| {
8154                drawn.push(c.viewport_id());
8155                self.dispatch_keys(c);
8156            });
8157        }
8158        // A window no longer drawn takes its dispatcher with it.
8159        self.panel_keys.retain(|v, _| drawn.contains(v));
8160        handle.show_zone(ui, &zones::OVERLAYS);
8161        handle.show_zone(ui, &zones::WINDOW_OVERLAYS);
8162        // Files dropped on the main window: its `pop.files.drop`.
8163        crate::bus::files::end_pass(&handle, ui);
8164        crate::bus::drag::end_pass(&handle, &ctx);
8165        // A focus screen without its page, a window that painted nothing:
8166        // said and repaired, never left as it is.
8167        handle.end_shell_pass(ui);
8168        crate::menus::draw_popup(&ctx, &self.handle);
8169        a11y::live_regions(ui);
8170        // Interactive indicators bound to a command, activated this frame.
8171        for command in egui_pop_core::indicator::take_commands(&ctx) {
8172            self.handle.run(command, Json::Null);
8173        }
8174        // The requests asked while the panels and windows drew, heard now
8175        // that nothing is borrowed for the drawing (`AppHandle::ask`):
8176        // in this pass, after it drew. One asked by them waits for the
8177        // next pass's drain.
8178        self.handle.drain_asks();
8179        self.process_requests();
8180        // What this pass changed (a Settings row, a bound widget), said
8181        // and followed in it.
8182        self.handle.deliver_settings();
8183        if self.keymap_changed.get() {
8184            self.process_requests();
8185        }
8186    }
8187
8188    /// Dispatches the keys of the window being drawn (`ctx`'s current
8189    /// viewport: the main window, or a detached panel's) in that window's
8190    /// context: its focus chain, its overlays, `window`.
8191    fn dispatch_keys(&mut self, ctx: &Context) {
8192        self.handle.follow_focus(ctx);
8193        let cx = self.handle.when_context();
8194        let v = ctx.viewport_id();
8195        let keys = if v == egui::ViewportId::ROOT {
8196            &mut self.keys
8197        } else {
8198            self.panel_keys.entry(v).or_default()
8199        };
8200        let dispatcher = keys.dispatcher(&self.handle);
8201        let dispatched = if self.handle.0.capturing.get() {
8202            Vec::new()
8203        } else {
8204            dispatcher.process(ctx, &self.reg.keymap.borrow(), &cx)
8205        };
8206        // What the debug bridge shows: the main window's, or the
8207        // detached window worked in.
8208        if v == egui::ViewportId::ROOT || self.handle.active_window() == v {
8209            *self.handle.0.traces.borrow_mut() = dispatcher.traces().cloned().collect();
8210            *self.handle.0.pending_keys.borrow_mut() = dispatcher.pending().map(|k| k.to_string());
8211        }
8212        for d in dispatched {
8213            // A key bound to a command no longer there is worth a
8214            // warning; one whose command is not enabled here is not.
8215            let unknown = self.reg.commands.spec(&d.command).is_none();
8216            if let Reply::Done(Err(e)) = self.run(&d.command, Json::Null, Origin::User) {
8217                if unknown {
8218                    log::warn!(target: "egui_pop", "{}: {e}", d.keys);
8219                } else {
8220                    log::info!(target: "egui_pop", "{}: {e}", d.keys);
8221                }
8222            }
8223        }
8224    }
8225
8226    /// The shell, inside the kit's outline when the application draws
8227    /// the window (`window.rest.border-width`).
8228    fn outlined(&mut self, ui: &mut Ui) {
8229        if !crate::frame::own_frame(&self.handle) {
8230            return self.shell(ui);
8231        }
8232        let edge = egui_pop_core::frame::window_edge(ui.ctx(), &crate::window::screens());
8233        egui_pop_core::frame::paint_window_edge(ui.ctx(), edge);
8234        let outline = edge.stroke;
8235        if outline.width <= 0.0 {
8236            return self.shell(ui);
8237        }
8238        let rect = ui.max_rect();
8239        ui.scope_builder(
8240            egui::UiBuilder::new().max_rect(rect.shrink(outline.width)),
8241            |ui| self.shell(ui),
8242        );
8243    }
8244
8245    fn shell(&mut self, ui: &mut Ui) {
8246        let h = self.handle.clone();
8247        h.follow_zen();
8248        crate::zen::show(&h, ui.ctx());
8249        if h.main_zen() {
8250            // Zen mode: the centre alone, and no caption published.
8251            h.mark_shell_start(ui);
8252            egui_pop_core::frame::hide_title_bar(ui.ctx());
8253            crate::workbench::show(&h, ui);
8254            return;
8255        }
8256        // The bars hold no dock: no dragged tab is dropped there.
8257        let mut no_drop = Vec::new();
8258        if h.zone_has_blocks(&zones::TITLE) {
8259            // No least height: a title zone whose blocks draw nothing (the
8260            // system draws the frame) takes no room.
8261            let shown = egui::Panel::top(Id::unique("egui_pop.title"))
8262                .frame(egui::Frame::NONE)
8263                // The kit's `title-bar` draws the line under the bar.
8264                .show_separator_line(false)
8265                .min_size(0.0)
8266                .show(ui, |ui| {
8267                    focus::scope(ui, "titleBar", &[], |ui| h.show_zone(ui, &zones::TITLE));
8268                });
8269            no_drop.push(shown.response.rect);
8270        }
8271        // What is painted from here on is the shell's content: the paint
8272        // guard looks for it at the end of the pass.
8273        h.mark_shell_start(ui);
8274        // A wizard as a focus screen covers the page: the title bar alone
8275        // under it (to move or quit), no menus, status bar or centre. Not
8276        // while its page is not drawn (the Settings closed under it): the
8277        // shell is drawn then, never the title bar alone.
8278        if h.hidden_by_focus_screen() {
8279            h.workbench_mut().no_drop = no_drop;
8280            return;
8281        }
8282        if h.menu_bar() {
8283            let shown = egui::Panel::top(Id::unique("egui_pop.top")).show(ui, |ui| {
8284                focus::scope(ui, "topBar", &[], |ui| {
8285                    egui::MenuBar::new().ui(ui, |ui| {
8286                        // The top bar's blocks keep the width they took
8287                        // last pass; the menus overflow before them.
8288                        let reserve = TOP_BAR_RESERVE.get(ui.ctx()).unwrap_or(0.0);
8289                        crate::menus::bar_within(ui, &h, &MENU_MAIN, reserve);
8290                        let mut used = 0.0;
8291                        if h.zone_has_blocks(&zones::TOP_BAR) {
8292                            // The bar takes its whole width: the zone is
8293                            // measured in its own scope.
8294                            let start = ui.cursor().min.x;
8295                            ui.separator();
8296                            let zone = ui.scope(|ui| h.show_zone(ui, &zones::TOP_BAR));
8297                            used = zone.response.rect.max.x - start + ui.spacing().item_spacing.x;
8298                        }
8299                        let commands = crate::menus::has_end_items(&h, &MENU_BAR_END);
8300                        let blocks = h.zone_has_blocks(&zones::TOP_BAR_END);
8301                        if commands || blocks {
8302                            // At the bar's end, whatever the menus and
8303                            // the zone left: the commands last, the end
8304                            // zone's blocks before them.
8305                            let end = ui.with_layout(
8306                                egui::Layout::right_to_left(egui::Align::Center),
8307                                |ui| {
8308                                    let mut width = 0.0;
8309                                    if commands {
8310                                        width += crate::menus::bar_end(ui, &h, &MENU_BAR_END);
8311                                    }
8312                                    if blocks {
8313                                        if commands {
8314                                            width += ui.spacing().item_spacing.x;
8315                                        }
8316                                        width += top_bar_end(ui, &h);
8317                                    }
8318                                    width
8319                                },
8320                            );
8321                            used += end.inner + 2.0 * ui.spacing().item_spacing.x;
8322                        }
8323                        if used != reserve {
8324                            TOP_BAR_RESERVE.set(ui.ctx(), used);
8325                            // Laid out again at once when a menu moves.
8326                            if crate::menus::refit_needed(&h, &MENU_MAIN, used) {
8327                                ui.ctx().request_repaint();
8328                            }
8329                        }
8330                    });
8331                });
8332            });
8333            no_drop.push(shown.response.rect);
8334        } else if h.zone_has_blocks(&zones::TOP_BAR) || h.zone_has_blocks(&zones::TOP_BAR_END) {
8335            let shown = egui::Panel::top(Id::unique("egui_pop.top")).show(ui, |ui| {
8336                focus::scope(ui, "topBar", &[], |ui| {
8337                    ui.horizontal(|ui| {
8338                        h.show_zone(ui, &zones::TOP_BAR);
8339                        if h.zone_has_blocks(&zones::TOP_BAR_END) {
8340                            ui.with_layout(
8341                                egui::Layout::right_to_left(egui::Align::Center),
8342                                |ui| top_bar_end(ui, &h),
8343                            );
8344                        }
8345                    });
8346                });
8347            });
8348            no_drop.push(shown.response.rect);
8349        }
8350        if h.zone_has_blocks(&zones::STATUS_BAR) {
8351            let shown = egui::Panel::bottom(Id::unique("egui_pop.status")).show(ui, |ui| {
8352                let region = focus::Region::new("statusBar", crate::workbench::RANK_STATUS_BAR);
8353                focus::region(ui, &region, |ui| {
8354                    // One Tab stop, Left and Right between its items.
8355                    let axis = egui_pop_core::tab::Axis::Horizontal;
8356                    egui_pop_core::tab::roving(ui, "statusBar", axis, |ui| {
8357                        ui.horizontal(|ui| h.show_zone(ui, &zones::STATUS_BAR));
8358                    });
8359                });
8360            });
8361            no_drop.push(shown.response.rect);
8362        }
8363        h.workbench_mut().no_drop = no_drop;
8364        crate::workbench::show(&h, ui);
8365    }
8366}
8367
8368/// Diagnostic codes recomputed by each rebuild.
8369/// An icon name a declaration gives, as the `icons` collector and the
8370/// `unknown-icon` diagnostic read it.
8371#[derive(Clone, Debug, PartialEq, serde::Serialize)]
8372pub struct DeclaredIcon {
8373    /// What declares it: `command`, `command (on)`, `panel`, `frame`,
8374    /// `status item`.
8375    pub surface: &'static str,
8376    /// The command's, panel's or frame's id.
8377    pub subject: String,
8378    pub owner: Option<OwnerId>,
8379    pub name: String,
8380    /// Whether the name is in the icon vocabulary.
8381    pub resolves: bool,
8382}
8383
8384/// A command's icon names that do not resolve.
8385fn unknown_icons(spec: &CommandSpec) -> Vec<&str> {
8386    [&spec.icon, &spec.icon_on]
8387        .into_iter()
8388        .flatten()
8389        .map(String::as_str)
8390        .filter(|n| !egui_pop_core::icon::registry::is_known(n))
8391        .collect()
8392}
8393
8394/// Every icon name the commands, panels, frames (places and modes) and
8395/// status items declare.
8396pub fn declared_icons(app: &AppHandle) -> Vec<DeclaredIcon> {
8397    let known = |n: &str| egui_pop_core::icon::registry::is_known(n);
8398    let mut out = Vec::new();
8399    let derived = app.0.derived.borrow();
8400    for (spec, owner) in &derived.commands {
8401        // An icon set by another plugin is that plugin's.
8402        let owner = derived.icons_set_by.get(&spec.id).unwrap_or(owner);
8403        for (surface, name) in [("command", &spec.icon), ("command (on)", &spec.icon_on)] {
8404            if let Some(name) = name {
8405                out.push(DeclaredIcon {
8406                    surface,
8407                    subject: spec.id.to_string(),
8408                    owner: Some(owner.clone()),
8409                    name: name.clone(),
8410                    resolves: known(name),
8411                });
8412            }
8413        }
8414    }
8415    for (spec, owner) in &derived.panels {
8416        if !spec.icon.is_empty() {
8417            out.push(DeclaredIcon {
8418                surface: "panel",
8419                subject: spec.id.to_string(),
8420                owner: Some(owner.clone()),
8421                name: spec.icon.clone(),
8422                resolves: known(&spec.icon),
8423            });
8424        }
8425    }
8426    drop(derived);
8427    for slot in app.0.indicators.borrow().iter() {
8428        let (ind, _) = &slot.item;
8429        if let Some(name) = &ind.initial.icon {
8430            out.push(DeclaredIcon {
8431                surface: "status item",
8432                subject: ind.id.clone(),
8433                owner: Some(slot.owner.clone()),
8434                name: name.clone(),
8435                resolves: known(name),
8436            });
8437        }
8438    }
8439    for (frame, name) in crate::contexts::frame_icons(app) {
8440        out.push(DeclaredIcon {
8441            surface: "frame",
8442            subject: frame.to_string(),
8443            owner: None,
8444            resolves: known(&name),
8445            name,
8446        });
8447    }
8448    out
8449}
8450
8451const RESOLUTION_CODES: &[&str] = &[
8452    "unknown-icon",
8453    "unknown-zone",
8454    "duplicate-block",
8455    "dangling-replace",
8456    "dangling-extend",
8457    "dangling-wrap",
8458    "dangling-after",
8459    "hook-order",
8460    "unknown-command",
8461    "unknown-step",
8462    "step-replaced-twice",
8463];
8464
8465/// The asks made by the `on_exit` functions, and by the listeners that
8466/// hear them, drained before the application closes: a few rounds at
8467/// most, so a listener asking again each time cannot hold the exit; what
8468/// is left is said.
8469fn drain_before_exit(handle: &AppHandle) {
8470    const ROUNDS: usize = 8;
8471    for _ in 0..ROUNDS {
8472        if handle.drain_asks().is_empty() {
8473            return;
8474        }
8475    }
8476    let left = handle.asks_waiting();
8477    if left > 0 {
8478        log::warn!(target: "egui_pop", "{left} request(s) asked for after the drawing still wait at exit");
8479    }
8480}
8481
8482#[cfg(feature = "eframe")]
8483impl eframe::App for App {
8484    fn logic(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
8485        App::logic(self, ctx);
8486    }
8487
8488    fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
8489        self.show_wrapped(ui);
8490    }
8491
8492    /// Transparent where windows are built transparent for their rounded
8493    /// corners: what egui leaves unpainted outside a corner shows the
8494    /// desktop. An opaque window ignores the alpha.
8495    fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
8496        if self.handle.rounded_windows() {
8497            [0.0; 4]
8498        } else {
8499            // eframe's own default.
8500            egui::Color32::from_rgba_unmultiplied(12, 12, 12, 180).to_normalized_gamma_f32()
8501        }
8502    }
8503
8504    fn on_exit(&mut self) {
8505        match self.exit() {
8506            Outcome::Done(Err(e)) => log::error!(target: "egui_pop", "saving: {e}"),
8507            Outcome::Vetoed { by, reason } => {
8508                log::warn!(target: "egui_pop", "exit step vetoed by {by}: {reason}");
8509            }
8510            Outcome::Done(Ok(_)) => {}
8511        }
8512    }
8513}
8514
8515/// Draws the top bar's end zone (`zones::TOP_BAR_END`) in a right-to-left
8516/// `Ui`, its blocks left to right in the width they took last pass;
8517/// returns that width. The first time, the pass is drawn again once
8518/// measured (`Context::request_discard`), so it is never shown out of
8519/// place.
8520fn top_bar_end(ui: &mut Ui, h: &AppHandle) -> f32 {
8521    let height = ui.available_height();
8522    let layout = egui::Layout::left_to_right(egui::Align::Center);
8523    let known = TOP_BAR_END_WIDTH.get(ui.ctx());
8524    let width = known.unwrap_or(0.0);
8525    let r = ui.allocate_ui_with_layout(egui::vec2(width, height), layout, |ui| {
8526        h.show_zone(ui, &zones::TOP_BAR_END);
8527    });
8528    let took = r.response.rect.width();
8529    if (took - width).abs() > 0.5 {
8530        if known.is_none() {
8531            ui.ctx()
8532                .request_discard("the top bar's end zone was measured");
8533        } else {
8534            ui.ctx().request_repaint();
8535        }
8536    }
8537    TOP_BAR_END_WIDTH.set(ui.ctx(), took);
8538    took
8539}
8540
8541#[cfg(test)]
8542mod make_tests {
8543    use super::*;
8544
8545    /// eframe's clipboard shortcuts go off only with a plugin reading the
8546    /// system clipboard, or when the options have them off already; the
8547    /// keymap then runs the chords.
8548    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
8549    #[test]
8550    fn a_reading_clipboard_turns_eframes_clipboard_shortcuts_off() {
8551        struct Reading;
8552        impl Plugin for Reading {
8553            fn id(&self) -> PluginId {
8554                crate::clipboard::SYSTEM_PLUGIN
8555            }
8556            fn connect(&mut self, _: &mut Ctx<'_>) -> Result<(), PluginError> {
8557                Ok(())
8558            }
8559        }
8560        let mut options = eframe::NativeOptions::default();
8561        assert!(!App::builder().clipboard_shortcuts(&mut options));
8562        assert!(options.clipboard_shortcuts, "no reading backend: kept on");
8563        assert!(
8564            App::builder()
8565                .plugin(Reading)
8566                .clipboard_shortcuts(&mut options)
8567        );
8568        assert!(!options.clipboard_shortcuts);
8569        let mut options = eframe::NativeOptions {
8570            clipboard_shortcuts: false,
8571            ..Default::default()
8572        };
8573        assert!(App::builder().clipboard_shortcuts(&mut options));
8574        assert!(
8575            !options.clipboard_shortcuts,
8576            "the application's choice kept"
8577        );
8578    }
8579
8580    #[test]
8581    fn a_failed_make_is_logged_and_published() {
8582        let app = App::builder().build(&Context::default()).unwrap();
8583        let h = app.handle().clone();
8584        let mark = h.last_event();
8585        let e: MakeError = "the kernel did not start".into();
8586        report_make_error(&h, e.as_ref());
8587        let events = h.events_since(mark);
8588        let ev = events.last().expect("published");
8589        assert_eq!(ev.name, "app.make_failed");
8590        assert_eq!(ev.data["error"], "the kernel did not start");
8591    }
8592
8593    /// `make` may fail; it compiles with an error of any kind.
8594    #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
8595    #[allow(
8596        dead_code,
8597        reason = "compiled, never called: it checks that `make` may fail with an error of any kind"
8598    )]
8599    fn fallible_make(b: AppBuilder) -> eframe::Result {
8600        b.run_native_with("demo", eframe::NativeOptions::default(), |app, _| {
8601            if app.handle().panels().is_empty() {
8602                return Err("nothing to show".into());
8603            }
8604            Ok(Box::new(app))
8605        })
8606    }
8607}
8608
8609#[cfg(test)]
8610mod names_surface_tests {
8611    use super::names_surface;
8612
8613    #[test]
8614    fn a_kind_names_its_instances_surfaces_an_exact_id_only_its_own() {
8615        // A surface's name, a panel's id.
8616        assert!(names_surface("sheet.graph", "sheet.graph"));
8617        assert!(names_surface("app.log", "app.log"));
8618        // A kind: its panel declared and its instances.
8619        assert!(names_surface("app.gallery", "app.gallery_2"));
8620        assert!(names_surface("app.gallery", "app.gallery_12"));
8621        assert!(!names_surface("app.gallery", "app.gallery_x"));
8622        assert!(!names_surface("app.gallery", "app.gallery_"));
8623        assert!(!names_surface("app.gallery", "app.gallery2"));
8624        assert!(!names_surface("app.gallery", "app.galleryx_2"));
8625        // An instance's id: that instance only.
8626        assert!(names_surface("app.gallery#2", "app.gallery_2"));
8627        assert!(!names_surface("app.gallery#2", "app.gallery"));
8628        assert!(!names_surface("app.gallery#2", "app.gallery_3"));
8629        // Another panel never.
8630        assert!(!names_surface("app.log", "app.gallery_2"));
8631    }
8632}