Skip to main content

egui_pop_api/admin/
mod.rs

1//! The administration app (`docs/design/admin-forms.md`), titled
2//! "Settings": every setting, and later every tool and task that is not
3//! the work surface, as full pages generated from declarations. Nothing
4//! here draws a component's own widgets: a component declares a
5//! [`Manifest`] and the shell renders it with egui-pop's bricks.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - **Full page**: an overlay of the whole main window, or "Pop out" to
11//!   a window of its own; the mode used last is remembered (the
12//!   `admin.window` setting). The window is an application window
13//!   ([`crate::windows`], id [`APP_WINDOW`]): it repaints on its own, gets
14//!   the application's title bar, keeps its size and place, and closing
15//!   the main window while it is open moves it into the main window.
16//!   Where the backend has no windows of its own, the overlay.
17//! - **Two panes**: on the left, a tree of the scopes with their
18//!   sections nested under them; on the right, the section's page, which
19//!   wraps to the width it gets. The divider between them is dragged (or
20//!   moved by its arrow keys) and its width kept ([`NAV_WIDTH`]). The
21//!   search above the tree searches every scope.
22//! - **Rows**: each setting's editor, a modified bar, an origin tag
23//!   (a host scope's label, `command line`), its reset (of the layer
24//!   shown), and a labelled "Set for" menu only on a setting that opted
25//!   into a host scope open now. Applied live, undone with the settings'
26//!   history.
27//! - **Generated**: the declared settings become pages with no
28//!   hand-written page ([`egui_pop_model::admin::generate`]); manifests
29//!   add scopes and sections ([`Admin::manifest`]).
30//! - **Value scopes**: a setting is app-wide by default. The host
31//!   declares its own scopes above `app` ([`Admin::declare_scope`], a
32//!   later one winning), a setting opts into them in its declaration
33//!   ([`Descriptor::scopes`]) or a manifest's field
34//!   ([`model::Field::scopes`]); [`Admin::offer`] opens a scope's layer,
35//!   the store fills it, [`Admin::set_run`] records a command line
36//!   override ([`egui_pop_model::admin::layers`]).
37//! - **Storage**: the host provides where the values are kept, a
38//!   [`store::SettingsStore`] ([`Admin::attach_store`]): loaded when
39//!   attached and when a scope is offered, saved away from the UI thread
40//!   as values change, followed when they change elsewhere; its errors
41//!   are shown in the window. egui-pop keeps no location of its own:
42//!   without a store, the values last the session, and the window says
43//!   so.
44//! - **Records and statuses**: lists and tables read their rows from a
45//!   `read_only` command or a `records` hook, statuses their value from a
46//!   `read_only` command or a `status` hook; read once, and again after
47//!   a command that changes something or an event they name.
48//! - **Clauses**: a node's `when` hides it and its `enabled` greys it
49//!   (with its reason), read against the application's context keys and
50//!   the section's values as `form.<field id>`.
51//! - **Commands**: `admin.open` (`{"path": "scope/section/key"}`, or
52//!   `{"key": "<setting id>"}`, and `{"mode": "overlay" | "window"}`),
53//!   `admin.close`, `admin.popOut`, `admin.set` and `admin.reset` (a value
54//!   in a scope, for agents); `{"wizard": "<id>"}` opens a wizard. The `admin` collector shows the tree.
55//! - **Settings files**: `settings.export` and `settings.import` (with
56//!   `dryRun`), and their wizards in General › Advanced ([`transfer`]).
57//!
58//! - **Wizards**: multi-step flows declared in a manifest
59//!   ([`egui_pop_model::admin::wizard`]) fill the page while they run
60//!   ([`wizard`]): `admin.wizard.open` and its sibling commands drive one.
61//!
62//! `Ctrl+,` and `app.settings` open it ([`crate::settings_window`]).
63//! The shortcuts editor, the gestures, the Fonts page and the custom
64//! settings pages are its pages, as registered widget kinds (`shortcuts`,
65//! `gestures`, `fonts`, `settings-page`); the settings window of before
66//! opens from General › Advanced.
67
68mod detail;
69pub mod focus;
70pub mod quick;
71mod shell;
72pub mod store;
73mod sync;
74pub mod transfer;
75mod window;
76pub mod wizard;
77
78use std::collections::BTreeMap;
79use std::sync::{Arc, Mutex};
80
81use egui::Ui;
82use egui_pop_core::lock;
83use egui_pop_core::strings::StrKey;
84use egui_pop_model::admin::generate::{self, Entry};
85use egui_pop_model::admin::hooks::{Hook, Hooks};
86use egui_pop_model::admin::layers::Layers;
87use egui_pop_model::admin::{Manifest, Tree, ValueScope};
88use egui_pop_model::commands::{CommandSpec, Origin};
89use egui_pop_model::diagnostics::Diagnostics;
90use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PluginId, SettingId};
91use egui_pop_model::values::{Change, Descriptor, Set, Value};
92use serde_json::{Value as Json, json};
93
94use crate::app::AppHandle;
95use crate::history::StoreScope;
96use crate::services::ServiceToken;
97use crate::zones::{self, Block};
98use crate::{Ctx, Plugin, PluginError};
99
100pub use egui_pop_model::admin as model;
101pub use wizard::{
102    CMD_WIZARD_BACK, CMD_WIZARD_CANCEL, CMD_WIZARD_FINISH, CMD_WIZARD_GO, CMD_WIZARD_NEXT,
103    CMD_WIZARD_OPEN, CMD_WIZARD_SET, CMD_WIZARD_SKIP,
104};
105
106/// Opens the administration app (`{"path"}`, `{"key"}`, `{"mode"}`).
107pub const CMD_OPEN: CommandId = CommandId::from_static("admin.open");
108/// Closes it.
109pub const CMD_CLOSE: CommandId = CommandId::from_static("admin.close");
110/// The Settings app's listener on the bus's `pop.window.open` and
111/// `pop.window.close`: the app is open while its window is, and its window
112/// closing closes the app, whoever asked (ADR 0029).
113pub const WINDOW_LISTENER: &str = "pop.admin.window";
114/// The plugin owning the Settings app (its window, its listeners).
115pub const OWNER: &str = "egui_pop.admin";
116/// Moves it between the overlay and a window of its own.
117pub const CMD_POP_OUT: CommandId = CommandId::from_static("admin.popOut");
118/// Sets a setting's value in a value scope (`{"key", "scope", "value"}`).
119pub const CMD_SET: CommandId = CommandId::from_static("admin.set");
120/// Takes a value scope's value of a setting back (`{"key", "scope"}`).
121pub const CMD_RESET: CommandId = CommandId::from_static("admin.reset");
122
123/// Whether it opens in a window of its own: the mode used last.
124pub const WINDOW: SettingId = SettingId::from_static("admin.window");
125
126/// The id of its application window ([`crate::windows`]), in the window
127/// mode: `appWindow == 'settings'` in `when` clauses, `window: "settings"`
128/// for agents, its size and place kept under it.
129pub const APP_WINDOW: &str = "settings";
130
131/// The service.
132pub const ADMIN: ServiceToken<Admin> = ServiceToken::new("admin");
133
134/// A value scope the host application declares above `app` (egui-pop
135/// has none of its own): its name, its label and what it means. A
136/// setting is app-wide unless its field opts into a declared scope
137/// ([`model::Field::scopes`]); the "Set for" choice shows only then.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct ExtraScope {
140    pub scope: ValueScope,
141    /// Its name in the "Set for" choice and as a value's origin ("This
142    /// library").
143    pub label: StrKey,
144    /// What it means, in the choice's tooltip ("While this library is
145    /// open").
146    pub about: StrKey,
147}
148
149impl ExtraScope {
150    pub const fn new(name: &'static str, label: StrKey, about: StrKey) -> ExtraScope {
151        ExtraScope {
152            scope: ValueScope::new(name),
153            label,
154            about,
155        }
156    }
157}
158
159/// The focus surface the pages are drawn in: its local scope is the
160/// settings' history.
161pub const SURFACE: &str = "adminWindow";
162
163/// A registered widget kind: draws a node of its kind with its options
164/// (the declared exception to "components never draw").
165pub type WidgetKindFn = Arc<dyn Fn(&mut Ui, &AppHandle, &Json) + Send + Sync>;
166
167/// A widget kind's search: the items of a node of its kind matching the
168/// query (every word), each as its key and its title. The key is what
169/// `scope/section/<key>` lands on: the widget marks the item while its
170/// section shows ([`Admin::marked`]) and scrolls to it once
171/// ([`Admin::take_key`]).
172pub type WidgetSearchFn =
173    Arc<dyn Fn(&egui::Context, &AppHandle, &Json, &str) -> Vec<(String, String)> + Send + Sync>;
174
175#[derive(Debug, Default)]
176struct State {
177    open: bool,
178    scope: Option<String>,
179    section: Option<String>,
180    /// An item to scroll to once (a deep link's key).
181    key: Option<String>,
182    /// A record a deep link named (its key's value): marked while its
183    /// section shows.
184    row: Option<String>,
185    /// The item a deep link or a search hit landed on (a setting id, or
186    /// a widget's item key): marked while its section shows.
187    mark: Option<String>,
188    filter: String,
189    /// The value scope a row writes to, when its "Set for" menu chose.
190    target: BTreeMap<String, ValueScope>,
191}
192
193/// The administration app's state, manifests, hooks, widget kinds and
194/// value layers.
195///
196/// Need (dialog): a settings or admin page declared as a manifest.
197#[derive(Default)]
198pub struct Admin {
199    state: Mutex<State>,
200    layers: Mutex<Layers>,
201    manifests: Mutex<Vec<Manifest>>,
202    hooks: Mutex<Hooks>,
203    widgets: Mutex<BTreeMap<String, WidgetKindFn>>,
204    searches: Mutex<BTreeMap<String, WidgetSearchFn>>,
205    diagnostics: Mutex<Diagnostics>,
206    reads: Mutex<Reads>,
207    /// The host's read kernel: the commands its transport serves are read
208    /// through it, away from the UI thread ([`Admin::attach_reads`]).
209    kernel: Mutex<Option<Arc<crate::reads::ReadKernel>>>,
210    /// The wizard running, if any.
211    wizard: Mutex<Option<wizard::Running>>,
212    /// The page was drawn in the main window in this pass (the shell's
213    /// paint guard reads it: a focus screen without its page).
214    page_drawn: std::sync::atomic::AtomicBool,
215    /// What the last wizard finished ran.
216    finished: Mutex<Option<Json>>,
217    /// A path field's Browse waiting for its choice: the draft key.
218    browsing: Mutex<Option<(String, crate::host::Pending)>>,
219    /// The host's value scopes, lowest first.
220    extra: Mutex<Vec<ExtraScope>>,
221    /// Settings export and import: retired settings, the last import.
222    transfer: transfer::State,
223    /// The host's settings store and what was last loaded from or saved
224    /// to it.
225    sync: Mutex<sync::Synced>,
226    /// What the store's threads hand to the UI thread.
227    shared: Arc<sync::Shared>,
228    /// The host loads and saves the layers itself (the deprecated
229    /// `load_layer` and `export_layer`).
230    legacy: std::sync::atomic::AtomicBool,
231    /// The settings the person changed, with when (seconds since the
232    /// epoch), the latest last ([`quick`]).
233    recent: Mutex<Vec<(String, f64)>>,
234    /// The quick settings open, per window group.
235    quick: Mutex<BTreeMap<egui::ViewportId, quick::Open>>,
236    /// The host's foci and the one the Settings edit ([`focus`]).
237    foci: Mutex<focus::Foci>,
238    /// The strings a manifest's texts are ([`Admin::texts`]).
239    texts: Mutex<Vec<StrKey>>,
240}
241
242/// The answers of the `read_only` commands statuses and records read:
243/// asked once, kept until an event says they changed (a command that
244/// changes something ran, or an event a node names in `refresh`), never
245/// read per frame. Asked again, a read keeps its last answer, shown
246/// (stale) until the new one comes: a refresh never blanks a page.
247#[derive(Debug, Default)]
248struct Reads {
249    answers: BTreeMap<String, Result<Json, String>>,
250    /// The answers a refresh set aside, each kept until its read answers
251    /// again ([`Admin::refreshing`]).
252    stale: BTreeMap<String, Result<Json, String>>,
253    /// A read asked: its command, its arguments, and how many runs of
254    /// that command the history held then (its answer is a later one).
255    asked: BTreeMap<String, (CommandId, Json, usize)>,
256    /// The last journal event looked at.
257    seq: Option<crate::host::Seq>,
258}
259
260fn read_key(command: &str, args: &Json) -> String {
261    format!("{command} {args}")
262}
263
264impl std::fmt::Debug for Admin {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        f.debug_struct("Admin")
267            .field("state", &self.state)
268            .field("layers", &self.layers)
269            .finish_non_exhaustive()
270    }
271}
272
273impl Admin {
274    fn new() -> Admin {
275        Admin {
276            layers: Mutex::new(Layers::new()),
277            ..Admin::default()
278        }
279    }
280
281    pub fn is_open(&self) -> bool {
282        lock(&self.state).open
283    }
284
285    /// Opens it on a place: `scope`, `scope/section`, `scope/section/key`
286    /// or a setting id (`None`: where it was). Asked in a window of one of
287    /// the host's foci, it edits that focus ([`focus`]).
288    pub fn open(&self, app: &AppHandle, place: Option<&str>) -> Result<(), String> {
289        let asked = app.window_of_group(app.current_window_group());
290        self.asked_in(app, &asked);
291        if let Some(link) = place.filter(|p| !p.is_empty()) {
292            let tree = self.tree(app);
293            let p = tree
294                .resolve(link)
295                .ok_or_else(|| format!("no place `{link}` in the settings"))?;
296            let mut s = lock(&self.state);
297            s.scope = Some(p.scope);
298            s.section = p.section;
299            s.row = None;
300            s.mark.clone_from(&p.key);
301            s.key = p.key;
302            s.filter.clear();
303        }
304        lock(&self.state).open = true;
305        self.refresh();
306        // In its window: opened, or brought to the front (`pop.window.open`).
307        window::settle(app, self, true);
308        Ok(())
309    }
310
311    /// The page was drawn in the main window in this pass.
312    pub(crate) fn note_page_drawn(&self) {
313        self.page_drawn
314            .store(true, std::sync::atomic::Ordering::Relaxed);
315    }
316
317    /// Whether the page was drawn in the main window since the last ask.
318    pub(crate) fn take_page_drawn(&self) -> bool {
319        self.page_drawn
320            .swap(false, std::sync::atomic::Ordering::Relaxed)
321    }
322
323    /// Closes it, and the wizard running with it. In its window, it is
324    /// the window's close (`pop.window.close`, the app asking): the app closes
325    /// in that call, its window's listeners after it.
326    pub fn close(&self, app: &AppHandle) {
327        if window::held(app) {
328            window::close(app);
329        }
330        self.close_state();
331    }
332
333    /// The app's state closed: by [`Admin::close`], or by its window's
334    /// close (`pop.admin.window`).
335    fn close_state(&self) {
336        // A wizard run as a sheet is not the app's: it stays.
337        let mut run = lock(&self.wizard);
338        if run.as_ref().is_some_and(|r| r.sheet.is_none()) {
339            run.take();
340        }
341        drop(run);
342        let mut s = lock(&self.state);
343        s.open = false;
344        s.filter.clear();
345        s.mark = None;
346    }
347
348    /// The scope, section and search shown.
349    pub fn shown(&self) -> (Option<String>, Option<String>, String) {
350        let s = lock(&self.state);
351        (s.scope.clone(), s.section.clone(), s.filter.clone())
352    }
353
354    /// Adds a manifest (checked when the tree is built: what does not
355    /// resolve is left out and reported).
356    pub fn manifest(&self, manifest: Manifest) {
357        lock(&self.manifests).push(manifest);
358    }
359
360    /// Registers the strings a manifest's texts are, so they show in the
361    /// interface's language: a declared text (a section's title, a
362    /// group's, a column's, an action's, a confirmation's, an empty
363    /// state's, a row field's and its choices') equal to a key's English
364    /// fallback is shown translated. A text with no key shows as
365    /// declared.
366    pub fn texts(&self, keys: &[StrKey]) {
367        let mut t = lock(&self.texts);
368        for k in keys {
369            if !t.contains(k) {
370                t.push(*k);
371            }
372        }
373    }
374
375    /// The registered string whose English is `text`.
376    pub(crate) fn text_key(&self, text: &str) -> Option<StrKey> {
377        lock(&self.texts)
378            .iter()
379            .find(|k| k.fallback == text)
380            .copied()
381    }
382
383    /// Registers a hook a manifest names; `false` when the name is taken.
384    pub fn hook(&self, name: &str, hook: Hook) -> bool {
385        lock(&self.hooks).register(name, hook)
386    }
387
388    /// Registers a widget kind: draws a node of its kind with its options
389    /// (`shortcuts`, `gestures`, `fonts` and `settings-page` are
390    /// egui-pop's own). One that edits settings names them in its
391    /// options' `settings`, so the generated pages leave them out.
392    pub fn widget_kind(
393        &self,
394        id: &str,
395        draw: impl Fn(&mut Ui, &AppHandle, &Json) + Send + Sync + 'static,
396    ) {
397        lock(&self.widgets).insert(id.into(), Arc::new(draw));
398    }
399
400    pub(crate) fn widget(&self, id: &str) -> Option<WidgetKindFn> {
401        lock(&self.widgets).get(id).cloned()
402    }
403
404    /// Registers a widget kind's search, so the Settings app's search
405    /// finds the items inside a node of that kind (the shortcuts editor's
406    /// commands, by name and by key). The settings a widget names in its
407    /// options' `settings` are searched without it.
408    pub fn widget_search(
409        &self,
410        kind: &str,
411        search: impl Fn(&egui::Context, &AppHandle, &Json, &str) -> Vec<(String, String)>
412        + Send
413        + Sync
414        + 'static,
415    ) {
416        lock(&self.searches).insert(kind.into(), Arc::new(search));
417    }
418
419    pub(crate) fn search_of(&self, kind: &str) -> Option<WidgetSearchFn> {
420        lock(&self.searches).get(kind).cloned()
421    }
422
423    /// The item a deep link or a search hit landed on, marked while its
424    /// section shows: a setting id, or a widget's item key.
425    pub fn marked(&self) -> Option<String> {
426        lock(&self.state).mark.clone()
427    }
428
429    /// Whether `key` is the item to scroll to, taken once: the widget
430    /// that draws it scrolls to it.
431    pub fn take_key(&self, key: &str) -> bool {
432        let mut s = lock(&self.state);
433        if s.key.as_deref() == Some(key) {
434            s.key = None;
435            true
436        } else {
437            false
438        }
439    }
440
441    /// Whether `key` is still waiting to be scrolled to.
442    pub(crate) fn key_is(&self, key: &str) -> bool {
443        lock(&self.state).key.as_deref() == Some(key)
444    }
445
446    pub(crate) fn hooks(&self) -> std::sync::MutexGuard<'_, Hooks> {
447        lock(&self.hooks)
448    }
449
450    /// The diagnostics of the last tree built.
451    pub fn diagnostics(&self) -> Diagnostics {
452        lock(&self.diagnostics).clone()
453    }
454
455    /// The resolved tree: the declared settings' pages (less the settings
456    /// a manifest places), then every manifest, checked.
457    pub fn tree(&self, app: &AppHandle) -> Tree {
458        let entries = app.settings();
459        let mut manifests = lock(&self.manifests).clone();
460        // The pages the settings window drew itself: shortcuts, gestures,
461        // fonts, custom pages, and the window behind Advanced.
462        if app
463            .service(&crate::settings_window::SETTINGS_WINDOW)
464            .is_some()
465        {
466            manifests.insert(0, crate::settings_window::admin_manifest(app));
467        }
468        let placed: std::collections::BTreeSet<&str> =
469            manifests.iter().flat_map(|m| m.bound_settings()).collect();
470        let mut tree = Tree::default();
471        tree.merge(generate::settings(
472            entries
473                .iter()
474                .filter(|e| !placed.contains(e.id.as_str()))
475                .map(|e| Entry {
476                    id: e.id.as_str(),
477                    section: &e.section,
478                }),
479        ));
480        let mut d = Diagnostics::new();
481        let mut scopes: Vec<String> = tree.scopes.iter().map(|s| s.meta.id.clone()).collect();
482        for m in &manifests {
483            scopes.extend(m.scopes.iter().map(|s| s.meta.id.clone()));
484        }
485        let exists = |id: &str| entries.iter().any(|e| e.id.as_str() == id);
486        for mut m in manifests {
487            if m.version > model::FORMAT {
488                d.warn(
489                    "admin-newer",
490                    None,
491                    "manifest",
492                    format!(
493                        "manifest format {} is newer than {}: left out",
494                        m.version,
495                        model::FORMAT
496                    ),
497                );
498                continue;
499            }
500            for x in m.check(&scopes, &exists).all() {
501                d.push_quiet(x.clone());
502            }
503            tree.merge(m);
504        }
505        // Settings export and import: their wizards offer the places of
506        // the tree built so far.
507        let mut m = transfer::manifest(self, app, &tree);
508        for x in m.check(&scopes, &exists).all() {
509            d.push_quiet(x.clone());
510        }
511        tree.merge(m);
512        // The tree is built often: an ordering problem is logged once,
513        // when it first shows, and kept with the others.
514        let mut last = lock(&self.diagnostics);
515        for x in tree.order_diagnostics() {
516            if last.all().contains(x) {
517                d.push_quiet(x.clone());
518            } else {
519                d.push(x.clone());
520            }
521        }
522        *last = d;
523        drop(last);
524        tree
525    }
526
527    /// The value layers.
528    pub fn layers(&self) -> Layers {
529        lock(&self.layers).clone()
530    }
531
532    /// Declares a host value scope above those declared before it: a
533    /// value set for it wins over theirs and `app`'s. Declare them in
534    /// order, lowest first, before offering them; declaring one again
535    /// changes its label and about.
536    pub fn declare_scope(&self, extra: ExtraScope) {
537        let mut d = lock(&self.extra);
538        match d.iter_mut().find(|x| x.scope == extra.scope) {
539            Some(x) => *x = extra,
540            None => d.push(extra),
541        }
542        lock(&self.layers).declare(extra.scope);
543    }
544
545    /// The host's value scopes, lowest first.
546    pub fn extra_scopes(&self) -> Vec<ExtraScope> {
547        lock(&self.extra).clone()
548    }
549
550    /// A declared scope's declaration.
551    pub fn extra_scope(&self, scope: ValueScope) -> Option<ExtraScope> {
552        lock(&self.extra).iter().find(|x| x.scope == scope).copied()
553    }
554
555    /// Offers a host value scope for editing (the application opened its
556    /// library, its workspace...), or takes it back.
557    pub fn offer(&self, scope: ValueScope, on: bool) {
558        let was = self.offered().contains(&scope);
559        lock(&self.layers).offer(scope, on);
560        if was != on {
561            // The store's layer is read (or taken back) at the next pass.
562            self.reload(scope);
563        }
564    }
565
566    /// The editable value scopes offered (`app` always).
567    pub fn offered(&self) -> Vec<ValueScope> {
568        lock(&self.layers).offered().to_vec()
569    }
570
571    /// Replaces a layer's values (setting id to JSON), as the application
572    /// keeps them with its library or workspace; the effective values
573    /// change at once.
574    #[deprecated(note = "attach a `store::SettingsStore` with `Admin::attach_store`")]
575    pub fn load_layer(&self, app: &AppHandle, scope: ValueScope, values: BTreeMap<String, Json>) {
576        self.legacy
577            .store(true, std::sync::atomic::Ordering::Relaxed);
578        self.put_layer(app, scope, values);
579    }
580
581    /// A layer's values, by setting id: what the application saves.
582    #[deprecated(note = "attach a `store::SettingsStore` with `Admin::attach_store`")]
583    pub fn export_layer(&self, scope: ValueScope) -> BTreeMap<String, Json> {
584        self.legacy
585            .store(true, std::sync::atomic::Ordering::Relaxed);
586        self.layer_values(scope)
587    }
588
589    /// Replaces a layer's values (setting id to JSON).
590    fn put_layer(&self, app: &AppHandle, scope: ValueScope, values: BTreeMap<String, Json>) {
591        let store = app.store();
592        let values = values
593            .into_iter()
594            .map(|(k, v)| (SettingId::new(&k).map_or(k, |id| id.path()), v))
595            .collect();
596        let writes = {
597            let s = lock(&store);
598            lock(&self.layers).load(scope, values, &|p| s.get(p).map(|e| e.value.to_json()))
599        };
600        for (path, v) in writes {
601            write(app, &path, &v);
602        }
603    }
604
605    /// A layer's values, by setting id.
606    fn layer_values(&self, scope: ValueScope) -> BTreeMap<String, Json> {
607        lock(&self.layers)
608            .export(scope)
609            .into_iter()
610            .map(|(p, v)| (p.strip_prefix("settings/").unwrap_or(&p).to_string(), v))
611            .collect()
612    }
613
614    /// A command line override (`--set key=value`): shown as the `command
615    /// line` origin, never edited.
616    pub fn set_run(&self, app: &AppHandle, id: &SettingId, value: Json) -> Result<(), String> {
617        let path = id.path();
618        let now = current(app, &path)?;
619        let w = lock(&self.layers).set_run(&path, value, &now);
620        if let Some(v) = w {
621            write(app, &path, &v);
622        }
623        Ok(())
624    }
625
626    /// Sets a setting's value in a value scope; `app` writes the store as
627    /// the settings form does (an undo step) unless a layer above holds
628    /// it.
629    pub fn set_in(
630        &self,
631        app: &AppHandle,
632        scope: ValueScope,
633        id: &SettingId,
634        value: Json,
635    ) -> Result<(), String> {
636        let path = id.path();
637        let now = current(app, &path)?;
638        if !scope.editable() {
639            return Err("the command line's values are not edited here".into());
640        }
641        if scope != ValueScope::App && !self.offered().contains(&scope) {
642            return Err(format!("no {} is open", scope.name()));
643        }
644        if scope != ValueScope::App && !self.allows(app, id, scope) {
645            return Err(format!("`{id}` is not set for a {}", scope.name()));
646        }
647        // The write is said on the bus as made in this scope.
648        let _writing = crate::bus::settings::writing(scope.name(), None);
649        let (w, plain) = {
650            let mut l = lock(&self.layers);
651            let plain = scope == ValueScope::App && l.origin(&path) == ValueScope::App;
652            (l.set(scope, &path, value, &now), plain)
653        };
654        let set = match (w, plain) {
655            (Some(v), true) => {
656                let ty = descriptor(app, &path)?.ty;
657                let v = Value::from_json(ty, &v)?;
658                lock(&app.store())
659                    .set(Set::new(&path, Change::To(v), Origin::User).by(&OwnerId::FRAMEWORK))
660                    .map(|_| ())
661                    .map_err(|e| format!("{e:?}"))
662            }
663            (Some(v), false) => {
664                write(app, &path, &v);
665                Ok(())
666            }
667            (None, _) => Ok(()),
668        };
669        // The window mode changed: the window follows in this call
670        // ("Pop out", "Pop in").
671        if set.is_ok() && *id == WINDOW {
672            window::settle(app, self, false);
673        }
674        set
675    }
676
677    /// Whether a setting opted into a host scope: in its declaration
678    /// ([`Descriptor::scopes`]) or on a field of a manifest placing it.
679    pub fn allows(&self, app: &AppHandle, id: &SettingId, scope: ValueScope) -> bool {
680        if scope == ValueScope::App {
681            return true;
682        }
683        if descriptor(app, &id.path()).is_ok_and(|d| d.scopes.contains(&scope)) {
684            return true;
685        }
686        self.tree(app)
687            .fields()
688            .into_iter()
689            .any(|(_, f)| f.setting_id() == Some(id.as_str()) && f.scopes.contains(&scope))
690    }
691
692    /// Takes a value scope's value of a setting back: `app` goes back to
693    /// the default, a layer above to what is under it.
694    pub fn clear_in(
695        &self,
696        app: &AppHandle,
697        scope: ValueScope,
698        id: &SettingId,
699    ) -> Result<(), String> {
700        let path = id.path();
701        let now = current(app, &path)?;
702        let default = descriptor(app, &path)?.default.to_json();
703        let plain = scope == ValueScope::App && lock(&self.layers).origin(&path) == ValueScope::App;
704        if plain {
705            return lock(&app.store())
706                .set(Set::new(&path, Change::Reset, Origin::User).by(&OwnerId::FRAMEWORK))
707                .map(|_| ())
708                .map_err(|e| format!("{e:?}"));
709        }
710        let w = lock(&self.layers).clear(scope, &path, &now, &default);
711        if let Some(v) = w {
712            write(app, &path, &v);
713        }
714        Ok(())
715    }
716
717    /// A `read_only` command's answer: `None` while it is read for the
718    /// first time (the command is asked for, run before the next frame;
719    /// its result is taken from the runs). Read again after a refresh, it
720    /// answers what it answered before until the new answer comes
721    /// ([`Admin::refreshing`] says so meanwhile).
722    pub fn read(
723        &self,
724        app: &AppHandle,
725        command: &str,
726        args: &Json,
727    ) -> Option<Result<Json, String>> {
728        let args = if args.is_null() {
729            json!({})
730        } else {
731            args.clone()
732        };
733        if let Some(k) = self.kernel_for(command) {
734            k.set_context(&app.egui());
735            return k.read(command, &args).answer();
736        }
737        let key = read_key(command, &args);
738        let mut r = lock(&self.reads);
739        if let Some(a) = r.answers.get(&key) {
740            return Some(a.clone());
741        }
742        if let Some((id, args, before)) = r.asked.get(&key).cloned() {
743            // Its run, by its arguments, else the last of the command (a
744            // host may record them completed with their defaults); not
745            // one from before it was asked.
746            let runs = app.history();
747            // (A full history drops runs: the count proves nothing then.)
748            if runs.len() < egui_pop_model::commands::HISTORY
749                && runs.iter().filter(|x| x.id == id).count() == before
750            {
751                return r.stale.get(&key).cloned();
752            }
753            let Some(run) = runs
754                .iter()
755                .rev()
756                .find(|x| x.id == id && x.args == args)
757                .or_else(|| runs.iter().rev().find(|x| x.id == id))
758                .cloned()
759            else {
760                return r.stale.get(&key).cloned();
761            };
762            r.asked.remove(&key);
763            r.stale.remove(&key);
764            r.answers.insert(key, run.result.clone());
765            return Some(run.result);
766        }
767        let answer = match CommandId::new(command) {
768            Err(e) => Err(format!("{e:?}")),
769            Ok(id) => match app.command(&id) {
770                None => Err(format!("no command `{command}`")),
771                Some(spec) if !spec.read_only => {
772                    Err(format!("`{command}` is not read-only: it is not read here"))
773                }
774                Some(_) => {
775                    let before = app.history().iter().filter(|x| x.id == id).count();
776                    app.run(id.clone(), args.clone());
777                    let stale = r.stale.get(&key).cloned();
778                    r.asked.insert(key, (id, args, before));
779                    return stale;
780                }
781            },
782        };
783        r.stale.remove(&key);
784        r.answers.insert(key, answer.clone());
785        Some(answer)
786    }
787
788    /// Whether the read of `command` with `args` shows its last answer
789    /// while a new one is read (after a refresh): a page marks it
790    /// "Refreshing…" and keeps its rows.
791    pub fn refreshing(&self, command: &str, args: &Json) -> bool {
792        let args = if args.is_null() {
793            json!({})
794        } else {
795            args.clone()
796        };
797        if let Some(k) = self.kernel_for(command) {
798            return k.peek(command, &args).state == crate::reads::ReadState::Refreshing;
799        }
800        let key = read_key(command, &args);
801        let r = lock(&self.reads);
802        r.stale.contains_key(&key) && !r.answers.contains_key(&key)
803    }
804
805    /// Reads the commands `kernel`'s transport serves through it: a
806    /// status or a list shows at once what the kernel holds, read again
807    /// in the background ([`crate::reads`]); the events the page looks at
808    /// reach the kernel's policies, and a refresh makes its values out of
809    /// date without dropping them. Other commands are run as before.
810    pub fn attach_reads(&self, kernel: Arc<crate::reads::ReadKernel>) {
811        *lock(&self.kernel) = Some(kernel);
812    }
813
814    /// The read kernel attached, if any.
815    pub fn reads(&self) -> Option<Arc<crate::reads::ReadKernel>> {
816        lock(&self.kernel).clone()
817    }
818
819    fn kernel_for(&self, command: &str) -> Option<Arc<crate::reads::ReadKernel>> {
820        lock(&self.kernel).clone().filter(|k| k.serves(command))
821    }
822
823    /// Sets the answers read aside and forgets the reads still in flight
824    /// (their answer may predate the change): they are read again when
825    /// shown, each showing its last answer until the new one comes.
826    pub fn refresh(&self) {
827        let mut r = lock(&self.reads);
828        let answers = std::mem::take(&mut r.answers);
829        r.stale.extend(answers);
830        r.asked.clear();
831        drop(r);
832        if let Some(k) = self.reads() {
833            k.invalidate_all();
834        }
835    }
836
837    /// Looks at the journal since the last look: a command that changes
838    /// something, or an event matching one of `patterns` (`name`, or
839    /// `prefix.*`), and the answers are read again.
840    pub(crate) fn watch(&self, app: &AppHandle, patterns: &[String]) {
841        let since = lock(&self.reads).seq;
842        let events = app.events_since(since.unwrap_or(0));
843        let Some(last) = events.last().map(|e| e.seq) else {
844            return;
845        };
846        lock(&self.reads).seq = Some(last);
847        if since.is_none() {
848            return;
849        }
850        if let Some(k) = self.reads() {
851            for e in &events {
852                k.event(&e.name);
853            }
854        }
855        let matches = |name: &str| {
856            patterns.iter().any(|p| match p.strip_suffix('*') {
857                Some(prefix) => name.starts_with(prefix),
858                None => name == p,
859            })
860        };
861        let changed = events.iter().any(|e| {
862            matches(&e.name)
863                || (e.name == "command.done"
864                    && e.data["command"]
865                        .as_str()
866                        .and_then(|c| CommandId::new(c).ok())
867                        .and_then(|c| app.command(&c))
868                        .is_some_and(|s| !s.read_only))
869        });
870        if changed {
871            self.refresh();
872        }
873    }
874
875    /// The row's target scope ("Set for").
876    pub(crate) fn target(&self, path: &str) -> Option<ValueScope> {
877        lock(&self.state).target.get(path).copied()
878    }
879
880    pub(crate) fn set_target(&self, path: &str, scope: ValueScope) {
881        lock(&self.state).target.insert(path.into(), scope);
882    }
883
884    /// The user's settings document as saved: the `app` values in place of
885    /// those a layer above holds.
886    pub(crate) fn app_doc(&self, app: &AppHandle, values: &mut BTreeMap<String, Json>) {
887        let store = app.store();
888        let s = lock(&store);
889        lock(&self.layers).app_doc(values, &|p| {
890            s.get(p).map(|e| e.descriptor.default.to_json())
891        });
892    }
893}
894
895fn current(app: &AppHandle, path: &str) -> Result<Json, String> {
896    lock(&app.store())
897        .get(path)
898        .map(|e| e.value.to_json())
899        .ok_or_else(|| format!("no setting at `{path}`"))
900}
901
902fn descriptor(app: &AppHandle, path: &str) -> Result<Descriptor, String> {
903    lock(&app.store())
904        .get(path)
905        .map(|e| e.descriptor.clone())
906        .ok_or_else(|| format!("no setting at `{path}`"))
907}
908
909/// Writes an effective value a layer change gives: no undo step (the
910/// layers would not follow it back).
911fn write(app: &AppHandle, path: &str, v: &Json) {
912    let store = app.store();
913    let mut s = lock(&store);
914    let Some(ty) = s.get(path).map(|e| e.descriptor.ty) else {
915        return;
916    };
917    if let Ok(v) = Value::from_json(ty, v) {
918        let _ = s.set(
919            Set::new(path, Change::To(v), Origin::User)
920                .force()
921                .untracked()
922                .by(&OwnerId::FRAMEWORK),
923        );
924    }
925}
926
927/// Draws a setting a custom page draws as the Settings app's row, while
928/// the app draws the page; `false` elsewhere.
929pub(crate) fn setting_row(ui: &mut Ui, app: &AppHandle, id: &SettingId) -> bool {
930    shell::setting_row(ui, app, id)
931}
932
933/// A value scope from its name (`app`, `run` or a host's).
934pub fn scope_named(name: &str) -> Option<ValueScope> {
935    (!name.is_empty()).then(|| ValueScope::named(name))
936}
937
938/// Whether the application's administration app is open.
939pub fn is_open(app: &AppHandle) -> bool {
940    app.service(&ADMIN).is_some_and(|a| a.is_open())
941}
942
943/// Where the width of the tree of sections is kept, in points (dragged,
944/// not typed: no setting of its own in the settings).
945pub const NAV_WIDTH: &str = "settings/admin.nav_width";
946
947/// The tree's width when none is kept.
948pub const NAV_WIDTH_DEFAULT: f32 = 220.0;
949
950/// The width of the tree of sections, as kept (the room in the page may
951/// hold it smaller).
952pub fn nav_width(app: &AppHandle) -> f32 {
953    lock(&app.store())
954        .get(NAV_WIDTH)
955        .and_then(|e| e.value.as_f64())
956        .map_or(NAV_WIDTH_DEFAULT, |w| w as f32)
957}
958
959/// Keeps the width of the tree of sections.
960pub fn want_nav_width(app: &AppHandle, width: f32) {
961    let set = Set::new(
962        NAV_WIDTH,
963        Change::To(Value::Float(f64::from(width))),
964        Origin::User,
965    )
966    .by(&OwnerId::FRAMEWORK)
967    .untracked();
968    if let Err(e) = lock(&app.store()).set(set) {
969        log::warn!(target: "egui_pop", "{NAV_WIDTH}: {e:?}");
970    }
971}
972
973/// Whether it opens in a window of its own: never while a wizard runs
974/// as a focus screen ([`Admin::open_focus_wizard`]).
975pub fn in_window(app: &AppHandle) -> bool {
976    !focus_screen(app) && app.setting::<bool>(&WINDOW).unwrap_or(false)
977}
978
979/// Whether a wizard runs as a focus screen: the shell draws its title bar
980/// alone under it.
981pub fn focus_screen(app: &AppHandle) -> bool {
982    app.service(&ADMIN).is_some_and(|a| a.focus_screen())
983}
984
985/// The plugin: the `admin` service, its commands, its setting and its
986/// overlay. Not in `DefaultPlugins` yet: the settings window keeps
987/// `Ctrl+,` until the migration.
988#[derive(Debug, Default)]
989pub struct AdminPlugin;
990
991fn admin(call: &crate::app::Call<'_>) -> Result<Arc<Admin>, String> {
992    call.app.service(&ADMIN).ok_or_else(|| "no admin".into())
993}
994
995fn key_arg(call: &crate::app::Call<'_>) -> Result<SettingId, String> {
996    let key = call
997        .args
998        .get("key")
999        .and_then(Json::as_str)
1000        .ok_or("`key` is missing")?;
1001    SettingId::new(key).map_err(|e| format!("{e:?}"))
1002}
1003
1004fn scope_arg(call: &crate::app::Call<'_>) -> Result<ValueScope, String> {
1005    let name = call
1006        .args
1007        .get("scope")
1008        .and_then(Json::as_str)
1009        .unwrap_or("app");
1010    scope_named(name).ok_or_else(|| format!("no value scope `{name}`"))
1011}
1012
1013impl Plugin for AdminPlugin {
1014    fn id(&self) -> PluginId {
1015        PluginId::from_static("egui_pop.admin")
1016    }
1017
1018    fn title(&self) -> String {
1019        "Settings app".into()
1020    }
1021
1022    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1023        let service = Admin::new();
1024        crate::settings_window::register_kinds(&service);
1025        transfer::hooks(&service);
1026        ctx.service(&ADMIN, service)?;
1027        if let Some(admin) = ctx.app().service(&ADMIN) {
1028            window::listen(&ctx.app(), admin);
1029        }
1030        ctx.local_scope(
1031            SURFACE,
1032            StoreScope::new(egui_pop_model::history::SETTINGS, "Settings"),
1033        );
1034        ctx.setting(
1035            WINDOW,
1036            Descriptor::bool("Settings in their own window", false).description(
1037                "Opens the settings in a window of their own rather than over the main window.",
1038            ),
1039        )?;
1040        lock(&ctx.app().store())
1041            .declare(
1042                ctx.owner(),
1043                NAV_WIDTH,
1044                Descriptor::float(
1045                    "Settings sections width",
1046                    0.0,
1047                    4096.0,
1048                    f64::from(NAV_WIDTH_DEFAULT),
1049                ),
1050            )
1051            .map_err(|e| PluginError::Failed(format!("{NAV_WIDTH}: {e:?}")))?;
1052        ctx.command(
1053            CommandSpec::new(CMD_OPEN, "Settings", "File")
1054                .icon("settings")
1055                .description(
1056                    "Every setting as full pages: families and their sections in a tree on the side, one search.",
1057                )
1058                .args(json!({ "path": "", "key": "", "mode": "", "wizard": "" })),
1059            |call| {
1060                let a = admin(call)?;
1061                // A wizard: its own page.
1062                if let Some(id) = call
1063                    .args
1064                    .get("wizard")
1065                    .and_then(Json::as_str)
1066                    .filter(|w| !w.is_empty())
1067                {
1068                    return a.open_wizard(call.app, id, None, Default::default());
1069                }
1070                if let Some(mode) = call.args.get("mode").and_then(Json::as_str)
1071                    && !mode.is_empty()
1072                {
1073                    let window = match mode {
1074                        "window" => true,
1075                        "overlay" => false,
1076                        other => return Err(format!("no mode `{other}`")),
1077                    };
1078                    a.set_in(call.app, ValueScope::App, &WINDOW, json!(window))?;
1079                }
1080                // A path first, else a setting id alone.
1081                let place = ["path", "key"].iter().find_map(|k| {
1082                    call.args
1083                        .get(*k)
1084                        .and_then(Json::as_str)
1085                        .filter(|p| !p.is_empty())
1086                });
1087                a.open(call.app, place)?;
1088                let (scope, section, _) = a.shown();
1089                Ok(json!({ "open": true, "scope": scope, "section": section, "window": in_window(call.app) }))
1090            },
1091        )?;
1092        ctx.command(
1093            CommandSpec::new(CMD_CLOSE, "Close settings", "File").hidden(),
1094            |call| {
1095                admin(call)?.close(call.app);
1096                Ok(json!({ "open": false }))
1097            },
1098        )?;
1099        ctx.command(
1100            CommandSpec::new(CMD_POP_OUT, "Settings: pop out", "File")
1101                .description(
1102                    "Moves the settings between the main window and a window of their own.",
1103                )
1104                .hidden(),
1105            |call| {
1106                let window = !in_window(call.app);
1107                admin(call)?.set_in(call.app, ValueScope::App, &WINDOW, json!(window))?;
1108                Ok(json!({ "window": window }))
1109            },
1110        )?;
1111        ctx.command(
1112            CommandSpec::new(CMD_SET, "Set a setting in a value scope", "File")
1113                .hidden()
1114                .args(json!({ "key": "", "scope": "app", "value": null })),
1115            |call| {
1116                let id = key_arg(call)?;
1117                let scope = scope_arg(call)?;
1118                let value = call
1119                    .args
1120                    .get("value")
1121                    .cloned()
1122                    .ok_or("`value` is missing")?;
1123                admin(call)?.set_in(call.app, scope, &id, value)?;
1124                Ok(json!({ "key": id.as_str(), "scope": scope.name() }))
1125            },
1126        )?;
1127        ctx.command(
1128            CommandSpec::new(CMD_RESET, "Reset a setting in a value scope", "File")
1129                .hidden()
1130                .args(json!({ "key": "", "scope": "app" })),
1131            |call| {
1132                let id = key_arg(call)?;
1133                let scope = scope_arg(call)?;
1134                admin(call)?.clear_in(call.app, scope, &id)?;
1135                Ok(json!({ "key": id.as_str(), "scope": scope.name() }))
1136            },
1137        )?;
1138        wizard::commands(ctx)?;
1139        transfer::commands(ctx)?;
1140        quick::commands(ctx)?;
1141        focus::commands(ctx)?;
1142        ctx.block(
1143            zones::OVERLAYS,
1144            Block::add(BlockId::from_static("egui_pop.admin"), 6, shell::show),
1145        );
1146        // Drawn in every window, shown in its own.
1147        ctx.block(
1148            zones::WINDOW_OVERLAYS,
1149            Block::add(BlockId::from_static("egui_pop.admin.quick"), 1, quick::show),
1150        );
1151        let w = ctx.app().downgrade();
1152        ctx.collector(
1153            egui_pop_core::debug::FnCollector::new(
1154                "admin",
1155                "The administration app (Settings as full pages): open or not, the mode, the scope, section and search shown, the value scopes offered, the values set above the app layer and their origin, the resolved tree (scopes, sections, items) and the diagnostics of its manifests.",
1156            )
1157            .snapshot(move |_| match w.get() {
1158                Ok(app) => describe(&app),
1159                Err(_) => Json::Null,
1160            }),
1161        )?;
1162        Ok(())
1163    }
1164}
1165
1166/// What the `admin` collector shows.
1167fn describe(app: &AppHandle) -> Json {
1168    let Some(a) = app.service(&ADMIN) else {
1169        return Json::Null;
1170    };
1171    let tree = a.tree(app);
1172    let (scope, section, filter) = a.shown();
1173    let layers = a.layers();
1174    let mut origins = BTreeMap::new();
1175    for (_, f) in tree.fields() {
1176        if let Some(id) = f.setting_id() {
1177            let o = layers.origin(&format!("settings/{id}"));
1178            if o != ValueScope::App {
1179                origins.insert(id.to_string(), o.name());
1180            }
1181        }
1182    }
1183    json!({
1184        "open": a.is_open(),
1185        "window": in_window(app),
1186        "scope": scope,
1187        "section": section,
1188        "filter": filter,
1189        "marked": a.marked(),
1190        "offered": a.offered().iter().map(|s| s.name()).collect::<Vec<_>>(),
1191        "origins": origins,
1192        "tree": tree,
1193        "wizard": a.wizard_state(app),
1194        "quick": a.quick_settings(app),
1195        "focus": focus::state(app, &a),
1196        "recent": a.recent_settings(app, quick::now()),
1197        "lastFinished": a.last_finished(),
1198        "hooks": a.hooks().list().into_iter().map(|(n, k)| json!({"name": n, "kind": k})).collect::<Vec<_>>(),
1199        "diagnostics": a.diagnostics().all().iter().map(|d| json!({"code": d.code, "subject": d.subject, "message": d.message})).collect::<Vec<_>>(),
1200    })
1201}