Skip to main content

egui_pop_api/
settings_pages.rs

1//! Custom pages in the settings window (ADR 0013): a page a plugin
2//! draws itself, next to the pages generated from declared settings.
3//!
4//! A page has an id, a title, a place in the tree (under a section or
5//! another page, in an order), keywords the settings search finds it
6//! by, and the settings it edits: those leave the generated sections,
7//! are searched with the page, and its reset takes them back to their
8//! defaults as one undo step, with a hook of its own for what is not a
9//! setting. It is mounted through the mount contract in the settings
10//! page host ([`crate::mounts::SETTINGS_PAGE`]): what its component
11//! needs is checked first, and a refusal is reported (ADR 0003) with
12//! nothing added. Its body is drawn in a focus scope and a fault
13//! boundary, only while it is the page shown.
14//!
15//! Agents see the pages in the `settings_window` collector, and open one
16//! with the `app.settings.page` command (`{"page": "<id>"}`).
17//!
18//! ```
19//! use egui_pop_api::settings_pages::SettingsPage;
20//! use egui_pop_api::{App, Ctx, Plugin, PluginError, DefaultPlugins};
21//! use egui_pop_model::ids::PluginId;
22//!
23//! struct Compute;
24//!
25//! impl Plugin for Compute {
26//!     fn id(&self) -> PluginId {
27//!         PluginId::from_static("compute")
28//!     }
29//!
30//!     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
31//!         ctx.settings_page(
32//!             SettingsPage::new("compute.devices", "Compute")
33//!                 .keywords(&["GPU", "OpenCL", "threads"])
34//!                 .order(10),
35//!             |ui, _app| {
36//!                 ui.label("The devices found, and which one runs what.");
37//!             },
38//!         );
39//!         Ok(())
40//!     }
41//! }
42//!
43//! let app = App::builder()
44//!     .plugins(DefaultPlugins)
45//!     .plugin(Compute)
46//!     .build(&egui::Context::default())
47//!     .unwrap();
48//! let pages = app.handle().settings_pages();
49//! assert_eq!(pages[0].title, "Compute");
50//! assert!(app.handle().mounts().iter().any(|m| m.host == "settings.page"));
51//! ```
52//!
53//! A body is drawn while the settings window holds its own state: it
54//! moves the window by commands (`app.settings`, `app.settings.page`),
55//! which run before the next frame, not through the
56//! [`crate::settings_window::SettingsWindow`] service directly.
57
58use std::cell::RefCell;
59use std::fmt;
60use std::rc::Rc;
61
62use egui::{Role, Ui};
63use egui_pop_core::a11y;
64use egui_pop_core::lock;
65use egui_pop_core::strings;
66use egui_pop_model::commands::Origin;
67use egui_pop_model::diagnostics::{Diagnostic, Level};
68use egui_pop_model::fuzzy;
69use egui_pop_model::ids::{OwnerId, SettingId};
70use egui_pop_model::mount::{
71    ClaimKey, Dismiss, FocusPolicy, HostOffer, HostSize, Lifetime, Mountable,
72};
73use egui_pop_model::values::{Change, Set};
74use serde::Serialize;
75use serde_json::{Value as Json, json};
76
77use crate::app::AppHandle;
78use crate::ctx::Ctx;
79use crate::hooks::SettingEntry;
80use crate::strings as txt;
81
82/// A page's body: drawn every frame the page is shown.
83pub type PageFn = Box<dyn FnMut(&mut Ui, &AppHandle)>;
84
85/// A page's own reset, for what it shows that is not a setting.
86pub type ResetFn = Rc<dyn Fn(&AppHandle)>;
87
88/// Whether a page's own state is away from its defaults.
89pub type ChangedFn = Rc<dyn Fn(&AppHandle) -> bool>;
90
91/// A custom page of the settings window: its place, what finds it, what
92/// it edits and what it needs.
93///
94/// ```
95/// use egui_pop_api::settings_pages::SettingsPage;
96/// use egui_pop_model::ids::SettingId;
97///
98/// let page = SettingsPage::new("app.compute", "Compute")
99///     .under("Performance")
100///     .order(20)
101///     .keywords(&["GPU", "OpenCL"])
102///     .settings(&[SettingId::from_static("app.threads")]);
103/// assert_eq!(page.parent.as_deref(), Some("Performance"));
104/// assert!(page.has_reset());
105/// ```
106#[derive(Clone, Serialize)]
107pub struct SettingsPage {
108    /// A stable id: what `app.settings.page` and
109    /// [`crate::settings_window::SettingsWindow::open`] take.
110    pub id: String,
111    /// As shown in the tree and over the page.
112    pub title: String,
113    /// The section (as the tree names it) or the page (its id) it goes
114    /// under; `None`, or one that does not exist: a page of its own
115    /// after the generated sections.
116    pub parent: Option<String>,
117    /// Its order among the pages of the same parent (lower first, then
118    /// by title).
119    pub order: i32,
120    /// Words the settings search finds it by, besides its title, its
121    /// description and its settings.
122    pub keywords: Vec<String>,
123    /// Said under its title, and searched.
124    pub description: String,
125    /// The declared settings it edits: they leave the generated
126    /// sections, the search finds the page by them, and its reset takes
127    /// them back to their defaults.
128    pub settings: Vec<SettingId>,
129    /// What its component needs, checked against the settings page
130    /// host's offer; `None`: a plain widget (`settings-page:<id>`).
131    pub needs: Option<Mountable>,
132    #[serde(skip)]
133    reset: Option<ResetFn>,
134    #[serde(skip)]
135    changed: Option<ChangedFn>,
136}
137
138impl fmt::Debug for SettingsPage {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        f.debug_struct("SettingsPage")
141            .field("id", &self.id)
142            .field("title", &self.title)
143            .field("parent", &self.parent)
144            .field("order", &self.order)
145            .field("keywords", &self.keywords)
146            .field("settings", &self.settings)
147            .field("reset", &self.reset.is_some())
148            .finish_non_exhaustive()
149    }
150}
151
152impl SettingsPage {
153    pub fn new(id: &str, title: &str) -> Self {
154        Self {
155            id: id.into(),
156            title: title.into(),
157            parent: None,
158            order: 0,
159            keywords: Vec::new(),
160            description: String::new(),
161            settings: Vec::new(),
162            needs: None,
163            reset: None,
164            changed: None,
165        }
166    }
167
168    /// Under a section (as the tree names it: "Appearance") or a page
169    /// (its id).
170    pub fn under(mut self, parent: &str) -> Self {
171        self.parent = Some(parent.into());
172        self
173    }
174
175    pub fn order(mut self, order: i32) -> Self {
176        self.order = order;
177        self
178    }
179
180    pub fn keywords(mut self, words: &[&str]) -> Self {
181        self.keywords.extend(words.iter().map(|w| (*w).to_string()));
182        self
183    }
184
185    pub fn description(mut self, text: &str) -> Self {
186        self.description = text.into();
187        self
188    }
189
190    /// The declared settings it edits.
191    pub fn settings(mut self, ids: &[SettingId]) -> Self {
192        for id in ids {
193            if !self.settings.contains(id) {
194                self.settings.push(id.clone());
195            }
196        }
197        self
198    }
199
200    /// What its component needs (checked when it is mounted).
201    pub fn needs(mut self, needs: Mountable) -> Self {
202        self.needs = Some(needs);
203        self
204    }
205
206    /// Its own reset, for what it shows that is not a setting (run with
207    /// its settings' resets, in the same undo step when it writes to the
208    /// store), and whether that is away from its defaults.
209    pub fn reset_with(
210        mut self,
211        changed: impl Fn(&AppHandle) -> bool + 'static,
212        reset: impl Fn(&AppHandle) + 'static,
213    ) -> Self {
214        self.changed = Some(Rc::new(changed));
215        self.reset = Some(Rc::new(reset));
216        self
217    }
218
219    /// Whether it has a reset (settings, or a reset of its own).
220    pub fn has_reset(&self) -> bool {
221        !self.settings.is_empty() || self.reset.is_some()
222    }
223
224    /// Whether what it edits is away from its defaults.
225    pub fn is_changed(&self, app: &AppHandle) -> bool {
226        let store = app.store();
227        let settings = {
228            let s = lock(&store);
229            self.settings.iter().any(|id| {
230                s.get(&format!("settings/{id}"))
231                    .is_some_and(|x| x.value != x.descriptor.default)
232            })
233        };
234        settings || self.changed.as_ref().is_some_and(|f| f(app))
235    }
236
237    /// Takes what it edits back to its defaults: its settings, then its
238    /// own reset, as one undo step of the settings.
239    pub fn reset(&self, app: &AppHandle) {
240        let store = app.store();
241        let group = lock(&store).begin_group(Origin::User, &format!("Reset {}", self.title));
242        for id in &self.settings {
243            let path = format!("settings/{id}");
244            let _ = lock(&store)
245                .set(Set::new(&path, Change::Reset, Origin::User).by(&OwnerId::FRAMEWORK));
246        }
247        if let Some(f) = &self.reset {
248            f(app);
249        }
250        lock(&store).end(group);
251    }
252
253    /// What its component needs: its own, or a plain widget.
254    pub fn component(&self) -> Mountable {
255        self.needs.clone().unwrap_or_else(|| {
256            Mountable::new(&format!("settings-page:{}", self.id), &self.title)
257                .needs_app()
258                .role("group")
259        })
260    }
261}
262
263/// What the settings page host offers a page (ADR 0013): the form's
264/// width and the content's height in the settings window, a modal
265/// (Escape closes the window), transient, the main window, a focus scope
266/// and a fault boundary, sRGB; its content is not drawn while another
267/// page is shown.
268pub fn host() -> HostOffer {
269    HostOffer::new(crate::mounts::SETTINGS_PAGE, "T", "Settings page")
270        .source("Ctx::settings_page, SettingsPage")
271        .size(HostSize::Content)
272        .focus(FocusPolicy::ModalExclusive)
273        .owns_keys(&[ClaimKey::Escape])
274        .dismissed_by(&[Dismiss::Escape])
275        .lifetime(Lifetime::Transient)
276        .hides_content(true)
277}
278
279struct Entry {
280    owner: OwnerId,
281    page: SettingsPage,
282    /// Taken out while it is drawn.
283    body: Option<PageFn>,
284}
285
286/// The pages declared, in declaration order.
287#[derive(Default)]
288pub(crate) struct Pages(RefCell<Vec<Entry>>);
289
290impl Ctx<'_> {
291    /// Mounts a custom page in the settings window, drawn by `body`
292    /// (see [`crate::settings_pages`]). The page's component is checked
293    /// against the settings page host first; a refusal, an empty id or
294    /// an id another plugin took is reported as a diagnostic and adds
295    /// nothing. Declared again by the same plugin, it replaces its own.
296    pub fn settings_page(
297        &mut self,
298        page: SettingsPage,
299        body: impl FnMut(&mut Ui, &AppHandle) + 'static,
300    ) -> &mut Self {
301        let app = self.app.clone();
302        if page.id.trim().is_empty() {
303            app.report_diagnostic(Diagnostic {
304                level: Level::Error,
305                code: "settings-page-id",
306                owner: Some(self.owner.clone()),
307                subject: page.title.clone(),
308                message: "a settings page needs an id; nothing is added".into(),
309            });
310            return self;
311        }
312        let pages = app.local::<Pages>();
313        let taken = pages.0.borrow().iter().any(|e| {
314            e.page.id == page.id && e.owner != self.owner && app.owner_connected(&e.owner)
315        });
316        if taken {
317            app.report_diagnostic(Diagnostic {
318                level: Level::Warning,
319                code: "duplicate-id",
320                owner: Some(self.owner.clone()),
321                subject: page.id.clone(),
322                message:
323                    "a settings page of this id is declared already; this declaration is ignored"
324                        .into(),
325            });
326            return self;
327        }
328        if app.mount_needs(&page.component(), &host()).is_err() {
329            return self;
330        }
331        let mut list = pages.0.borrow_mut();
332        list.retain(|e| e.page.id != page.id);
333        list.push(Entry {
334            owner: self.owner.clone(),
335            page,
336            body: Some(Box::new(body)),
337        });
338        self
339    }
340}
341
342impl AppHandle {
343    /// The custom pages of the settings window, of the connected
344    /// plugins, in declaration order.
345    pub fn settings_pages(&self) -> Vec<SettingsPage> {
346        self.local::<Pages>()
347            .0
348            .borrow()
349            .iter()
350            .filter(|e| self.owner_connected(&e.owner))
351            .map(|e| e.page.clone())
352            .collect()
353    }
354
355    /// A custom page by id.
356    pub fn settings_page(&self, id: &str) -> Option<SettingsPage> {
357        self.settings_pages().into_iter().find(|p| p.id == id)
358    }
359}
360
361/// Draws a page's body in a focus scope and a fault boundary; `false`
362/// when no page has that id.
363pub(crate) fn draw(ui: &mut Ui, app: &AppHandle, id: &str) -> bool {
364    let pages = app.local::<Pages>();
365    let taken = {
366        let mut list = pages.0.borrow_mut();
367        list.iter_mut()
368            .find(|e| e.page.id == id)
369            .and_then(|e| e.body.take().map(|b| (b, e.page.title.clone())))
370    };
371    let Some((mut body, title)) = taken else {
372        return false;
373    };
374    egui_pop_core::focus::scope(ui, "settingsPage", &[], |ui| {
375        egui_pop_core::fault::boundary(ui, ("egui_pop.settings.page", id), &title, |ui| {
376            body(ui, app);
377        });
378    });
379    if let Some(e) = pages.0.borrow_mut().iter_mut().find(|e| e.page.id == id) {
380        e.body.get_or_insert(body);
381    }
382    true
383}
384
385/// A line of the settings tree: a section or a page, indented under its
386/// parent.
387#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
388pub(crate) struct Node {
389    /// The section's name, or the page's id.
390    pub key: String,
391    /// 0 at the top, 1 under a parent.
392    pub depth: usize,
393    /// A custom page (not a generated section).
394    pub page: bool,
395}
396
397/// The tree: each section (the shortcuts last) followed by the pages
398/// under it, then the pages of their own each followed by its own; the
399/// pages of a parent by order, then title. A page goes under a section
400/// or a page of its own; under anything else it is a page of its own.
401pub(crate) fn tree(sections: &[String], pages: &[SettingsPage]) -> Vec<Node> {
402    let mut sorted: Vec<&SettingsPage> = pages.iter().collect();
403    sorted.sort_by(|a, b| (a.order, &a.title, &a.id).cmp(&(b.order, &b.title, &b.id)));
404    // A page under no section and no page is a page of its own.
405    let own = |q: &SettingsPage| {
406        q.parent.as_ref().is_none_or(|parent| {
407            !sections.contains(parent) && !pages.iter().any(|r| r.id == *parent)
408        })
409    };
410    // A page goes under a section or a page of its own (one level only).
411    let resolved: Vec<(&SettingsPage, Option<&str>)> = sorted
412        .iter()
413        .map(|p| {
414            let parent = p.parent.as_deref().filter(|parent| {
415                sections.iter().any(|s| s == parent)
416                    || pages
417                        .iter()
418                        .any(|q| q.id == *parent && q.id != p.id && own(q))
419            });
420            (*p, parent)
421        })
422        .collect();
423    let children = |key: &str| -> Vec<Node> {
424        resolved
425            .iter()
426            .filter(|(_, parent)| *parent == Some(key))
427            .map(|(p, _)| Node {
428                key: p.id.clone(),
429                depth: 1,
430                page: true,
431            })
432            .collect()
433    };
434    let mut out = Vec::new();
435    let (last, firsts) = sections
436        .split_last()
437        .map_or((None, sections), |(l, f)| (Some(l), f));
438    for s in firsts {
439        out.push(Node {
440            key: s.clone(),
441            depth: 0,
442            page: false,
443        });
444        out.extend(children(s));
445    }
446    for (p, _) in resolved.iter().filter(|(_, parent)| parent.is_none()) {
447        out.push(Node {
448            key: p.id.clone(),
449            depth: 0,
450            page: true,
451        });
452        out.extend(children(&p.id));
453    }
454    if let Some(s) = last {
455        out.push(Node {
456            key: s.clone(),
457            depth: 0,
458            page: false,
459        });
460        out.extend(children(s));
461    }
462    out
463}
464
465/// The settings no page claims: those the generated sections show.
466pub(crate) fn unclaimed(entries: &[SettingEntry], pages: &[SettingsPage]) -> Vec<SettingEntry> {
467    entries
468        .iter()
469        .filter(|e| !pages.iter().any(|p| p.settings.contains(&e.id)))
470        .cloned()
471        .collect()
472}
473
474/// A page's settings, as declared (those that are).
475pub(crate) fn page_entries<'a>(
476    page: &SettingsPage,
477    entries: &'a [SettingEntry],
478) -> Vec<&'a SettingEntry> {
479    page.settings
480        .iter()
481        .filter_map(|id| entries.iter().find(|e| e.id == *id))
482        .collect()
483}
484
485/// Whether a page matches the search: every word in its title, its
486/// settings' labels (fuzzy), its parent or keywords (fuzzy, as
487/// keywords), or its and its settings' descriptions (by words).
488pub(crate) fn matches(
489    ctx: &egui::Context,
490    page: &SettingsPage,
491    parent_title: &str,
492    entries: &[SettingEntry],
493    filter: &str,
494) -> bool {
495    let mut fields = fuzzy::Fields::new()
496        .label(page.title.as_str())
497        .keyword(parent_title)
498        .keywords(page.keywords.iter().cloned())
499        .description(page.description.as_str());
500    for e in page_entries(page, entries) {
501        let d = crate::settings_window::shown(ctx, e);
502        fields = fields.label(d.label).description(d.description);
503    }
504    fields.find(filter).is_some()
505}
506
507/// The page's reset, greyed at its defaults, and its description.
508pub(crate) fn header(ui: &mut Ui, app: &AppHandle, page: &SettingsPage) {
509    let ctx = ui.ctx().clone();
510    if page.has_reset() {
511        let name = [("page", page.title.as_str())];
512        let changed = page.is_changed(app);
513        let r = ui
514            .add_enabled(
515                changed,
516                egui::Button::new(strings::tr(&ctx, &txt::SETTINGS_RESET_PAGE)).small(),
517            )
518            .on_disabled_hover_text(strings::tr_args(
519                &ctx,
520                &txt::SETTINGS_PAGE_AT_DEFAULT,
521                &name,
522            ));
523        a11y::name(
524            &r,
525            Role::Button,
526            &strings::tr_args(&ctx, &txt::SETTINGS_RESET_PAGE_NAME, &name),
527        );
528        if r.clicked() {
529            page.reset(app);
530        }
531    }
532    if !page.description.is_empty() {
533        ui.weak(&page.description);
534    }
535}
536
537/// A page found by the search: its title, the button opening it, and
538/// its settings that match. Returns whether it was asked open.
539pub(crate) fn search_hit(
540    ui: &mut Ui,
541    app: &AppHandle,
542    page: &SettingsPage,
543    entries: &[SettingEntry],
544    filter: &str,
545) -> bool {
546    let ctx = ui.ctx().clone();
547    let mut open = false;
548    ui.horizontal(|ui| {
549        ui.strong(&page.title);
550        let r = ui.small_button(strings::tr(&ctx, &txt::SETTINGS_OPEN_PAGE));
551        a11y::name(
552            &r,
553            Role::Button,
554            &strings::tr_args(
555                &ctx,
556                &txt::SETTINGS_OPEN_PAGE_NAME,
557                &[("page", &page.title)],
558            ),
559        );
560        open = r.clicked();
561    });
562    if !page.description.is_empty() {
563        ui.weak(&page.description);
564    }
565    for e in page_entries(page, entries) {
566        if crate::settings_window::matches(&ctx, app, e, filter) {
567            crate::settings_window::row(ui, app, e);
568        }
569    }
570    open
571}
572
573/// The pages as the `settings_window` collector shows them.
574pub(crate) fn describe(app: &AppHandle) -> Json {
575    json!(
576        app.settings_pages()
577            .iter()
578            .map(|p| json!({
579                "id": p.id,
580                "title": p.title,
581                "parent": p.parent,
582                "order": p.order,
583                "keywords": p.keywords,
584                "description": p.description,
585                "settings": p.settings,
586                "component": p.component().id,
587                "reset": p.has_reset(),
588                "changed": p.is_changed(app),
589            }))
590            .collect::<Vec<_>>()
591    )
592}
593
594#[cfg(test)]
595mod tests {
596    use super::*;
597
598    fn keys(nodes: &[Node]) -> Vec<(String, usize)> {
599        nodes.iter().map(|n| (n.key.clone(), n.depth)).collect()
600    }
601
602    fn s(v: &[&str]) -> Vec<String> {
603        v.iter().map(|x| (*x).to_string()).collect()
604    }
605
606    #[test]
607    fn pages_go_under_their_parent_by_order_and_title() {
608        let sections = s(&["Appearance", "Editor", "Keyboard shortcuts"]);
609        let pages = [
610            SettingsPage::new("b", "Beta").under("Appearance").order(2),
611            SettingsPage::new("a", "Alpha").under("Appearance").order(2),
612            SettingsPage::new("z", "Zeta").under("Appearance").order(1),
613            SettingsPage::new("k", "Keys").under("Keyboard shortcuts"),
614        ];
615        let t = tree(&sections, &pages);
616        assert_eq!(
617            keys(&t),
618            [
619                ("Appearance".into(), 0),
620                ("z".into(), 1),
621                ("a".into(), 1),
622                ("b".into(), 1),
623                ("Editor".into(), 0),
624                ("Keyboard shortcuts".into(), 0),
625                ("k".into(), 1),
626            ]
627        );
628        assert!(t[1].page && !t[0].page);
629    }
630
631    #[test]
632    fn pages_of_their_own_come_before_the_shortcuts_with_their_children() {
633        let sections = s(&["Appearance", "Keyboard shortcuts"]);
634        let pages = [
635            SettingsPage::new("compute", "Compute").order(5),
636            SettingsPage::new("devices", "Devices").under("compute"),
637            SettingsPage::new("lost", "Lost").under("Nowhere"),
638            SettingsPage::new("deep", "Deep").under("devices"),
639        ];
640        assert_eq!(
641            keys(&tree(&sections, &pages)),
642            [
643                ("Appearance".into(), 0),
644                ("deep".into(), 0),
645                ("lost".into(), 0),
646                ("compute".into(), 0),
647                ("devices".into(), 1),
648                ("Keyboard shortcuts".into(), 0),
649            ]
650        );
651    }
652
653    #[test]
654    fn a_page_without_settings_or_a_reset_of_its_own_has_no_reset() {
655        let page = SettingsPage::new("p", "Page");
656        assert!(!page.has_reset());
657        let page = page.reset_with(|_| true, |_| {});
658        assert!(page.has_reset());
659        assert_eq!(page.component().id, "settings-page:p");
660    }
661}