egui_pop_api/steps.rs
1//! Steps: the moments of a feature's life an application can reach
2//! (ADR 0011). egui-pop does the plumbing (closing a window, detaching a
3//! panel, switching an arrangement, rebinding a key); at each step a
4//! plugin may:
5//!
6//! - **observe**: every step publishes a signal on the host's journal,
7//! named after the step (`frame.close`), with its arguments and result,
8//! or `<step>.vetoed`;
9//! - **veto or redirect** with a before-hook ([`Before`]): stop the step
10//! with a reason, or change its arguments;
11//! - **replace** with a run-hook: do the step its own way instead of
12//! egui-pop's default (the last plugin to replace a step wins; two are
13//! reported);
14//! - **extend** with an after-hook: act on the result.
15//!
16//! Each is optional; without hooks a step runs its default. Every run is
17//! traced (who redirected, vetoed, ran, followed) and shown by the debug
18//! bridge's `steps` collector.
19//!
20//! ```
21//! use egui_pop_api::steps::{Before, StepSpec};
22//! use egui_pop_api::{App, Ctx, Plugin, PluginError};
23//! use egui_pop_model::ids::{PluginId, StepId};
24//!
25//! const SAVE: StepId = StepId::from_static("demo.save");
26//!
27//! struct Guard;
28//! impl Plugin for Guard {
29//! fn id(&self) -> PluginId { PluginId::from_static("guard") }
30//! fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
31//! ctx.step(StepSpec::new(SAVE, "Saves the demo."))?;
32//! ctx.before(SAVE, |_, args| {
33//! if args["name"] == "" { Before::Veto("no name".into()) } else { Before::Go }
34//! });
35//! Ok(())
36//! }
37//! }
38//!
39//! let app = App::builder().plugin(Guard).build(&egui::Context::default()).unwrap();
40//! let h = app.handle();
41//! let out = h.step(&SAVE, serde_json::json!({ "name": "" }), |_, _| Ok(serde_json::json!("saved")));
42//! assert_eq!(out.vetoed(), Some("no name"));
43//! let out = h.step(&SAVE, serde_json::json!({ "name": "a" }), |_, _| Ok(serde_json::json!("saved")));
44//! assert_eq!(out.result(), Some(&Ok(serde_json::json!("saved"))));
45//! ```
46
47use std::fmt;
48use std::rc::Rc;
49
50use egui_pop_model::ids::{OwnerId, StepId};
51use serde::Serialize;
52use serde_json::{Value as Json, json};
53
54use crate::app::AppHandle;
55
56/// What a before-hook decides.
57#[derive(Clone, Debug, PartialEq)]
58pub enum Before {
59 /// The step goes on.
60 Go,
61 /// The step stops; the reason is traced and published.
62 Veto(String),
63 /// The step goes on with these arguments instead.
64 Redirect(Json),
65}
66
67/// A before-hook.
68pub type BeforeFn = Rc<dyn Fn(&AppHandle, &Json) -> Before>;
69/// A run-hook: does the step instead of the default.
70pub type RunFn = Rc<dyn Fn(&AppHandle, &Json) -> Result<Json, String>>;
71/// An after-hook: sees the arguments and the result.
72pub type AfterFn = Rc<dyn Fn(&AppHandle, &Json, &Result<Json, String>)>;
73
74/// A step as declared: its id, what it does, an example of its
75/// arguments.
76#[derive(Clone, Debug, PartialEq, Serialize)]
77pub struct StepSpec {
78 pub id: StepId,
79 pub description: String,
80 pub args: Json,
81}
82
83impl StepSpec {
84 pub fn new(id: StepId, description: &str) -> Self {
85 Self {
86 id,
87 description: description.into(),
88 args: Json::Null,
89 }
90 }
91
92 /// An example of its arguments, shown by the debug bridge.
93 pub fn args(mut self, example: Json) -> Self {
94 self.args = example;
95 self
96 }
97}
98
99/// A declared step with its hooks, as the debug bridge shows it.
100#[derive(Clone, Debug, PartialEq, Serialize)]
101pub struct StepInfo {
102 #[serde(flatten)]
103 pub spec: StepSpec,
104 pub owner: OwnerId,
105 pub hooks: Vec<HookInfo>,
106}
107
108/// A hook on a step: its owner and kind (`before`, `replace`, `after`).
109#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
110pub struct HookInfo {
111 pub owner: OwnerId,
112 pub kind: &'static str,
113}
114
115/// The kind of a hook.
116#[derive(Clone)]
117pub(crate) enum HookFn {
118 Before(BeforeFn),
119 Run(RunFn),
120 After(AfterFn),
121}
122
123impl HookFn {
124 pub(crate) fn kind(&self) -> &'static str {
125 match self {
126 HookFn::Before(_) => "before",
127 HookFn::Run(_) => "replace",
128 HookFn::After(_) => "after",
129 }
130 }
131}
132
133/// A hook on a step.
134#[derive(Clone)]
135pub(crate) struct StepHook {
136 pub step: StepId,
137 pub f: HookFn,
138}
139
140impl fmt::Debug for StepHook {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 write!(f, "{} {}", self.f.kind(), self.step)
143 }
144}
145
146/// How a step ended.
147#[derive(Clone, Debug, PartialEq)]
148pub enum Outcome {
149 /// It ran (by default or by a run-hook): its result.
150 Done(Result<Json, String>),
151 /// A before-hook stopped it.
152 Vetoed { by: OwnerId, reason: String },
153}
154
155impl Outcome {
156 /// The result, when it ran.
157 pub fn result(&self) -> Option<&Result<Json, String>> {
158 match self {
159 Outcome::Done(r) => Some(r),
160 Outcome::Vetoed { .. } => None,
161 }
162 }
163
164 /// Whether it ran and succeeded.
165 pub fn ok(&self) -> bool {
166 matches!(self, Outcome::Done(Ok(_)))
167 }
168
169 /// The reason, when it was vetoed.
170 pub fn vetoed(&self) -> Option<&str> {
171 match self {
172 Outcome::Vetoed { reason, .. } => Some(reason),
173 Outcome::Done(_) => None,
174 }
175 }
176}
177
178/// One run of a step, as the `steps` collector shows it.
179#[derive(Clone, Debug, PartialEq, Serialize)]
180pub struct StepTrace {
181 pub step: StepId,
182 /// The arguments it was asked with.
183 pub asked: Json,
184 /// The arguments it ran with, after redirections.
185 pub args: Json,
186 /// Who redirected it, in order.
187 pub redirected_by: Vec<OwnerId>,
188 /// Who vetoed it, and why.
189 pub vetoed_by: Option<(OwnerId, String)>,
190 /// Who ran it: a plugin's run-hook, or `default`.
191 pub ran_by: Option<String>,
192 /// Who followed it with an after-hook.
193 pub after: Vec<OwnerId>,
194 pub result: Option<Result<Json, String>>,
195 /// Whether nobody declared the step.
196 pub undeclared: bool,
197 /// Whether its arguments carry private data (asked with
198 /// `"private": true`, [`PRIVATE`]): readers that do not read private
199 /// data get its arguments and result redacted
200 /// (`host::redact_private`).
201 #[serde(skip_serializing_if = "std::ops::Not::not")]
202 pub private: bool,
203}
204
205/// The key a step's arguments carry, `true`, when they hold private data
206/// (a private command's arguments, say): the step's events and trace are
207/// then marked private, and readers that do not read private data get
208/// their arguments, result and error redacted (`host::redact_private`).
209/// A redirection cannot take the mark off.
210pub const PRIVATE: &str = "private";
211
212/// Whether a step's arguments carry the [`PRIVATE`] mark.
213pub fn is_private(args: &Json) -> bool {
214 args.get(PRIVATE) == Some(&Json::Bool(true))
215}
216
217/// How many runs the trace keeps.
218pub const TRACES: usize = 64;
219
220/// The hooks of one step, taken out of the registry for a run.
221pub(crate) fn run(
222 app: &AppHandle,
223 step: &StepId,
224 args: Json,
225 hooks: Vec<(OwnerId, HookFn)>,
226 declared: bool,
227 quiet: bool,
228 default: impl FnOnce(&AppHandle, &Json) -> Result<Json, String>,
229) -> (Outcome, StepTrace) {
230 let mut trace = StepTrace {
231 step: step.clone(),
232 asked: args.clone(),
233 args: Json::Null,
234 redirected_by: Vec::new(),
235 vetoed_by: None,
236 ran_by: None,
237 after: Vec::new(),
238 result: None,
239 undeclared: !declared,
240 private: is_private(&args),
241 };
242 // The step's events carry the mark its trace does.
243 let private = trace.private;
244 let mark = |mut data: Json| {
245 if private {
246 data[PRIVATE] = Json::Bool(true);
247 }
248 data
249 };
250 let mut args = args;
251 for (owner, f) in &hooks {
252 if let HookFn::Before(f) = f {
253 match f(app, &args) {
254 Before::Go => {}
255 Before::Redirect(new) => {
256 args = new;
257 trace.redirected_by.push(owner.clone());
258 }
259 Before::Veto(reason) => {
260 trace.args = args.clone();
261 trace.vetoed_by = Some((owner.clone(), reason.clone()));
262 app.publish(
263 "egui_pop",
264 None,
265 &format!("{step}.vetoed"),
266 mark(json!({ "args": args, "by": owner, "reason": reason })),
267 );
268 return (
269 Outcome::Vetoed {
270 by: owner.clone(),
271 reason,
272 },
273 trace,
274 );
275 }
276 }
277 }
278 }
279 let runner = hooks.iter().rev().find_map(|(o, f)| match f {
280 HookFn::Run(f) => Some((o.clone(), f.clone())),
281 _ => None,
282 });
283 let result = match runner {
284 Some((owner, f)) => {
285 trace.ran_by = Some(owner.to_string());
286 f(app, &args)
287 }
288 None => {
289 trace.ran_by = Some("default".into());
290 default(app, &args)
291 }
292 };
293 for (owner, f) in &hooks {
294 if let HookFn::After(f) = f {
295 f(app, &args, &result);
296 trace.after.push(owner.clone());
297 }
298 }
299 let data = mark(match &result {
300 Ok(v) => json!({ "args": args, "result": v }),
301 Err(e) => json!({ "args": args, "error": e }),
302 });
303 // Quiet, a run is published only when it fails.
304 if !quiet || result.is_err() {
305 app.publish("egui_pop", None, step.as_str(), data);
306 }
307 trace.args = args;
308 trace.result = Some(result.clone());
309 (Outcome::Done(result), trace)
310}