Skip to main content

egui_pop_api/bus/
commands.rs

1//! A command run on the bus (ADR 0029): every run of a command, whatever
2//! asked it (a key, the palette, a menu, a toolbar, a toast's action, an
3//! agent), is asked on `pop.command.run` ([`CommandRun`]) before its handler
4//! runs. The point is declared fail-closed: a listener may refuse the run
5//! with a reason (`HookError::refuse`), and a listener that fails, panics
6//! or misses its deadline refuses it too. A refused run never reaches the
7//! host; it is said as `command.refused` with the listener that refused
8//! it (`by`) and its reason, and the caller gets the refusal as its
9//! error.
10//!
11//! egui-pop registers no listener on it: with nobody listening, a run
12//! goes on as before, to the host's dispatch and its handler, said as
13//! `command.dispatched` then `command.done` or `command.failed`. A
14//! command not offered to agents, unknown or disabled is refused before
15//! the point is asked, as before; so is a run whose arguments do not
16//! match its command's JSON Schema (`by: "pop.command.args"`,
17//! [`ARGS_VALIDATOR`]).
18
19use bus_contract::{Point, PointId, PointKind, Refusal};
20use egui_pop_model::commands::Origin;
21use egui_pop_model::ids::CommandId;
22use serde_json::Value as Json;
23
24use super::{ASKING, Asking};
25use crate::app::AppHandle;
26
27/// A command about to run: which, with what, for whom, and in which
28/// window.
29#[derive(Clone, Debug, PartialEq)]
30#[non_exhaustive]
31pub struct CommandAsk {
32    /// The command.
33    pub command: CommandId,
34    /// Its arguments.
35    pub args: Json,
36    /// Who asks: the person, an agent, a script.
37    pub origin: Origin,
38    /// The application window it was asked in, when it was not the main
39    /// window.
40    pub window: Option<String>,
41}
42
43impl CommandAsk {
44    pub fn new(command: CommandId, args: Json, origin: Origin) -> Self {
45        Self {
46            command,
47            args,
48            origin,
49            window: None,
50        }
51    }
52
53    /// The application window it was asked in.
54    pub fn window(mut self, window: impl Into<String>) -> Self {
55        self.window = Some(window.into());
56        self
57    }
58}
59
60/// A command is about to run (`pop.command.run`): its listeners run in their
61/// declared order before the handler; one may refuse the run with a
62/// reason. Fail-closed: a listener's failure refuses it too. The value
63/// is what the listeners noted, one line each.
64#[derive(Debug)]
65pub struct CommandRun;
66impl Point for CommandRun {
67    const KIND: PointKind = PointKind::Request;
68    const ID: PointId = PointId::new("pop.command.run");
69    type Input = CommandAsk;
70    type Value = Vec<String>;
71}
72
73/// Who refuses a run whose arguments do not match its command's JSON
74/// Schema (`CommandSpec::schema`): the `by` of its `command.refused`. The
75/// check is not a listener: it runs before `pop.command.run` is asked,
76/// for every origin.
77pub const ARGS_VALIDATOR: &str = "pop.command.args";
78
79/// Why `args` do not match `spec`'s JSON Schema, `None` when they do or
80/// when its arguments are only described (an example, a text). `null`
81/// arguments are checked as `{}` against an object's schema.
82pub(crate) fn args_refusal(
83    spec: &egui_pop_model::commands::CommandSpec,
84    args: &Json,
85) -> Option<String> {
86    if !egui_pop_core::debug::is_schema(&spec.args) {
87        return None;
88    }
89    let empty = Json::Object(Default::default());
90    let args = if args.is_null() && spec.args.get("type").and_then(Json::as_str) == Some("object") {
91        &empty
92    } else {
93        args
94    };
95    egui_pop_core::schema::check(&spec.args, args)
96        .err()
97        .map(|e| format!("its arguments do not match its schema: {e}"))
98}
99
100/// The command points, in the order [`super::order_dump`] prints them.
101pub const COMMAND_POINTS: [&str; 1] = [CommandRun::ID.as_str()];
102
103/// Asks `pop.command.run` for `app`, inline: the refusal that stopped the
104/// run, if one did; the listeners' failures logged.
105pub(crate) fn ask(app: &AppHandle, ask: CommandAsk) -> Option<Refusal> {
106    ASKING.with_borrow_mut(|a| a.push(app.downgrade()));
107    let _asking = Asking;
108    let out = app.bus().alter::<CommandRun>(ask, Vec::new());
109    for f in &out.failures {
110        log::error!(target: "egui_pop", "{f}");
111    }
112    out.refused
113}
114
115/// A refusal as the run's error and the journal's reason: "refused by
116/// `listener`: reason", or "refused, `listener` failed: reason".
117pub(crate) fn reason(refusal: &Refusal) -> String {
118    if refusal.failed {
119        format!("refused, `{}` failed: {}", refusal.listener, refusal.reason)
120    } else {
121        format!("refused by `{}`: {}", refusal.listener, refusal.reason)
122    }
123}