Skip to main content

egui_pop_api/
contexts.rs

1//! The context stack (ADR 0012): places (drill-downs, shown as a
2//! breadcrumb) and modes (global states, shown as chips), owned by the
3//! application's kernel and projected by the interface.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! - **The owner** implements [`Contexts`]: the frames, the state, the
9//!   transitions (through the pure `egui_pop_model::context::apply`), the
10//!   holds. The host gives it ([`Host::contexts`](crate::host::Host::contexts));
11//!   without one, [`ContextsPlugin`] keeps a [`LocalContexts`], which
12//!   writes the stack to the `context` document inside each transition.
13//!   The owner publishes `context.changed` (with the whole new state and
14//!   its revision), then `context.left` and `context.entered` per frame,
15//!   or `context.refused`; `context.restored` at start, `context.held`
16//!   and `context.released`.
17//! - **The interface asks, never writes.** Every transition is the step
18//!   `context.request` (ADR 0011): a before-hook vetoes it (unsaved typed
19//!   input) or redirects it, its default asks the owner. Nothing is shown
20//!   until the owner's state has a new revision, so a refusal leaves the
21//!   display as it was.
22//! - **The projection** follows the owner's state: per projection key
23//!   (the place path and the active modes), the main window's workbench
24//!   layout (a place's arrangement the first time, a mode's panels shown
25//!   or hidden; a change made in a mode belongs to it and goes when it is
26//!   left; panels docked in other application windows stay there), the
27//!   focused panel and the values components keep ([`view_value`],
28//!   [`scroll_area`]); the context keys `place`, `placeDepth`,
29//!   `modePushed`, `mode.<group>` and the frames' own keys, read by
30//!   `when` clauses (a frame's own key bindings use
31//!   `FrameSpec::clause`: [`Ctx::frame_keybinding`]). It is written to
32//!   the `view` document about a second after it changes.
33//! - **Widgets**: [`breadcrumb`], [`mode_chips`], [`mode_switch`],
34//!   [`mode_toggle`]. **Commands**: `nav.back` (Alt+Left; Escape while a
35//!   mode is pushed), `nav.up` (Alt+Shift+Up), `nav.enter`, and for
36//!   agents `context.read`, `context.request` (with `if_rev` and
37//!   `dry_run`), `context.go`, `context.set_mode`, `context.hold` and
38//!   `context.release`. The `contexts` collector shows it all.
39//! - **Undo out of sight**: the value store's new steps carry the place
40//!   shown (`Store::set_place`); an undo, a redo or a jump that walks a
41//!   step made in another place (its `StepInfo::place`) says so in a
42//!   toast, with "Go there".
43//!
44//! ```
45//! use egui_pop_api::contexts::{self, ContextsPlugin, FrameSpec};
46//! use egui_pop_api::{App, Ctx, Plugin, PluginError};
47//! use egui_pop_model::ids::{FrameId, GroupId, PluginId};
48//!
49//! const ALBUM: FrameId = FrameId::from_static("demo.album");
50//! const CULLING: FrameId = FrameId::from_static("demo.culling");
51//!
52//! struct Demo;
53//! impl Plugin for Demo {
54//!     fn id(&self) -> PluginId { PluginId::from_static("demo") }
55//!     fn requires(&self) -> Vec<PluginId> { vec![contexts::PLUGIN] }
56//!     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
57//!         ctx.frame(FrameSpec::place(ALBUM, "Album"))?
58//!             .frame(FrameSpec::mode(CULLING, GroupId::from_static("orientation"), "Culling"))?;
59//!         Ok(())
60//!     }
61//! }
62//!
63//! let app = App::builder().plugin(ContextsPlugin::default()).plugin(Demo)
64//!     .build(&egui::Context::default()).unwrap();
65//! let h = app.handle();
66//! assert!(contexts::enter(h, ALBUM, serde_json::Value::Null).ok());
67//! assert!(contexts::set_mode(h, CULLING).ok());
68//! assert_eq!(h.context().get("place"), "demo.album");
69//! assert_eq!(h.context().get("mode.orientation"), "demo.culling");
70//! assert!(contexts::back(h).vetoed().is_none());
71//! assert_eq!(h.context().get("place"), "root");
72//! ```
73
74use std::cell::RefCell;
75use std::collections::{BTreeMap, BTreeSet};
76use std::fmt;
77use std::rc::Rc;
78use std::sync::atomic::{AtomicBool, Ordering};
79use std::sync::{Arc, Mutex};
80
81use egui::{Role, Ui};
82use egui_pop_core::a11y::{self, Politeness};
83use egui_pop_core::debug::FnCollector;
84use egui_pop_core::lock;
85use egui_pop_core::persist::Persist;
86use egui_pop_core::state::Slot;
87use egui_pop_core::strings;
88use egui_pop_core::ui::UiPop as _;
89use egui_pop_core::widgets;
90
91/// The view generation a scroll area last applied its saved offset for.
92const SCROLL_APPLIED: Slot<u64> = Slot::new("api.contexts.scroll_applied");
93use egui_pop_model::commands::{CommandSpec, Origin};
94use egui_pop_model::context::{self as model, ContextDoc, ViewDoc, ViewState};
95use egui_pop_model::ids::{CommandId, OwnerId, PanelId, PluginId, StepId};
96use egui_pop_model::keymap::Layer;
97use egui_pop_model::layout::Layout;
98use serde_json::{Value as Json, json};
99
100pub use egui_pop_model::context::{
101    Dropped, Entry, Envelope, FrameRegistry, FrameSpec, Hold, Kind, LabelCall, Life, ModeEntry,
102    PLACES, ROOT, Refusal, RefusalKind, Request, State, Transition, Verdict,
103};
104pub use egui_pop_model::ids::{FrameId, GroupId};
105
106use crate::app::{AppHandle, STEP_REDO, STEP_UNDO};
107use crate::history::{self, StepInfo};
108use crate::hooks::{Lifecycle, On};
109use crate::host::{Pending, source_of};
110use crate::services::ServiceToken;
111use crate::steps::{Outcome, StepSpec};
112use crate::strings as txt;
113use crate::{Ctx, CtxError, Plugin, PluginError};
114
115/// The plugin's id: plugins declaring frames require it.
116pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.contexts");
117
118/// The context stack's service.
119pub const CONTEXTS: ServiceToken<ContextService> = ServiceToken::new("app.contexts");
120
121/// A transition asked of the owner (`{ "request": envelope, "origin" }`):
122/// a before-hook vetoes it (the interface's own guards) or redirects it;
123/// the default asks the owner. Its result: the new revision, the frames
124/// entered and left; a refusal is its error.
125pub const STEP_REQUEST: StepId = StepId::from_static("context.request");
126
127/// Back: pops the last pushed mode, else leaves the top place.
128pub const CMD_BACK: CommandId = CommandId::from_static("nav.back");
129/// Up: leaves the top place.
130pub const CMD_UP: CommandId = CommandId::from_static("nav.up");
131/// Enters a place (`frame`, `payload`).
132pub const CMD_ENTER: CommandId = CommandId::from_static("nav.enter");
133/// The stack, its holds and its frames.
134pub const CMD_READ: CommandId = CommandId::from_static("context.read");
135/// Any transition, as an envelope (`request`, `if_rev`, `dry_run`).
136pub const CMD_REQUEST: CommandId = CommandId::from_static("context.request");
137/// Goes to a place path (`places`: `[{ "frame", "payload" }]`).
138pub const CMD_GO: CommandId = CommandId::from_static("context.go");
139/// Sets a mode (`mode`), pushes it (`push: true`), or turns a group off
140/// (`group`, no `mode`).
141pub const CMD_SET_MODE: CommandId = CommandId::from_static("context.set_mode");
142/// Holds groups of the stack (`groups`, `reason`): requests touching
143/// them are refused until released.
144pub const CMD_HOLD: CommandId = CommandId::from_static("context.hold");
145/// Releases a hold (`token`).
146pub const CMD_RELEASE: CommandId = CommandId::from_static("context.release");
147
148/// The document `LocalContexts` writes the stack to, beside the
149/// layout's (`workspaces/photos/context` when the host keeps the layout
150/// in `workspaces/photos/layout`; see [`documents`]).
151pub const CONTEXT_DOCUMENT: &str = "context";
152/// The document the projection writes its layouts and view states to,
153/// beside the layout's too.
154pub const VIEW_DOCUMENT: &str = "view";
155
156const NO_STACK: &str = "no context stack: the ContextsPlugin is not connected";
157
158/// What the owner answers a request.
159#[derive(Debug)]
160pub enum Answer {
161    /// Applied (or, for a dry run, would be), or refused.
162    Done(Result<Transition, Refusal>),
163    /// A remote owner answers later; its new state comes with a new
164    /// revision.
165    Later(Pending),
166}
167
168/// The owner of the context stack, as the interface reaches it.
169pub trait Contexts {
170    /// The frames that exist.
171    fn registry(&self) -> FrameRegistry;
172
173    /// The stack now.
174    fn state(&self) -> State;
175
176    /// Its revision (the projection follows it).
177    fn rev(&self) -> u64 {
178        self.state().rev
179    }
180
181    /// The holds in force.
182    fn holds(&self) -> Vec<Hold> {
183        Vec::new()
184    }
185
186    /// Applies a transition, or refuses it. The owner writes the new
187    /// stack before it answers, then publishes (see [`Contexts::take_events`]).
188    fn request(&mut self, envelope: &Envelope, origin: &Origin) -> Answer;
189
190    /// Holds groups (empty: everything; [`PLACES`] for places): its
191    /// token.
192    fn hold(&mut self, _groups: Vec<GroupId>, _reason: &str, _by: &str) -> Result<u64, String> {
193        Err("this owner takes no holds".into())
194    }
195
196    /// Releases a hold; whether it was held.
197    fn release(&mut self, _token: u64) -> bool {
198        false
199    }
200
201    /// A plugin declares a frame (`Ctx::frame`).
202    fn declare(&mut self, _owner: &OwnerId, _spec: FrameSpec) -> Result<(), String> {
203        Err("this host declares its own frames".into())
204    }
205
206    /// A plugin is gone: its frames go.
207    fn remove_owner(&mut self, _owner: &OwnerId) {}
208
209    /// The events to publish since the last call, as (name, data): egui-pop
210    /// publishes them on the host's journal. An owner publishing on its
211    /// own bus gives none.
212    fn take_events(&mut self) -> Vec<(String, Json)> {
213        Vec::new()
214    }
215}
216
217/// The default owner, in process: frames declared by plugins, the stack
218/// written to a document inside each transition when given one.
219#[derive(Debug, Default)]
220pub struct LocalContexts {
221    registry: FrameRegistry,
222    owners: BTreeMap<FrameId, OwnerId>,
223    state: State,
224    holds: Vec<Hold>,
225    next_hold: u64,
226    events: Vec<(String, Json)>,
227    persist: Option<(Persist, String)>,
228}
229
230/// Decides whether a saved frame may come back (its payload still
231/// exists): `None` when it may, else why not.
232pub type Validator = Arc<dyn Fn(&FrameId, &Json) -> Option<String> + Send + Sync>;
233
234impl LocalContexts {
235    pub fn new() -> Self {
236        Self::default()
237    }
238
239    /// Writes the stack to `document` under `persist`, inside each
240    /// transition (before answering and publishing).
241    pub fn with_persist(mut self, persist: Persist, document: &str) -> Self {
242        self.persist = Some((persist, document.into()));
243        self
244    }
245
246    /// Where it writes (`None`: nowhere).
247    pub fn set_persist(&mut self, persist: Option<Persist>, document: &str) {
248        self.persist = persist.map(|p| (p, document.to_string()));
249    }
250
251    fn write(&self, state: &State) -> Result<(), String> {
252        let Some((p, document)) = &self.persist else {
253            return Ok(());
254        };
255        p.save(
256            document,
257            &model::schema(),
258            &ContextDoc {
259                state: state.clone(),
260            },
261        )
262        .map_err(|e| e.to_string())
263    }
264
265    /// Loads the saved stack and brings it back against today's frames
266    /// (`egui_pop_model::context::restore`); publishes
267    /// `context.restored`. What could not come back, and why.
268    pub fn restore(
269        &mut self,
270        valid: &dyn Fn(&FrameId, &Json) -> Option<String>,
271    ) -> Result<Vec<Dropped>, String> {
272        let Some((p, document)) = &self.persist else {
273            return Ok(Vec::new());
274        };
275        let read = p
276            .load::<ContextDoc>(document, &model::schema())
277            .map_err(|e| e.to_string())?;
278        let Some(read) = read else {
279            return Ok(Vec::new());
280        };
281        let (state, dropped) = model::restore(&read.value.state, &self.registry, valid);
282        if !dropped.is_empty() {
283            self.write(&state)?;
284        }
285        self.state = state;
286        self.events.push((
287            "context.restored".into(),
288            json!({ "rev": self.state.rev, "state": self.state, "dropped": dropped }),
289        ));
290        Ok(dropped)
291    }
292}
293
294impl Contexts for LocalContexts {
295    fn registry(&self) -> FrameRegistry {
296        self.registry.clone()
297    }
298
299    fn state(&self) -> State {
300        self.state.clone()
301    }
302
303    fn rev(&self) -> u64 {
304        self.state.rev
305    }
306
307    fn holds(&self) -> Vec<Hold> {
308        self.holds.clone()
309    }
310
311    fn request(&mut self, envelope: &Envelope, origin: &Origin) -> Answer {
312        let source = source_of(origin);
313        match model::apply(&self.state, &self.registry, &self.holds, envelope) {
314            Ok(t) => {
315                if envelope.dry_run {
316                    return Answer::Done(Ok(t));
317                }
318                // Written before anyone hears of it.
319                if let Err(e) = self.write(&t.state) {
320                    log::warn!(target: "egui_pop", "writing the context stack: {e}");
321                }
322                self.state = t.state.clone();
323                self.events.push((
324                    "context.changed".into(),
325                    json!({
326                        "rev": t.state.rev,
327                        "state": t.state,
328                        "entered": t.entered,
329                        "left": t.left,
330                        "request": envelope.request,
331                        "redirected": t.redirected,
332                        "origin": source,
333                    }),
334                ));
335                for f in &t.left {
336                    self.events.push((
337                        "context.left".into(),
338                        json!({ "frame": f, "rev": t.state.rev }),
339                    ));
340                }
341                for f in &t.entered {
342                    self.events.push((
343                        "context.entered".into(),
344                        json!({ "frame": f, "rev": t.state.rev }),
345                    ));
346                }
347                Answer::Done(Ok(t))
348            }
349            Err(r) => {
350                if !envelope.dry_run {
351                    self.events.push((
352                        "context.refused".into(),
353                        json!({
354                            "request": envelope.request,
355                            "kind": r.kind,
356                            "reason": r.reason,
357                            "by": r.by,
358                            "rev": r.rev,
359                            "origin": source,
360                        }),
361                    ));
362                }
363                Answer::Done(Err(r))
364            }
365        }
366    }
367
368    fn hold(&mut self, groups: Vec<GroupId>, reason: &str, by: &str) -> Result<u64, String> {
369        self.next_hold += 1;
370        let hold = Hold {
371            token: self.next_hold,
372            groups,
373            reason: reason.into(),
374            by: by.into(),
375        };
376        self.events.push(("context.held".into(), json!(hold)));
377        self.holds.push(hold);
378        Ok(self.next_hold)
379    }
380
381    fn release(&mut self, token: u64) -> bool {
382        let before = self.holds.len();
383        self.holds.retain(|h| h.token != token);
384        let released = self.holds.len() != before;
385        if released {
386            self.events
387                .push(("context.released".into(), json!({ "token": token })));
388        }
389        released
390    }
391
392    fn declare(&mut self, owner: &OwnerId, spec: FrameSpec) -> Result<(), String> {
393        let id = spec.id.clone();
394        self.registry.insert(spec)?;
395        self.owners.insert(id, owner.clone());
396        Ok(())
397    }
398
399    fn remove_owner(&mut self, owner: &OwnerId) {
400        let gone: Vec<FrameId> = self
401            .owners
402            .iter()
403            .filter(|(_, o)| *o == owner)
404            .map(|(f, _)| f.clone())
405            .collect();
406        for f in gone {
407            self.registry.remove(&f);
408            self.owners.remove(&f);
409        }
410    }
411
412    fn take_events(&mut self) -> Vec<(String, Json)> {
413        std::mem::take(&mut self.events)
414    }
415}
416
417/// What the projection keeps.
418#[derive(Debug, Default)]
419struct Projection {
420    /// The state projected last.
421    applied: Option<State>,
422    /// The frames, as the owner had them then.
423    registry: FrameRegistry,
424    /// The layouts of the places not shown now, by layout key
425    /// (`State::layout_key`).
426    layouts: BTreeMap<String, Layout>,
427    /// The view states, by projection key.
428    views: BTreeMap<String, ViewState>,
429    /// Values kept per place (its frame id, `root`).
430    places: BTreeMap<String, BTreeMap<String, Json>>,
431    /// The context keys it set.
432    keys: BTreeSet<String>,
433    /// Counts the projection's moves (scroll areas restore once per
434    /// move).
435    generation: u64,
436}
437
438impl Projection {
439    fn key(&self) -> String {
440        self.applied
441            .as_ref()
442            .map_or_else(|| State::default().projection_key(), State::projection_key)
443    }
444
445    fn doc(&self) -> ViewDoc {
446        ViewDoc {
447            layouts: self.layouts.clone(),
448            views: self.views.clone(),
449            places: self.places.clone(),
450        }
451    }
452
453    fn title(&self, ctx: &egui::Context, frame: &FrameId) -> String {
454        title_in(ctx, &self.registry, frame)
455    }
456
457    /// A place as its crumb says it: its frame's label for the payload
458    /// (`FrameSpec::label`), else its title, and its payload when it is a
459    /// text or a number (`Album Holidays`, `Photo 3`).
460    fn crumb(&self, ctx: &egui::Context, e: &Entry) -> String {
461        let title = self.title(ctx, &e.frame);
462        if let Some(label) = self
463            .registry
464            .get(&e.frame)
465            .and_then(|s| s.label_of(&title, &e.payload))
466        {
467            return label;
468        }
469        match &e.payload {
470            Json::String(s) if !s.is_empty() => format!("{title} {s}"),
471            Json::Number(n) => format!("{title} {n}"),
472            _ => title,
473        }
474    }
475}
476
477/// A frame's title in the interface's language (`frame-<id>.title`,
478/// else its English); its id when it is not declared.
479fn title_in(ctx: &egui::Context, registry: &FrameRegistry, frame: &FrameId) -> String {
480    registry.get(frame).map_or_else(
481        || frame.to_string(),
482        |s| strings::frame_title(ctx, s.id.as_str(), &s.title),
483    )
484}
485
486/// The context stack in the application: the default owner, the
487/// projection, the requests waiting for a remote owner.
488pub struct ContextService {
489    local: Mutex<LocalContexts>,
490    projection: Mutex<Projection>,
491    /// The host owns the stack.
492    custom: AtomicBool,
493    pending: Mutex<Vec<(Pending, Origin)>>,
494    /// The stack's keys written by hand, by key.
495    hand_writes: Mutex<Vec<HandWrite>>,
496    /// The documents the stack and its view are kept in (see
497    /// [`documents`]), as read at start or at the last [`reload`].
498    documents: Mutex<(String, String)>,
499    /// The root crumb's title and label.
500    root: Root,
501    valid: Option<Validator>,
502}
503
504impl fmt::Debug for ContextService {
505    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506        f.debug_struct("ContextService")
507            .field("custom", &self.custom.load(Ordering::Relaxed))
508            .field("root", &self.root)
509            .finish_non_exhaustive()
510    }
511}
512
513impl ContextService {
514    /// Whether requests wait for a remote owner's answer.
515    pub fn switching(&self) -> bool {
516        !lock(&self.pending).is_empty()
517    }
518
519    /// The state the interface shows (the owner's, as projected last).
520    pub fn shown(&self) -> State {
521        lock(&self.projection).applied.clone().unwrap_or_default()
522    }
523
524    /// The frames, as projected last.
525    pub fn frames(&self) -> FrameRegistry {
526        lock(&self.projection).registry.clone()
527    }
528
529    /// The projection key shown.
530    pub fn key(&self) -> String {
531        lock(&self.projection).key()
532    }
533
534    /// The stack's own context keys written by hand, by key (see
535    /// [`is_stack_key`]).
536    pub fn hand_writes(&self) -> Vec<HandWrite> {
537        lock(&self.hand_writes).clone()
538    }
539}
540
541/// Whether a context key is the stack's own: `place`, `placeDepth`,
542/// `modePushed`, `mode.<group>`, the top place's `payload` and
543/// `payload.<field>`. Only the projection sets them; a plugin declares
544/// frames and reads them.
545pub fn is_stack_key(key: &str) -> bool {
546    matches!(key, "place" | "placeDepth" | "modePushed" | "payload")
547        || key.starts_with("mode.")
548        || key.starts_with("payload.")
549}
550
551/// One of the stack's own context keys, set by hand (`AppHandle::set_context`)
552/// instead of by the projection: two truths, and the projection's
553/// overwrites the plugin's at the next transition.
554#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
555pub struct HandWrite {
556    pub key: String,
557    /// The value written last.
558    pub value: String,
559    /// How many times.
560    pub times: u64,
561    /// The command running at the last write, when one was.
562    #[serde(skip_serializing_if = "Option::is_none")]
563    pub command: Option<CommandId>,
564    /// Who declared that command.
565    #[serde(skip_serializing_if = "Option::is_none")]
566    pub owner: Option<OwnerId>,
567}
568
569impl fmt::Display for HandWrite {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        write!(
572            f,
573            "`{}` set by hand to `{}` ({} time{}",
574            self.key,
575            self.value,
576            self.times,
577            if self.times == 1 { "" } else { "s" }
578        )?;
579        if let Some(c) = &self.command {
580            write!(f, ", last by the command `{c}`")?;
581            if let Some(o) = &self.owner {
582                write!(f, " of `{o}`")?;
583            }
584        }
585        write!(
586            f,
587            "): the context stack owns this key; declare a frame (`Ctx::frame`) and read the key instead"
588        )
589    }
590}
591
592/// Two frames that can be on together (a place and a mode, two modes of
593/// different groups) binding the same keys to different commands
594/// (`Ctx::frame_keybinding`): while both are on, one wins (the later
595/// declared, between equals) and the other never fires.
596#[derive(Clone, Debug, PartialEq, serde::Serialize)]
597pub struct FrameClash {
598    pub keys: String,
599    /// The frame whose binding loses, and its command.
600    pub loser: (FrameId, String),
601    /// The frame whose binding wins, and its command.
602    pub winner: (FrameId, String),
603    /// Why it wins: `declared later`, `higher layer`, `more specific
604    /// clause`.
605    pub because: &'static str,
606}
607
608impl fmt::Display for FrameClash {
609    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610        write!(
611            f,
612            "`{}`: the frames `{}` and `{}` can be on together and both bind it; while they are, `{}` ({}) wins over `{}` ({}), {}",
613            self.keys,
614            self.loser.0,
615            self.winner.0,
616            self.winner.1,
617            self.winner.0,
618            self.loser.1,
619            self.loser.0,
620            self.because
621        )
622    }
623}
624
625/// The keymap's frame clashes (see [`FrameClash`]): the key conflicts
626/// (`AppHandle::key_conflicts`) between two frames' own bindings.
627pub fn frame_clashes(app: &AppHandle) -> Vec<FrameClash> {
628    let Some(registry) = with_owner(app, |c| c.registry()) else {
629        return Vec::new();
630    };
631    let frame_of = |clause: &str| {
632        registry
633            .iter()
634            .find(|f| f.clause() == clause)
635            .map(|f| f.id.clone())
636    };
637    app.key_conflicts()
638        .into_iter()
639        .filter_map(|(lose, win)| {
640            let (lf, wf) = (frame_of(&lose.when)?, frame_of(&win.when)?);
641            if lf == wf {
642                return None;
643            }
644            let because = if lose.layer != win.layer {
645                "higher layer"
646            } else {
647                "declared later"
648            };
649            Some(FrameClash {
650                keys: lose.keys.to_string(),
651                loser: (lf, lose.action.to_string()),
652                winner: (wf, win.action.to_string()),
653                because,
654            })
655        })
656        .collect()
657}
658
659/// Says each frame clash once, as a diagnostic (`context-frame-key-clash`).
660fn report_clashes(app: &AppHandle) {
661    let said: BTreeSet<String> = app
662        .diagnostics()
663        .into_iter()
664        .filter(|d| d.code == "context-frame-key-clash")
665        .map(|d| d.message)
666        .collect();
667    for c in frame_clashes(app) {
668        let text = c.to_string();
669        if !said.contains(&text) {
670            app.warn("context-frame-key-clash", None, &c.keys, text);
671        }
672    }
673}
674
675/// Records a write of a stack key by hand; the first one of a key is a
676/// diagnostic (`context-key-by-hand`). Nothing without the plugin.
677pub(crate) fn written_by_hand(app: &AppHandle, key: &str, value: &str) {
678    let Some(svc) = app.service(&CONTEXTS) else {
679        return;
680    };
681    let (command, owner) = app
682        .running_command()
683        .map_or((None, None), |(c, o)| (Some(c), o));
684    let first = {
685        let mut writes = lock(&svc.hand_writes);
686        match writes.iter_mut().find(|w| w.key == key) {
687            Some(w) => {
688                w.value = value.into();
689                w.times += 1;
690                w.command = command;
691                w.owner = owner;
692                None
693            }
694            None => {
695                let w = HandWrite {
696                    key: key.into(),
697                    value: value.into(),
698                    times: 1,
699                    command,
700                    owner,
701                };
702                writes.push(w.clone());
703                Some(w)
704            }
705        }
706    };
707    if let Some(w) = first {
708        app.warn("context-key-by-hand", w.owner.as_ref(), key, w.to_string());
709    }
710}
711
712/// Runs `f` on the owner: the host's, else the plugin's `LocalContexts`.
713/// `None` without the plugin, or while the host (owning the stack) runs a
714/// command.
715pub fn with_owner<R>(app: &AppHandle, f: impl FnOnce(&mut dyn Contexts) -> R) -> Option<R> {
716    let svc = app.service(&CONTEXTS)?;
717    let custom = match app.with_host_mut(|h| h.contexts().is_some()) {
718        Some(c) => {
719            svc.custom.store(c, Ordering::Relaxed);
720            c
721        }
722        None => svc.custom.load(Ordering::Relaxed),
723    };
724    if custom {
725        app.with_host_mut(|h| h.contexts().map(f)).flatten()
726    } else {
727        let mut local = lock(&svc.local);
728        Some(f(&mut *local))
729    }
730}
731
732fn publish_events(app: &AppHandle, source: &str, events: Vec<(String, Json)>) {
733    for (name, data) in events {
734        app.publish(source, None, &name, data);
735    }
736}
737
738/// The state the interface shows, as projected last (`None` without the
739/// plugin).
740pub fn state(app: &AppHandle) -> Option<State> {
741    app.service(&CONTEXTS).map(|s| s.shown())
742}
743
744/// Asks the owner for a transition, through the `context.request` step;
745/// the projection follows (at once, or at the next pass while the areas
746/// are drawn). A refusal or a veto asked by the user shows in a toast,
747/// unless there was nothing to do.
748pub fn request(app: &AppHandle, envelope: Envelope, origin: &Origin) -> Outcome {
749    let args = json!({ "request": envelope, "origin": source_of(origin) });
750    let refused: Rc<RefCell<Option<Refusal>>> = Rc::default();
751    let said = refused.clone();
752    let who = origin.clone();
753    let out = app.step(&STEP_REQUEST, args, move |app, args| {
754        let env: Envelope = serde_json::from_value(args["request"].clone())
755            .map_err(|e| format!("not a context request: {e}"))?;
756        let (answer, events) = with_owner(app, |c| {
757            let a = c.request(&env, &who);
758            (a, c.take_events())
759        })
760        .ok_or_else(|| NO_STACK.to_string())?;
761        publish_events(app, &source_of(&who), events);
762        match answer {
763            Answer::Done(Ok(t)) => Ok(json!({
764                "rev": t.state.rev,
765                "entered": t.entered,
766                "left": t.left,
767                "redirected": t.redirected,
768                "dry_run": env.dry_run,
769            })),
770            Answer::Done(Err(r)) => {
771                let msg = r.to_string();
772                *said.borrow_mut() = Some(r);
773                Err(msg)
774            }
775            Answer::Later(p) => {
776                if let Some(svc) = app.service(&CONTEXTS) {
777                    lock(&svc.pending).push((p, who.clone()));
778                }
779                Ok(json!({ "pending": true }))
780            }
781        }
782    });
783    if app.drawing_areas() {
784        app.egui().request_repaint();
785    } else {
786        sync(app);
787    }
788    if *origin == Origin::User {
789        let reason = match &out {
790            Outcome::Vetoed { reason, .. } => Some(reason.clone()),
791            Outcome::Done(Err(e)) => match &*refused.borrow() {
792                Some(r) if r.kind == RefusalKind::Nothing => None,
793                Some(r) => Some(r.reason.clone()),
794                None => Some(e.clone()),
795            },
796            Outcome::Done(Ok(_)) => None,
797        };
798        if let Some(reason) = reason {
799            refusal_toast(app, &reason);
800        }
801    }
802    out
803}
804
805fn refusal_toast(app: &AppHandle, reason: &str) {
806    if let Some(t) = app.service(&crate::toasts::TOASTS) {
807        let ctx = app.egui();
808        t.notify(crate::toasts::Toast::warning(&strings::tr_args(
809            &ctx,
810            &txt::CONTEXT_REFUSED,
811            &[("reason", reason)],
812        )));
813    }
814}
815
816/// Enters a place, as the user.
817pub fn enter(app: &AppHandle, frame: FrameId, payload: Json) -> Outcome {
818    request(
819        app,
820        Envelope::new(Request::Enter { frame, payload }),
821        &Origin::User,
822    )
823}
824
825/// Leaves the top place, as the user.
826pub fn leave(app: &AppHandle) -> Outcome {
827    request(app, Envelope::new(Request::Leave), &Origin::User)
828}
829
830/// Back, as the user: pops the last pushed mode, else leaves the top
831/// place.
832pub fn back(app: &AppHandle) -> Outcome {
833    request(app, Envelope::new(Request::Back), &Origin::User)
834}
835
836/// Leaves places until `depth` are left (0: the root), as the user.
837pub fn jump(app: &AppHandle, depth: usize) -> Outcome {
838    request(app, Envelope::new(Request::Jump { depth }), &Origin::User)
839}
840
841/// Goes to a place path, as the user.
842pub fn go(app: &AppHandle, places: Vec<Entry>) -> Outcome {
843    request(app, Envelope::new(Request::Go { places }), &Origin::User)
844}
845
846/// Sets a mode, as the user.
847pub fn set_mode(app: &AppHandle, mode: FrameId) -> Outcome {
848    request(app, Envelope::new(Request::set(mode)), &Origin::User)
849}
850
851/// Pushes a mode, as the user.
852pub fn push_mode(app: &AppHandle, mode: FrameId) -> Outcome {
853    request(app, Envelope::new(Request::push(mode)), &Origin::User)
854}
855
856/// Pops the last pushed mode, as the user.
857pub fn pop_mode(app: &AppHandle) -> Outcome {
858    request(app, Envelope::new(Request::PopMode), &Origin::User)
859}
860
861/// Turns a group's mode off, as the user.
862pub fn clear_mode(app: &AppHandle, group: GroupId) -> Outcome {
863    request(
864        app,
865        Envelope::new(Request::ClearMode { group }),
866        &Origin::User,
867    )
868}
869
870/// Holds groups of the stack (empty: all of it) for `by`: requests
871/// touching them are refused with `reason` until [`release`].
872pub fn hold(app: &AppHandle, groups: Vec<GroupId>, reason: &str, by: &str) -> Result<u64, String> {
873    let (r, events) = with_owner(app, |c| {
874        let r = c.hold(groups, reason, by);
875        (r, c.take_events())
876    })
877    .ok_or_else(|| NO_STACK.to_string())?;
878    publish_events(app, by, events);
879    r
880}
881
882/// Releases a hold; whether it was held.
883pub fn release(app: &AppHandle, token: u64) -> bool {
884    let Some((r, events)) = with_owner(app, |c| {
885        let r = c.release(token);
886        (r, c.take_events())
887    }) else {
888        return false;
889    };
890    publish_events(app, "egui_pop", events);
891    r
892}
893
894/// Projects the owner's state when its revision moved (each pass does).
895pub fn sync(app: &AppHandle) {
896    let Some(svc) = app.service(&CONTEXTS) else {
897        return;
898    };
899    let applied = lock(&svc.projection).applied.as_ref().map(|s| s.rev);
900    let Some(rev) = with_owner(app, |c| c.rev()) else {
901        return;
902    };
903    if applied == Some(rev) {
904        return;
905    }
906    let Some((state, registry, events)) =
907        with_owner(app, |c| (c.state(), c.registry(), c.take_events()))
908    else {
909        return;
910    };
911    publish_events(app, "egui_pop", events);
912    project(app, &svc, state, registry);
913}
914
915/// Shows a panel in a layout, in its declared area when it was closed.
916fn show_panel(app: &AppHandle, layout: &mut Layout, panel: &PanelId) {
917    if layout.shows(panel) {
918        return;
919    }
920    if let Some(spec) = app.panels().into_iter().find(|s| s.id == *panel) {
921        layout.place(panel, spec.area);
922    }
923}
924
925/// The layout of a projection key seen for the first time: the arranged
926/// frame's arrangement when it changed (a mode declaring one, else the
927/// place; see `arrangements::arranged_frame`), the place's layout as it
928/// was left, else the nearest enclosing place's (as it was left, else
929/// its arrangement; the root's last), else the layout shown; then the modes' panels shown and
930/// hidden.
931fn derive(
932    app: &AppHandle,
933    p: &Projection,
934    old: Option<&State>,
935    new: &State,
936    registry: &FrameRegistry,
937    current: &Layout,
938) -> Layout {
939    // Another payload of the same places is the same place for the
940    // layout, unless the payload chooses the arrangement.
941    let without_modes = |s: &State| {
942        State {
943            modes: Vec::new(),
944            ..s.clone()
945        }
946        .layout_key(registry)
947    };
948    let same_place = old.is_some_and(|o| without_modes(o) == without_modes(new));
949    let arranged = crate::arrangements::arranged_in(new, registry);
950    let was_arranged = old.and_then(|o| crate::arrangements::arranged_in(o, registry));
951    let arrangement = |frame: &FrameId, declared: Option<String>| {
952        crate::arrangements::of_frame(app, frame, declared)
953            .and_then(|name| crate::arrangements::layout_of(app, &name))
954    };
955    let mut layout =
956        if same_place && arranged.as_ref().map(|a| &a.0) == was_arranged.as_ref().map(|a| &a.0) {
957            let mut l = current.clone();
958            // The modes left take back what they did.
959            if let Some(o) = old {
960                for m in o.modes.iter().filter(|m| !new.is_on(&m.frame)) {
961                    if let Some(spec) = registry.get(&m.frame) {
962                        for panel in &spec.show {
963                            l.hide(panel);
964                        }
965                        for panel in &spec.hide {
966                            show_panel(app, &mut l, panel);
967                        }
968                    }
969                }
970            }
971            l
972        } else {
973            let base = State {
974                modes: Vec::new(),
975                ..new.clone()
976            };
977            let place = new.places.last().map(|e| &e.frame);
978            match arranged {
979                // A mode with an arrangement of its own.
980                Some((frame, declared)) if Some(&frame) != place => arrangement(&frame, declared),
981                // The place: as it was left, else its arrangement (the
982                // one its payload chooses, `FrameSpec::arrangement_for`),
983                // else the nearest enclosing place's layout (the root's
984                // last), whichever place the user came from.
985                Some((frame, declared)) => p
986                    .layouts
987                    .get(&base.layout_key(registry))
988                    .cloned()
989                    .or_else(|| arrangement(&frame, declared))
990                    .or_else(|| enclosing_layout(p, new, &frame, registry, &arrangement)),
991                // The root, as it was left.
992                None => p.layouts.get(&base.layout_key(registry)).cloned(),
993            }
994            // Nothing remembered at all: the layout shown.
995            .unwrap_or_else(|| current.clone())
996        };
997    for m in &new.modes {
998        if let Some(spec) = registry.get(&m.frame) {
999            for panel in &spec.show {
1000                show_panel(app, &mut layout, panel);
1001            }
1002            for panel in &spec.hide {
1003                layout.hide(panel);
1004            }
1005        }
1006    }
1007    layout
1008}
1009
1010/// The layout of the nearest place enclosing the top one, the root last:
1011/// as it was left (without modes, else with the new state's modes), else
1012/// the arrangement it starts from (`arrangement`, given its frame and what
1013/// it declares). For a place (`frame`) that declares no arrangement and
1014/// has no layout of its own, entered for the first time; debug builds
1015/// warn about it.
1016fn enclosing_layout(
1017    p: &Projection,
1018    new: &State,
1019    frame: &FrameId,
1020    registry: &FrameRegistry,
1021    arrangement: &dyn Fn(&FrameId, Option<String>) -> Option<Layout>,
1022) -> Option<Layout> {
1023    let found = (0..new.places.len()).rev().find_map(|depth| {
1024        let outer = State {
1025            places: new.places[..depth].to_vec(),
1026            modes: Vec::new(),
1027            ..new.clone()
1028        };
1029        let with_modes = State {
1030            modes: new.modes.clone(),
1031            ..outer.clone()
1032        };
1033        [outer.layout_key(registry), with_modes.layout_key(registry)]
1034            .into_iter()
1035            .find_map(|key| p.layouts.get(&key).cloned().map(|l| (key, l)))
1036            .or_else(|| {
1037                let (f, declared) = crate::arrangements::arranged_in(&outer, registry)?;
1038                arrangement(&f, declared).map(|l| (outer.layout_key(registry), l))
1039            })
1040    });
1041    #[cfg(debug_assertions)]
1042    {
1043        let from = found.as_ref().map_or_else(
1044            || "the layout shown".to_string(),
1045            |(k, _)| format!("`{k}`'s layout"),
1046        );
1047        log::warn!(
1048            target: "egui_pop",
1049            "the place `{frame}` declares no arrangement and has no layout of its own: it starts \
1050             from {from}; declare one with `FrameSpec::arrangement`"
1051        );
1052    }
1053    #[cfg(not(debug_assertions))]
1054    let _ = frame;
1055    found.map(|(_, l)| l)
1056}
1057
1058/// The application window whose workbench the stack's places and modes
1059/// arrange: the main one. A place switch puts in that window's part of
1060/// a layout ([`Layout::with_window_from`]) and keeps that part only;
1061/// the panels docked in other windows are left alone.
1062const PROJECTED_WINDOW: &str = egui_pop_model::layout::MAIN_WINDOW;
1063
1064/// The part of a layout a place keeps: the projected window's, without
1065/// the other windows' areas (they are not the place's to restore).
1066fn window_part(layout: &Layout) -> Layout {
1067    Layout {
1068        windows: Vec::new(),
1069        ..layout.clone()
1070    }
1071}
1072
1073/// Projects a new state: keeps the view of the key left, puts the
1074/// layout of the key entered, sets the context keys, gives the focus
1075/// back, says where the user is now.
1076fn project(app: &AppHandle, svc: &ContextService, new: State, registry: FrameRegistry) {
1077    let current = app.layout();
1078    let focused = app.focused_panel();
1079    let mut p = lock(&svc.projection);
1080    let old = p.applied.clone();
1081    let old_key = old.as_ref().map(State::projection_key);
1082    let new_key = new.projection_key();
1083    let moved = old_key.as_deref() != Some(new_key.as_str());
1084    // The layout's own key: another photo in the same place keeps the
1085    // layout shown (a detached panel stays in its window).
1086    let old_layout = old.as_ref().map(|o| o.layout_key(&p.registry));
1087    let new_layout = new.layout_key(&registry);
1088    let mut target: Option<Layout> = None;
1089    let mut focus: Option<PanelId> = None;
1090    if moved {
1091        if let Some(k) = &old_key {
1092            p.views.entry(k.clone()).or_default().focus = focused;
1093        }
1094        if let Some(k) = old_layout.as_ref().filter(|k| **k != new_layout) {
1095            p.layouts.insert(k.clone(), window_part(&current));
1096            let kept = p.layouts.remove(&new_layout);
1097            target = Some(match kept {
1098                Some(l) => l,
1099                None => derive(app, &p, old.as_ref(), &new, &registry, &current),
1100            });
1101        } else if old_key.is_none() {
1102            // At start the layout loaded is the shown key's, unless the
1103            // restore dropped frames and the key shown is another one.
1104            target = p.layouts.remove(&new_layout);
1105        }
1106        // Only the stack's window changes: panels docked in the other
1107        // application windows stay where they are.
1108        target = target.map(|l| current.with_window_from(&l, PROJECTED_WINDOW));
1109        focus = p.views.get(&new_key).and_then(|v| v.focus.clone());
1110        p.generation += 1;
1111    }
1112    let keys = new.when_keys(&registry);
1113    let stale: Vec<String> = p
1114        .keys
1115        .iter()
1116        .filter(|k| !keys.iter().any(|(n, _)| n == *k))
1117        .cloned()
1118        .collect();
1119    p.keys = keys.iter().map(|(k, _)| k.clone()).collect();
1120    p.registry = registry;
1121    p.applied = Some(new.clone());
1122    let ctx = app.egui();
1123    let path: Vec<String> = std::iter::once(root_title(app, svc))
1124        .chain(new.places.iter().map(|e| p.crumb(&ctx, e)))
1125        .collect();
1126    let doc = p.doc();
1127    drop(p);
1128    // The value store's new steps are made here (`StepInfo::place`).
1129    lock(&app.store()).set_place(new.places.clone());
1130    for k in stale {
1131        app.set_stack_context(&k, "");
1132    }
1133    for (k, v) in &keys {
1134        app.set_stack_context(k, v);
1135    }
1136    if let Some(l) = target
1137        && l != current
1138    {
1139        app.set_layout(l);
1140    }
1141    if let Some(panel) = focus
1142        && app.panel_visible(&panel)
1143    {
1144        app.focus_panel(&panel);
1145    }
1146    save_view(app, &doc);
1147    if moved && old.is_some() {
1148        let text = strings::tr_args(&ctx, &txt::CONTEXT_NOW_IN, &[("place", &path.join(" › "))]);
1149        a11y::announce(&ctx, text, Politeness::Polite);
1150    }
1151    app.egui().request_repaint();
1152}
1153
1154fn save_view(app: &AppHandle, doc: &ViewDoc) {
1155    if app.persist().is_none() {
1156        return;
1157    }
1158    match model::view_schema().save(doc) {
1159        Ok(text) => {
1160            let document = app
1161                .service(&CONTEXTS)
1162                .map_or_else(|| VIEW_DOCUMENT.into(), |s| lock(&s.documents).1.clone());
1163            app.save_later(&document, text);
1164        }
1165        Err(e) => log::warn!(target: "egui_pop", "the view document: {e}"),
1166    }
1167}
1168
1169fn root_title(app: &AppHandle, svc: &ContextService) -> String {
1170    svc.root.say(&app.egui())
1171}
1172
1173/// What the root crumb's label is asked about
1174/// ([`ContextsPlugin::root_label`]).
1175#[derive(Debug)]
1176pub struct RootLabelCall<'a> {
1177    /// To translate with (`egui_pop_core::strings::tr_args`).
1178    pub ctx: &'a egui::Context,
1179    /// The root's title as it would be said without the label: "Home",
1180    /// or what [`ContextsPlugin::root`] or
1181    /// [`root_key`](ContextsPlugin::root_key) give, translated.
1182    pub title: &'a str,
1183}
1184
1185/// The root crumb's label (`ContextsPlugin::root_label`): `None` keeps
1186/// the title.
1187pub type RootLabel = Arc<dyn Fn(&RootLabelCall<'_>) -> Option<String> + Send + Sync>;
1188
1189/// How the root's crumb is said.
1190#[derive(Clone, Default)]
1191struct Root {
1192    /// A text as given ([`ContextsPlugin::root`]).
1193    text: Option<String>,
1194    /// A string translated each time it is said
1195    /// ([`ContextsPlugin::root_key`]).
1196    key: Option<strings::StrKey>,
1197    label: Option<RootLabel>,
1198}
1199
1200impl fmt::Debug for Root {
1201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1202        f.debug_struct("Root")
1203            .field("text", &self.text)
1204            .field("key", &self.key)
1205            .field("label", &self.label.is_some())
1206            .finish()
1207    }
1208}
1209
1210impl Root {
1211    /// The root's crumb, as the interface says it now: the label, else
1212    /// the title (the text given, else the key or "Home", translated).
1213    fn say(&self, ctx: &egui::Context) -> String {
1214        let title = self
1215            .text
1216            .clone()
1217            .unwrap_or_else(|| strings::tr(ctx, self.key.as_ref().unwrap_or(&txt::CONTEXT_ROOT)));
1218        self.label
1219            .as_ref()
1220            .and_then(|f| f(&RootLabelCall { ctx, title: &title }))
1221            .unwrap_or(title)
1222    }
1223}
1224
1225/// A value a component keeps for the projection key shown (a list's
1226/// scroll offset, a selection), saved with the view state.
1227pub fn view_value(app: &AppHandle, name: &str) -> Option<Json> {
1228    let svc = app.service(&CONTEXTS)?;
1229    let p = lock(&svc.projection);
1230    let key = p.key();
1231    p.views.get(&key).and_then(|v| v.values.get(name).cloned())
1232}
1233
1234/// Keeps a value for the projection key shown; written to the `view`
1235/// document a second later.
1236pub fn set_view_value(app: &AppHandle, name: &str, value: Json) {
1237    let Some(svc) = app.service(&CONTEXTS) else {
1238        return;
1239    };
1240    let doc = {
1241        let mut p = lock(&svc.projection);
1242        let key = p.key();
1243        let view = p.views.entry(key).or_default();
1244        if view.values.get(name) == Some(&value) {
1245            return;
1246        }
1247        view.values.insert(name.to_string(), value);
1248        p.doc()
1249    };
1250    save_view(app, &doc);
1251}
1252
1253/// A value kept for a place (its frame id, [`ROOT`] at the root) rather
1254/// than for a projection key: the same in every album, whatever the
1255/// modes. Saved with the view state.
1256pub fn place_value_of(app: &AppHandle, place: &str, name: &str) -> Option<Json> {
1257    let svc = app.service(&CONTEXTS)?;
1258    let p = lock(&svc.projection);
1259    p.places.get(place).and_then(|v| v.get(name).cloned())
1260}
1261
1262/// A value kept for the place shown ([`place_value_of`]).
1263pub fn place_value(app: &AppHandle, name: &str) -> Option<Json> {
1264    let place = state(app)?.place().to_string();
1265    place_value_of(app, &place, name)
1266}
1267
1268/// Keeps a value for the place shown (`Json::Null` forgets it); written
1269/// to the `view` document a second later.
1270pub fn set_place_value(app: &AppHandle, name: &str, value: Json) {
1271    let Some(svc) = app.service(&CONTEXTS) else {
1272        return;
1273    };
1274    let doc = {
1275        let mut p = lock(&svc.projection);
1276        let place = p.applied.clone().unwrap_or_default().place().to_string();
1277        let values = p.places.entry(place.clone()).or_default();
1278        if value.is_null() {
1279            if values.remove(name).is_none() {
1280                return;
1281            }
1282            if values.is_empty() {
1283                p.places.remove(&place);
1284            }
1285        } else {
1286            if values.get(name) == Some(&value) {
1287                return;
1288            }
1289            values.insert(name.to_string(), value);
1290        }
1291        p.doc()
1292    };
1293    save_view(app, &doc);
1294}
1295
1296/// A scroll area whose offset is kept per projection key: entering a
1297/// place and coming back finds it where it was.
1298pub fn scroll_area<R>(
1299    ui: &mut Ui,
1300    app: &AppHandle,
1301    name: &str,
1302    area: egui::ScrollArea,
1303    add: impl FnOnce(&mut Ui) -> R,
1304) -> R {
1305    let generation = app
1306        .service(&CONTEXTS)
1307        .map_or(0, |s| lock(&s.projection).generation);
1308    let saved = view_value(app, name)
1309        .and_then(|v| v.as_f64())
1310        .map(|v| v as f32);
1311    let id = ui.make_persistent_id(("egui_pop.contexts.scroll", name));
1312    let slot = SCROLL_APPLIED.keyed(id);
1313    let applied = slot.get(ui.ctx());
1314    let mut area = area.id_salt(id);
1315    if applied != Some(generation) {
1316        area = area.vertical_scroll_offset(saved.unwrap_or(0.0));
1317        slot.set(ui.ctx(), generation);
1318    }
1319    let out = ui.scroll_area(area, add);
1320    let y = out.state.clamped_offset().y;
1321    let changed = match saved {
1322        Some(s) => (s - y).abs() > 0.5,
1323        None => y > 0.5,
1324    };
1325    if changed {
1326        set_view_value(app, name, json!(y));
1327    }
1328    out.inner
1329}
1330
1331/// The breadcrumb's crumbs as the interface says them: the root's title,
1332/// then each place's (its title, and its payload when it is a text or a
1333/// number). Crumb `i` is reached with [`jump`]`(app, i)`. Empty without
1334/// the context plugin.
1335pub fn crumbs(app: &AppHandle) -> Vec<String> {
1336    let Some(svc) = app.service(&CONTEXTS) else {
1337        return Vec::new();
1338    };
1339    let ctx = app.egui();
1340    let p = lock(&svc.projection);
1341    let state = p.applied.clone().unwrap_or_default();
1342    std::iter::once(root_title(app, &svc))
1343        .chain(state.places.iter().map(|e| p.crumb(&ctx, e)))
1344        .collect()
1345}
1346
1347/// The icon each crumb's place declares (`FrameSpec::icon`), by name,
1348/// in [`crumbs`]' order: `None` for the root and for a place without one.
1349pub fn crumb_icons(app: &AppHandle) -> Vec<Option<String>> {
1350    let Some(svc) = app.service(&CONTEXTS) else {
1351        return Vec::new();
1352    };
1353    let p = lock(&svc.projection);
1354    let state = p.applied.clone().unwrap_or_default();
1355    std::iter::once(None)
1356        .chain(
1357            state
1358                .places
1359                .iter()
1360                .map(|e| p.registry.get(&e.frame).and_then(|s| s.icon.clone())),
1361        )
1362        .collect()
1363}
1364
1365/// Every declared frame's icon name (places and modes).
1366pub(crate) fn frame_icons(app: &AppHandle) -> Vec<(FrameId, String)> {
1367    let Some(svc) = app.service(&CONTEXTS) else {
1368        return Vec::new();
1369    };
1370    // The owner's registry, current right after a plugin connects; the
1371    // projection's while the owner is busy.
1372    let registry =
1373        with_owner(app, |c| c.registry()).unwrap_or_else(|| lock(&svc.projection).registry.clone());
1374    registry
1375        .iter()
1376        .filter_map(|s| s.icon.clone().map(|i| (s.id.clone(), i)))
1377        .collect()
1378}
1379
1380/// An active mode, as a chip shows it.
1381#[derive(Clone, Debug, PartialEq, serde::Serialize)]
1382pub struct Chip {
1383    pub frame: FrameId,
1384    pub group: GroupId,
1385    /// Its title, translated.
1386    pub title: String,
1387    #[serde(skip_serializing_if = "Option::is_none")]
1388    pub icon: Option<String>,
1389    /// Its tone's name, as declared (`FrameSpec::tone`).
1390    #[serde(skip_serializing_if = "Option::is_none")]
1391    pub tone: Option<String>,
1392    /// The last pushed mode: leaving it goes back to what it replaced.
1393    pub pushed: bool,
1394    /// Its group is shown in the status bar (`FrameSpec::visible`).
1395    pub visible: bool,
1396}
1397
1398impl Chip {
1399    /// The request leaving it: a pop for the last pushed mode (back to
1400    /// what it replaced), else its group turned off.
1401    pub fn leave(&self) -> Request {
1402        if self.pushed {
1403            Request::PopMode
1404        } else {
1405            Request::ClearMode {
1406                group: self.group.clone(),
1407            }
1408        }
1409    }
1410}
1411
1412/// The active modes, in the order they came. Empty without the context
1413/// plugin.
1414pub fn chips(app: &AppHandle) -> Vec<Chip> {
1415    let Some(svc) = app.service(&CONTEXTS) else {
1416        return Vec::new();
1417    };
1418    let ctx = app.egui();
1419    let p = lock(&svc.projection);
1420    let state = p.applied.clone().unwrap_or_default();
1421    let visible = p.registry.visible_groups();
1422    let last_pushed = state.modes.iter().rposition(|m| m.life == Life::Pushed);
1423    state
1424        .modes
1425        .iter()
1426        .enumerate()
1427        .map(|(i, m)| {
1428            let spec = p.registry.get(&m.frame);
1429            Chip {
1430                frame: m.frame.clone(),
1431                group: m.group.clone(),
1432                title: p.title(&ctx, &m.frame),
1433                icon: spec.and_then(|s| s.icon.clone()),
1434                tone: spec.and_then(|s| s.tone.clone()),
1435                pushed: Some(i) == last_pushed,
1436                visible: visible.contains(&m.group),
1437            }
1438        })
1439        .collect()
1440}
1441
1442/// Why the owner would refuse a request now (its guards, a hold), asked
1443/// as a dry run of the stack's own owner; `None` when it would go, when
1444/// there is nothing to do, or when the host owns the stack (its answer
1445/// may come later).
1446pub fn why_not(app: &AppHandle, request: Request) -> Option<String> {
1447    let svc = app.service(&CONTEXTS)?;
1448    if svc.custom.load(Ordering::Relaxed) {
1449        return None;
1450    }
1451    let env = Envelope::new(request).dry_run();
1452    let answer = with_owner(app, |c| c.request(&env, &Origin::User))?;
1453    match answer {
1454        Answer::Done(Err(r)) if r.kind != RefusalKind::Nothing => Some(r.reason),
1455        _ => None,
1456    }
1457}
1458
1459/// The breadcrumb: the root, then each place; a crumb jumps back to its
1460/// level (the last one is where the user is).
1461pub fn breadcrumb(ui: &mut Ui, app: &AppHandle) {
1462    let Some(svc) = app.service(&CONTEXTS) else {
1463        return;
1464    };
1465    let crumbs = crumbs(app);
1466    let mut jump_to = None;
1467    ui.horizontal_wrapped(|ui| {
1468        for (i, title) in crumbs.iter().enumerate() {
1469            if i > 0 {
1470                ui.weak("›");
1471            }
1472            let here = i + 1 == crumbs.len();
1473            if ui
1474                .add(widgets::SelectableRow::new(here, title.as_str()))
1475                .clicked()
1476                && !here
1477            {
1478                jump_to = Some(i);
1479            }
1480        }
1481        if svc.switching() {
1482            ui.spinner();
1483        }
1484    });
1485    if let Some(depth) = jump_to {
1486        jump(app, depth);
1487    }
1488}
1489
1490/// The active modes as chips, each with a way out (a pushed mode pops,
1491/// a set one is turned off).
1492pub fn mode_chips(ui: &mut Ui, app: &AppHandle) {
1493    let chips = chips(app);
1494    let mut leave = None;
1495    ui.horizontal_wrapped(|ui| {
1496        for chip in &chips {
1497            let title = &chip.title;
1498            let r = ui.add(widgets::SelectableRow::new(true, format!("{title}  ×")));
1499            let name = strings::tr_args(ui.ctx(), &txt::CONTEXT_LEAVE_MODE, &[("mode", title)]);
1500            a11y::name(&r, Role::Button, &name);
1501            let r = r.on_hover_text(name.as_str());
1502            if r.clicked() {
1503                leave = Some(chip.leave());
1504            }
1505        }
1506    });
1507    if let Some(r) = leave {
1508        request(app, Envelope::new(r), &Origin::User);
1509    }
1510}
1511
1512/// The modes of a group as a row of choices, the one on selected;
1513/// `none` adds a choice turning the group off.
1514pub fn mode_switch(ui: &mut Ui, app: &AppHandle, group: &GroupId, none: bool) {
1515    let Some(svc) = app.service(&CONTEXTS) else {
1516        return;
1517    };
1518    let (modes, on): (Vec<(FrameId, String)>, Option<FrameId>) = {
1519        let p = lock(&svc.projection);
1520        let groups = p.registry.groups();
1521        let modes = groups
1522            .get(group)
1523            .map(|v| {
1524                v.iter()
1525                    .map(|s| {
1526                        (
1527                            s.id.clone(),
1528                            strings::frame_title(ui.ctx(), s.id.as_str(), &s.title),
1529                        )
1530                    })
1531                    .collect::<Vec<_>>()
1532            })
1533            .unwrap_or_default();
1534        let on = p
1535            .applied
1536            .as_ref()
1537            .and_then(|s| s.mode_of(group.as_str()).cloned());
1538        (modes, on)
1539    };
1540    let mut asked = None;
1541    ui.horizontal_wrapped(|ui| {
1542        if none {
1543            let label = strings::tr(ui.ctx(), &txt::CONTEXT_NO_MODE);
1544            if ui
1545                .add(widgets::SelectableRow::new(on.is_none(), label))
1546                .clicked()
1547                && on.is_some()
1548            {
1549                asked = Some(Request::ClearMode {
1550                    group: group.clone(),
1551                });
1552            }
1553        }
1554        for (id, title) in &modes {
1555            let selected = on.as_ref() == Some(id);
1556            if ui
1557                .add(widgets::SelectableRow::new(selected, title.as_str()))
1558                .clicked()
1559                && !selected
1560            {
1561                asked = Some(Request::set(id.clone()));
1562            }
1563        }
1564    });
1565    if let Some(r) = asked {
1566        request(app, Envelope::new(r), &Origin::User);
1567    }
1568}
1569
1570/// A pushed mode as a toggle: pushes it, or pops it (turns it off when
1571/// it is not the last pushed).
1572pub fn mode_toggle(ui: &mut Ui, app: &AppHandle, mode: &FrameId) -> egui::Response {
1573    let (title, on, last) = match app.service(&CONTEXTS) {
1574        Some(svc) => {
1575            let p = lock(&svc.projection);
1576            let state = p.applied.clone().unwrap_or_default();
1577            let entry = state.modes.iter().find(|m| m.frame == *mode).cloned();
1578            let last = state
1579                .modes
1580                .iter()
1581                .rev()
1582                .find(|m| m.life == Life::Pushed)
1583                .is_some_and(|m| m.frame == *mode);
1584            (p.title(ui.ctx(), mode), entry, last)
1585        }
1586        None => (mode.to_string(), None, false),
1587    };
1588    let r = ui.add(widgets::SelectableRow::new(on.is_some(), title));
1589    if r.clicked() {
1590        let req = match &on {
1591            None => Request::push(mode.clone()),
1592            Some(_) if last => Request::PopMode,
1593            Some(m) => Request::ClearMode {
1594                group: m.group.clone(),
1595            },
1596        };
1597        request(app, Envelope::new(req), &Origin::User);
1598    }
1599    r
1600}
1601
1602/// After an undo, a redo or a jump in one of the owner's scopes: a step
1603/// made in another place than the one shown says where, with "Go there".
1604/// The place is the step's own (`StepInfo::place`, root first; empty:
1605/// the root); a component's local scope is undone where it is shown,
1606/// and says nothing.
1607fn undone(app: &AppHandle, what: Walked, result: &Result<Json, String>) {
1608    let Ok(v) = result else { return };
1609    let Some(step) = v["steps"]
1610        .as_array()
1611        .and_then(|s| s.last())
1612        .and_then(|s| serde_json::from_value::<StepInfo>(s.clone()).ok())
1613    else {
1614        return;
1615    };
1616    if history::scopes(app)
1617        .iter()
1618        .any(|s| s.local && s.id == step.scope)
1619    {
1620        return;
1621    }
1622    let Some(svc) = app.service(&CONTEXTS) else {
1623        return;
1624    };
1625    let redo = match what {
1626        Walked::Undo => false,
1627        Walked::Redo => true,
1628        // A jump that left the step done redid it.
1629        Walked::Jump => {
1630            history::line(app, &step.scope).is_some_and(|l| l.undo.iter().any(|s| s.id == step.id))
1631        }
1632    };
1633    let (here, title) = {
1634        let p = lock(&svc.projection);
1635        let here = p
1636            .applied
1637            .as_ref()
1638            .map(|s| s.places.clone())
1639            .unwrap_or_default();
1640        let title = step.place.last().map(|e| p.crumb(&app.egui(), e));
1641        (here, title)
1642    };
1643    if step.place == here {
1644        return;
1645    }
1646    let Some(t) = app.service(&crate::toasts::TOASTS) else {
1647        return;
1648    };
1649    let ctx = app.egui();
1650    let place = title.unwrap_or_else(|| root_title(app, &svc));
1651    let text = strings::tr_args(
1652        &ctx,
1653        if redo {
1654            &txt::CONTEXT_REDONE_IN
1655        } else {
1656            &txt::CONTEXT_UNDONE_IN
1657        },
1658        &[("place", &place)],
1659    );
1660    t.notify(crate::toasts::Toast::info(&text).action(
1661        &strings::tr(&ctx, &txt::CONTEXT_GO_THERE),
1662        CMD_GO,
1663        json!({ "places": step.place }),
1664    ));
1665}
1666
1667/// Which walk of a history ran.
1668#[derive(Clone, Copy, Debug)]
1669enum Walked {
1670    Undo,
1671    Redo,
1672    Jump,
1673}
1674
1675/// Each pass: the answers a remote owner gave, the projection.
1676fn pass(app: &AppHandle) {
1677    let Some(svc) = app.service(&CONTEXTS) else {
1678        return;
1679    };
1680    let arrived: Vec<(Result<Json, String>, Origin)> = {
1681        let mut pending = lock(&svc.pending);
1682        let mut out = Vec::new();
1683        pending.retain(|(p, o)| match p.take() {
1684            Some(r) => {
1685                out.push((r, o.clone()));
1686                false
1687            }
1688            None => true,
1689        });
1690        out
1691    };
1692    for (r, origin) in arrived {
1693        if let (Err(e), Origin::User) = (&r, &origin) {
1694            refusal_toast(app, e);
1695        }
1696    }
1697    sync(app);
1698}
1699
1700/// The documents the stack (`LocalContexts`) and its view are kept in:
1701/// [`CONTEXT_DOCUMENT`] and [`VIEW_DOCUMENT`] beside the layout's
1702/// document as the host names it (`Host::layout_document`), so a host
1703/// keeping a layout per workspace keeps a stack per workspace too; at the
1704/// top when it names none.
1705pub fn documents(app: &AppHandle) -> (String, String) {
1706    let layout = app.with_host_mut(|h| h.layout_document()).flatten();
1707    match layout.as_deref().and_then(|l| l.rsplit_once('/')) {
1708        Some((dir, _)) => (
1709            format!("{dir}/{CONTEXT_DOCUMENT}"),
1710            format!("{dir}/{VIEW_DOCUMENT}"),
1711        ),
1712        None => (CONTEXT_DOCUMENT.into(), VIEW_DOCUMENT.into()),
1713    }
1714}
1715
1716/// Reads the stack and its view again from [`documents`], as at start:
1717/// after the host changed where they are (another workspace opened in
1718/// the same window). What was shown is forgotten (its view was written
1719/// already); what the documents hold, checked against today's frames,
1720/// is projected.
1721pub fn reload(app: &AppHandle) {
1722    let Some(svc) = app.service(&CONTEXTS) else {
1723        return;
1724    };
1725    {
1726        let mut p = lock(&svc.projection);
1727        p.applied = None;
1728        p.layouts.clear();
1729        p.views.clear();
1730        p.places.clear();
1731    }
1732    if !svc.custom.load(Ordering::Relaxed) {
1733        let mut l = lock(&svc.local);
1734        // Without a document the stack starts empty, its revision kept.
1735        let rev = l.state.rev;
1736        l.state = State {
1737            rev,
1738            ..State::default()
1739        };
1740    }
1741    start(app);
1742}
1743
1744/// At start: the owner's stack restored (`LocalContexts` from its
1745/// document), the view document loaded, the first projection.
1746fn start(app: &AppHandle) {
1747    let Some(svc) = app.service(&CONTEXTS) else {
1748        return;
1749    };
1750    let (context_document, view_document) = documents(app);
1751    *lock(&svc.documents) = (context_document.clone(), view_document.clone());
1752    let custom = app
1753        .with_host_mut(|h| h.contexts().is_some())
1754        .unwrap_or(false);
1755    svc.custom.store(custom, Ordering::Relaxed);
1756    let Some(persist) = app.persist() else {
1757        sync(app);
1758        return;
1759    };
1760    if !custom {
1761        let valid = svc.valid.clone();
1762        let (restored, events) = {
1763            let mut l = lock(&svc.local);
1764            l.set_persist(Some(persist.clone()), &context_document);
1765            let r = match &valid {
1766                Some(v) => l.restore(&**v),
1767                None => l.restore(&|_, _| None),
1768            };
1769            (r, l.take_events())
1770        };
1771        publish_events(app, "egui_pop", events);
1772        match restored {
1773            Ok(dropped) if !dropped.is_empty() => {
1774                if let Some(t) = app.service(&crate::toasts::TOASTS) {
1775                    let registry = lock(&svc.local).registry();
1776                    let ctx = app.egui();
1777                    let frames = dropped
1778                        .iter()
1779                        .map(|d| format!("{} ({})", title_in(&ctx, &registry, &d.frame), d.why))
1780                        .collect::<Vec<_>>()
1781                        .join(", ");
1782                    t.notify(crate::toasts::Toast::warning(&strings::tr_args(
1783                        &app.egui(),
1784                        &txt::CONTEXT_DROPPED,
1785                        &[("frames", &frames)],
1786                    )));
1787                }
1788            }
1789            Ok(_) => {}
1790            Err(e) => log::warn!(target: "egui_pop", "the context stack could not be read: {e}"),
1791        }
1792    }
1793    match persist.load::<ViewDoc>(&view_document, &model::view_schema()) {
1794        Ok(Some(read)) => {
1795            if let Ok(text) = model::view_schema().save(&read.value) {
1796                app.saved_already(&view_document, &text);
1797            }
1798            let mut p = lock(&svc.projection);
1799            p.layouts = read.value.layouts;
1800            p.views = read.value.views;
1801            p.places = read.value.places;
1802        }
1803        Ok(None) => {}
1804        Err(e) => log::warn!(target: "egui_pop", "the view document could not be read: {e}"),
1805    }
1806    sync(app);
1807}
1808
1809/// The crumbs as the interface says them, for `context.read`: the
1810/// root's title, then each place's.
1811fn crumb_labels(app: &AppHandle, svc: &ContextService, p: &Projection) -> Vec<String> {
1812    let ctx = app.egui();
1813    let places = p
1814        .applied
1815        .as_ref()
1816        .map(|s| s.places.as_slice())
1817        .unwrap_or_default();
1818    std::iter::once(root_title(app, svc))
1819        .chain(places.iter().map(|e| p.crumb(&ctx, e)))
1820        .collect()
1821}
1822
1823/// What the `contexts` collector shows.
1824fn describe(app: &AppHandle) -> Json {
1825    let Some(svc) = app.service(&CONTEXTS) else {
1826        return Json::Null;
1827    };
1828    let owner = with_owner(app, |c| {
1829        json!({
1830            "state": c.state(),
1831            "holds": c.holds(),
1832            "frames": c.registry().iter().collect::<Vec<_>>(),
1833        })
1834    });
1835    let projection = {
1836        let p = lock(&svc.projection);
1837        json!({
1838            "rev": p.applied.as_ref().map(|s| s.rev),
1839            "key": p.key(),
1840            "keys": p.keys,
1841            "layouts": p.layouts.keys().collect::<Vec<_>>(),
1842            "views": p.views,
1843            "places": p.places,
1844            "crumbs": crumb_labels(app, &svc, &p),
1845        })
1846    };
1847    let last = app.last_event();
1848    let events: Vec<_> = app
1849        .events_since(last.saturating_sub(64))
1850        .into_iter()
1851        .filter(|e| e.name.starts_with("context."))
1852        .collect();
1853    let hand_writes = svc.hand_writes();
1854    let clashes = frame_clashes(app);
1855    let warnings: Vec<String> = hand_writes
1856        .iter()
1857        .map(ToString::to_string)
1858        .chain(clashes.iter().map(ToString::to_string))
1859        .collect();
1860    json!({
1861        "owner": owner,
1862        "status": crate::strips::visible(app),
1863        "warnings": warnings,
1864        "hand_writes": hand_writes,
1865        "clashes": clashes,
1866        "host_owns": svc.custom.load(Ordering::Relaxed),
1867        "switching": svc.switching(),
1868        "projection": projection,
1869        "events": events,
1870    })
1871}
1872
1873fn outcome_json(o: Outcome) -> Result<Json, String> {
1874    match o {
1875        Outcome::Done(r) => r,
1876        Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
1877    }
1878}
1879
1880fn parse<T: serde::de::DeserializeOwned>(args: &Json, what: &str) -> Result<T, String> {
1881    serde_json::from_value(args.clone()).map_err(|e| format!("{what}: {e}"))
1882}
1883
1884/// The context stack as a plugin: the default owner (a
1885/// [`LocalContexts`], unless the host owns the stack), the projection,
1886/// the `context.request` step, the commands and keys, the `contexts`
1887/// collector, the undo toasts.
1888#[derive(Default)]
1889pub struct ContextsPlugin {
1890    root: Root,
1891    valid: Option<Validator>,
1892}
1893
1894impl fmt::Debug for ContextsPlugin {
1895    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1896        f.debug_struct("ContextsPlugin")
1897            .field("root", &self.root)
1898            .finish_non_exhaustive()
1899    }
1900}
1901
1902impl ContextsPlugin {
1903    /// The root crumb's title, as given ("Home", translated, by default).
1904    pub fn root(mut self, title: &str) -> Self {
1905        self.root.text = Some(title.into());
1906        self.root.key = None;
1907        self
1908    }
1909
1910    /// The root crumb's title, a string of the application's catalogue
1911    /// translated each time the crumb is said, so it follows the
1912    /// language.
1913    pub fn root_key(mut self, key: strings::StrKey) -> Self {
1914        self.root.text = None;
1915        self.root.key = Some(key);
1916        self
1917    }
1918
1919    /// The root crumb's label, asked each time the crumb is said (the
1920    /// breadcrumb, the status bar, `context.read`, the announcement of
1921    /// where the user is, the undo toast), given the translated title:
1922    /// the name of what is open (a workspace, a project), read from the
1923    /// application's own state, translated with the call's `ctx`. `None`
1924    /// keeps the title. Like [`FrameSpec::label`] it is called while the
1925    /// interface draws: it reads what the application keeps (behind an
1926    /// `Arc` it captured), never the context stack itself.
1927    pub fn root_label(
1928        mut self,
1929        f: impl Fn(&RootLabelCall<'_>) -> Option<String> + Send + Sync + 'static,
1930    ) -> Self {
1931        self.root.label = Some(Arc::new(f));
1932        self
1933    }
1934
1935    /// Whether a saved frame may come back at start (its payload still
1936    /// exists): `None` when it may, else why not.
1937    pub fn valid(
1938        mut self,
1939        f: impl Fn(&FrameId, &Json) -> Option<String> + Send + Sync + 'static,
1940    ) -> Self {
1941        self.valid = Some(Arc::new(f));
1942        self
1943    }
1944}
1945
1946impl Plugin for ContextsPlugin {
1947    fn id(&self) -> PluginId {
1948        PLUGIN
1949    }
1950
1951    fn title(&self) -> String {
1952        "Context stack".into()
1953    }
1954
1955    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1956        ctx.service(
1957            &CONTEXTS,
1958            ContextService {
1959                local: Mutex::new(LocalContexts::new()),
1960                projection: Mutex::new(Projection::default()),
1961                custom: AtomicBool::new(false),
1962                pending: Mutex::new(Vec::new()),
1963                hand_writes: Mutex::new(Vec::new()),
1964                documents: Mutex::new((CONTEXT_DOCUMENT.into(), VIEW_DOCUMENT.into())),
1965                root: self.root.clone(),
1966                valid: self.valid.clone(),
1967            },
1968        )?;
1969        ctx.step(
1970            StepSpec::new(
1971                STEP_REQUEST,
1972                "A transition of the context stack is asked of its owner; a veto keeps it from being asked, a redirect asks another.",
1973            )
1974            .args(json!({ "request": { "request": { "op": "enter", "frame": "demo.album" } }, "origin": "user" })),
1975        )?;
1976        let category = "Navigation";
1977        ctx.command(
1978            CommandSpec::new(CMD_BACK, "Back", category)
1979                .icon("chevron-left")
1980                .description("Pops the last pushed mode, else leaves the place shown for its parent.")
1981                // Under a modal its key is the modal's: the file picker's back.
1982                .when("!modalOpen")
1983                .key("Alt+Left"),
1984            |call| outcome_json(request(call.app, Envelope::new(Request::Back), call.origin)),
1985        )?
1986        .command(
1987            CommandSpec::new(CMD_UP, "Up to the parent place", category)
1988                .icon("up")
1989                .description("Leaves the place shown for its parent.")
1990                .key("Alt+Shift+Up")
1991                .when("placeDepth != '0'"),
1992            |call| outcome_json(request(call.app, Envelope::new(Request::Leave), call.origin)),
1993        )?
1994        .command(
1995            CommandSpec::new(CMD_ENTER, "Enter a place", category)
1996                .description("Enters a place under the one shown (`frame`, `payload`).")
1997                .args(json!({ "frame": "demo.album", "payload": null })),
1998            |call| {
1999                let frame: FrameId = parse(&call.args["frame"], "`frame`")?;
2000                let payload = call.args.get("payload").cloned().unwrap_or(Json::Null);
2001                outcome_json(request(
2002                    call.app,
2003                    Envelope::new(Request::Enter { frame, payload }),
2004                    call.origin,
2005                ))
2006            },
2007        )?
2008        .command(
2009            CommandSpec::new(CMD_READ, "Read the context stack", category)
2010                .description("The places and modes on, their revision, the holds and the frames declared, and what the status bar shows (`status`: each visible item's id, text, tone, count and progress, whether it is busy, its error and warning counts, and its hover card).")
2011                .read_only(),
2012            |call| Ok(describe(call.app)),
2013        )?
2014        .command(
2015            CommandSpec::new(CMD_REQUEST, "Ask for a context transition", category)
2016                .description("Asks the owner for a transition (`request`: `op` enter, leave, jump, go, set_mode, push_mode, pop_mode, clear_mode or back), checked against `if_rev`, applied unless `dry_run`.")
2017                .args(json!({ "request": { "op": "back" }, "if_rev": null, "dry_run": false })),
2018            |call| {
2019                let env: Envelope = parse(call.args, "a context request")?;
2020                outcome_json(request(call.app, env, call.origin))
2021            },
2022        )?
2023        .command(
2024            CommandSpec::new(CMD_GO, "Go to a place", category)
2025                .description("Goes to a place path (`places`: each `frame` with its `payload`).")
2026                .args(json!({ "places": [{ "frame": "demo.album" }] })),
2027            |call| {
2028                let places: Vec<Entry> = parse(&call.args["places"], "`places`")?;
2029                outcome_json(request(call.app, Envelope::new(Request::Go { places }), call.origin))
2030            },
2031        )?
2032        .command(
2033            CommandSpec::new(CMD_SET_MODE, "Set a mode", category)
2034                .description("Sets a mode (`mode`), or pushes it (`push`: true); with `group` and no mode, turns the group off.")
2035                .args(json!({ "mode": "demo.culling", "push": false })),
2036            |call| {
2037                let req = match call.args.get("mode").filter(|m| !m.is_null()) {
2038                    Some(m) => {
2039                        let mode: FrameId = parse(m, "`mode`")?;
2040                        if call.args["push"] == true {
2041                            Request::push(mode)
2042                        } else {
2043                            Request::set(mode)
2044                        }
2045                    }
2046                    None => Request::ClearMode {
2047                        group: parse(&call.args["group"], "`group`")?,
2048                    },
2049                };
2050                outcome_json(request(call.app, Envelope::new(req), call.origin))
2051            },
2052        )?
2053        .command(
2054            CommandSpec::new(CMD_HOLD, "Hold the context stack", category)
2055                .description("Holds groups of the stack (`groups`, empty: all of it; `place` for places) with a `reason`: transitions touching them are refused until released. Its token.")
2056                .args(json!({ "groups": ["orientation"], "reason": "an agent holds the image" })),
2057            |call| {
2058                let groups: Vec<GroupId> = match call.args.get("groups") {
2059                    Some(g) if !g.is_null() => parse(g, "`groups`")?,
2060                    _ => Vec::new(),
2061                };
2062                let reason = call.args["reason"].as_str().unwrap_or("held");
2063                let token = hold(call.app, groups, reason, &source_of(call.origin))?;
2064                Ok(json!({ "token": token }))
2065            },
2066        )?
2067        .command(
2068            CommandSpec::new(CMD_RELEASE, "Release a hold", category)
2069                .description("Releases a hold of the context stack (`token`).")
2070                .args(json!({ "token": 1 })),
2071            |call| {
2072                let token = call.args["token"].as_u64().ok_or("`token` is missing")?;
2073                Ok(json!({ "released": release(call.app, token) }))
2074            },
2075        )?;
2076        // Escape pops a pushed mode, unless an overlay or a field wants it.
2077        ctx.keybinding(
2078            "Escape",
2079            CMD_BACK,
2080            "modePushed && !overlayOpen",
2081            Layer::Default,
2082        )?;
2083        let (w1, w2, w3, w4) = (
2084            ctx.app().downgrade(),
2085            ctx.app().downgrade(),
2086            ctx.app().downgrade(),
2087            ctx.app().downgrade(),
2088        );
2089        ctx.collector(
2090            FnCollector::new(
2091                "contexts",
2092                "The context stack: the owner's state (places, modes, revision), its holds and frames; the projection (its key, the context keys it set, the layouts and view states kept); the last context events; warnings: the stack's own keys set by hand (`hand_writes`), frames that can be on together binding the same keys (`clashes`). `request` asks for a transition as its caller; `hold` and `release`, held in the caller's name.",
2093            )
2094            .snapshot(move |_| match w1.get() {
2095                Ok(app) => describe(&app),
2096                Err(_) => Json::Null,
2097            })
2098            .action_as(
2099                "request",
2100                "Asks the owner for a transition (`request`, `if_rev`, `dry_run`), as its caller.",
2101                true,
2102                move |_, args, origin| {
2103                    let app = w2.get()?;
2104                    let env: Envelope = parse(args, "a context request")?;
2105                    outcome_json(request(&app, env, origin))
2106                },
2107            )
2108            .args(json!({ "request": { "op": "back" }, "dry_run": true }))
2109            .action_as(
2110                "hold",
2111                "Holds groups of the stack (`groups`, `reason`) in the caller's name; its token.",
2112                true,
2113                move |_, args, origin| {
2114                    let app = w3.get()?;
2115                    let groups: Vec<GroupId> = match args.get("groups") {
2116                        Some(g) if !g.is_null() => parse(g, "`groups`")?,
2117                        _ => Vec::new(),
2118                    };
2119                    let reason = args["reason"].as_str().unwrap_or("held through the debug bridge");
2120                    let by = crate::host::source_of(origin);
2121                    Ok(json!({ "token": hold(&app, groups, reason, &by)? }))
2122                },
2123            )
2124            .args(json!({ "groups": [], "reason": "an agent holds the stack" }))
2125            .action("release", "Releases a hold (`token`).", true, move |_, args| {
2126                let app = w4.get()?;
2127                let token = args["token"].as_u64().ok_or("`token` is missing")?;
2128                Ok(json!({ "released": release(&app, token) }))
2129            })
2130            .args(json!({ "token": 1 })),
2131        )?;
2132        ctx.on(On::Started, |app, _| {
2133            start(app);
2134            report_clashes(app);
2135        })
2136        .on(On::Pass, |app, _| pass(app))
2137        .on(On::Rebuilt, |app, _| {
2138            if let (Some(svc), Some(reg)) =
2139                (app.service(&CONTEXTS), with_owner(app, |c| c.registry()))
2140            {
2141                lock(&svc.projection).registry = reg;
2142            }
2143            report_clashes(app);
2144        })
2145        .on(On::Disconnected, |app, ev| {
2146            if let Lifecycle::Disconnected(p) = ev {
2147                with_owner(app, |c| c.remove_owner(&OwnerId::from(p)));
2148            }
2149        });
2150        ctx.after(STEP_UNDO, |app, _, result| {
2151            undone(app, Walked::Undo, result)
2152        })
2153        .after(STEP_REDO, |app, _, result| {
2154            undone(app, Walked::Redo, result)
2155        })
2156        .after(history::STEP_JUMP, |app, _, result| {
2157            undone(app, Walked::Jump, result);
2158        });
2159        Ok(())
2160    }
2161}
2162
2163impl Ctx<'_> {
2164    /// Declares a frame of the context stack, owned by this plugin (gone
2165    /// with it). The plugin requires [`PLUGIN`].
2166    pub fn frame(&mut self, spec: FrameSpec) -> Result<&mut Self, CtxError> {
2167        let owner = self.owner.clone();
2168        let app = self.app.clone();
2169        with_owner(&app, |c| c.declare(&owner, spec))
2170            .ok_or_else(|| CtxError::Frame(NO_STACK.into()))?
2171            .map_err(CtxError::Frame)?;
2172        Ok(self)
2173    }
2174
2175    /// Binds keys to a command while a frame is on: the frame's own
2176    /// keymap layer, through its `when` clause (`mode.<group> == 'id'`,
2177    /// `place == 'id'`), winning over a binding without a clause.
2178    pub fn frame_keybinding(
2179        &mut self,
2180        frame: &FrameSpec,
2181        keys: &str,
2182        command: CommandId,
2183    ) -> Result<&mut Self, CtxError> {
2184        self.keybinding(keys, command, &frame.clause(), Layer::Default)
2185    }
2186}