Skip to main content

egui_pop_model/
context.rs

1//! The context stack (ADR 0012): where the user is and how the
2//! application behaves right now, without egui.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - **Places** are drill-downs (an album, a group, a sub-workspace):
8//!   a path from the root, shown as a breadcrumb.
9//! - **Modes** are global states (an orientation, compare, read-only):
10//!   at most one per **group**, modes of different groups combine. A mode
11//!   is **set** (sticky until changed) or **pushed** (temporary: popping
12//!   it puts back what it replaced in its group).
13//! - A frame may be **transient**: on the live stack, never restored.
14//!
15//! Frames are declared in a [`FrameRegistry`]; the [`State`] is the place
16//! path, the active modes and a revision. [`apply`] is the pure
17//! transition function (guards, holds, `if_rev`, redirections) and
18//! [`restore`] brings a saved state back against today's frames. The
19//! owner of the stack (the application's kernel, or egui-pop's
20//! `LocalContexts`) calls them; nothing here does I/O.
21//!
22//! ```
23//! use egui_pop_model::context::{self, Envelope, FrameRegistry, FrameSpec, Request, State};
24//! use egui_pop_model::ids::{FrameId, GroupId};
25//!
26//! const ALBUM: FrameId = FrameId::from_static("demo.album");
27//! const CULLING: FrameId = FrameId::from_static("demo.culling");
28//! let mut frames = FrameRegistry::new();
29//! frames.insert(FrameSpec::place(ALBUM, "Album")).unwrap();
30//! frames
31//!     .insert(FrameSpec::mode(CULLING, GroupId::from_static("orientation"), "Culling"))
32//!     .unwrap();
33//!
34//! let s = State::default();
35//! let t = context::apply(&s, &frames, &[], &Envelope::new(Request::enter(ALBUM))).unwrap();
36//! assert_eq!(t.state.place(), "demo.album");
37//! let t = context::apply(&t.state, &frames, &[], &Envelope::new(Request::set(CULLING))).unwrap();
38//! assert_eq!(t.state.mode_of("orientation"), Some(&CULLING));
39//! assert_eq!(t.state.rev, 2);
40//! ```
41
42use std::collections::{BTreeMap, BTreeSet};
43use std::fmt;
44use std::sync::Arc;
45
46use serde::{Deserialize, Serialize};
47use serde_json::Value as Json;
48
49use crate::doc::{Schema, same};
50use crate::ids::{FrameId, GroupId, PanelId};
51use crate::layout::Layout;
52
53/// The place at the bottom of every path, as the `place` context key
54/// says it.
55pub const ROOT: &str = "root";
56
57/// The group a hold names to stop place transitions (enter, leave,
58/// jump, go).
59pub const PLACES: GroupId = GroupId::from_static("place");
60
61/// How many redirections a request may go through.
62const HOPS: usize = 4;
63
64/// What a frame is.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "lowercase")]
67pub enum Kind {
68    /// A drill-down: entered, left.
69    Place,
70    /// A global state: set, pushed, cleared.
71    Mode,
72}
73
74/// How a mode is on.
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "lowercase")]
77pub enum Life {
78    /// Sticky until changed.
79    #[default]
80    Set,
81    /// Temporary: popped by `nav.back` (Escape), putting back what it
82    /// replaced in its group.
83    Pushed,
84}
85
86/// What a guard decides.
87#[derive(Clone, Debug, PartialEq)]
88pub enum Verdict {
89    Go,
90    /// The transition does not happen, for this reason.
91    Refuse(String),
92    /// Another transition happens instead.
93    Redirect(Request),
94}
95
96/// What a guard is asked about.
97#[derive(Debug)]
98pub struct GuardCall<'a> {
99    pub frame: &'a FrameId,
100    pub payload: &'a Json,
101    /// Entering (`can_enter`) or leaving (`can_leave`).
102    pub entering: bool,
103    /// The state before the transition.
104    pub state: &'a State,
105}
106
107/// A guard on a frame: `can_enter` or `can_leave`, evaluated by the
108/// owner of the stack.
109pub type Guard = Arc<dyn Fn(&GuardCall<'_>) -> Verdict + Send + Sync>;
110
111/// What a place's crumb label is asked about.
112#[derive(Debug)]
113pub struct LabelCall<'a> {
114    pub frame: &'a FrameId,
115    pub payload: &'a Json,
116    /// The frame's title, translated by the interface.
117    pub title: &'a str,
118}
119
120/// A place's crumb label from its payload (`FrameSpec::label`): `None`
121/// keeps the default (the title, and the payload when it is a text or a
122/// number).
123pub type Label = Arc<dyn Fn(&LabelCall<'_>) -> Option<String> + Send + Sync>;
124
125/// The arrangement a place starts from, chosen from its payload
126/// (`FrameSpec::arrangement_for`): `None` falls back to its arrangement.
127pub type ArrangementFor = Arc<dyn Fn(&Json) -> Option<String> + Send + Sync>;
128
129/// A frame as declared.
130#[derive(Clone, Serialize)]
131pub struct FrameSpec {
132    pub id: FrameId,
133    pub kind: Kind,
134    /// A mode's group (one mode of a group at a time); none for a place.
135    pub group: Option<GroupId>,
136    /// For the breadcrumb and the mode chips, in English; the interface
137    /// translates it through the key derived from the id,
138    /// `frame-<id>.title` (`egui_pop_core::strings::frame_title`).
139    pub title: String,
140    /// An icon's name, for the chips and crumbs (`egui_pop_core::icon`).
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub icon: Option<String>,
143    /// On the live stack, never restored.
144    pub transient: bool,
145    /// A mode: its group shows in the status bar, as a chip while one of
146    /// its modes is on. A group is shown when any of its modes says so;
147    /// a group that is pure plumbing stays out of the bar.
148    #[serde(skip_serializing_if = "std::ops::Not::not")]
149    pub visible: bool,
150    /// A mode: its chip's tone, by the kit's tone name (`accent`, `info`,
151    /// `success`, `warning`, `danger`, `muted`, `record`); `accent` when
152    /// none.
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub tone: Option<String>,
155    /// Context keys the frame sets while it is on (the top place's, every
156    /// active mode's).
157    #[serde(skip_serializing_if = "Vec::is_empty")]
158    pub keys: Vec<(String, String)>,
159    /// The arrangement (a template or a saved name) the frame's
160    /// projection starts from the first time, until the user picks
161    /// another there: a place's, or a mode's, which wins over the place's
162    /// while it is on.
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub arrangement: Option<String>,
165    /// A mode: panels it shows while on.
166    #[serde(skip_serializing_if = "Vec::is_empty")]
167    pub show: Vec<PanelId>,
168    /// A mode: panels it hides while on.
169    #[serde(skip_serializing_if = "Vec::is_empty")]
170    pub hide: Vec<PanelId>,
171    #[serde(skip)]
172    pub can_enter: Option<Guard>,
173    #[serde(skip)]
174    pub can_leave: Option<Guard>,
175    /// A place: its crumb's label from its payload.
176    #[serde(skip)]
177    pub label: Option<Label>,
178    /// A place: the arrangement it starts from, from its payload.
179    #[serde(skip)]
180    pub arrangement_for: Option<ArrangementFor>,
181}
182
183impl fmt::Debug for FrameSpec {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.debug_struct("FrameSpec")
186            .field("id", &self.id)
187            .field("kind", &self.kind)
188            .field("group", &self.group)
189            .field("transient", &self.transient)
190            .field(
191                "guarded",
192                &(self.can_enter.is_some() || self.can_leave.is_some()),
193            )
194            .finish_non_exhaustive()
195    }
196}
197
198impl FrameSpec {
199    fn new(id: FrameId, kind: Kind, group: Option<GroupId>, title: &str) -> Self {
200        Self {
201            id,
202            kind,
203            group,
204            title: title.into(),
205            icon: None,
206            transient: false,
207            visible: false,
208            tone: None,
209            keys: Vec::new(),
210            arrangement: None,
211            show: Vec::new(),
212            hide: Vec::new(),
213            can_enter: None,
214            can_leave: None,
215            label: None,
216            arrangement_for: None,
217        }
218    }
219
220    /// A place.
221    pub fn place(id: FrameId, title: &str) -> Self {
222        Self::new(id, Kind::Place, None, title)
223    }
224
225    /// A mode of a group.
226    pub fn mode(id: FrameId, group: GroupId, title: &str) -> Self {
227        Self::new(id, Kind::Mode, Some(group), title)
228    }
229
230    pub fn icon(mut self, icon: &str) -> Self {
231        self.icon = Some(icon.into());
232        self
233    }
234
235    /// Never restored (an agent driving, a modal tool mode).
236    pub fn transient(mut self) -> Self {
237        self.transient = true;
238        self
239    }
240
241    /// A mode: shows its group in the status bar (a chip while one of
242    /// its modes is on).
243    pub fn visible(mut self) -> Self {
244        self.visible = true;
245        self
246    }
247
248    /// A mode: its chip's tone, a kit tone name (`record` for "an agent
249    /// is driving").
250    pub fn tone(mut self, tone: &str) -> Self {
251        self.tone = Some(tone.into());
252        self
253    }
254
255    /// A context key set while the frame is on.
256    pub fn key(mut self, key: &str, value: &str) -> Self {
257        self.keys.push((key.into(), value.into()));
258        self
259    }
260
261    /// The arrangement the frame's projection starts from (a place's, or
262    /// a mode's, which wins over the place's while it is on).
263    pub fn arrangement(mut self, name: &str) -> Self {
264        self.arrangement = Some(name.into());
265        self
266    }
267
268    /// A panel a mode shows.
269    pub fn show(mut self, panel: PanelId) -> Self {
270        self.show.push(panel);
271        self
272    }
273
274    /// A panel a mode hides.
275    pub fn hide(mut self, panel: PanelId) -> Self {
276        self.hide.push(panel);
277        self
278    }
279
280    /// Whether the frame may be entered.
281    pub fn can_enter(
282        mut self,
283        f: impl Fn(&GuardCall<'_>) -> Verdict + Send + Sync + 'static,
284    ) -> Self {
285        self.can_enter = Some(Arc::new(f));
286        self
287    }
288
289    /// Whether the frame may be left.
290    pub fn can_leave(
291        mut self,
292        f: impl Fn(&GuardCall<'_>) -> Verdict + Send + Sync + 'static,
293    ) -> Self {
294        self.can_leave = Some(Arc::new(f));
295        self
296    }
297
298    /// A place: its crumb's label from its payload (a sub-workspace's
299    /// name for `{"id": "…"}`), wherever the interface says the crumb
300    /// (the breadcrumb, `context.read`, an announcement, an undo toast).
301    /// `None` keeps the default: the title, and the payload when it is a
302    /// text or a number. Called while the interface draws: it must not
303    /// call back into the context stack.
304    pub fn label(
305        mut self,
306        f: impl Fn(&LabelCall<'_>) -> Option<String> + Send + Sync + 'static,
307    ) -> Self {
308        self.label = Some(Arc::new(f));
309        self
310    }
311
312    /// A place: the arrangement (a template or a saved name) an entry
313    /// starts from, chosen from its payload; `None` falls back to
314    /// [`arrangement`](Self::arrangement). Read the first time a
315    /// projection key is shown: the layout it was left with wins on
316    /// later entries.
317    pub fn arrangement_for(
318        mut self,
319        f: impl Fn(&Json) -> Option<String> + Send + Sync + 'static,
320    ) -> Self {
321        self.arrangement_for = Some(Arc::new(f));
322        self
323    }
324
325    /// The crumb label [`label`](Self::label) gives for a payload, if
326    /// any.
327    pub fn label_of(&self, title: &str, payload: &Json) -> Option<String> {
328        let f = self.label.as_ref()?;
329        f(&LabelCall {
330            frame: &self.id,
331            payload,
332            title,
333        })
334    }
335
336    /// The arrangement [`arrangement_for`](Self::arrangement_for) chooses
337    /// for a payload, if any.
338    pub fn arrangement_of(&self, payload: &Json) -> Option<String> {
339        self.arrangement_for.as_ref().and_then(|f| f(payload))
340    }
341
342    /// The `when` clause that holds while the frame is on: `place ==
343    /// 'id'` for a place (the top one), `mode.<group> == 'id'` for a
344    /// mode. A frame's own key bindings use it (its keymap layer).
345    pub fn clause(&self) -> String {
346        match (&self.kind, &self.group) {
347            (Kind::Mode, Some(g)) => format!("mode.{g} == '{}'", self.id),
348            _ => format!("place == '{}'", self.id),
349        }
350    }
351}
352
353/// The frames that exist.
354#[derive(Clone, Debug, Default)]
355pub struct FrameRegistry {
356    frames: BTreeMap<FrameId, FrameSpec>,
357}
358
359impl FrameRegistry {
360    pub fn new() -> Self {
361        Self::default()
362    }
363
364    /// Declares a frame; refused when its id is taken, or when a mode has
365    /// no group.
366    pub fn insert(&mut self, spec: FrameSpec) -> Result<(), String> {
367        if self.frames.contains_key(&spec.id) {
368            return Err(format!("frame `{}` is already declared", spec.id));
369        }
370        if spec.kind == Kind::Mode && spec.group.is_none() {
371            return Err(format!("mode `{}` has no group", spec.id));
372        }
373        self.frames.insert(spec.id.clone(), spec);
374        Ok(())
375    }
376
377    pub fn get(&self, id: &FrameId) -> Option<&FrameSpec> {
378        self.frames.get(id)
379    }
380
381    pub fn remove(&mut self, id: &FrameId) -> Option<FrameSpec> {
382        self.frames.remove(id)
383    }
384
385    pub fn iter(&self) -> impl Iterator<Item = &FrameSpec> {
386        self.frames.values()
387    }
388
389    pub fn len(&self) -> usize {
390        self.frames.len()
391    }
392
393    pub fn is_empty(&self) -> bool {
394        self.frames.is_empty()
395    }
396
397    /// The groups shown in the status bar: those with a mode declared
398    /// [`FrameSpec::visible`].
399    pub fn visible_groups(&self) -> BTreeSet<GroupId> {
400        self.frames
401            .values()
402            .filter(|f| f.kind == Kind::Mode && f.visible)
403            .filter_map(|f| f.group.clone())
404            .collect()
405    }
406
407    /// Every mode group, with its modes in id order.
408    pub fn groups(&self) -> BTreeMap<GroupId, Vec<&FrameSpec>> {
409        let mut out: BTreeMap<GroupId, Vec<&FrameSpec>> = BTreeMap::new();
410        for f in self.frames.values() {
411            if let (Kind::Mode, Some(g)) = (f.kind, &f.group) {
412                out.entry(g.clone()).or_default().push(f);
413            }
414        }
415        out
416    }
417}
418
419/// A place on the path, with its payload (the application's own: a
420/// sub-workspace's id).
421#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
422pub struct Entry {
423    pub frame: FrameId,
424    #[serde(default, skip_serializing_if = "Json::is_null")]
425    pub payload: Json,
426}
427
428impl Entry {
429    pub fn new(frame: FrameId) -> Self {
430        Self {
431            frame,
432            payload: Json::Null,
433        }
434    }
435}
436
437/// An active mode.
438#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
439pub struct ModeEntry {
440    pub frame: FrameId,
441    pub group: GroupId,
442    #[serde(default)]
443    pub life: Life,
444    #[serde(default, skip_serializing_if = "Json::is_null")]
445    pub payload: Json,
446    /// What a pushed mode replaced in its group, put back when it pops.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub under: Option<Box<ModeEntry>>,
449}
450
451/// The stack: the place path, the active modes, a revision.
452#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
453pub struct State {
454    /// Incremented by every transition.
455    pub rev: u64,
456    /// The places from the root's child to the top.
457    #[serde(default)]
458    pub places: Vec<Entry>,
459    /// The active modes, at most one per group, in the order they came.
460    #[serde(default)]
461    pub modes: Vec<ModeEntry>,
462}
463
464impl State {
465    /// The top place's id, [`ROOT`] at the root.
466    pub fn place(&self) -> &str {
467        self.places.last().map_or(ROOT, |e| e.frame.as_str())
468    }
469
470    /// How many places deep (0 at the root).
471    pub fn depth(&self) -> usize {
472        self.places.len()
473    }
474
475    /// The mode on in a group.
476    pub fn mode_of(&self, group: &str) -> Option<&FrameId> {
477        self.modes
478            .iter()
479            .find(|m| m.group.as_str() == group)
480            .map(|m| &m.frame)
481    }
482
483    /// Whether a frame is on (a place on the path or an active mode).
484    pub fn is_on(&self, frame: &FrameId) -> bool {
485        self.places.iter().any(|e| e.frame == *frame)
486            || self.modes.iter().any(|m| m.frame == *frame)
487    }
488
489    /// Whether a pushed mode is on (what `nav.back` pops first).
490    pub fn has_pushed(&self) -> bool {
491        self.modes.iter().any(|m| m.life == Life::Pushed)
492    }
493
494    /// The place path as a key: `root/demo.album/demo.photo`, payloads
495    /// included when they are not null (`demo.album=3`).
496    pub fn path_key(&self) -> String {
497        self.path_key_with(|_| true)
498    }
499
500    /// The place path as a key, a place's payload included when `payload`
501    /// says so for its frame (and it is not null).
502    fn path_key_with(&self, payload: impl Fn(&FrameId) -> bool) -> String {
503        let mut key = ROOT.to_string();
504        for e in &self.places {
505            key.push('/');
506            key.push_str(e.frame.as_str());
507            if !e.payload.is_null() && payload(&e.frame) {
508                key.push('=');
509                key.push_str(&e.payload.to_string());
510            }
511        }
512        key
513    }
514
515    /// The projection's key: the path, then the active modes by group
516    /// (`root/demo.album|orientation=demo.culling`). A layout change made
517    /// in a mode belongs to this key, so leaving the mode reverts it.
518    pub fn projection_key(&self) -> String {
519        self.with_modes(self.path_key())
520    }
521
522    /// The key a layout is kept under: the projection's key, a place's
523    /// payload left out unless its frame chooses its arrangement from it
524    /// ([`FrameSpec::arrangement_for`]). Another photo in the darkroom is
525    /// the same place for the layout (a panel detached there stays in its
526    /// window); a space whose payload picks its arrangement keeps one
527    /// layout per payload.
528    pub fn layout_key(&self, registry: &FrameRegistry) -> String {
529        let chooses = |f: &FrameId| {
530            registry
531                .get(f)
532                .is_some_and(|spec| spec.arrangement_for.is_some())
533        };
534        self.with_modes(self.path_key_with(chooses))
535    }
536
537    /// `key` followed by the active modes by group.
538    fn with_modes(&self, mut key: String) -> String {
539        let mut modes: Vec<(&str, &str)> = self
540            .modes
541            .iter()
542            .map(|m| (m.group.as_str(), m.frame.as_str()))
543            .collect();
544        modes.sort();
545        for (g, f) in modes {
546            key.push('|');
547            key.push_str(g);
548            key.push('=');
549            key.push_str(f);
550        }
551        key
552    }
553
554    /// The context keys the stack sets: `place`, `placeDepth`,
555    /// `modePushed`, `mode.<group>` for every group of the registry (empty
556    /// when none is on), the keys of the top place and active modes, and
557    /// the top place's payload ([`payload_keys`]).
558    pub fn when_keys(&self, registry: &FrameRegistry) -> Vec<(String, String)> {
559        let mut out = vec![
560            ("place".to_string(), self.place().to_string()),
561            ("placeDepth".to_string(), self.depth().to_string()),
562            (
563                "modePushed".to_string(),
564                if self.has_pushed() { "true" } else { "false" }.to_string(),
565            ),
566        ];
567        let mut groups: Vec<String> = registry.groups().keys().map(|g| g.to_string()).collect();
568        for m in &self.modes {
569            if !groups.iter().any(|g| g == m.group.as_str()) {
570                groups.push(m.group.to_string());
571            }
572        }
573        for g in groups {
574            let on = self.mode_of(&g).map(|f| f.to_string()).unwrap_or_default();
575            out.push((format!("mode.{g}"), on));
576        }
577        let on = self
578            .places
579            .last()
580            .map(|e| &e.frame)
581            .into_iter()
582            .chain(self.modes.iter().map(|m| &m.frame));
583        for f in on {
584            if let Some(spec) = registry.get(f) {
585                out.extend(spec.keys.iter().cloned());
586            }
587        }
588        if let Some(top) = self.places.last() {
589            out.extend(payload_keys(&top.payload));
590        }
591        out
592    }
593}
594
595/// The context keys a top place's payload sets, for `when` clauses: a
596/// text, a number or a boolean as `payload`; an object's fields that
597/// are one of those as `payload.<field>` (`payload.id == 'darkroom'`).
598/// Nested values set nothing.
599pub fn payload_keys(payload: &Json) -> Vec<(String, String)> {
600    fn scalar(v: &Json) -> Option<String> {
601        match v {
602            Json::String(s) => Some(s.clone()),
603            Json::Number(n) => Some(n.to_string()),
604            Json::Bool(b) => Some(b.to_string()),
605            _ => None,
606        }
607    }
608    match payload {
609        Json::Object(fields) => fields
610            .iter()
611            .filter_map(|(k, v)| scalar(v).map(|v| (format!("payload.{k}"), v)))
612            .collect(),
613        v => scalar(v)
614            .map(|v| vec![("payload".to_string(), v)])
615            .unwrap_or_default(),
616    }
617}
618
619/// A transition asked of the owner.
620#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
621#[serde(tag = "op", rename_all = "snake_case")]
622pub enum Request {
623    /// Enters a place under the top one.
624    Enter {
625        frame: FrameId,
626        #[serde(default, skip_serializing_if = "Json::is_null")]
627        payload: Json,
628    },
629    /// Leaves the top place.
630    Leave,
631    /// Leaves places until `depth` are left (0: the root).
632    Jump { depth: usize },
633    /// Goes to a place path (a crumb from elsewhere, "Go there").
634    Go {
635        #[serde(default)]
636        places: Vec<Entry>,
637    },
638    /// Sets a mode (sticky), replacing its group's.
639    SetMode {
640        mode: FrameId,
641        #[serde(default, skip_serializing_if = "Json::is_null")]
642        payload: Json,
643    },
644    /// Pushes a mode (temporary), replacing its group's until popped.
645    PushMode {
646        mode: FrameId,
647        #[serde(default, skip_serializing_if = "Json::is_null")]
648        payload: Json,
649    },
650    /// Pops the last pushed mode.
651    PopMode,
652    /// Turns a group's mode off.
653    ClearMode { group: GroupId },
654    /// Back: pops the last pushed mode, else leaves the top place.
655    Back,
656}
657
658impl Request {
659    pub fn enter(frame: FrameId) -> Self {
660        Request::Enter {
661            frame,
662            payload: Json::Null,
663        }
664    }
665
666    pub fn set(mode: FrameId) -> Self {
667        Request::SetMode {
668            mode,
669            payload: Json::Null,
670        }
671    }
672
673    pub fn push(mode: FrameId) -> Self {
674        Request::PushMode {
675            mode,
676            payload: Json::Null,
677        }
678    }
679
680    /// The group a hold must not cover for this request to go.
681    fn group(&self, registry: &FrameRegistry, state: &State) -> Option<GroupId> {
682        match self {
683            Request::Enter { .. } | Request::Leave | Request::Jump { .. } | Request::Go { .. } => {
684                Some(PLACES)
685            }
686            Request::SetMode { mode, .. } | Request::PushMode { mode, .. } => {
687                registry.get(mode).and_then(|s| s.group.clone())
688            }
689            Request::PopMode => state
690                .modes
691                .iter()
692                .rev()
693                .find(|m| m.life == Life::Pushed)
694                .map(|m| m.group.clone()),
695            Request::ClearMode { group } => Some(group.clone()),
696            Request::Back => None,
697        }
698    }
699}
700
701/// A request with its conditions.
702#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
703pub struct Envelope {
704    pub request: Request,
705    /// Refused as stale unless the state is still at this revision.
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub if_rev: Option<u64>,
708    /// Checked, answered, not applied.
709    #[serde(default)]
710    pub dry_run: bool,
711}
712
713impl Envelope {
714    pub fn new(request: Request) -> Self {
715        Self {
716            request,
717            if_rev: None,
718            dry_run: false,
719        }
720    }
721
722    pub fn if_rev(mut self, rev: u64) -> Self {
723        self.if_rev = Some(rev);
724        self
725    }
726
727    pub fn dry_run(mut self) -> Self {
728        self.dry_run = true;
729        self
730    }
731}
732
733/// A short lock on groups of the stack: a drag in progress, a batch
734/// writing, an agent holding the image. Requests touching a held group
735/// are refused with its reason.
736#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
737pub struct Hold {
738    pub token: u64,
739    /// The groups held ([`PLACES`] for places); empty: the whole stack.
740    #[serde(default)]
741    pub groups: Vec<GroupId>,
742    pub reason: String,
743    /// Who holds it (`user`, `agent:<name>`, a plugin).
744    pub by: String,
745}
746
747impl Hold {
748    /// Whether it holds a group.
749    pub fn covers(&self, group: &GroupId) -> bool {
750        self.groups.is_empty() || self.groups.contains(group)
751    }
752}
753
754/// Why a transition did not happen.
755#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
756#[serde(rename_all = "snake_case")]
757pub enum RefusalKind {
758    /// No such frame, or not of the right kind.
759    Unknown,
760    /// A guard said no.
761    Guard,
762    /// A hold covers the group.
763    Held,
764    /// `if_rev` no longer matches.
765    Stale,
766    /// Nothing to do (leaving the root, setting the mode that is on).
767    Nothing,
768    /// Redirected in a loop.
769    Loop,
770}
771
772/// A refusal, with its reason and who refused.
773#[derive(Clone, Debug, PartialEq, Serialize)]
774pub struct Refusal {
775    pub kind: RefusalKind,
776    pub reason: String,
777    /// A frame's guard, a hold's holder, `stack`.
778    pub by: String,
779    /// The revision the state is at.
780    pub rev: u64,
781}
782
783impl fmt::Display for Refusal {
784    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785        write!(f, "{} ({})", self.reason, self.by)
786    }
787}
788
789impl std::error::Error for Refusal {}
790
791/// A transition applied (or, for a dry run, that would be).
792#[derive(Clone, Debug, PartialEq, Serialize)]
793pub struct Transition {
794    pub state: State,
795    /// Frames turned on, in order.
796    pub entered: Vec<FrameId>,
797    /// Frames turned off, top first.
798    pub left: Vec<FrameId>,
799    /// The request applied instead, when a guard redirected.
800    #[serde(skip_serializing_if = "Option::is_none")]
801    pub redirected: Option<Request>,
802}
803
804fn refuse(kind: RefusalKind, reason: impl Into<String>, by: &str, state: &State) -> Refusal {
805    Refusal {
806        kind,
807        reason: reason.into(),
808        by: by.into(),
809        rev: state.rev,
810    }
811}
812
813fn spec_of<'a>(
814    registry: &'a FrameRegistry,
815    frame: &FrameId,
816    kind: Kind,
817    state: &State,
818) -> Result<&'a FrameSpec, Refusal> {
819    match registry.get(frame) {
820        Some(s) if s.kind == kind => Ok(s),
821        Some(_) => Err(refuse(
822            RefusalKind::Unknown,
823            format!(
824                "`{frame}` is not a {}",
825                if kind == Kind::Place { "place" } else { "mode" }
826            ),
827            "stack",
828            state,
829        )),
830        None => Err(refuse(
831            RefusalKind::Unknown,
832            format!("no frame `{frame}`"),
833            "stack",
834            state,
835        )),
836    }
837}
838
839/// What a guard said: go on, or another request.
840enum Checked {
841    Go,
842    Redirect(Request),
843}
844
845fn guard(
846    guard: &Option<Guard>,
847    frame: &FrameId,
848    payload: &Json,
849    entering: bool,
850    state: &State,
851) -> Result<Checked, Refusal> {
852    let Some(g) = guard else {
853        return Ok(Checked::Go);
854    };
855    match g(&GuardCall {
856        frame,
857        payload,
858        entering,
859        state,
860    }) {
861        Verdict::Go => Ok(Checked::Go),
862        Verdict::Refuse(reason) => Err(refuse(RefusalKind::Guard, reason, frame.as_str(), state)),
863        Verdict::Redirect(r) => Ok(Checked::Redirect(r)),
864    }
865}
866
867/// Checks a guard; on a redirection, returns early with the redirected
868/// transition.
869macro_rules! check {
870    ($g:expr, $frame:expr, $payload:expr, $entering:expr, $state:expr, $reg:expr, $holds:expr, $hops:expr) => {
871        if let Checked::Redirect(r) = guard($g, $frame, $payload, $entering, $state)? {
872            return redirect($state, $reg, $holds, r, $hops);
873        }
874    };
875}
876
877fn redirect(
878    state: &State,
879    registry: &FrameRegistry,
880    holds: &[Hold],
881    r: Request,
882    hops: usize,
883) -> Result<Transition, Refusal> {
884    if hops >= HOPS {
885        return Err(refuse(
886            RefusalKind::Loop,
887            "redirected too many times",
888            "stack",
889            state,
890        ));
891    }
892    let mut t = step(state, registry, holds, &r, hops + 1)?;
893    t.redirected.get_or_insert(r);
894    Ok(t)
895}
896
897/// Applies a request to a state: the new state and what was entered and
898/// left, or why not. Pure: the owner writes and publishes.
899pub fn apply(
900    state: &State,
901    registry: &FrameRegistry,
902    holds: &[Hold],
903    envelope: &Envelope,
904) -> Result<Transition, Refusal> {
905    if let Some(rev) = envelope.if_rev
906        && rev != state.rev
907    {
908        return Err(refuse(
909            RefusalKind::Stale,
910            format!("the stack is at revision {}, not {rev}", state.rev),
911            "stack",
912            state,
913        ));
914    }
915    step(state, registry, holds, &envelope.request, 0)
916}
917
918fn held(
919    request: &Request,
920    registry: &FrameRegistry,
921    holds: &[Hold],
922    state: &State,
923) -> Result<(), Refusal> {
924    let Some(group) = request.group(registry, state) else {
925        return Ok(());
926    };
927    match holds.iter().find(|h| h.covers(&group)) {
928        Some(h) => Err(refuse(RefusalKind::Held, h.reason.clone(), &h.by, state)),
929        None => Ok(()),
930    }
931}
932
933fn step(
934    state: &State,
935    registry: &FrameRegistry,
936    holds: &[Hold],
937    request: &Request,
938    hops: usize,
939) -> Result<Transition, Refusal> {
940    let nothing = |why: &str| Err(refuse(RefusalKind::Nothing, why, "stack", state));
941    if let Request::Back = request {
942        return if state.has_pushed() {
943            step(state, registry, holds, &Request::PopMode, hops)
944        } else if !state.places.is_empty() {
945            step(state, registry, holds, &Request::Leave, hops)
946        } else {
947            nothing("there is nothing to go back to")
948        };
949    }
950    held(request, registry, holds, state)?;
951    let mut next = state.clone();
952    let mut entered = Vec::new();
953    let mut left = Vec::new();
954    match request {
955        Request::Enter { frame, payload } => {
956            let spec = spec_of(registry, frame, Kind::Place, state)?;
957            check!(
958                &spec.can_enter,
959                frame,
960                payload,
961                true,
962                state,
963                registry,
964                holds,
965                hops
966            );
967            next.places.push(Entry {
968                frame: frame.clone(),
969                payload: payload.clone(),
970            });
971            entered.push(frame.clone());
972        }
973        Request::Leave => {
974            let Some(top) = state.places.last() else {
975                return nothing("the root has no parent");
976            };
977            if let Some(spec) = registry.get(&top.frame) {
978                check!(
979                    &spec.can_leave,
980                    &top.frame,
981                    &top.payload,
982                    false,
983                    state,
984                    registry,
985                    holds,
986                    hops
987                );
988            }
989            next.places.pop();
990            left.push(top.frame.clone());
991        }
992        Request::Jump { depth } => {
993            if *depth >= state.places.len() {
994                return nothing("already there");
995            }
996            for e in state.places[*depth..].iter().rev() {
997                if let Some(spec) = registry.get(&e.frame) {
998                    check!(
999                        &spec.can_leave,
1000                        &e.frame,
1001                        &e.payload,
1002                        false,
1003                        state,
1004                        registry,
1005                        holds,
1006                        hops
1007                    );
1008                }
1009                left.push(e.frame.clone());
1010            }
1011            next.places.truncate(*depth);
1012        }
1013        Request::Go { places } => {
1014            let common = state
1015                .places
1016                .iter()
1017                .zip(places)
1018                .take_while(|(a, b)| a == b)
1019                .count();
1020            if common == state.places.len() && common == places.len() {
1021                return nothing("already there");
1022            }
1023            for e in state.places[common..].iter().rev() {
1024                if let Some(spec) = registry.get(&e.frame) {
1025                    check!(
1026                        &spec.can_leave,
1027                        &e.frame,
1028                        &e.payload,
1029                        false,
1030                        state,
1031                        registry,
1032                        holds,
1033                        hops
1034                    );
1035                }
1036                left.push(e.frame.clone());
1037            }
1038            for e in &places[common..] {
1039                let spec = spec_of(registry, &e.frame, Kind::Place, state)?;
1040                check!(
1041                    &spec.can_enter,
1042                    &e.frame,
1043                    &e.payload,
1044                    true,
1045                    state,
1046                    registry,
1047                    holds,
1048                    hops
1049                );
1050                entered.push(e.frame.clone());
1051            }
1052            next.places = places.clone();
1053        }
1054        Request::SetMode { mode, payload } | Request::PushMode { mode, payload } => {
1055            let pushed = matches!(request, Request::PushMode { .. });
1056            let spec = spec_of(registry, mode, Kind::Mode, state)?;
1057            let group = spec.group.clone().expect("a mode has a group");
1058            let at = state.modes.iter().position(|m| m.group == group);
1059            let life = if pushed { Life::Pushed } else { Life::Set };
1060            if let Some(i) = at {
1061                let old = &state.modes[i];
1062                if old.frame == *mode && old.life == life && old.payload == *payload {
1063                    return nothing("this mode is on already");
1064                }
1065                if old.frame != *mode
1066                    && let Some(old_spec) = registry.get(&old.frame)
1067                {
1068                    check!(
1069                        &old_spec.can_leave,
1070                        &old.frame,
1071                        &old.payload,
1072                        false,
1073                        state,
1074                        registry,
1075                        holds,
1076                        hops
1077                    );
1078                }
1079            }
1080            check!(
1081                &spec.can_enter,
1082                mode,
1083                payload,
1084                true,
1085                state,
1086                registry,
1087                holds,
1088                hops
1089            );
1090            let old = at.map(|i| next.modes.remove(i));
1091            if let Some(o) = &old {
1092                left.push(o.frame.clone());
1093            }
1094            let entry = ModeEntry {
1095                frame: mode.clone(),
1096                group,
1097                life,
1098                payload: payload.clone(),
1099                under: if pushed { old.map(Box::new) } else { None },
1100            };
1101            match at {
1102                Some(i) => next.modes.insert(i, entry),
1103                None => next.modes.push(entry),
1104            }
1105            entered.push(mode.clone());
1106        }
1107        Request::PopMode => {
1108            let Some(i) = state.modes.iter().rposition(|m| m.life == Life::Pushed) else {
1109                return nothing("no mode is pushed");
1110            };
1111            let m = &state.modes[i];
1112            if let Some(spec) = registry.get(&m.frame) {
1113                check!(
1114                    &spec.can_leave,
1115                    &m.frame,
1116                    &m.payload,
1117                    false,
1118                    state,
1119                    registry,
1120                    holds,
1121                    hops
1122                );
1123            }
1124            let m = next.modes.remove(i);
1125            left.push(m.frame.clone());
1126            if let Some(under) = m.under {
1127                entered.push(under.frame.clone());
1128                next.modes.insert(i, *under);
1129            }
1130        }
1131        Request::ClearMode { group } => {
1132            let Some(i) = state.modes.iter().position(|m| m.group == *group) else {
1133                return nothing("no mode of this group is on");
1134            };
1135            let m = &state.modes[i];
1136            if let Some(spec) = registry.get(&m.frame) {
1137                check!(
1138                    &spec.can_leave,
1139                    &m.frame,
1140                    &m.payload,
1141                    false,
1142                    state,
1143                    registry,
1144                    holds,
1145                    hops
1146                );
1147            }
1148            left.push(next.modes.remove(i).frame);
1149        }
1150        Request::Back => unreachable!("handled above"),
1151    }
1152    next.rev = state.rev + 1;
1153    Ok(Transition {
1154        state: next,
1155        entered,
1156        left,
1157        redirected: None,
1158    })
1159}
1160
1161/// A frame dropped on restore, and why.
1162#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1163pub struct Dropped {
1164    pub frame: FrameId,
1165    pub why: String,
1166}
1167
1168/// Brings a saved state back against today's frames: a place that is
1169/// unknown, transient or refused by `valid` (its payload no longer
1170/// exists) cuts the path there (its children go with it); a mode is
1171/// dropped alone (a pushed one gives its place back to what it
1172/// replaced). Restoring never fails; the revision is kept.
1173pub fn restore(
1174    saved: &State,
1175    registry: &FrameRegistry,
1176    valid: &dyn Fn(&FrameId, &Json) -> Option<String>,
1177) -> (State, Vec<Dropped>) {
1178    let check = |frame: &FrameId, payload: &Json, kind: Kind| -> Option<String> {
1179        match registry.get(frame) {
1180            None => Some("it is not declared any more".into()),
1181            Some(s) if s.kind != kind => Some("it is not of the same kind any more".into()),
1182            Some(s) if s.transient => Some("it is transient".into()),
1183            Some(_) => valid(frame, payload),
1184        }
1185    };
1186    let mut out = State {
1187        rev: saved.rev,
1188        ..State::default()
1189    };
1190    let mut dropped = Vec::new();
1191    let mut cut = false;
1192    for e in &saved.places {
1193        if cut {
1194            dropped.push(Dropped {
1195                frame: e.frame.clone(),
1196                why: "a place above it was dropped".into(),
1197            });
1198            continue;
1199        }
1200        match check(&e.frame, &e.payload, Kind::Place) {
1201            None => out.places.push(e.clone()),
1202            Some(why) => {
1203                dropped.push(Dropped {
1204                    frame: e.frame.clone(),
1205                    why,
1206                });
1207                cut = true;
1208            }
1209        }
1210    }
1211    for m in &saved.modes {
1212        let mut current = Some(m.clone());
1213        while let Some(mut entry) = current.take() {
1214            let mut why = check(&entry.frame, &entry.payload, Kind::Mode);
1215            if why.is_none() {
1216                let spec_group = registry.get(&entry.frame).and_then(|s| s.group.clone());
1217                if spec_group.as_ref() != Some(&entry.group) {
1218                    why = Some("its group changed".into());
1219                } else if out.modes.iter().any(|o| o.group == entry.group) {
1220                    why = Some("another mode of its group is on".into());
1221                }
1222            }
1223            match why {
1224                None => {
1225                    // What it replaced comes back only if it is valid.
1226                    if let Some(under) = entry.under.take() {
1227                        let ok = check(&under.frame, &under.payload, Kind::Mode).is_none()
1228                            && registry.get(&under.frame).and_then(|s| s.group.clone())
1229                                == Some(entry.group.clone());
1230                        if ok {
1231                            entry.under = Some(under);
1232                        } else {
1233                            dropped.push(Dropped {
1234                                frame: under.frame.clone(),
1235                                why: "what it replaced is not valid any more".into(),
1236                            });
1237                        }
1238                    }
1239                    out.modes.push(entry);
1240                }
1241                Some(why) => {
1242                    dropped.push(Dropped {
1243                        frame: entry.frame.clone(),
1244                        why,
1245                    });
1246                    current = entry.under.map(|u| *u);
1247                }
1248            }
1249        }
1250    }
1251    (out, dropped)
1252}
1253
1254/// The `context` document: the stack as its owner writes it at each
1255/// transition.
1256#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1257pub struct ContextDoc {
1258    pub state: State,
1259}
1260
1261/// The `context` document's schema.
1262pub fn schema() -> Schema {
1263    Schema::new("context", 1).migration(0, same)
1264}
1265
1266/// What the projection keeps for one projection key: the focused panel
1267/// and the values components remember there (a list's scroll offset).
1268#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1269pub struct ViewState {
1270    #[serde(default, skip_serializing_if = "Option::is_none")]
1271    pub focus: Option<PanelId>,
1272    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1273    pub values: BTreeMap<String, Json>,
1274}
1275
1276/// The `view` document: the projection's layouts and view states, by
1277/// projection key ([`State::projection_key`]), and values kept per place
1278/// (the top place's frame id, `root` at the root: the status bar's
1279/// choices).
1280#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1281pub struct ViewDoc {
1282    #[serde(default)]
1283    pub layouts: BTreeMap<String, Layout>,
1284    #[serde(default)]
1285    pub views: BTreeMap<String, ViewState>,
1286    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1287    pub places: BTreeMap<String, BTreeMap<String, Json>>,
1288}
1289
1290/// The `view` document's schema.
1291pub fn view_schema() -> Schema {
1292    Schema::new("view", 1).migration(0, same)
1293}
1294
1295#[cfg(test)]
1296mod tests {
1297    use super::*;
1298    use serde_json::json;
1299
1300    const ALBUM: FrameId = FrameId::from_static("t.album");
1301    const PHOTO: FrameId = FrameId::from_static("t.photo");
1302    const MASK: FrameId = FrameId::from_static("t.mask");
1303    const LOCKED: FrameId = FrameId::from_static("t.locked");
1304    const CULLING: FrameId = FrameId::from_static("t.culling");
1305    const REVIEW: FrameId = FrameId::from_static("t.review");
1306    const COMPARE: FrameId = FrameId::from_static("t.compare");
1307    const AGENT: FrameId = FrameId::from_static("t.agent");
1308    const ORIENTATION: GroupId = GroupId::from_static("orientation");
1309    const VIEW: GroupId = GroupId::from_static("view");
1310
1311    fn registry() -> FrameRegistry {
1312        let mut r = FrameRegistry::new();
1313        r.insert(FrameSpec::place(ALBUM, "Album").key("albumOpen", "true"))
1314            .unwrap();
1315        r.insert(FrameSpec::place(PHOTO, "Photo").can_leave(|c| {
1316            if c.payload == &json!("dirty") {
1317                Verdict::Refuse("unsaved changes".into())
1318            } else {
1319                Verdict::Go
1320            }
1321        }))
1322        .unwrap();
1323        r.insert(FrameSpec::place(MASK, "Mask")).unwrap();
1324        // Entering it lands on the album instead.
1325        r.insert(
1326            FrameSpec::place(LOCKED, "Locked")
1327                .can_enter(|_| Verdict::Redirect(Request::enter(ALBUM))),
1328        )
1329        .unwrap();
1330        r.insert(FrameSpec::mode(CULLING, ORIENTATION, "Culling"))
1331            .unwrap();
1332        r.insert(FrameSpec::mode(REVIEW, ORIENTATION, "Review"))
1333            .unwrap();
1334        r.insert(FrameSpec::mode(COMPARE, VIEW, "Compare").show(PanelId::from_static("t.second")))
1335            .unwrap();
1336        r.insert(FrameSpec::mode(AGENT, GroupId::from_static("driver"), "Agent").transient())
1337            .unwrap();
1338        r
1339    }
1340
1341    fn go(s: &State, r: &FrameRegistry, req: Request) -> State {
1342        apply(s, r, &[], &Envelope::new(req)).unwrap().state
1343    }
1344
1345    #[test]
1346    fn places_stack_and_leave_with_their_guards() {
1347        let r = registry();
1348        let s = go(&State::default(), &r, Request::enter(ALBUM));
1349        let s = go(&s, &r, Request::enter(PHOTO));
1350        let s = go(&s, &r, Request::enter(MASK));
1351        assert_eq!(s.depth(), 3);
1352        assert_eq!(s.place(), "t.mask");
1353        assert_eq!(s.path_key(), "root/t.album/t.photo/t.mask");
1354        let t = apply(&s, &r, &[], &Envelope::new(Request::Jump { depth: 1 })).unwrap();
1355        assert_eq!(t.left, [MASK, PHOTO]);
1356        assert_eq!(t.state.place(), "t.album");
1357        // A guard keeps a dirty photo.
1358        let dirty = go(
1359            &State::default(),
1360            &r,
1361            Request::Enter {
1362                frame: PHOTO,
1363                payload: json!("dirty"),
1364            },
1365        );
1366        let e = apply(&dirty, &r, &[], &Envelope::new(Request::Leave)).unwrap_err();
1367        assert_eq!(e.kind, RefusalKind::Guard);
1368        assert_eq!(e.by, "t.photo");
1369        // Nothing above the root; a mode is not a place.
1370        assert_eq!(
1371            apply(&State::default(), &r, &[], &Envelope::new(Request::Leave))
1372                .unwrap_err()
1373                .kind,
1374            RefusalKind::Nothing
1375        );
1376        assert_eq!(
1377            apply(
1378                &State::default(),
1379                &r,
1380                &[],
1381                &Envelope::new(Request::enter(CULLING))
1382            )
1383            .unwrap_err()
1384            .kind,
1385            RefusalKind::Unknown
1386        );
1387        // Go: from one path to another, common prefix kept.
1388        let t = apply(
1389            &s,
1390            &r,
1391            &[],
1392            &Envelope::new(Request::Go {
1393                places: vec![Entry::new(ALBUM), Entry::new(MASK)],
1394            }),
1395        )
1396        .unwrap();
1397        assert_eq!(t.left, [MASK, PHOTO]);
1398        assert_eq!(t.entered, [MASK]);
1399        assert_eq!(t.state.path_key(), "root/t.album/t.mask");
1400    }
1401
1402    #[test]
1403    fn a_guard_redirects() {
1404        let r = registry();
1405        let t = apply(
1406            &State::default(),
1407            &r,
1408            &[],
1409            &Envelope::new(Request::enter(LOCKED)),
1410        )
1411        .unwrap();
1412        assert_eq!(t.state.place(), "t.album");
1413        assert_eq!(t.redirected, Some(Request::enter(ALBUM)));
1414    }
1415
1416    #[test]
1417    fn groups_are_exclusive_and_combine_across() {
1418        let r = registry();
1419        let s = go(&State::default(), &r, Request::set(CULLING));
1420        let t = apply(&s, &r, &[], &Envelope::new(Request::set(REVIEW))).unwrap();
1421        assert_eq!(t.left, [CULLING]);
1422        assert_eq!(t.entered, [REVIEW]);
1423        let s = go(&t.state, &r, Request::set(COMPARE));
1424        assert_eq!(s.mode_of("orientation"), Some(&REVIEW));
1425        assert_eq!(s.mode_of("view"), Some(&COMPARE));
1426        assert_eq!(
1427            s.projection_key(),
1428            "root|orientation=t.review|view=t.compare"
1429        );
1430        // Setting what is on: nothing to do.
1431        assert_eq!(
1432            apply(&s, &r, &[], &Envelope::new(Request::set(REVIEW)))
1433                .unwrap_err()
1434                .kind,
1435            RefusalKind::Nothing
1436        );
1437        let s = go(&s, &r, Request::ClearMode { group: VIEW });
1438        assert_eq!(s.mode_of("view"), None);
1439        let keys = s.when_keys(&r);
1440        assert!(keys.contains(&("mode.orientation".into(), "t.review".into())));
1441        assert!(keys.contains(&("mode.view".into(), String::new())));
1442    }
1443
1444    #[test]
1445    fn pushed_modes_pop_back_to_what_they_replaced() {
1446        let r = registry();
1447        let s = go(&State::default(), &r, Request::set(CULLING));
1448        let s = go(&s, &r, Request::enter(ALBUM));
1449        let s = go(&s, &r, Request::push(REVIEW));
1450        assert!(s.has_pushed());
1451        assert_eq!(s.mode_of("orientation"), Some(&REVIEW));
1452        // Back pops the pushed mode first, then leaves places.
1453        let t = apply(&s, &r, &[], &Envelope::new(Request::Back)).unwrap();
1454        assert_eq!(t.left, [REVIEW]);
1455        assert_eq!(t.entered, [CULLING]);
1456        assert_eq!(t.state.mode_of("orientation"), Some(&CULLING));
1457        assert_eq!(t.state.place(), "t.album");
1458        let s = go(&t.state, &r, Request::Back);
1459        assert_eq!(s.place(), ROOT);
1460        // A set mode stays: nothing pushed, nothing to go back to.
1461        assert_eq!(
1462            apply(&s, &r, &[], &Envelope::new(Request::Back))
1463                .unwrap_err()
1464                .kind,
1465            RefusalKind::Nothing
1466        );
1467        assert_eq!(s.mode_of("orientation"), Some(&CULLING));
1468    }
1469
1470    #[test]
1471    fn holds_refuse_with_their_reason_and_stale_revisions_too() {
1472        let r = registry();
1473        let hold = Hold {
1474            token: 1,
1475            groups: vec![ORIENTATION],
1476            reason: "a drag is in progress".into(),
1477            by: "user".into(),
1478        };
1479        let e = apply(
1480            &State::default(),
1481            &r,
1482            std::slice::from_ref(&hold),
1483            &Envelope::new(Request::set(CULLING)),
1484        )
1485        .unwrap_err();
1486        assert_eq!(e.kind, RefusalKind::Held);
1487        assert_eq!(e.reason, "a drag is in progress");
1488        // Other groups and places go on.
1489        assert!(
1490            apply(
1491                &State::default(),
1492                &r,
1493                std::slice::from_ref(&hold),
1494                &Envelope::new(Request::set(COMPARE))
1495            )
1496            .is_ok()
1497        );
1498        assert!(
1499            apply(
1500                &State::default(),
1501                &r,
1502                std::slice::from_ref(&hold),
1503                &Envelope::new(Request::enter(ALBUM))
1504            )
1505            .is_ok()
1506        );
1507        // A hold of everything.
1508        let all = Hold {
1509            groups: Vec::new(),
1510            ..hold
1511        };
1512        assert!(
1513            apply(
1514                &State::default(),
1515                &r,
1516                &[all],
1517                &Envelope::new(Request::enter(ALBUM))
1518            )
1519            .is_err()
1520        );
1521        let s = go(&State::default(), &r, Request::enter(ALBUM));
1522        let e = apply(&s, &r, &[], &Envelope::new(Request::Leave).if_rev(0)).unwrap_err();
1523        assert_eq!(e.kind, RefusalKind::Stale);
1524        assert!(apply(&s, &r, &[], &Envelope::new(Request::Leave).if_rev(1)).is_ok());
1525    }
1526
1527    #[test]
1528    fn restore_cuts_at_the_first_invalid_place_and_drops_modes_alone() {
1529        let r = registry();
1530        let mut s = State::default();
1531        for req in [
1532            Request::enter(ALBUM),
1533            Request::Enter {
1534                frame: PHOTO,
1535                payload: json!(7),
1536            },
1537            Request::enter(MASK),
1538            Request::set(CULLING),
1539            Request::push(REVIEW),
1540            Request::set(AGENT),
1541            Request::push(COMPARE),
1542        ] {
1543            s = go(&s, &r, req);
1544        }
1545        // Everything valid, but the transient agent.
1546        let (back, dropped) = restore(&s, &r, &|_, _| None);
1547        assert_eq!(back.places, s.places);
1548        assert_eq!(back.rev, s.rev);
1549        assert_eq!(back.mode_of("orientation"), Some(&REVIEW));
1550        assert_eq!(back.mode_of("view"), Some(&COMPARE));
1551        assert_eq!(back.mode_of("driver"), None);
1552        assert_eq!(dropped.len(), 1);
1553        assert_eq!(dropped[0].frame, AGENT);
1554        // Photo 7 is gone: the path is cut there, the mask with it.
1555        let (back, dropped) = restore(&s, &r, &|f, p| {
1556            (*f == PHOTO && *p == json!(7)).then(|| "deleted".to_string())
1557        });
1558        assert_eq!(back.path_key(), "root/t.album");
1559        assert_eq!(dropped[0].why, "deleted");
1560        assert_eq!(dropped[1].frame, MASK);
1561        // Review is not declared any more: culling, which it replaced,
1562        // comes back.
1563        let mut fewer = registry();
1564        fewer.remove(&REVIEW);
1565        let (back, dropped) = restore(&s, &fewer, &|_, _| None);
1566        assert_eq!(back.mode_of("orientation"), Some(&CULLING));
1567        assert!(dropped.iter().any(|d| d.frame == REVIEW));
1568    }
1569
1570    #[test]
1571    fn the_stack_round_trips_through_its_document() {
1572        let r = registry();
1573        let mut s = State::default();
1574        for req in [
1575            Request::Enter {
1576                frame: ALBUM,
1577                payload: json!({ "id": 3 }),
1578            },
1579            Request::set(CULLING),
1580            Request::push(REVIEW),
1581        ] {
1582            s = go(&s, &r, req);
1583        }
1584        let text = schema().save(&ContextDoc { state: s.clone() }).unwrap();
1585        let back = schema().load::<ContextDoc>(&text).unwrap().value;
1586        assert_eq!(back.state, s);
1587        let req: Request =
1588            serde_json::from_value(json!({ "op": "enter", "frame": "t.album" })).unwrap();
1589        assert_eq!(req, Request::enter(ALBUM));
1590        let env: Envelope =
1591            serde_json::from_value(json!({ "request": { "op": "back" }, "dry_run": true }))
1592                .unwrap();
1593        assert!(env.dry_run);
1594        let mut view = ViewDoc::default();
1595        view.views.insert(
1596            s.projection_key(),
1597            ViewState {
1598                focus: Some(PanelId::from_static("t.list")),
1599                values: [("scroll".to_string(), json!(120.0))].into(),
1600            },
1601        );
1602        view.places.insert(
1603            ALBUM.to_string(),
1604            [("status".to_string(), json!({ "hidden": ["jobs"] }))].into(),
1605        );
1606        let text = view_schema().save(&view).unwrap();
1607        assert_eq!(view_schema().load::<ViewDoc>(&text).unwrap().value, view);
1608    }
1609
1610    #[test]
1611    fn a_group_is_visible_when_one_of_its_modes_says_so() {
1612        let mut r = FrameRegistry::new();
1613        r.insert(FrameSpec::mode(CULLING, ORIENTATION, "Culling").visible())
1614            .unwrap();
1615        r.insert(FrameSpec::mode(REVIEW, ORIENTATION, "Review"))
1616            .unwrap();
1617        r.insert(FrameSpec::mode(
1618            FrameId::from_static("t.plumbing"),
1619            GroupId::from_static("plumbing"),
1620            "Plumbing",
1621        ))
1622        .unwrap();
1623        assert_eq!(r.visible_groups(), [ORIENTATION].into());
1624        let spec = FrameSpec::mode(CULLING, ORIENTATION, "Culling").tone("record");
1625        assert_eq!(spec.tone.as_deref(), Some("record"));
1626        assert!(!spec.visible);
1627    }
1628
1629    #[test]
1630    fn a_frames_clause_names_its_key() {
1631        let r = registry();
1632        assert_eq!(r.get(&ALBUM).unwrap().clause(), "place == 't.album'");
1633        assert_eq!(
1634            r.get(&CULLING).unwrap().clause(),
1635            "mode.orientation == 't.culling'"
1636        );
1637        let w = crate::when::When::parse(&r.get(&CULLING).unwrap().clause()).unwrap();
1638        let s = go(&State::default(), &r, Request::set(CULLING));
1639        let mut cx = crate::when::WhenContext::new();
1640        for (k, v) in s.when_keys(&r) {
1641            cx.set(&k, &v);
1642        }
1643        assert!(w.eval(&cx));
1644        let s = go(&s, &r, Request::enter(ALBUM));
1645        assert!(
1646            s.when_keys(&r)
1647                .contains(&("albumOpen".into(), "true".into()))
1648        );
1649        assert!(
1650            FrameRegistry::new()
1651                .insert(FrameSpec {
1652                    group: None,
1653                    ..FrameSpec::mode(CULLING, ORIENTATION, "x")
1654                })
1655                .is_err()
1656        );
1657    }
1658
1659    #[test]
1660    fn a_place_labels_its_crumb_from_its_payload() {
1661        let space = FrameSpec::place(ALBUM, "Space").label(|c| {
1662            c.payload["id"]
1663                .as_str()
1664                .map(|id| format!("{} {}", c.title, id.to_uppercase()))
1665        });
1666        assert_eq!(
1667            space
1668                .label_of("Espace", &json!({ "id": "dark" }))
1669                .as_deref(),
1670            Some("Espace DARK")
1671        );
1672        assert_eq!(space.label_of("Space", &json!(3)), None);
1673        assert_eq!(
1674            FrameSpec::place(PHOTO, "Photo").label_of("Photo", &json!("x")),
1675            None
1676        );
1677        // The hook is not part of what is serialised (`context.read`).
1678        let text = serde_json::to_value(&space).unwrap();
1679        assert!(text.get("label").is_none(), "{text}");
1680    }
1681
1682    #[test]
1683    fn a_place_picks_its_arrangement_from_its_payload() {
1684        let space = FrameSpec::place(ALBUM, "Space")
1685            .arrangement("Plain")
1686            .arrangement_for(|p| (p["id"] == "dark").then(|| "Darkroom".to_string()));
1687        assert_eq!(
1688            space.arrangement_of(&json!({ "id": "dark" })).as_deref(),
1689            Some("Darkroom")
1690        );
1691        assert_eq!(space.arrangement_of(&json!({ "id": "map" })), None);
1692        assert_eq!(
1693            FrameSpec::place(PHOTO, "Photo").arrangement_of(&json!(1)),
1694            None
1695        );
1696        let text = serde_json::to_value(&space).unwrap();
1697        assert!(text.get("arrangement_for").is_none(), "{text}");
1698    }
1699
1700    #[test]
1701    fn the_top_places_payload_sets_keys() {
1702        let r = registry();
1703        let s = go(
1704            &State::default(),
1705            &r,
1706            Request::Enter {
1707                frame: ALBUM,
1708                payload: json!({ "id": "dark", "n": 2, "deep": { "x": 1 } }),
1709            },
1710        );
1711        let keys = s.when_keys(&r);
1712        assert!(
1713            keys.contains(&("payload.id".into(), "dark".into())),
1714            "{keys:?}"
1715        );
1716        assert!(keys.contains(&("payload.n".into(), "2".into())), "{keys:?}");
1717        assert!(!keys.iter().any(|(k, _)| k.starts_with("payload.deep")));
1718        let w = crate::when::When::parse("place == 't.album' && payload.id == 'dark'").unwrap();
1719        let mut cx = crate::when::WhenContext::new();
1720        for (k, v) in &keys {
1721            cx.set(k, v);
1722        }
1723        assert!(w.eval(&cx));
1724        // Only the top place's payload counts.
1725        let s = go(&s, &r, Request::enter(MASK));
1726        assert!(
1727            !s.when_keys(&r)
1728                .iter()
1729                .any(|(k, _)| k.starts_with("payload"))
1730        );
1731        assert_eq!(
1732            payload_keys(&json!("holidays")),
1733            vec![("payload".to_string(), "holidays".to_string())]
1734        );
1735        assert!(payload_keys(&Json::Null).is_empty());
1736    }
1737}