Skip to main content

egui_pop_api/
mounts.rs

1//! The mount contract in the application (ADR 0013): the hosts this
2//! crate builds and what each offers, the components of this crate and
3//! of `egui-pop-core` and what each needs, the components and hosts an
4//! application declares ([`Ctx::mountable`], [`Ctx::host_offer`]), and
5//! the questions agents and code ask:
6//!
7//! - [`AppHandle::where_can`]: every host and the verdict for a
8//!   component;
9//! - [`AppHandle::mount`]: a component put in a host, recorded with its
10//!   conditions, or refused with its rule (reported, ADR 0003);
11//! - the debug bridge's `mounts` collector: the declarations, what is
12//!   mounted where, and the `where_can` and `check` actions.
13//!
14//! ```
15//! use egui_pop_api::{App, mounts};
16//!
17//! let app = App::builder().build(&egui::Context::default()).unwrap();
18//! let verdicts = app.handle().where_can(mounts::JOBS_CENTRE).unwrap();
19//! let status_bar = verdicts.iter().find(|v| v.host == mounts::STATUS_BAR).unwrap();
20//! assert_eq!(status_bar.fit.cell(), "D1");
21//! ```
22
23use egui_pop_model::diagnostics::{Diagnostic, Level};
24use egui_pop_model::ids::OwnerId;
25use egui_pop_model::mount::{
26    self, ClaimKey, Dismiss, Fit, FocusPolicy, HostDisplay, HostOffer, HostSize, Keep, Keyboard,
27    Lifetime, Mountable, Window,
28};
29use egui_pop_model::panels::{PanelHost, Place};
30use serde::Serialize;
31use serde_json::{Value as Json, json};
32use std::cell::RefCell;
33
34use crate::app::{AppHandle, WeakApp};
35use crate::ctx::Ctx;
36
37/// A docked panel: a tab in an area.
38pub const PANEL: &str = "panel";
39/// A floating palette.
40pub const PALETTE: &str = "palette";
41/// A panel detached into an auxiliary window.
42pub const WINDOW: &str = "window";
43/// A dialog of the four kinds (`Confirm`, `Form`, `Choose`, `Info`).
44pub const DIALOG: &str = "dialog";
45/// A custom dialog: a body of its own, the dialog rules kept
46/// ([`crate::dialogs::Custom`]).
47pub const CUSTOM_DIALOG: &str = "dialog.custom";
48/// A raw modal overlay, drawn from a block of the `OVERLAYS` zone.
49pub const MODAL: &str = "modal";
50/// A popover anchored to something.
51pub const POPOVER: &str = "popover";
52/// A block of a line zone (the top bar, the caption, the activity bar).
53pub const LINE: &str = "line";
54/// The status bar.
55pub const STATUS_BAR: &str = "status-bar";
56/// A custom page of the settings window
57/// ([`crate::settings_pages::SettingsPage`]).
58pub const SETTINGS_PAGE: &str = "settings.page";
59/// A gallery story.
60pub const STORY: &str = "story";
61
62/// The value-descriptor sliders (`egui_pop_core::slider`).
63pub const SLIDERS: &str = "sliders";
64/// Forms of value-descriptor fields.
65pub const FORMS: &str = "forms";
66/// The progress bar and spinner (`egui_pop_core::progress`).
67pub const PROGRESS: &str = "progress";
68/// The jobs centre ([`crate::jobs_centre`]).
69pub const JOBS_CENTRE: &str = "jobs-centre";
70/// The theme editor ([`crate::theme_editor`]).
71pub const THEME_EDITOR: &str = "theme-editor";
72/// The tip of the day and hints ([`crate::tips`]).
73pub const TIPS: &str = "tips";
74
75/// A docked panel: the area's whole rect, resized by the user.
76pub fn panel() -> HostOffer {
77    HostOffer::new(PANEL, "P", "Docked panel")
78        .source("Ctx::panel, PanelSpec, workbench")
79        .resizable(true)
80        .keeps(&[Keep::Place])
81        .display(HostDisplay::Wide)
82        .hides_content(true)
83}
84
85/// A floating palette: a bounded width, the content's height, until the
86/// user resizes it (the size kept in the layout).
87pub fn palette() -> HostOffer {
88    HostOffer::new(PALETTE, "F", "Floating palette")
89        .source("palettes")
90        .size(HostSize::Content)
91        .resizable(true)
92        .focus(FocusPolicy::ClickInto)
93        .keeps(&[Keep::Place, Keep::Size])
94        .hides_content(true)
95}
96
97/// An auxiliary window: a detachable panel in a window of its own.
98pub fn window() -> HostOffer {
99    HostOffer::new(WINDOW, "W", "Auxiliary window")
100        .source("workbench::windows, show_viewport_immediate")
101        .resizable(true)
102        .window(Window::Auxiliary)
103        .keeps(&[Keep::Place, Keep::Size])
104        .cursor_images(false)
105        .headless(false)
106}
107
108/// A dialog of the four kinds: descriptors, no free content.
109pub fn dialog() -> HostOffer {
110    HostOffer::new(DIALOG, "D", "Dialog (four kinds)")
111        .source("dialogs: Confirm, Form, Choose, Info")
112        .size(HostSize::Content)
113        .focus(FocusPolicy::ModalExclusive)
114        .owns_keys(&[ClaimKey::Enter, ClaimKey::Escape])
115        .dismissed_by(&[Dismiss::Answer, Dismiss::Escape])
116        .lifetime(Lifetime::Transient)
117        .keeps(&[Keep::Place])
118        .gives_app(false)
119        .scope(false)
120        .fault_boundary(false)
121        .free_content(false)
122}
123
124/// A raw modal overlay: any `Ui`, none of the dialog rules.
125pub fn modal() -> HostOffer {
126    HostOffer::new(MODAL, "M", "Raw modal")
127        .source("overlay::show with Kind::Modal")
128        .size(HostSize::Content)
129        .focus(FocusPolicy::ModalExclusive)
130        .owns_keys(&[ClaimKey::Escape])
131        .dismissed_by(&[Dismiss::Escape])
132        .lifetime(Lifetime::Transient)
133        .scope(false)
134}
135
136/// A popover: next to its anchor, closed by Escape or a click outside.
137pub fn popover() -> HostOffer {
138    HostOffer::new(POPOVER, "O", "Popover")
139        .source("overlay::show with Kind::Popover, egui::Popup")
140        .size(HostSize::Content)
141        .owns_keys(&[ClaimKey::Escape])
142        .dismissed_by(&[Dismiss::Escape, Dismiss::OutsideClick])
143        .lifetime(Lifetime::Transient)
144        .scope(false)
145        .fault_boundary(false)
146}
147
148/// A block of a line zone.
149pub fn line() -> HostOffer {
150    HostOffer::new(LINE, "L", "Line zone")
151        .source("zones: TOP_BAR, TOP_BAR_END, TITLE_BAR, ACTIVITY_BAR")
152        .size(HostSize::Row)
153}
154
155/// The status bar.
156pub fn status_bar() -> HostOffer {
157    HostOffer::new(STATUS_BAR, "S", "Status bar")
158        .source("zones: STATUS_BAR, strips")
159        .size(HostSize::Row)
160}
161
162/// A gallery story: drawn by the gallery in its main zone.
163pub fn story() -> HostOffer {
164    HostOffer::new(STORY, "G", "Gallery story")
165        .source("Ctx::story, Story")
166        .resizable(true)
167        .display(HostDisplay::Wide)
168}
169
170/// The hosts of this crate, in the order of `docs/hosts.md`'s columns
171/// (the viewport's overlays are `egui-pop-viewport`'s).
172pub fn hosts() -> Vec<HostOffer> {
173    vec![
174        panel(),
175        palette(),
176        window(),
177        dialog(),
178        crate::dialogs::custom_host(),
179        modal(),
180        popover(),
181        line(),
182        status_bar(),
183        crate::settings_pages::host(),
184        story(),
185    ]
186}
187
188/// A panel's host for a place: the panel's offer in an area, the
189/// palette's floating, the window's detached.
190pub fn panel_host(place: Place) -> PanelHost {
191    let offer = match place {
192        Place::Area(_) => panel(),
193        Place::Floating => palette(),
194        Place::Window => window(),
195    };
196    PanelHost { place, offer }
197}
198
199/// Sliders: a value dragged, typed or stepped.
200pub fn sliders() -> Mountable {
201    Mountable::new(SLIDERS, "Sliders")
202        .crate_name("egui-pop-core")
203        .claims(&[ClaimKey::Enter, ClaimKey::Escape])
204        .drag()
205        .min(120.0, 20.0)
206        .role("slider")
207        .descriptor_field()
208}
209
210/// Forms: one row per value-descriptor field.
211pub fn forms() -> Mountable {
212    Mountable::new(FORMS, "Forms")
213        .crate_name("egui-pop-core")
214        .claims(&[ClaimKey::Enter])
215        .min(200.0, 48.0)
216        .popups()
217        .role("form")
218        .descriptor_field()
219}
220
221/// The progress bar and spinner: not interactive.
222pub fn progress() -> Mountable {
223    Mountable::new(PROGRESS, "Progress")
224        .crate_name("egui-pop-core")
225        .keyboard(Keyboard::None)
226        .min(40.0, 4.0)
227        .preferred(200.0, 8.0)
228        .role("progressbar")
229        .preview()
230}
231
232/// The jobs centre: one per application, from the host's journal.
233pub fn jobs_centre() -> Mountable {
234    Mountable::new(JOBS_CENTRE, "Jobs centre")
235        .crate_name("egui-pop-api")
236        .keymap()
237        .min(240.0, 120.0)
238        .fills()
239        .single()
240        .needs_app()
241        .role("list")
242}
243
244/// The theme editor: one draft per application.
245pub fn theme_editor() -> Mountable {
246    Mountable::new(THEME_EDITOR, "Theme editor")
247        .crate_name("egui-pop-api")
248        .keymap()
249        .min(520.0, 320.0)
250        .fills()
251        .single()
252        .needs_app()
253        .session()
254        .popups()
255        .role("form")
256}
257
258/// The tip of the day and hints.
259pub fn tips() -> Mountable {
260    Mountable::new(TIPS, "Tips")
261        .crate_name("egui-pop-api")
262        .min(240.0, 80.0)
263        .needs_app()
264        .role("group")
265}
266
267/// The components of this crate and of `egui-pop-core`.
268pub fn components() -> Vec<Mountable> {
269    vec![
270        sliders(),
271        forms(),
272        progress(),
273        jobs_centre(),
274        theme_editor(),
275        tips(),
276    ]
277}
278
279/// A host's verdict for a component.
280#[derive(Clone, Debug, PartialEq, Serialize)]
281pub struct Placement {
282    /// The host's id.
283    pub host: String,
284    /// Its column (`P`, `F`...).
285    pub code: String,
286    pub name: String,
287    pub fit: Fit,
288}
289
290/// A component mounted in a host.
291#[derive(Clone, Debug, PartialEq, Serialize)]
292pub struct Mounted {
293    pub component: String,
294    pub host: String,
295    pub fit: Fit,
296}
297
298/// What the application declared, and what is mounted: each mount with
299/// the owner that mounted it (the plugin whose command, connection or
300/// handler was running), when one was.
301#[derive(Debug, Default)]
302pub(crate) struct Registry {
303    components: RefCell<Vec<(OwnerId, Mountable)>>,
304    hosts: RefCell<Vec<(OwnerId, HostOffer)>>,
305    mounted: RefCell<Vec<(Option<OwnerId>, Mounted)>>,
306}
307
308/// What went with an owner ([`remove_owner`]).
309#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
310pub(crate) struct RemovedMounts {
311    pub components: usize,
312    pub hosts: usize,
313    pub mounts: usize,
314}
315
316/// Removes what an owner declared and mounted (ADR 0028): its components
317/// and host offers, the mounts it made, and the mounts of its components
318/// or in its hosts, whoever made them.
319pub(crate) fn remove_owner(app: &AppHandle, owner: &OwnerId) -> RemovedMounts {
320    let registry = app.mount_registry();
321    let mut components = registry.components.borrow_mut();
322    let mut hosts = registry.hosts.borrow_mut();
323    let mut mounted = registry.mounted.borrow_mut();
324    let its_components: Vec<String> = (components.iter())
325        .filter(|(o, _)| o == owner)
326        .map(|(_, m)| m.id.clone())
327        .collect();
328    let its_hosts: Vec<String> = (hosts.iter())
329        .filter(|(o, _)| o == owner)
330        .map(|(_, h)| h.id.clone())
331        .collect();
332    components.retain(|(o, _)| o != owner);
333    hosts.retain(|(o, _)| o != owner);
334    let before = mounted.len();
335    mounted.retain(|(by, m)| {
336        by.as_ref() != Some(owner)
337            && !its_components.contains(&m.component)
338            && !its_hosts.contains(&m.host)
339    });
340    RemovedMounts {
341        components: its_components.len(),
342        hosts: its_hosts.len(),
343        mounts: before - mounted.len(),
344    }
345}
346
347impl AppHandle {
348    fn mount_registry(&self) -> std::rc::Rc<Registry> {
349        self.local::<Registry>()
350    }
351
352    /// Whether what `owner` declared still counts (the framework, or a
353    /// connected plugin).
354    pub(crate) fn owner_connected(&self, owner: &OwnerId) -> bool {
355        *owner == OwnerId::FRAMEWORK
356            || self
357                .plugins()
358                .iter()
359                .any(|p| p.connected && OwnerId::from(&p.id) == *owner)
360    }
361
362    /// Every component declared: this crate's and `egui-pop-core`'s,
363    /// then those of the connected plugins.
364    pub fn mountables(&self) -> Vec<Mountable> {
365        let mut out = components();
366        let declared = self.mount_registry().components.borrow().clone();
367        out.extend(
368            declared
369                .into_iter()
370                .filter(|(o, _)| self.owner_connected(o))
371                .map(|(_, m)| m),
372        );
373        out
374    }
375
376    /// Every host: this crate's, then those of the connected plugins
377    /// (the viewport's overlays among them).
378    pub fn host_offers(&self) -> Vec<HostOffer> {
379        let mut out = hosts();
380        let declared = self.mount_registry().hosts.borrow().clone();
381        out.extend(
382            declared
383                .into_iter()
384                .filter(|(o, _)| self.owner_connected(o))
385                .map(|(_, h)| h),
386        );
387        out
388    }
389
390    /// Every host and its verdict for a component (ADR 0013): where it
391    /// fits, under which conditions, and why not elsewhere.
392    pub fn where_can(&self, component: &str) -> Result<Vec<Placement>, String> {
393        let needs = self
394            .mountables()
395            .into_iter()
396            .find(|m| m.id == component)
397            .ok_or_else(|| format!("no component `{component}` is declared"))?;
398        Ok(self
399            .host_offers()
400            .into_iter()
401            .map(|h| Placement {
402                fit: mount::check(&needs, &h),
403                host: h.id,
404                code: h.code,
405                name: h.name,
406            })
407            .collect())
408    }
409
410    /// The verdict for a component in a host, without mounting it.
411    pub fn check_mount(&self, component: &str, host: &str) -> Result<Fit, String> {
412        self.where_can(component)?
413            .into_iter()
414            .find(|p| p.host == host)
415            .map(|p| p.fit)
416            .ok_or_else(|| format!("no host `{host}` is declared"))
417    }
418
419    /// Mounts a component in a host: recorded with its conditions (the
420    /// `mounts` collector shows it), or refused with its rule, reported
421    /// as a diagnostic (`mount-refused`) and returned as the error.
422    pub fn mount(&self, component: &str, host: &str) -> Result<Fit, String> {
423        let fit = match self.check_mount(component, host) {
424            Ok(fit) => fit,
425            Err(e) => {
426                self.report_diagnostic(Diagnostic {
427                    level: Level::Error,
428                    code: "mount-unknown",
429                    owner: None,
430                    subject: format!("{component} in {host}"),
431                    message: format!("{e}; nothing is mounted"),
432                });
433                return Err(e);
434            }
435        };
436        self.record_mount(component, host, fit)
437    }
438
439    /// Mounts a component by its needs in a host by its offer, declared
440    /// or not (a custom dialog's body): recorded, or refused, reported.
441    pub(crate) fn mount_needs(&self, needs: &Mountable, host: &HostOffer) -> Result<Fit, String> {
442        self.record_mount(&needs.id, &host.id, mount::check(needs, host))
443    }
444
445    fn record_mount(&self, component: &str, host: &str, fit: Fit) -> Result<Fit, String> {
446        if let Some(refusal) = fit.refusal() {
447            let reason = refusal.reason();
448            self.report_diagnostic(Diagnostic {
449                level: Level::Error,
450                code: "mount-refused",
451                owner: None,
452                subject: format!("{component} in {host}"),
453                message: format!("{reason}; nothing is mounted"),
454            });
455            return Err(reason);
456        }
457        let registry = self.mount_registry();
458        let mut mounted = registry.mounted.borrow_mut();
459        if !mounted
460            .iter()
461            .any(|(_, m)| m.component == component && m.host == host)
462        {
463            mounted.push((
464                egui_pop_model::values::current_scope(),
465                Mounted {
466                    component: component.into(),
467                    host: host.into(),
468                    fit: fit.clone(),
469                },
470            ));
471        }
472        Ok(fit)
473    }
474
475    /// Takes a component out of a host; `false` when it was not mounted
476    /// there.
477    pub fn unmount(&self, component: &str, host: &str) -> bool {
478        let registry = self.mount_registry();
479        let mut mounted = registry.mounted.borrow_mut();
480        let before = mounted.len();
481        mounted.retain(|(_, m)| !(m.component == component && m.host == host));
482        mounted.len() != before
483    }
484
485    /// What is mounted where, in mounting order.
486    pub fn mounts(&self) -> Vec<Mounted> {
487        (self.mount_registry().mounted.borrow().iter())
488            .map(|(_, m)| m.clone())
489            .collect()
490    }
491}
492
493impl Ctx<'_> {
494    /// Declares a component of the plugin's (ADR 0013): what it needs.
495    /// A component of the same id declared by another owner wins: this
496    /// one is ignored, with a diagnostic; declared again by the same
497    /// plugin (connected again), it replaces its own.
498    pub fn mountable(&mut self, needs: Mountable) -> &mut Self {
499        let registry = self.app.local::<Registry>();
500        let builtin = components().iter().any(|m| m.id == needs.id);
501        let ok = declare(
502            &mut registry.components.borrow_mut(),
503            &self.owner,
504            builtin,
505            needs.id.clone(),
506            needs,
507            |m| m.id.as_str(),
508        );
509        if let Err(id) = ok {
510            self.app
511                .report_diagnostic(duplicate(&self.owner, id, "component"));
512        }
513        self
514    }
515
516    /// Declares a host of the plugin's (ADR 0013): what it offers, with
517    /// the same rule for a second declaration of an id.
518    pub fn host_offer(&mut self, offer: HostOffer) -> &mut Self {
519        let registry = self.app.local::<Registry>();
520        let builtin = hosts().iter().any(|h| h.id == offer.id);
521        let ok = declare(
522            &mut registry.hosts.borrow_mut(),
523            &self.owner,
524            builtin,
525            offer.id.clone(),
526            offer,
527            |h| h.id.as_str(),
528        );
529        if let Err(id) = ok {
530            self.app
531                .report_diagnostic(duplicate(&self.owner, id, "host"));
532        }
533        self
534    }
535}
536
537/// Adds a declaration, or replaces the owner's own of the same id;
538/// `Err(id)` when the id is another owner's (or built in).
539fn declare<T>(
540    list: &mut Vec<(OwnerId, T)>,
541    owner: &OwnerId,
542    builtin: bool,
543    id: String,
544    item: T,
545    id_of: impl Fn(&T) -> &str,
546) -> Result<(), String> {
547    if builtin {
548        return Err(id);
549    }
550    match list.iter().position(|(_, t)| id_of(t) == id) {
551        Some(i) if list[i].0 == *owner => {
552            list[i].1 = item;
553            Ok(())
554        }
555        Some(_) => Err(id),
556        None => {
557            list.push((owner.clone(), item));
558            Ok(())
559        }
560    }
561}
562
563fn duplicate(owner: &OwnerId, id: String, what: &str) -> Diagnostic {
564    Diagnostic {
565        level: Level::Warning,
566        code: "duplicate-id",
567        owner: Some(owner.clone()),
568        subject: id,
569        message: format!("a {what} of this id is declared already; this declaration is ignored"),
570    }
571}
572
573/// The `mounts` collector.
574pub(crate) fn collector(app: WeakApp) -> egui_pop_core::debug::FnCollector {
575    let (a, b, c) = (app.clone(), app.clone(), app);
576    egui_pop_core::debug::FnCollector::new(
577        "mounts",
578        "The mount contract (ADR 0013): every component and host declared, what is mounted where with its conditions; `where_can` and `check` give the verdicts.",
579    )
580    .snapshot(move |_| {
581        let Ok(app) = a.get() else { return Json::Null };
582        json!({
583            "components": app.mountables(),
584            "hosts": app.host_offers(),
585            "mounted": app.mounts(),
586        })
587    })
588    .action(
589        "where_can",
590        "Every host and its verdict for a component (`component`).",
591        false,
592        move |_, args| {
593            let app = b.get()?;
594            let id = args
595                .get("component")
596                .and_then(Json::as_str)
597                .ok_or("`component` is missing")?;
598            Ok(json!(app.where_can(id)?))
599        },
600    )
601    .args(json!({ "component": "viewport" }))
602    .action(
603        "check",
604        "The verdict for a component in a host (`component`, `host`), with the reason when it does not fit.",
605        false,
606        move |_, args| {
607            let app = c.get()?;
608            let get = |k: &str| {
609                args.get(k)
610                    .and_then(Json::as_str)
611                    .ok_or_else(|| format!("`{k}` is missing"))
612            };
613            let fit = app.check_mount(get("component")?, get("host")?)?;
614            let reason = fit.refusal().map(mount::Refusal::reason);
615            Ok(json!({ "fit": fit, "cell": fit.cell(), "reason": reason }))
616        },
617    )
618    .args(json!({ "component": "viewport", "host": "dialog.custom" }))
619}