Skip to main content

egui_pop_api/
ctx.rs

1//! `Ctx`: what a plugin registers through, at connect time. One fluent
2//! facade: `command`, `keybinding`, `menu_item`, `panel`, `zone`,
3//! `block`, `setting`, `service`, `on`, `hook`, `story`. Everything is
4//! owned by the plugin.
5
6use std::fmt;
7use std::rc::Rc;
8use std::sync::Arc;
9
10use egui::Ui;
11use egui_pop_core::binding::SharedStore;
12use egui_pop_core::strings::{self, StrKey};
13use egui_pop_model::commands::{CommandSpec, RegisterError};
14use egui_pop_model::ids::{CommandId, MenuId, OwnerId, PanelId, PluginId, SettingId, ZoneId};
15use egui_pop_model::keymap::{Action, BindOptions, Layer};
16use egui_pop_model::menus::MenuItem;
17use egui_pop_model::panels::PanelSpec;
18use egui_pop_model::values::{Applied, DeclareError, Descriptor, Refused, Set};
19use serde_json::Value as Json;
20
21use crate::app::{AppHandle, Call, CommandFn, Registries};
22use crate::hooks::{Hook, LifecycleFn, On};
23use crate::services::ServiceToken;
24use crate::stories::Story;
25use crate::strings as txt;
26use crate::zones::Block;
27
28/// A registration refused.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum CtxError {
31    Command(RegisterError),
32    /// A key binding that does not parse.
33    Keys {
34        keys: String,
35        error: String,
36    },
37    Menu(String),
38    Panel(String),
39    /// The zone is declared already.
40    Zone {
41        zone: ZoneId,
42        by: OwnerId,
43    },
44    /// A setting or a value the store refused to declare (`Ctx::setting`,
45    /// `Ctx::value`).
46    Setting(DeclareError),
47    Service {
48        id: String,
49        by: OwnerId,
50    },
51    Story {
52        id: String,
53        by: OwnerId,
54    },
55    Hook {
56        id: String,
57        by: OwnerId,
58    },
59    /// The step is declared already.
60    Step {
61        id: String,
62        by: OwnerId,
63    },
64    /// A debug bridge collector of that name exists.
65    Collector(String),
66    /// A frame of the context stack the owner refused (its id is taken,
67    /// a mode has no group, no context stack).
68    Frame(String),
69    /// A clipboard type, transform or sanitiser declared already.
70    Clipboard(String),
71}
72
73impl fmt::Display for CtxError {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        match self {
76            CtxError::Command(e) => write!(f, "{e}"),
77            CtxError::Keys { keys, error } => write!(f, "key binding `{keys}`: {error}"),
78            CtxError::Menu(e) | CtxError::Panel(e) => write!(f, "{e}"),
79            CtxError::Zone { zone, by } => write!(f, "zone `{zone}` is already declared by `{by}`"),
80            CtxError::Setting(e) => write!(f, "{e}"),
81            CtxError::Collector(e) | CtxError::Frame(e) | CtxError::Clipboard(e) => {
82                write!(f, "{e}")
83            }
84            CtxError::Service { id, by } => {
85                write!(f, "service `{id}` is already provided by `{by}`")
86            }
87            CtxError::Story { id, by } => {
88                write!(f, "story `{id}` is already contributed by `{by}`")
89            }
90            CtxError::Hook { id, by } => write!(f, "hook `{id}` is already registered by `{by}`"),
91            CtxError::Step { id, by } => write!(f, "step `{id}` is already declared by `{by}`"),
92        }
93    }
94}
95
96impl std::error::Error for CtxError {}
97
98/// Writes to the value store as one plugin (`Ctx::writer`): each write
99/// names the plugin as its scope, checked against the path's writers
100/// (`Descriptor::writers`). Cheap to clone, to keep in a panel, a block
101/// or a thread.
102#[derive(Clone)]
103pub struct ValueWriter {
104    store: SharedStore,
105    scope: OwnerId,
106}
107
108impl fmt::Debug for ValueWriter {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        f.debug_struct("ValueWriter")
111            .field("scope", &self.scope)
112            .finish_non_exhaustive()
113    }
114}
115
116impl ValueWriter {
117    /// A writer for `scope` over a store.
118    pub fn new(store: SharedStore, scope: OwnerId) -> Self {
119        Self { store, scope }
120    }
121
122    /// Applies a write as this plugin (a scope the write names is
123    /// replaced).
124    pub fn set(&self, set: Set) -> Result<Applied, Refused> {
125        egui_pop_core::lock(&self.store).set(set.by(&self.scope))
126    }
127
128    /// The scope its writes name.
129    pub fn scope(&self) -> &OwnerId {
130        &self.scope
131    }
132}
133
134/// What a plugin registers through.
135pub struct Ctx<'a> {
136    pub(crate) owner: OwnerId,
137    pub(crate) plugin: PluginId,
138    pub(crate) rank: usize,
139    pub(crate) reg: &'a mut Registries,
140    pub(crate) app: &'a AppHandle,
141    pub(crate) connected: &'a [PluginId],
142}
143
144impl fmt::Debug for Ctx<'_> {
145    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146        f.debug_struct("Ctx").field("plugin", &self.plugin).finish()
147    }
148}
149
150impl<'a> Ctx<'a> {
151    /// The plugin registering.
152    pub fn plugin(&self) -> &PluginId {
153        &self.plugin
154    }
155
156    /// The owner its registrations are tagged with.
157    pub fn owner(&self) -> &OwnerId {
158        &self.owner
159    }
160
161    /// The application, to keep in closures (blocks, handlers).
162    pub fn app(&self) -> AppHandle {
163        self.app.clone()
164    }
165
166    /// Writes to the value store as this plugin, to keep in closures:
167    /// a write to a path it may not write (one it neither owns nor is
168    /// named a writer of) is refused. Writes made while it connects and
169    /// in its command handlers and lifecycle hooks name it already.
170    pub fn writer(&self) -> ValueWriter {
171        ValueWriter::new(self.app.store(), self.owner.clone())
172    }
173
174    /// Registers an SVG icon of this plugin under `<plugin-id>:<name>`
175    /// (`my-plugin:mask-circle`), the name its declarations then use
176    /// (`CommandSpec::icon`, `PanelSpec::icon`). Needs the `svg` feature
177    /// of `egui-pop-core`.
178    pub fn icon(
179        &mut self,
180        name: &str,
181        svg: impl Into<std::sync::Arc<[u8]>>,
182        paint: egui_pop_core::icon_set::Paint,
183    ) -> Result<egui_pop_core::icon::Icon, egui_pop_core::icon_set::IconError> {
184        egui_pop_core::icon_set::register_for(self.plugin.as_str(), name, svg, paint)
185    }
186
187    /// Whether another plugin is connected.
188    pub fn is_connected(&self, plugin: &PluginId) -> bool {
189        self.connected.contains(plugin)
190    }
191
192    /// Declares a command and everything derived from it (its default
193    /// key bindings, its menu entries, its palette entry and its agent
194    /// surface), with an in-process handler: the default `LocalHost`
195    /// runs it on the interface thread.
196    pub fn command(
197        &mut self,
198        spec: CommandSpec,
199        handler: impl Fn(&Call<'_>) -> Result<Json, String> + 'static,
200    ) -> Result<&mut Self, CtxError> {
201        let handler: CommandFn = Rc::new(handler);
202        self.add_command(spec, Some(handler))
203    }
204
205    /// Declares a command the application's host runs (`AppBuilder::host`):
206    /// keys, menus, palette and traces as for [`Ctx::command`], no
207    /// handler here.
208    pub fn declare(&mut self, spec: CommandSpec) -> Result<&mut Self, CtxError> {
209        self.add_command(spec, None)
210    }
211
212    fn add_command(
213        &mut self,
214        spec: CommandSpec,
215        handler: Option<CommandFn>,
216    ) -> Result<&mut Self, CtxError> {
217        add_command(self.reg, &self.owner, spec, handler)?;
218        Ok(self)
219    }
220
221    /// Binds keys to a command (`layer` defaults: use `Layer::Default`
222    /// for a plugin's own, `Layer::Suggestion` for a soft one).
223    pub fn keybinding(
224        &mut self,
225        keys: &str,
226        command: CommandId,
227        when: &str,
228        layer: Layer,
229    ) -> Result<&mut Self, CtxError> {
230        self.reg
231            .keymap
232            .borrow_mut()
233            .bind(&self.owner, layer, keys, Action::Run(command), when)
234            .map_err(|error| CtxError::Keys {
235                keys: keys.into(),
236                error,
237            })?;
238        Ok(self)
239    }
240
241    /// Binds keys to a command, listening as `options` say (on a
242    /// surface, while typing, through modals).
243    pub fn keybinding_with(
244        &mut self,
245        keys: &str,
246        command: CommandId,
247        when: &str,
248        layer: Layer,
249        options: BindOptions,
250    ) -> Result<&mut Self, CtxError> {
251        self.reg
252            .keymap
253            .borrow_mut()
254            .bind_with(
255                &self.owner,
256                layer,
257                keys,
258                Action::Run(command),
259                when,
260                options,
261            )
262            .map_err(|error| CtxError::Keys {
263                keys: keys.into(),
264                error,
265            })?;
266        Ok(self)
267    }
268
269    /// Unbinds keys (in the layers below `layer`).
270    pub fn unbind(&mut self, keys: &str, layer: Layer) -> Result<&mut Self, CtxError> {
271        self.reg
272            .keymap
273            .borrow_mut()
274            .bind(&self.owner, layer, keys, Action::Unbind, "")
275            .map_err(|error| CtxError::Keys {
276                keys: keys.into(),
277                error,
278            })?;
279        Ok(self)
280    }
281
282    /// Sets the icon of a command, whoever declared it (one of
283    /// egui-pop's own, another plugin's): `icon` and `icon_on` (shown
284    /// while its `checked` clause holds; `None` for none) replace the
285    /// declared ones on every surface running the command. The last
286    /// plugin to set one wins; it goes with the plugin. A command not
287    /// declared is reported (`unknown-command`); names are checked as a
288    /// declaration's (`unknown-icon`).
289    pub fn command_icon(
290        &mut self,
291        command: CommandId,
292        icon: &str,
293        icon_on: Option<&str>,
294    ) -> &mut Self {
295        self.reg.command_icons.push(
296            &self.owner,
297            crate::app::CommandIcon {
298                command,
299                icon: icon.into(),
300                icon_on: icon_on.map(Into::into),
301            },
302        );
303        self
304    }
305
306    /// Contributes a menu item.
307    pub fn menu_item(&mut self, item: MenuItem) -> Result<&mut Self, CtxError> {
308        self.reg
309            .menus
310            .contribute(&self.owner, item)
311            .map_err(CtxError::Menu)?;
312        Ok(self)
313    }
314
315    /// Fills the lists named `name` (`MenuItem::list`) when their menu
316    /// opens: the entries `f` gives in the context of that moment (the
317    /// last plugin to provide a name wins).
318    pub fn list_provider(
319        &mut self,
320        name: &str,
321        f: impl Fn(&AppHandle, &egui_pop_model::when::WhenContext) -> Vec<crate::menus::ListItem>
322        + 'static,
323    ) -> &mut Self {
324        self.app.add_list_provider(
325            &self.owner,
326            crate::menus::Provider {
327                name: name.into(),
328                f: Rc::new(f),
329            },
330        );
331        self
332    }
333
334    /// Declares a submenu under a menu (`app.menu.view`).
335    pub fn submenu(
336        &mut self,
337        parent: MenuId,
338        group: &str,
339        order: i32,
340        menu: MenuId,
341        label: &str,
342    ) -> Result<&mut Self, CtxError> {
343        self.menu_item(MenuItem::submenu(parent, group, order, menu, label))
344    }
345
346    /// Declares a panel and how to draw it; the workbench places it in
347    /// its area (see `workbench`), inside a fault boundary and a focus
348    /// scope, and its commands `<id>.focus` and `<id>.toggle` are
349    /// declared with it.
350    pub fn panel(
351        &mut self,
352        spec: PanelSpec,
353        draw: impl FnMut(&mut Ui, &AppHandle) + 'static,
354    ) -> Result<&mut Self, CtxError> {
355        let id: PanelId = spec.id.clone();
356        let title = spec.title.clone();
357        self.reg
358            .panels
359            .declare(&self.owner, spec)
360            .map_err(CtxError::Panel)?;
361        self.app.add_panel_view(
362            &self.owner,
363            id.clone(),
364            crate::app::PanelDraw::Plain(Box::new(draw)),
365        );
366        self.panel_commands(id, title)
367    }
368
369    /// Declares a panel that opens as many times as asked
370    /// ([`Instances::Multiple`](egui_pop_model::panels::Instances::Multiple)),
371    /// and the one function drawing each instance, told which it draws
372    /// ([`Instance`](crate::workbench::instances::Instance)): the panel
373    /// declared is instance 1, `pop.panel.open` with `instance: "new"`
374    /// opens `<id>#<n>`. Each instance's payload is the application's
375    /// ([`AppHandle::instance_payload`]), kept in the layout.
376    ///
377    /// <div class="warning">Experimental: may change in any release
378    /// (docs/stability.md).</div>
379    pub fn instance_panel(
380        &mut self,
381        spec: PanelSpec,
382        draw: impl FnMut(&mut Ui, &AppHandle, &crate::workbench::instances::Instance) + 'static,
383    ) -> Result<&mut Self, CtxError> {
384        let spec = spec.instances(egui_pop_model::panels::Instances::Multiple);
385        let id: PanelId = spec.id.clone();
386        let title = spec.title.clone();
387        self.reg
388            .panels
389            .declare(&self.owner, spec)
390            .map_err(CtxError::Panel)?;
391        self.app.add_panel_view(
392            &self.owner,
393            id.clone(),
394            crate::app::PanelDraw::Instance(Box::new(draw)),
395        );
396        self.panel_commands(id, title)
397    }
398
399    /// A panel's commands, `<id>.focus` and `<id>.toggle`.
400    fn panel_commands(&mut self, id: PanelId, title: String) -> Result<&mut Self, CtxError> {
401        let command = |suffix: &str| {
402            CommandId::new(format!("{id}.{suffix}")).map_err(|e| CtxError::Panel(e.to_string()))
403        };
404        let (focus, toggle) = (id.clone(), id.clone());
405        let fill = |key: &StrKey| strings::fill(key.fallback, &[("panel", &title)]);
406        let (focus_id, toggle_id) = (command("focus")?, command("toggle")?);
407        // The texts are shared by every panel, the title filled in the
408        // interface's language; the specs keep the English.
409        self.app.add_panel_commands(
410            [
411                (
412                    &focus_id,
413                    txt::PANEL_FOCUS_TITLE,
414                    txt::PANEL_FOCUS_DESCRIPTION,
415                ),
416                (
417                    &toggle_id,
418                    txt::PANEL_TOGGLE_TITLE,
419                    txt::PANEL_TOGGLE_DESCRIPTION,
420                ),
421            ]
422            .map(|(cmd, title_key, description)| {
423                (
424                    cmd.to_string(),
425                    strings::PanelCommand {
426                        title: title_key,
427                        description,
428                        panel: id.to_string(),
429                        panel_title: title.clone(),
430                    },
431                )
432            }),
433        );
434        self.command(
435            CommandSpec::new(focus_id, &fill(&txt::PANEL_FOCUS_TITLE), "View")
436                .description(&fill(&txt::PANEL_FOCUS_DESCRIPTION)),
437            move |call| {
438                call.app.focus_panel(&focus);
439                // Someone typing keeps the keyboard, whatever an agent asks.
440                if !matches!(call.origin, egui_pop_model::commands::Origin::User)
441                    && egui_pop_core::focus::text_input_owns_keyboard(&call.app.egui())
442                {
443                    call.app.workbench_mut().cancel_focus_request();
444                }
445                Ok(Json::Null)
446            },
447        )?
448        .command(
449            CommandSpec::new(toggle_id, &fill(&txt::PANEL_TOGGLE_TITLE), "View")
450                .description(&fill(&txt::PANEL_TOGGLE_DESCRIPTION)),
451            move |call| {
452                let shown = call.app.panel_visible(&toggle);
453                if shown {
454                    call.app.set_panel_visible(&toggle, false);
455                } else {
456                    // Opened where it was, through `pop.panel.open`.
457                    let ask = crate::bus::PanelOpenAsk::new(
458                        toggle.as_str(),
459                        crate::bus::OpenPlace::Last,
460                        crate::bus::OWNER,
461                    );
462                    call.app.open_panel(ask)?;
463                }
464                Ok(serde_json::json!({ "shown": !shown }))
465            },
466        )?;
467        Ok(self)
468    }
469
470    /// Shows a zone as a panel (the shell's side bar, main and inspector
471    /// zones): no commands, drawn bare when alone in its area.
472    pub(crate) fn zone_panel(
473        &mut self,
474        spec: PanelSpec,
475        zone: ZoneId,
476        scope: &'static str,
477    ) -> Result<&mut Self, CtxError> {
478        let id = spec.id.clone();
479        self.reg
480            .panels
481            .declare(&self.owner, spec.bare())
482            .map_err(CtxError::Panel)?;
483        self.app
484            .workbench_mut()
485            .zone_of
486            .insert(id.clone(), zone.clone());
487        self.app.add_panel_view(
488            &self.owner,
489            id,
490            crate::app::PanelDraw::Plain(Box::new(move |ui, app| {
491                egui_pop_core::focus::scope(ui, scope, &[], |ui| app.show_zone(ui, &zone));
492            })),
493        );
494        Ok(self)
495    }
496
497    /// Declares a zone other plugins may contribute blocks to.
498    pub fn zone(&mut self, zone: ZoneId, title: &str) -> Result<&mut Self, CtxError> {
499        self.app
500            .zones_mut()
501            .declare(&self.owner, zone.clone(), title)
502            .map_err(|by| CtxError::Zone { zone, by })?;
503        Ok(self)
504    }
505
506    /// Contributes a block to a zone: add, replace, extend or wrap. What
507    /// cannot apply (unknown zone, missing target, duplicate id) is
508    /// reported when the application resolves zones.
509    pub fn block(&mut self, zone: ZoneId, block: Block) -> &mut Self {
510        self.app
511            .zones_mut()
512            .contribute(&self.owner, self.rank, zone, block);
513        self
514    }
515
516    /// Declares a value of the application's state at `path`, owned by
517    /// the plugin and removed with it: each change is an undo step, and
518    /// widgets bind to it (`egui_pop_core::param::bound`). Its value
519    /// starts at the descriptor's default. A setting, saved and in the
520    /// settings window, is a [`Ctx::setting`].
521    ///
522    /// ```
523    /// use egui_pop_api::{App, Ctx, Plugin, PluginError};
524    /// use egui_pop_model::ids::PluginId;
525    /// use egui_pop_model::values::Descriptor;
526    ///
527    /// struct Swatch;
528    /// impl Plugin for Swatch {
529    ///     fn id(&self) -> PluginId { PluginId::from_static("swatch") }
530    ///     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
531    ///         ctx.value("swatch/hue", Descriptor::float("Hue", 0.0, 360.0, 200.0))?;
532    ///         Ok(())
533    ///     }
534    /// }
535    ///
536    /// let app = App::builder().plugin(Swatch).build(&egui::Context::default()).unwrap();
537    /// assert_eq!(app.handle().value::<f64>("swatch/hue"), Some(200.0));
538    /// ```
539    pub fn value(&mut self, path: &str, descriptor: Descriptor) -> Result<&mut Self, CtxError> {
540        egui_pop_core::lock(&self.app.store())
541            .declare(&self.owner, path, descriptor)
542            .map_err(CtxError::Setting)?;
543        Ok(self)
544    }
545
546    /// Declares a setting at `settings/<id>` ([`SettingId::path`]),
547    /// applied live, with its reset; shown in the settings form under the
548    /// plugin's title. Read it with `AppHandle::setting`.
549    pub fn setting(
550        &mut self,
551        id: SettingId,
552        descriptor: Descriptor,
553    ) -> Result<&mut Self, CtxError> {
554        let path = id.path();
555        egui_pop_core::lock(&self.app.store())
556            .declare(&self.owner, &path, descriptor)
557            .map_err(CtxError::Setting)?;
558        self.reg
559            .settings
560            .insert(&self.owner, id, path)
561            .map_err(|t| {
562                CtxError::Setting(DeclareError::Taken {
563                    path: t.id.path(),
564                    by: t.by,
565                })
566            })?;
567        Ok(self)
568    }
569
570    /// Adds a collector to the debug bridge (removed with the plugin).
571    pub fn collector(
572        &mut self,
573        collector: egui_pop_core::debug::FnCollector,
574    ) -> Result<&mut Self, CtxError> {
575        self.app.add_collector(&self.owner, collector)?;
576        Ok(self)
577    }
578
579    /// Provides a service.
580    pub fn service<T: Send + Sync + 'static>(
581        &mut self,
582        token: &ServiceToken<T>,
583        value: T,
584    ) -> Result<&mut Self, CtxError> {
585        self.app
586            .services_mut()
587            .provide(&self.owner, token, Arc::new(value))
588            .map_err(|by| CtxError::Service {
589                id: token.id().to_string(),
590                by,
591            })?;
592        Ok(self)
593    }
594
595    /// Registers a local scope (ADR 0014) for a focus surface: while the
596    /// focus is in `surface` (`egui_pop_core::focus::scope`), Ctrl+Z and
597    /// Ctrl+Shift+Z undo and redo there, not in the application's
598    /// history, also in a modal (the settings window). A text field
599    /// inside keeps its own undo. One scope per surface: a second
600    /// replaces the first. It goes with the plugin.
601    ///
602    /// <div class="warning">Experimental: may change in any release
603    /// (docs/stability.md).</div>
604    pub fn local_scope(
605        &mut self,
606        surface: &str,
607        scope: impl crate::history::LocalScope + 'static,
608    ) -> &mut Self {
609        crate::history::register(&self.app(), &self.owner, surface, Rc::new(scope));
610        self
611    }
612
613    /// Declares which of the owner's histories a focus surface (or a
614    /// panel, by its id) works on: under
615    /// [`Routing::Focus`](crate::history::Routing::Focus), Ctrl+Z and
616    /// Ctrl+Shift+Z go there while the focus is in it, whatever step is
617    /// newest elsewhere. The surface-side twin of a scope's focus targets
618    /// (`ScopeInfo::focus`), which also make the scope active: this does
619    /// not, so an always-active history can claim surfaces too. One
620    /// history per surface: a second replaces the first. It goes with the
621    /// plugin.
622    ///
623    /// <div class="warning">Experimental: may change in any release
624    /// (docs/stability.md).</div>
625    pub fn history_target(&mut self, surface: &str, scope: crate::history::ScopeId) -> &mut Self {
626        crate::history::declare_target(&self.app(), &self.owner, surface, scope);
627        self
628    }
629
630    /// Calls `f` at a moment of the application's life.
631    pub fn on(
632        &mut self,
633        when: On,
634        f: impl FnMut(&AppHandle, &crate::hooks::Lifecycle) + 'static,
635    ) -> &mut Self {
636        let f: LifecycleFn = Box::new(f);
637        self.reg.lifecycle.push(&self.owner, (when, f));
638        self
639    }
640
641    /// Calls `f` after each change of a store path under `prefix`.
642    pub fn on_change(
643        &mut self,
644        prefix: &str,
645        f: impl FnMut(&egui_pop_model::values::Changed) + Send + 'static,
646    ) -> &mut Self {
647        egui_pop_core::lock(&self.app.store()).listen(&self.owner, prefix, f);
648        self
649    }
650
651    /// Registers an alter hook.
652    pub fn hook(&mut self, hook: Hook) -> Result<&mut Self, CtxError> {
653        if let Some(s) = self.reg.hooks.iter().find(|s| s.item.id == hook.id) {
654            return Err(CtxError::Hook {
655                id: hook.id.to_string(),
656                by: s.owner.clone(),
657            });
658        }
659        self.reg.hooks.push(&self.owner, hook);
660        Ok(self)
661    }
662
663    /// Declares a step of this plugin's features that other plugins may
664    /// watch, veto, replace or extend (ADR 0011).
665    pub fn step(&mut self, spec: crate::steps::StepSpec) -> Result<&mut Self, CtxError> {
666        self.app.declare_step(&self.owner, spec)?;
667        Ok(self)
668    }
669
670    /// Runs before a step: lets it go, vetoes it or changes its
671    /// arguments.
672    pub fn before(
673        &mut self,
674        step: egui_pop_model::ids::StepId,
675        f: impl Fn(&AppHandle, &Json) -> crate::steps::Before + 'static,
676    ) -> &mut Self {
677        self.app
678            .add_step_hook(&self.owner, step, crate::steps::HookFn::Before(Rc::new(f)));
679        self
680    }
681
682    /// Does a step instead of its default (the last plugin to replace a
683    /// step wins).
684    pub fn replace(
685        &mut self,
686        step: egui_pop_model::ids::StepId,
687        f: impl Fn(&AppHandle, &Json) -> Result<Json, String> + 'static,
688    ) -> &mut Self {
689        self.app
690            .add_step_hook(&self.owner, step, crate::steps::HookFn::Run(Rc::new(f)));
691        self
692    }
693
694    /// Runs after a step, with its arguments and result.
695    pub fn after(
696        &mut self,
697        step: egui_pop_model::ids::StepId,
698        f: impl Fn(&AppHandle, &Json, &Result<Json, String>) + 'static,
699    ) -> &mut Self {
700        self.app
701            .add_step_hook(&self.owner, step, crate::steps::HookFn::After(Rc::new(f)));
702        self
703    }
704
705    /// Adds an indicator to the status bar, fed by the journal's events
706    /// (shown by `strips::StripsPlugin`), or, speaking for a panel
707    /// (`Indicator::panel`), to that panel's icon in a folded side
708    /// area's strip.
709    /// Its `when` clause, when it has one, must parse: one that does not
710    /// keeps the indicator hidden and is reported (`indicator-when`).
711    ///
712    /// <div class="warning">Experimental: may change in any release
713    /// (docs/stability.md).</div>
714    pub fn indicator(&mut self, indicator: crate::strips::Indicator) -> &mut Self {
715        if let Some(Err(e)) = indicator.clause() {
716            self.app.warn(
717                "indicator-when",
718                Some(&self.owner),
719                &indicator.id,
720                format!("the `when` clause of the indicator `{}`: {e}", indicator.id),
721            );
722        }
723        self.app.add_indicator(&self.owner, indicator);
724        self
725    }
726
727    /// Offers a named layout of the workbench (an arrangement template):
728    /// what switching to `name` starts from and what resetting it goes
729    /// back to (see `arrangements`).
730    pub fn arrangement(&mut self, name: &str, layout: egui_pop_model::layout::Layout) -> &mut Self {
731        self.app
732            .workbench_mut()
733            .templates
734            .push((self.owner.clone(), name.to_string(), layout));
735        self
736    }
737
738    /// Contributes a gallery story.
739    pub fn story(&mut self, story: Story) -> Result<&mut Self, CtxError> {
740        self.app.add_story(&self.owner, story)?;
741        Ok(self)
742    }
743}
744
745/// Declares a command and what derives from it (keys, menu items), owned
746/// by `owner`: `Ctx::command`, `Ctx::declare` and `App::declare`.
747pub(crate) fn add_command(
748    reg: &mut Registries,
749    owner: &OwnerId,
750    mut spec: CommandSpec,
751    handler: Option<CommandFn>,
752) -> Result<(), CtxError> {
753    if reg.offered.contains(&spec.id) {
754        // The application offers it (`AppBuilder::offer_command_to_agents`).
755        spec.agent = true;
756    }
757    for k in &spec.keys {
758        egui_pop_model::keymap::Keys::parse(&k.keys).map_err(|error| CtxError::Keys {
759            keys: k.keys.clone(),
760            error,
761        })?;
762    }
763    let keys = spec.keys.clone();
764    let menus = spec.menus.clone();
765    let id = spec.id.clone();
766    let when = spec.when.clone();
767    let checked = spec.checked.clone();
768    reg.commands
769        .register(owner, spec, handler)
770        .map_err(CtxError::Command)?;
771    for k in keys {
772        reg.keymap
773            .borrow_mut()
774            .bind_with(
775                owner,
776                Layer::Default,
777                &k.keys,
778                Action::Run(id.clone()),
779                &when,
780                k.options,
781            )
782            .map_err(|error| CtxError::Keys {
783                keys: k.keys,
784                error,
785            })?;
786    }
787    for m in menus {
788        reg.menus
789            .contribute(
790                owner,
791                MenuItem::command(m.menu, &m.group, m.order, id.clone())
792                    .when(&when, true)
793                    .checked(&checked),
794            )
795            .map_err(CtxError::Menu)?;
796    }
797    Ok(())
798}