Skip to main content

egui_pop_api/
history.rs

1//! Undo (ADR 0014): histories owned by the kernel, routed by focus,
2//! projected by the interface.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - **The owner** implements [`History`]: its scopes (one history
8//!   each: a document's edit, a collection's marks), their steps as
9//!   [`StepInfo`]s, and the requests `undo`, `redo`, `jump` and `group`.
10//!   The host gives it ([`Host::history`](crate::host::Host::history));
11//!   without one, egui-pop's [`StoreHistory`] answers over the value
12//!   store's application history ([`APP`]). The inverse of a step stays
13//!   with the owner; the interface only reads and asks.
14//! - **Local scopes** are a component's own history, kept in the
15//!   interface and never persisted: the theme editor's draft, the
16//!   settings window's values ([`StoreScope`] over the store's
17//!   [`SETTINGS`] history). A component registers one for its focus
18//!   surface ([`Ctx::local_scope`](crate::Ctx::local_scope)).
19//! - **Focus picks the history** ([`target`]). Ctrl+Z, outside a text
20//!   field (which keeps its own undo), undoes in the innermost focused
21//!   surface that has a local scope; nothing while a modal is open;
22//!   otherwise, by the [`Routing`] the application sets:
23//!   - [`Routing::Newest`] (the default): the newest step among the
24//!     owner's scopes active in the window (a scope's focus targets
25//!     drawn; none: always active). Redo goes back to the scope last
26//!     undone.
27//!   - [`Routing::Focus`]: the scope of the innermost focused surface
28//!     that names one: the surface declared it
29//!     ([`Ctx::history_target`](crate::Ctx::history_target)), or one of
30//!     the owner's scopes lists it among its focus targets
31//!     ([`ScopeInfo::focus`]); when no focused surface names one (the
32//!     menu bar, an empty spot, a panel without a history), the scope
33//!     focused last in that window, while the owner still has it. Never
34//!     the newest step of another scope: with no scope focused yet (at
35//!     start-up), Ctrl+Z does nothing and says why ([`NOTHING_FOCUSED`]).
36//!     Redo goes to the same scope.
37//!
38//!   Either way, the scope picked goes through the `pop.history.target`
39//!   step ([`STEP_TARGET`]) before Ctrl+Z, the Edit menu and the agents
40//!   use it: a before-hook may name another scope (or `null`: none).
41//! - **Undo, redo and jump are steps** (ADR 0011): `edit.undo`,
42//!   `edit.redo` and `edit.jump` ([`STEP_JUMP`]), their arguments naming
43//!   the scope, so a before-hook vetoes one or redirects it. A gesture in
44//!   progress in the scope refuses them. Each answer is published:
45//!   `history.changed` (the scope, its revision and head) or
46//!   `history.refused` (the scope, the kind and the reason); the owner's
47//!   own moves (a new step) are published at the next pass.
48//! - **Merging and groups**: writes with a merge key one second apart
49//!   are one step (`values::Set::merge`), the focus leaving seals them;
50//!   [`History::group`] opens an explicit group (an import, an agent's
51//!   request) whose steps are one entry.
52//! - **Beyond undo and redo**, each a request with a default, so an
53//!   owner that supports none of them keeps working: snapshots (named
54//!   states, restored as a new step through `edit.restore`), the history
55//!   panel's hover preview ([`hover`]), one step undone out of order
56//!   (`edit.undo_step`, refused when a later step changed the same
57//!   values), and the steps new steps replaced, reachable by a jump.
58//!   [`History::features`] says which a scope supports; [`StoreHistory`]
59//!   supports them all.
60//!
61//! ```
62//! use egui_pop_api::App;
63//! use egui_pop_api::history;
64//! use egui_pop_core::lock;
65//! use egui_pop_model::commands::Origin;
66//! use egui_pop_model::ids::OwnerId;
67//! use egui_pop_model::values::{Change, Descriptor, Set, Value};
68//!
69//! let app = App::builder().build(&egui::Context::default()).unwrap();
70//! let h = app.handle();
71//! let store = h.store();
72//! lock(&store).declare(&OwnerId::USER, "doc/n", Descriptor::int("N", 0, 9, 0)).unwrap();
73//! lock(&store).set(Set::new("doc/n", Change::To(Value::Int(3)), Origin::User)).unwrap();
74//! assert!(history::can_undo(h));
75//! assert!(history::undo(h, &Origin::User).ok());
76//! assert_eq!(lock(&store).get("doc/n").unwrap().value, Value::Int(0));
77//! assert_eq!(history::line(h, &history::APP).unwrap().redo.len(), 1);
78//! ```
79
80use std::cell::{Cell, RefCell};
81use std::collections::BTreeMap;
82use std::fmt;
83use std::rc::Rc;
84
85use egui_pop_core::binding::SharedStore;
86use egui_pop_core::{focus, lock, strings};
87use egui_pop_model::clock::ManualClock;
88use egui_pop_model::commands::Origin;
89use egui_pop_model::ids::{OwnerId, StepId};
90use egui_pop_model::values::{self, Store};
91use serde::Serialize;
92use serde_json::{Value as Json, json};
93
94pub use egui_pop_model::history::{
95    APP, At, CAP, Features, Jump, Label, Line, MERGE_WINDOW, MergeMark, Preview, PreviewChange,
96    Refusal, RefusalKind, Replaced, Request, SETTINGS, ScopeId, ScopeInfo, Snapshot, StepInfo,
97    may_undo_out_of_order, merges, newest, plan_jump,
98};
99
100use crate::app::{AppHandle, STEP_REDO, STEP_UNDO};
101use crate::host::{Pending, source_of};
102use crate::steps::Outcome;
103
104/// A jump to a step of a scope (`{ "scope", "to", "origin" }`, `to` 0:
105/// the start): vetoable like an undo; its result names the steps walked.
106pub const STEP_JUMP: StepId = StepId::from_static("edit.jump");
107
108/// A snapshot restored (`{ "scope", "snapshot", "origin" }`): a new step
109/// of the scope, vetoable like an undo.
110pub const STEP_RESTORE: StepId = StepId::from_static("edit.restore");
111
112/// One step undone out of order (`{ "scope", "step", "origin" }`, the
113/// history panel's "Undo this step"): vetoable like an undo.
114pub const STEP_UNDO_STEP: StepId = StepId::from_static("edit.undo_step");
115
116/// Where Ctrl+Z or Ctrl+Shift+Z goes (`{ "scope", "redo", "rule" }`,
117/// `rule` one of `focus`, `last_focused`, `none` under
118/// [`Routing::Focus`], `newest` under [`Routing::Newest`]): a
119/// before-hook may redirect it by naming another `scope` (`null`:
120/// none). With `none`, `scope` is `null`: no view was focused yet.
121/// Run quietly, whenever the target is read (the keys, the Edit menu, an agent's
122/// undo without a scope): neither published nor traced.
123pub const STEP_TARGET: StepId = StepId::from_static("pop.history.target");
124
125/// The rule [`STEP_TARGET`] names when, under [`Routing::Focus`], no
126/// view was focused yet in the window: Ctrl+Z goes nowhere, and says so
127/// (`egui-pop-history-nothing-focused`).
128pub const NOTHING_FOCUSED: &str = "none";
129
130/// How Ctrl+Z picks among the owner's scopes, outside a focused local
131/// scope and a modal ([`set_routing`]).
132#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
133#[serde(rename_all = "snake_case")]
134pub enum Routing {
135    /// The newest step among the active scopes; redo goes back to the
136    /// scope last undone. What a document-less application wants.
137    #[default]
138    Newest,
139    /// The scope the focus is in (its focus targets name the innermost
140    /// focused surface), else the one focused last in the window, else
141    /// none (never the newest of another scope); redo goes to the same
142    /// scope. What an application with several documents or editors on
143    /// screen wants: the newest step may be another one's.
144    Focus,
145}
146
147/// What the owner answers a request.
148#[derive(Debug)]
149pub enum Answer {
150    /// Done (or, for a dry run, would be), or refused.
151    Done(Result<Walked, Refusal>),
152    /// A remote owner answers later; it publishes the result on its bus.
153    Later(Pending),
154}
155
156/// An undo, a redo or a jump, as made.
157#[derive(Clone, Debug, PartialEq, Serialize)]
158pub struct Walked {
159    pub scope: ScopeId,
160    /// The steps undone or redone, in the order walked; empty: there was
161    /// nothing (or the jump was already there).
162    pub steps: Vec<StepInfo>,
163    /// The scope's revision after it.
164    pub rev: u64,
165    /// The scope's head after it (0: nothing done).
166    pub head: u64,
167    /// A dry run: nothing changed.
168    pub dry_run: bool,
169}
170
171/// The owner of the application's histories, as the interface reaches it.
172pub trait History {
173    /// The scopes there are.
174    fn scopes(&self) -> Vec<ScopeInfo>;
175
176    /// A scope's steps; `None`: no such scope.
177    fn line(&self, scope: &ScopeId) -> Option<Line>;
178
179    /// A scope's revision, read every pass (cheaper than its line).
180    fn rev(&self, scope: &ScopeId) -> u64 {
181        self.line(scope).map_or(0, |l| l.rev)
182    }
183
184    /// A scope's line cut to its head and its next step: what the routing
185    /// and the menus read, several times a pass.
186    fn tips(&self, scope: &ScopeId) -> Option<Line> {
187        self.line(scope).map(|l| tips_of(&l))
188    }
189
190    /// Undoes the scope's head.
191    fn undo(&mut self, request: &Request, origin: &Origin) -> Answer;
192
193    /// Redoes the scope's next step.
194    fn redo(&mut self, request: &Request, origin: &Origin) -> Answer;
195
196    /// Brings the scope to step `to` (0: the start), all or nothing.
197    fn jump(&mut self, request: &Request, to: u64, origin: &Origin) -> Answer;
198
199    /// Opens a group: what `origin` does until [`History::close`] is one
200    /// step labelled `label`. `None`: the owner groups nothing.
201    fn group(&mut self, _origin: &Origin, _label: &Label) -> Option<u64> {
202        None
203    }
204
205    /// Closes a group: kept as one step, or (`keep` false) put back.
206    fn close(&mut self, _group: u64, _keep: bool) {}
207
208    /// A gesture still going in the scope: undo, redo and jump wait for
209    /// it.
210    fn in_progress(&self, _scope: &ScopeId) -> Option<Label> {
211        None
212    }
213
214    /// What the owner supports in a scope beyond undo, redo and jump:
215    /// the history panel offers only that. None by default.
216    fn features(&self, _scope: &ScopeId) -> Features {
217        Features::default()
218    }
219
220    /// A scope's snapshots, oldest first.
221    fn snapshots(&self, _scope: &ScopeId) -> Vec<Snapshot> {
222        Vec::new()
223    }
224
225    /// Pins the scope's current state under `name` (`request.dry_run`:
226    /// the snapshot it would take, nothing kept). Refused as unsupported
227    /// by default.
228    fn snapshot(
229        &mut self,
230        request: &Request,
231        _name: &str,
232        _origin: &Origin,
233    ) -> Result<Snapshot, Refusal> {
234        Err(unsupported(&request.scope, "snapshots"))
235    }
236
237    /// Brings the scope back to a snapshot's state, as a new step.
238    fn restore(&mut self, request: &Request, _snapshot: u64, _origin: &Origin) -> Answer {
239        Answer::Done(Err(unsupported(&request.scope, "snapshots")))
240    }
241
242    /// Deletes a snapshot.
243    fn forget(&mut self, request: &Request, _snapshot: u64) -> Result<(), Refusal> {
244        Err(unsupported(&request.scope, "snapshots"))
245    }
246
247    /// Undoes one step out of order (the panel's "Undo this step"), or
248    /// refuses with the reason (a later step changed the same values:
249    /// VS Code's rule). Refused as unsupported by default.
250    fn undo_step(&mut self, request: &Request, _step: u64, _origin: &Origin) -> Answer {
251        Answer::Done(Err(unsupported(&request.scope, "undoing one step")))
252    }
253
254    /// The steps new steps dropped from the redo list, when the owner
255    /// keeps them: the panel shows them as "replaced" rows behind a
256    /// toggle, and [`History::jump`] reaches them. None by default.
257    fn replaced(&self, _scope: &ScopeId) -> Vec<Replaced> {
258        Vec::new()
259    }
260
261    /// The pointer is on a point of the history panel (`at`), or left it
262    /// (`None`): the owner may show the state there in its own views
263    /// without committing anything, and say what differs. `None`: no
264    /// preview (the default), the panel shows nothing.
265    fn preview(&mut self, _scope: &ScopeId, _at: Option<At>) -> Option<Preview> {
266        None
267    }
268}
269
270/// What an owner refuses when it does not support a request.
271pub fn unsupported(scope: &ScopeId, what: &str) -> Refusal {
272    Refusal::new(
273        RefusalKind::Unsupported,
274        format!("the history `{scope}` does not support {what}"),
275    )
276}
277
278/// egui-pop's default owner: the value store's histories, the
279/// application's ([`APP`]) by default.
280#[derive(Clone)]
281pub struct StoreHistory {
282    store: SharedStore,
283    scopes: Vec<ScopeInfo>,
284}
285
286impl fmt::Debug for StoreHistory {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        f.debug_struct("StoreHistory")
289            .field("scopes", &self.scopes)
290            .finish_non_exhaustive()
291    }
292}
293
294impl StoreHistory {
295    /// The store's application history, as one scope.
296    pub fn new(store: SharedStore) -> Self {
297        Self::with_scopes(store, vec![ScopeInfo::new(APP, "Application")])
298    }
299
300    /// The store's histories named by `scopes`.
301    pub fn with_scopes(store: SharedStore, scopes: Vec<ScopeInfo>) -> Self {
302        Self { store, scopes }
303    }
304
305    fn known(&self, scope: &ScopeId) -> Result<(), Refusal> {
306        if self.scopes.iter().any(|s| s.id == *scope) {
307            Ok(())
308        } else {
309            Err(unknown(scope))
310        }
311    }
312
313    fn answer(
314        &self,
315        request: &Request,
316        f: impl FnOnce(&mut Store) -> Result<Vec<StepInfo>, Refusal>,
317    ) -> Answer {
318        Answer::Done(self.known(&request.scope).and_then(|()| {
319            let mut s = lock(&self.store);
320            request.check(s.history_rev(&request.scope))?;
321            if let Some(label) = s.gesture_open(&request.scope) {
322                return Err(in_progress(label));
323            }
324            let steps = f(&mut s)?;
325            let line = store_line(&s, &request.scope);
326            Ok(Walked {
327                scope: request.scope.clone(),
328                steps,
329                rev: line.rev,
330                head: line.head_id(),
331                dry_run: request.dry_run,
332            })
333        }))
334    }
335}
336
337impl History for StoreHistory {
338    fn scopes(&self) -> Vec<ScopeInfo> {
339        let cap = lock(&self.store).history_cap();
340        self.scopes
341            .iter()
342            .cloned()
343            .map(|mut s| {
344                s.cap = cap;
345                s
346            })
347            .collect()
348    }
349
350    fn line(&self, scope: &ScopeId) -> Option<Line> {
351        self.known(scope).ok()?;
352        Some(store_line(&lock(&self.store), scope))
353    }
354
355    fn rev(&self, scope: &ScopeId) -> u64 {
356        lock(&self.store).history_rev(scope)
357    }
358
359    fn tips(&self, scope: &ScopeId) -> Option<Line> {
360        self.known(scope).ok()?;
361        let s = lock(&self.store);
362        Some(Line {
363            undo: s
364                .undo_steps_in(scope)
365                .last()
366                .map(|st| step_info(scope, st))
367                .into_iter()
368                .collect(),
369            redo: s
370                .redo_steps_in(scope)
371                .last()
372                .map(|st| step_info(scope, st))
373                .into_iter()
374                .collect(),
375            rev: s.history_rev(scope),
376        })
377    }
378
379    fn undo(&mut self, request: &Request, origin: &Origin) -> Answer {
380        self.answer(request, |s| store_walk(s, request, origin, false))
381    }
382
383    fn redo(&mut self, request: &Request, origin: &Origin) -> Answer {
384        self.answer(request, |s| store_walk(s, request, origin, true))
385    }
386
387    fn jump(&mut self, request: &Request, to: u64, origin: &Origin) -> Answer {
388        self.answer(request, |s| store_jump(s, request, to, origin))
389    }
390
391    fn group(&mut self, origin: &Origin, label: &Label) -> Option<u64> {
392        Some(lock(&self.store).begin_group(origin.clone(), &label.text).0)
393    }
394
395    fn close(&mut self, group: u64, keep: bool) {
396        let mut s = lock(&self.store);
397        let g = values::GestureId(group);
398        if keep {
399            s.end(g);
400        } else {
401            s.cancel(g);
402        }
403    }
404
405    fn in_progress(&self, scope: &ScopeId) -> Option<Label> {
406        lock(&self.store).gesture_open(scope).map(Label::text)
407    }
408
409    fn features(&self, scope: &ScopeId) -> Features {
410        if self.known(scope).is_ok() {
411            Features::all()
412        } else {
413            Features::default()
414        }
415    }
416
417    fn snapshots(&self, scope: &ScopeId) -> Vec<Snapshot> {
418        if self.known(scope).is_err() {
419            return Vec::new();
420        }
421        lock(&self.store).snapshots_in(scope)
422    }
423
424    fn snapshot(
425        &mut self,
426        request: &Request,
427        name: &str,
428        origin: &Origin,
429    ) -> Result<Snapshot, Refusal> {
430        self.known(&request.scope)?;
431        let mut s = lock(&self.store);
432        request.check(s.history_rev(&request.scope))?;
433        s.take_snapshot(&request.scope, name, origin, request.dry_run)
434    }
435
436    fn restore(&mut self, request: &Request, snapshot: u64, origin: &Origin) -> Answer {
437        self.answer(request, |s| {
438            let step = s.restore_snapshot(&request.scope, snapshot, origin, request.dry_run)?;
439            Ok(step
440                .map(|st| step_info(&request.scope, &st))
441                .into_iter()
442                .collect())
443        })
444    }
445
446    fn forget(&mut self, request: &Request, snapshot: u64) -> Result<(), Refusal> {
447        self.known(&request.scope)?;
448        let mut s = lock(&self.store);
449        request.check(s.history_rev(&request.scope))?;
450        let there = s
451            .snapshots_in(&request.scope)
452            .iter()
453            .any(|x| x.id == snapshot);
454        if !there {
455            return Err(Refusal::new(
456                RefusalKind::Nothing,
457                format!("no snapshot {snapshot} in `{}`", request.scope),
458            ));
459        }
460        if !request.dry_run {
461            s.forget_snapshot(&request.scope, snapshot);
462        }
463        Ok(())
464    }
465
466    fn undo_step(&mut self, request: &Request, step: u64, origin: &Origin) -> Answer {
467        self.answer(request, |s| {
468            let st = s.undo_step_in(&request.scope, step, origin, request.dry_run)?;
469            Ok(vec![step_info(&request.scope, &st)])
470        })
471    }
472
473    fn replaced(&self, scope: &ScopeId) -> Vec<Replaced> {
474        if self.known(scope).is_err() {
475            return Vec::new();
476        }
477        lock(&self.store)
478            .replaced_in(scope)
479            .into_iter()
480            .map(|(after, st)| Replaced {
481                step: step_info(scope, st),
482                after,
483            })
484            .collect()
485    }
486
487    fn preview(&mut self, scope: &ScopeId, at: Option<At>) -> Option<Preview> {
488        self.known(scope).ok()?;
489        let at = at?;
490        let s = lock(&self.store);
491        let changes = s
492            .values_at(scope, at)?
493            .into_iter()
494            .map(|(path, now, then)| {
495                let d = s.get(&path).map(|e| &e.descriptor);
496                PreviewChange {
497                    what: d.map_or_else(|| path.clone(), |d| d.label.clone()),
498                    then: value_text(d, &then),
499                    now: value_text(d, &now),
500                }
501            })
502            .collect();
503        Some(Preview {
504            shown: false,
505            changes,
506        })
507    }
508}
509
510/// A value as a preview shows it: a number scaled, to its precision,
511/// with its unit.
512fn value_text(d: Option<&values::Descriptor>, v: &values::Value) -> String {
513    let number = |x: f64, d: &values::Descriptor| {
514        let x = x * d.display_scale;
515        let text = format!("{x:.*}", d.precision as usize);
516        match &d.unit {
517            Some(u) => format!("{text} {u}"),
518            None => text,
519        }
520    };
521    match (d, v) {
522        (Some(d), values::Value::Float(x)) => number(*x, d),
523        (Some(d), values::Value::Int(x)) => number(*x as f64, d),
524        (_, values::Value::Text(t) | values::Value::Choice(t)) => t.clone(),
525        _ => v.to_json().to_string(),
526    }
527}
528
529/// A line cut to its head and its next step.
530pub fn tips_of(line: &Line) -> Line {
531    Line {
532        undo: line.head().cloned().into_iter().collect(),
533        redo: line.next().cloned().into_iter().collect(),
534        rev: line.rev,
535    }
536}
537
538fn unknown(scope: &ScopeId) -> Refusal {
539    Refusal::new(RefusalKind::Unknown, format!("no history `{scope}`"))
540}
541
542fn in_progress(label: &str) -> Refusal {
543    Refusal::new(RefusalKind::Held, format!("“{label}” is in progress"))
544}
545
546fn refused(r: values::Refused) -> Refusal {
547    let kind = match r {
548        values::Refused::Held { .. } => RefusalKind::Held,
549        _ => RefusalKind::Owner,
550    };
551    Refusal::new(kind, r.to_string())
552}
553
554/// A dry run's answer when `by` may not write one of the values a step
555/// changed: the refusal the walk itself would give, without the
556/// diagnostic a refused write leaves.
557fn not_writer(s: &Store, step: &values::Step, by: &OwnerId) -> Result<(), Refusal> {
558    let Some((path, e)) = step
559        .changes
560        .iter()
561        .find(|(p, _, _)| !s.may_write(p, by))
562        .and_then(|(p, _, _)| s.get(p).map(|e| (p, e)))
563    else {
564        return Ok(());
565    };
566    Err(refused(values::Refused::NotWriter {
567        path: path.clone(),
568        by: by.clone(),
569        owner: e.owner.clone(),
570        current: e.value.clone(),
571    }))
572}
573
574/// A store's step as the interface sees it.
575fn step_info(scope: &ScopeId, step: &values::Step) -> StepInfo {
576    StepInfo {
577        id: step.id,
578        scope: scope.clone(),
579        label: Label::text(&step.label),
580        origin: step.origin.clone(),
581        group: step.group,
582        place: step.place.clone(),
583        at: step.at,
584        in_progress: false,
585    }
586}
587
588/// One of the store's histories, as a [`Line`].
589pub fn store_line(store: &Store, scope: &ScopeId) -> Line {
590    Line {
591        undo: store
592            .undo_steps_in(scope)
593            .iter()
594            .map(|s| step_info(scope, s))
595            .collect(),
596        redo: store
597            .redo_steps_in(scope)
598            .iter()
599            .map(|s| step_info(scope, s))
600            .collect(),
601        rev: store.history_rev(scope),
602    }
603}
604
605fn store_walk(
606    s: &mut Store,
607    request: &Request,
608    origin: &Origin,
609    redo: bool,
610) -> Result<Vec<StepInfo>, Refusal> {
611    let scope = &request.scope;
612    // Walked by the origin's writer: an agent may not take back what it
613    // may not write (the user's writer, the framework, may).
614    let by = origin.writer();
615    if request.dry_run {
616        let step = s.check_walk(scope, redo).map_err(refused)?;
617        if let Some(st) = step {
618            not_writer(s, st, &by)?;
619        }
620        return Ok(step.map(|st| step_info(scope, st)).into_iter().collect());
621    }
622    let step = if redo {
623        s.redo_in_by(scope, origin, &by)
624    } else {
625        s.undo_in_by(scope, origin, &by)
626    }
627    .map_err(refused)?;
628    Ok(step.map(|st| step_info(scope, &st)).into_iter().collect())
629}
630
631fn store_jump(
632    s: &mut Store,
633    request: &Request,
634    to: u64,
635    origin: &Origin,
636) -> Result<Vec<StepInfo>, Refusal> {
637    let scope = &request.scope;
638    let line = store_line(s, scope);
639    let jump = match plan_jump(&line, to) {
640        Ok(j) => j,
641        // A replaced step: back to where its line left, then along it.
642        Err(e) => {
643            return match s
644                .jump_replaced(scope, to, origin, request.dry_run)
645                .map_err(refused)?
646            {
647                Some(steps) => Ok(steps.iter().map(|st| step_info(scope, st)).collect()),
648                None if s.replaced_in(scope).iter().any(|(_, st)| st.id == to) => {
649                    Err(Refusal::new(
650                        RefusalKind::Owner,
651                        "its line left from a step that is replaced too: go to that line first",
652                    ))
653                }
654                None => Err(e),
655            };
656        }
657    };
658    let walked = walked_by(&line, jump);
659    if request.dry_run {
660        let list = if jump.redo {
661            s.redo_steps_in(scope)
662        } else {
663            s.undo_steps_in(scope)
664        };
665        // Every step on the way must be free: try the first held.
666        for st in list.iter().rev().take(jump.count) {
667            if let Some((p, _, _)) = st.changes.iter().find(|(p, _, _)| s.held_by(p).is_some()) {
668                return Err(Refusal::new(
669                    RefusalKind::Held,
670                    format!("`{p}` is held by a gesture in progress"),
671                ));
672            }
673        }
674        // And writable by the origin, as the jump itself checks.
675        let by = origin.writer();
676        for st in list.iter().rev().take(jump.count) {
677            not_writer(s, st, &by)?;
678        }
679        return Ok(walked);
680    }
681    s.jump_in_by(scope, to, origin, &origin.writer())
682        .map_err(refused)?;
683    Ok(walked)
684}
685
686/// The steps a jump walks over, in the order walked.
687fn walked_by(line: &Line, jump: Jump) -> Vec<StepInfo> {
688    let list = if jump.redo { &line.redo } else { &line.undo };
689    list.iter().rev().take(jump.count).cloned().collect()
690}
691
692/// A component's own history, kept in the interface (ADR 0014): the
693/// theme editor's draft, the settings window's values. Registered for a
694/// focus surface with [`Ctx::local_scope`](crate::Ctx::local_scope):
695/// while the focus is in that surface, Ctrl+Z undoes here.
696pub trait LocalScope {
697    /// The scope (its `local` set).
698    fn info(&self) -> ScopeInfo;
699
700    /// Its steps.
701    fn line(&self, app: &AppHandle) -> Line;
702
703    /// Undoes its head: the step undone, `None` when there was none.
704    fn undo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal>;
705
706    /// Redoes its next step.
707    fn redo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal>;
708
709    /// A gesture still going: undo and redo wait for it.
710    fn in_progress(&self, _app: &AppHandle) -> Option<Label> {
711        None
712    }
713}
714
715/// A local scope over one of the value store's histories: what is
716/// written while [`values::enter_history`] names it goes there (the
717/// settings window's form).
718#[derive(Clone, Debug)]
719pub struct StoreScope {
720    info: ScopeInfo,
721}
722
723impl StoreScope {
724    pub fn new(scope: ScopeId, title: &str) -> Self {
725        let mut info = ScopeInfo::new(scope, title);
726        info.local = true;
727        Self { info }
728    }
729
730    fn walk(
731        &self,
732        app: &AppHandle,
733        origin: &Origin,
734        redo: bool,
735    ) -> Result<Option<StepInfo>, Refusal> {
736        let store = app.store();
737        let mut s = lock(&store);
738        if let Some(label) = s.gesture_open(&self.info.id) {
739            return Err(in_progress(label));
740        }
741        let by = origin.writer();
742        let step = if redo {
743            s.redo_in_by(&self.info.id, origin, &by)
744        } else {
745            s.undo_in_by(&self.info.id, origin, &by)
746        }
747        .map_err(refused)?;
748        Ok(step.map(|st| step_info(&self.info.id, &st)))
749    }
750}
751
752impl LocalScope for StoreScope {
753    fn info(&self) -> ScopeInfo {
754        self.info.clone()
755    }
756
757    fn line(&self, app: &AppHandle) -> Line {
758        store_line(&lock(&app.store()), &self.info.id)
759    }
760
761    fn undo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal> {
762        self.walk(app, origin, false)
763    }
764
765    fn redo(&self, app: &AppHandle, origin: &Origin) -> Result<Option<StepInfo>, Refusal> {
766        self.walk(app, origin, true)
767    }
768
769    fn in_progress(&self, app: &AppHandle) -> Option<Label> {
770        lock(&app.store())
771            .gesture_open(&self.info.id)
772            .map(Label::text)
773    }
774}
775
776/// A local scope registered: by whom, for which surface.
777type Registered = (OwnerId, String, Rc<dyn LocalScope>);
778
779/// What the interface keeps: the local scopes, the scopes undone last
780/// (for redo), the revisions published, the clock it gives the store.
781#[derive(Default)]
782pub(crate) struct Kept {
783    locals: RefCell<Vec<Registered>>,
784    undone: RefCell<Vec<ScopeId>>,
785    revs: RefCell<BTreeMap<ScopeId, u64>>,
786    focused: Cell<Option<egui::Id>>,
787    clock: RefCell<Option<ManualClock>>,
788    previewing: RefCell<Option<Previewing>>,
789    routing: Cell<Routing>,
790    /// The histories surfaces declared they work on (`Ctx::history_target`).
791    targets: RefCell<Vec<(OwnerId, String, ScopeId)>>,
792    /// The owner's scope whose surface had the focus last, per window.
793    last_focused: RefCell<Vec<(egui::ViewportId, ScopeId)>>,
794    /// The rule [`target`] picked by last (`focus`, `last_focused`,
795    /// `none`, `newest`).
796    rule: Cell<&'static str>,
797}
798
799/// The point the history panel previews: the owner's answer, the last
800/// pass a row was hovered and the view whose row it is.
801struct Previewing {
802    scope: ScopeId,
803    at: At,
804    answer: Option<Preview>,
805    pass: u64,
806    view: Option<egui::Id>,
807}
808
809/// Registers a local scope for a focus surface (`Ctx::local_scope`).
810pub(crate) fn register(app: &AppHandle, owner: &OwnerId, surface: &str, scope: Rc<dyn LocalScope>) {
811    let kept = app.local::<Kept>();
812    let mut locals = kept.locals.borrow_mut();
813    locals.retain(|(_, s, _)| s != surface);
814    locals.push((owner.clone(), surface.into(), scope));
815}
816
817/// Declares the owner's history a surface works on
818/// (`Ctx::history_target`).
819pub(crate) fn declare_target(app: &AppHandle, owner: &OwnerId, surface: &str, scope: ScopeId) {
820    let kept = app.local::<Kept>();
821    let mut targets = kept.targets.borrow_mut();
822    targets.retain(|(_, s, _)| s != surface);
823    targets.push((owner.clone(), surface.into(), scope));
824}
825
826/// A plugin is gone: its local scopes and the histories its surfaces
827/// declared go.
828pub(crate) fn remove_owner(app: &AppHandle, owner: &OwnerId) {
829    let kept = app.local::<Kept>();
830    kept.locals.borrow_mut().retain(|(o, _, _)| o != owner);
831    kept.targets.borrow_mut().retain(|(o, _, _)| o != owner);
832}
833
834/// Runs `f` on the owner: the host's, else a [`StoreHistory`] over the
835/// host's store. `None` while the host dispatches a command.
836pub fn with_owner<R>(app: &AppHandle, f: impl FnOnce(&mut dyn History) -> R) -> Option<R> {
837    app.with_host_mut(|h| {
838        let store = h.store();
839        match h.history() {
840            Some(owner) => f(owner),
841            None => f(&mut StoreHistory::new(store)),
842        }
843    })
844}
845
846/// Where an undo or a redo goes.
847#[derive(Clone)]
848pub enum Target {
849    /// A component's own history.
850    Local(Rc<dyn LocalScope>),
851    /// One of the owner's scopes.
852    Owner(ScopeId),
853}
854
855impl fmt::Debug for Target {
856    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857        match self {
858            Target::Local(l) => write!(f, "Local({})", l.info().id),
859            Target::Owner(s) => write!(f, "Owner({s})"),
860        }
861    }
862}
863
864impl Target {
865    /// The scope it names.
866    pub fn scope(&self) -> ScopeId {
867        match self {
868            Target::Local(l) => l.info().id,
869            Target::Owner(s) => s.clone(),
870        }
871    }
872
873    /// Its steps now.
874    pub fn line(&self, app: &AppHandle) -> Option<Line> {
875        match self {
876            Target::Local(l) => Some(l.line(app)),
877            Target::Owner(s) => with_owner(app, |h| h.line(s)).flatten(),
878        }
879    }
880}
881
882/// The local scope of the innermost focused surface that has one.
883fn focused_local(app: &AppHandle) -> Option<Rc<dyn LocalScope>> {
884    let chain = focus::chain_names(&app.egui());
885    let kept = app.local::<Kept>();
886    let locals = kept.locals.borrow();
887    chain.iter().rev().find_map(|name| {
888        locals
889            .iter()
890            .find(|(_, s, _)| s == name)
891            .map(|(_, _, l)| l.clone())
892    })
893}
894
895/// Sets how Ctrl+Z picks among the owner's scopes ([`Routing`]).
896pub fn set_routing(app: &AppHandle, routing: Routing) {
897    let kept = app.local::<Kept>();
898    if kept.routing.replace(routing) != routing {
899        kept.last_focused.borrow_mut().clear();
900    }
901}
902
903/// How Ctrl+Z picks among the owner's scopes now.
904pub fn routing(app: &AppHandle) -> Routing {
905    app.local::<Kept>().routing.get()
906}
907
908/// The owner's scope of the innermost focused surface that names one:
909/// the history the surface declared (`Ctx::history_target`), else a
910/// scope listing it among its focus targets. Where [`Routing::Focus`]
911/// sends Ctrl+Z.
912pub fn focused_scope(app: &AppHandle) -> Option<ScopeId> {
913    let chain = focus::chain_names(&app.egui());
914    if chain.is_empty() {
915        return None;
916    }
917    let scopes = with_owner(app, |h| h.scopes()).unwrap_or_default();
918    let kept = app.local::<Kept>();
919    let targets = kept.targets.borrow();
920    let names = crate::app::names_surface;
921    chain.iter().rev().find_map(|name| {
922        targets
923            .iter()
924            .find(|(_, s, id)| names(s, name) && scopes.iter().any(|i| i.id == *id))
925            .map(|(_, _, id)| id.clone())
926            .or_else(|| {
927                scopes
928                    .iter()
929                    .filter(|s| !s.local)
930                    .find(|s| s.focus.iter().any(|f| names(f, name)))
931                    .map(|s| s.id.clone())
932            })
933    })
934}
935
936/// The owner's scope whose surface had the focus last in the window the
937/// user works in (under [`Routing::Focus`]), if any.
938pub fn last_focused(app: &AppHandle) -> Option<ScopeId> {
939    let window = window_of(app);
940    app.local::<Kept>()
941        .last_focused
942        .borrow()
943        .iter()
944        .find(|(w, _)| *w == window)
945        .map(|(_, s)| s.clone())
946}
947
948/// The window a pass is drawing, else the one the user worked in last.
949fn window_of(app: &AppHandle) -> egui::ViewportId {
950    crate::app::pass_in_progress(&app.egui()).map_or_else(|| app.active_window(), |(v, _)| v)
951}
952
953/// Keeps `scope` as the window's scope focused last.
954fn keep_focused(app: &AppHandle, scope: ScopeId) {
955    let window = window_of(app);
956    let kept = app.local::<Kept>();
957    let mut last = kept.last_focused.borrow_mut();
958    last.retain(|(w, _)| *w != window);
959    last.push((window, scope));
960}
961
962/// The names of the surfaces drawn in the last pass.
963fn shown(app: &AppHandle) -> Vec<String> {
964    focus::scopes(&app.egui())
965        .into_iter()
966        .map(|r| r.name)
967        .collect()
968}
969
970/// Whether a scope's focus targets are drawn (a panel's id stands for
971/// its surface, a panel kind's for its instances' too).
972fn is_active(info: &ScopeInfo, shown: &[String]) -> bool {
973    info.focus.is_empty()
974        || info
975            .focus
976            .iter()
977            .any(|f| shown.iter().any(|s| crate::app::names_surface(f, s)))
978}
979
980/// The owner's scopes active in the window, with their heads and next
981/// steps.
982fn active_lines(app: &AppHandle) -> Vec<Line> {
983    let shown = shown(app);
984    with_owner(app, |h| {
985        h.scopes()
986            .iter()
987            .filter(|s| is_active(s, &shown))
988            .filter_map(|s| h.tips(&s.id))
989            .collect()
990    })
991    .unwrap_or_default()
992}
993
994/// The pointer is on a point of a history (a row of rows drawn by the
995/// host): the owner is asked to preview it, once while it stays there;
996/// its answer. The preview ends (the owner told, `None`) at the start of
997/// the second pass no row asks for it: the pointer left. Rows that want
998/// it ended in the pass the pointer leaves use [`hover_in`] and
999/// [`rows_drawn`].
1000pub fn hover(app: &AppHandle, scope: &ScopeId, at: At) -> Option<Preview> {
1001    hovered(app, None, scope, at)
1002}
1003
1004/// [`hover`] from a row of the rows `view` draws: [`rows_drawn`] with
1005/// that view, once they are drawn, ends the preview when none of them
1006/// asked for it in this pass.
1007pub fn hover_in(app: &AppHandle, view: egui::Id, scope: &ScopeId, at: At) -> Option<Preview> {
1008    hovered(app, Some(view), scope, at)
1009}
1010
1011/// The rows `view` draws are drawn for this pass: a preview one of them
1012/// asked for earlier and none asked for now ends here (the pointer
1013/// left), and the window is drawn again with the real state. Nothing
1014/// is asked while the pointer rests on a row: an idle window stays
1015/// idle.
1016pub fn rows_drawn(app: &AppHandle, view: egui::Id) {
1017    let ctx = app.egui();
1018    let left = app
1019        .local::<Kept>()
1020        .previewing
1021        .borrow()
1022        .as_ref()
1023        .is_some_and(|p| p.view == Some(view) && p.pass != ctx.cumulative_pass_nr());
1024    if left {
1025        end_preview(app);
1026        // What was drawn before the rows in this pass showed the preview.
1027        ctx.request_repaint();
1028    }
1029}
1030
1031fn hovered(app: &AppHandle, view: Option<egui::Id>, scope: &ScopeId, at: At) -> Option<Preview> {
1032    let kept = app.local::<Kept>();
1033    let pass = app.egui().cumulative_pass_nr();
1034    if let Some(p) = kept.previewing.borrow_mut().as_mut()
1035        && p.scope == *scope
1036        && p.at == at
1037    {
1038        p.pass = pass;
1039        p.view = view;
1040        return p.answer.clone();
1041    }
1042    let before = kept.previewing.borrow_mut().take();
1043    if let Some(b) = before
1044        && b.scope != *scope
1045    {
1046        preview(app, &b.scope, None);
1047    }
1048    let answer = preview(app, scope, Some(at));
1049    *kept.previewing.borrow_mut() = Some(Previewing {
1050        scope: scope.clone(),
1051        at,
1052        answer: answer.clone(),
1053        pass,
1054        view,
1055    });
1056    answer
1057}
1058
1059/// The point previewed now, if any.
1060pub fn previewing(app: &AppHandle) -> Option<(ScopeId, At)> {
1061    let kept = app.local::<Kept>();
1062    let p = kept.previewing.borrow();
1063    p.as_ref().map(|p| (p.scope.clone(), p.at))
1064}
1065
1066/// Ends the preview now (a click acts on the row: the state shown must
1067/// be the real one first).
1068pub fn end_preview(app: &AppHandle) {
1069    let before = app.local::<Kept>().previewing.borrow_mut().take();
1070    if let Some(b) = before {
1071        preview(app, &b.scope, None);
1072    }
1073}
1074
1075/// The scopes the owner has active in the window now.
1076pub fn active(app: &AppHandle) -> Vec<ScopeId> {
1077    let shown = shown(app);
1078    with_owner(app, |h| {
1079        h.scopes()
1080            .into_iter()
1081            .filter(|s| is_active(s, &shown))
1082            .map(|s| s.id)
1083            .collect()
1084    })
1085    .unwrap_or_default()
1086}
1087
1088/// Where Ctrl+Z (`redo` false) or Ctrl+Shift+Z goes now: the focused
1089/// local scope; while a modal is open, nothing else; else the owner's active scope with the newest head (for
1090/// a redo, the scope last undone that can still redo, else the first
1091/// active one that can). `None`: no history at all.
1092pub fn target(app: &AppHandle, redo: bool) -> Option<Target> {
1093    if let Some(l) = focused_local(app) {
1094        return Some(Target::Local(l));
1095    }
1096    // The keys reach a modal (its own local scope, the settings window),
1097    // never the application's history behind it.
1098    if egui_pop_core::overlay::modal_open(&app.egui()) {
1099        return None;
1100    }
1101    let (picked, rule) = match routing(app) {
1102        Routing::Newest => (by_newest(app, &active_lines(app), redo), "newest"),
1103        Routing::Focus => by_focus(app),
1104    };
1105    app.local::<Kept>().rule.set(rule);
1106    hooked(app, picked, redo, rule)
1107}
1108
1109/// [`Routing::Focus`]: the focused surface's scope, else the one focused
1110/// last in the window while the owner still has it (shown or not), else
1111/// none: never the newest step of another scope, which may be on an
1112/// orthogonal plane (the layout, a plugin's values).
1113fn by_focus(app: &AppHandle) -> (Option<ScopeId>, &'static str) {
1114    if let Some(s) = focused_scope(app) {
1115        keep_focused(app, s.clone());
1116        return (Some(s), "focus");
1117    }
1118    let sticky = last_focused(app)
1119        .filter(|s| with_owner(app, |h| h.scopes().iter().any(|i| i.id == *s)).unwrap_or(false));
1120    match sticky {
1121        Some(s) => (Some(s), "last_focused"),
1122        None => (None, NOTHING_FOCUSED),
1123    }
1124}
1125
1126/// Whether, under [`Routing::Focus`], Ctrl+Z (`redo` false) or
1127/// Ctrl+Shift+Z goes nowhere only because no view was focused yet in the
1128/// window, while some scope of the owner has a step to undo (or redo):
1129/// the keys and the Edit menu stay live to say why
1130/// (`undoNeedsView`, `redoNeedsView`).
1131pub fn needs_view(app: &AppHandle, redo: bool) -> bool {
1132    if routing(app) != Routing::Focus
1133        || focused_local(app).is_some()
1134        || egui_pop_core::overlay::modal_open(&app.egui())
1135        || by_focus(app).1 != NOTHING_FOCUSED
1136    {
1137        return false;
1138    }
1139    with_owner(app, |h| {
1140        h.scopes().iter().any(|s| {
1141            h.tips(&s.id).is_some_and(|l| {
1142                if redo {
1143                    l.next().is_some()
1144                } else {
1145                    l.head().is_some()
1146                }
1147            })
1148        })
1149    })
1150    .unwrap_or(false)
1151}
1152
1153/// Ctrl+Z or Ctrl+Shift+Z found no target because no view was focused
1154/// yet ([`NOTHING_FOCUSED`]): says why on the journal (`history.refused`,
1155/// kind `nothing_focused`), and to a person in a toast and to the screen
1156/// reader.
1157fn say_nothing_focused(app: &AppHandle, redo: bool, origin: &Origin) {
1158    let ctx = app.egui();
1159    let key = if redo {
1160        &crate::strings::HISTORY_NOTHING_FOCUSED_REDO
1161    } else {
1162        &crate::strings::HISTORY_NOTHING_FOCUSED
1163    };
1164    let text = strings::tr(&ctx, key);
1165    // A person pressed the keys (or a controller's button): told on
1166    // screen. An agent reads the journal.
1167    if matches!(origin, Origin::User | Origin::Device(_)) {
1168        if let Some(t) = app.service(&crate::toasts::TOASTS) {
1169            t.notify(crate::toasts::Toast::info(&text));
1170        }
1171        egui_pop_core::a11y::announce(&ctx, text.clone(), egui_pop_core::a11y::Politeness::Polite);
1172    }
1173    app.publish(
1174        &source_of(origin),
1175        None,
1176        "history.refused",
1177        json!({ "scope": Json::Null, "kind": "nothing_focused", "reason": text, "redo": redo }),
1178    );
1179}
1180
1181/// The scope picked, through the [`STEP_TARGET`] step: a before-hook may
1182/// name another one, or none.
1183fn hooked(
1184    app: &AppHandle,
1185    picked: Option<ScopeId>,
1186    redo: bool,
1187    rule: &'static str,
1188) -> Option<Target> {
1189    let args = json!({ "scope": picked, "redo": redo, "rule": rule });
1190    let out = app.step_with(&STEP_TARGET, args, true, |_, args| Ok(args.clone()));
1191    let scope = match out {
1192        Outcome::Done(Ok(v)) => v
1193            .get("scope")
1194            .and_then(Json::as_str)
1195            .and_then(|s| ScopeId::new(s).ok()),
1196        // A veto: nowhere.
1197        Outcome::Vetoed { .. } => None,
1198        Outcome::Done(Err(_)) => picked,
1199    }?;
1200    Some(scope_target(app, &scope).unwrap_or(Target::Owner(scope)))
1201}
1202
1203/// [`Routing::Newest`]: the newest head among the active scopes; for a
1204/// redo, the scope last undone that can still redo, else the first
1205/// active one that can.
1206fn by_newest(app: &AppHandle, lines: &[Line], redo: bool) -> Option<ScopeId> {
1207    if !redo {
1208        return newest(lines)
1209            .cloned()
1210            .or_else(|| lines.first().and_then(scope_of));
1211    }
1212    let undone = app.local::<Kept>().undone.borrow().clone();
1213    let can = |s: &ScopeId| {
1214        lines
1215            .iter()
1216            .any(|l| l.next().is_some_and(|n| n.scope == *s))
1217    };
1218    undone
1219        .iter()
1220        .rev()
1221        .find(|s| can(s))
1222        .cloned()
1223        .or_else(|| lines.iter().find_map(|l| l.next().map(|n| n.scope.clone())))
1224        .or_else(|| lines.first().and_then(scope_of))
1225}
1226
1227fn scope_of(line: &Line) -> Option<ScopeId> {
1228    line.undo
1229        .first()
1230        .or(line.redo.first())
1231        .map(|s| s.scope.clone())
1232}
1233
1234/// The scope named `scope`: a local scope's, else the owner's.
1235pub fn scope_target(app: &AppHandle, scope: &ScopeId) -> Option<Target> {
1236    let kept = app.local::<Kept>();
1237    if let Some(l) = kept
1238        .locals
1239        .borrow()
1240        .iter()
1241        .find(|(_, _, l)| l.info().id == *scope)
1242    {
1243        return Some(Target::Local(l.2.clone()));
1244    }
1245    with_owner(app, |h| h.scopes().iter().any(|s| s.id == *scope))
1246        .unwrap_or(false)
1247        .then(|| Target::Owner(scope.clone()))
1248}
1249
1250/// Every scope: the local ones, then the owner's.
1251pub fn scopes(app: &AppHandle) -> Vec<ScopeInfo> {
1252    let mut out: Vec<ScopeInfo> = app
1253        .local::<Kept>()
1254        .locals
1255        .borrow()
1256        .iter()
1257        .map(|(_, _, l)| l.info())
1258        .collect();
1259    out.extend(with_owner(app, |h| h.scopes()).unwrap_or_default());
1260    out
1261}
1262
1263/// A scope's steps, local or the owner's.
1264pub fn line(app: &AppHandle, scope: &ScopeId) -> Option<Line> {
1265    scope_target(app, scope)?.line(app)
1266}
1267
1268/// Whether Ctrl+Z would undo something now (`canUndo`).
1269pub fn can_undo(app: &AppHandle) -> bool {
1270    head_label(app, false).is_some()
1271}
1272
1273/// Whether Ctrl+Shift+Z would redo something now (`canRedo`).
1274pub fn can_redo(app: &AppHandle) -> bool {
1275    head_label(app, true).is_some()
1276}
1277
1278/// What Ctrl+Z would undo, as the Edit menu names it.
1279pub fn undo_label(app: &AppHandle) -> Option<String> {
1280    head_label(app, false)
1281}
1282
1283/// What Ctrl+Shift+Z would redo.
1284pub fn redo_label(app: &AppHandle) -> Option<String> {
1285    head_label(app, true)
1286}
1287
1288fn head_label(app: &AppHandle, redo: bool) -> Option<String> {
1289    let line = match target(app, redo)? {
1290        Target::Owner(s) => with_owner(app, |h| h.tips(&s)).flatten()?,
1291        t @ Target::Local(_) => t.line(app)?,
1292    };
1293    let step = if redo { line.next() } else { line.head() }?;
1294    Some(label_text(&app.egui(), &step.label))
1295}
1296
1297/// A label in the interface's language: its message when it has one,
1298/// else its text.
1299pub fn label_text(ctx: &egui::Context, label: &Label) -> String {
1300    match &label.key {
1301        Some(key) => {
1302            let args: Vec<(&str, &str)> = label
1303                .args
1304                .iter()
1305                .map(|(k, v)| (k.as_str(), v.as_str()))
1306                .collect();
1307            strings::lookup_args(ctx, key, &label.text, &args)
1308        }
1309        None => label.text.clone(),
1310    }
1311}
1312
1313/// What a walk asks: an undo, a redo, a jump to a step (0: the start),
1314/// a snapshot restored, or one step undone out of order.
1315#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1316pub enum Walk {
1317    Undo,
1318    Redo,
1319    Jump(u64),
1320    /// Back to a snapshot (its id), as a new step.
1321    Restore(u64),
1322    /// One step (its id) undone out of order.
1323    UndoStep(u64),
1324}
1325
1326/// Undoes or redoes (or jumps) in a target, now or as a dry run.
1327fn walk(
1328    app: &AppHandle,
1329    target: &Target,
1330    what: Walk,
1331    request: &Request,
1332    origin: &Origin,
1333) -> Result<Option<Walked>, Refusal> {
1334    match target {
1335        Target::Owner(scope) => {
1336            let mut request = request.clone();
1337            request.scope = scope.clone();
1338            let answer = with_owner(app, |h| {
1339                if let Some(label) = h.in_progress(scope) {
1340                    return Answer::Done(Err(in_progress(&label.text)));
1341                }
1342                match what {
1343                    Walk::Undo => h.undo(&request, origin),
1344                    Walk::Redo => h.redo(&request, origin),
1345                    Walk::Jump(to) => h.jump(&request, to, origin),
1346                    Walk::Restore(id) => h.restore(&request, id, origin),
1347                    Walk::UndoStep(id) => h.undo_step(&request, id, origin),
1348                }
1349            })
1350            .ok_or_else(|| Refusal::new(RefusalKind::Owner, "the host is dispatching a command"))?;
1351            match answer {
1352                Answer::Done(r) => r.map(Some),
1353                Answer::Later(_) => Ok(None),
1354            }
1355        }
1356        Target::Local(l) => {
1357            let info = l.info();
1358            let line = l.line(app);
1359            request.check(line.rev)?;
1360            if let Some(label) = l.in_progress(app) {
1361                return Err(in_progress(&label.text));
1362            }
1363            let (redo, count) = match what {
1364                Walk::Undo => (false, usize::from(line.head().is_some())),
1365                Walk::Redo => (true, usize::from(line.next().is_some())),
1366                Walk::Jump(to) => {
1367                    let j = plan_jump(&line, to)?;
1368                    (j.redo, j.count)
1369                }
1370                Walk::Restore(_) => return Err(unsupported(&info.id, "snapshots")),
1371                Walk::UndoStep(_) => return Err(unsupported(&info.id, "undoing one step")),
1372            };
1373            let mut steps = Vec::new();
1374            if request.dry_run {
1375                steps = walked_by(&line, Jump { redo, count });
1376            } else {
1377                for _ in 0..count {
1378                    let step = if redo {
1379                        l.redo(app, origin)?
1380                    } else {
1381                        l.undo(app, origin)?
1382                    };
1383                    match step {
1384                        Some(s) => steps.push(s),
1385                        None => break,
1386                    }
1387                }
1388            }
1389            let after = l.line(app);
1390            Ok(Some(Walked {
1391                scope: info.id,
1392                steps,
1393                rev: after.rev,
1394                head: after.head_id(),
1395                dry_run: request.dry_run,
1396            }))
1397        }
1398    }
1399}
1400
1401/// Undoes where Ctrl+Z goes ([`target`]), through the `edit.undo` step.
1402pub fn undo(app: &AppHandle, origin: &Origin) -> Outcome {
1403    let t = target(app, false);
1404    if t.is_none() && app.local::<Kept>().rule.get() == NOTHING_FOCUSED {
1405        say_nothing_focused(app, false, origin);
1406    }
1407    run(app, t, Walk::Undo, None, origin)
1408}
1409
1410/// Redoes where Ctrl+Shift+Z goes, through the `edit.redo` step.
1411pub fn redo(app: &AppHandle, origin: &Origin) -> Outcome {
1412    let t = target(app, true);
1413    if t.is_none() && app.local::<Kept>().rule.get() == NOTHING_FOCUSED {
1414        say_nothing_focused(app, true, origin);
1415    }
1416    run(app, t, Walk::Redo, None, origin)
1417}
1418
1419/// Undoes in a named scope, through the `edit.undo` step.
1420pub fn undo_in(app: &AppHandle, scope: &ScopeId, origin: &Origin) -> Outcome {
1421    let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1422    run(app, Some(t), Walk::Undo, None, origin)
1423}
1424
1425/// Redoes in a named scope, through the `edit.redo` step.
1426pub fn redo_in(app: &AppHandle, scope: &ScopeId, origin: &Origin) -> Outcome {
1427    let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1428    run(app, Some(t), Walk::Redo, None, origin)
1429}
1430
1431/// Brings a scope to step `to` (0: the start), through the `edit.jump`
1432/// step.
1433pub fn jump(app: &AppHandle, scope: &ScopeId, to: u64, origin: &Origin) -> Outcome {
1434    let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1435    run(app, Some(t), Walk::Jump(to), None, origin)
1436}
1437
1438/// Brings a scope back to one of its snapshots, as a new step, through
1439/// the `edit.restore` step.
1440pub fn restore(app: &AppHandle, scope: &ScopeId, snapshot: u64, origin: &Origin) -> Outcome {
1441    let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1442    run(app, Some(t), Walk::Restore(snapshot), None, origin)
1443}
1444
1445/// Undoes one step of a scope out of order, through the
1446/// `edit.undo_step` step; the owner may refuse it.
1447pub fn undo_step(app: &AppHandle, scope: &ScopeId, step: u64, origin: &Origin) -> Outcome {
1448    let t = scope_target(app, scope).unwrap_or_else(|| Target::Owner(scope.clone()));
1449    run(app, Some(t), Walk::UndoStep(step), None, origin)
1450}
1451
1452/// What the owner supports in a scope (nothing in a local scope).
1453pub fn features(app: &AppHandle, scope: &ScopeId) -> Features {
1454    match scope_target(app, scope) {
1455        Some(Target::Owner(s)) => with_owner(app, |h| h.features(&s)).unwrap_or_default(),
1456        _ => Features::default(),
1457    }
1458}
1459
1460/// A scope's snapshots, oldest first (none in a local scope).
1461pub fn snapshots(app: &AppHandle, scope: &ScopeId) -> Vec<Snapshot> {
1462    match scope_target(app, scope) {
1463        Some(Target::Owner(s)) => with_owner(app, |h| h.snapshots(&s)).unwrap_or_default(),
1464        _ => Vec::new(),
1465    }
1466}
1467
1468/// A scope's replaced steps, when its owner keeps them.
1469pub fn replaced(app: &AppHandle, scope: &ScopeId) -> Vec<Replaced> {
1470    match scope_target(app, scope) {
1471        Some(Target::Owner(s)) => with_owner(app, |h| h.replaced(&s)).unwrap_or_default(),
1472        _ => Vec::new(),
1473    }
1474}
1475
1476/// Takes a snapshot of a scope (where Undo goes when `scope` is `None`):
1477/// refused unless the scope's revision is still `if_rev`; with
1478/// `dry_run`, the snapshot it would take. Published on the journal as
1479/// `history.snapshot_taken`.
1480pub fn take_snapshot(
1481    app: &AppHandle,
1482    scope: Option<&ScopeId>,
1483    name: &str,
1484    if_rev: Option<u64>,
1485    dry_run: bool,
1486    origin: &Origin,
1487) -> Result<Snapshot, Refusal> {
1488    let scope = owner_scope(app, scope)?;
1489    let request = Request {
1490        scope: scope.clone(),
1491        if_rev,
1492        dry_run,
1493    };
1494    let taken = with_owner(app, |h| h.snapshot(&request, name, origin)).ok_or_else(busy)?;
1495    match &taken {
1496        Ok(snap) if !dry_run => app.publish(
1497            &source_of(origin),
1498            None,
1499            "history.snapshot_taken",
1500            json!({ "scope": scope, "snapshot": snap.id, "name": snap.name }),
1501        ),
1502        Ok(_) => {}
1503        Err(r) => refused_published(app, origin, &scope, r),
1504    }
1505    taken
1506}
1507
1508/// Deletes a snapshot, as [`take_snapshot`] takes one; published as
1509/// `history.snapshot_deleted`.
1510pub fn forget_snapshot(
1511    app: &AppHandle,
1512    scope: Option<&ScopeId>,
1513    snapshot: u64,
1514    if_rev: Option<u64>,
1515    dry_run: bool,
1516    origin: &Origin,
1517) -> Result<(), Refusal> {
1518    let scope = owner_scope(app, scope)?;
1519    let request = Request {
1520        scope: scope.clone(),
1521        if_rev,
1522        dry_run,
1523    };
1524    let done = with_owner(app, |h| h.forget(&request, snapshot)).ok_or_else(busy)?;
1525    match &done {
1526        Ok(()) if !dry_run => app.publish(
1527            &source_of(origin),
1528            None,
1529            "history.snapshot_deleted",
1530            json!({ "scope": scope, "snapshot": snapshot }),
1531        ),
1532        Ok(()) => {}
1533        Err(r) => refused_published(app, origin, &scope, r),
1534    }
1535    done
1536}
1537
1538/// Asks the owner to preview a point of a scope (`None`: the preview
1539/// ends). `None`: no preview.
1540pub fn preview(app: &AppHandle, scope: &ScopeId, at: Option<At>) -> Option<Preview> {
1541    match scope_target(app, scope) {
1542        Some(Target::Owner(s)) => with_owner(app, |h| h.preview(&s, at)).flatten(),
1543        _ => None,
1544    }
1545}
1546
1547/// The owner's scope named, else where Undo goes; a local scope has no
1548/// snapshots.
1549fn owner_scope(app: &AppHandle, scope: Option<&ScopeId>) -> Result<ScopeId, Refusal> {
1550    let t = match scope {
1551        Some(s) => scope_target(app, s).ok_or_else(|| unknown(s))?,
1552        None => {
1553            target(app, false).ok_or_else(|| Refusal::new(RefusalKind::Nothing, "no history"))?
1554        }
1555    };
1556    match t {
1557        Target::Owner(s) => Ok(s),
1558        Target::Local(l) => Err(unsupported(&l.info().id, "snapshots")),
1559    }
1560}
1561
1562fn busy() -> Refusal {
1563    Refusal::new(RefusalKind::Owner, "the host is dispatching a command")
1564}
1565
1566fn refused_published(app: &AppHandle, origin: &Origin, scope: &ScopeId, r: &Refusal) {
1567    app.publish(
1568        &source_of(origin),
1569        None,
1570        "history.refused",
1571        json!({ "scope": scope, "kind": r.kind, "reason": r.reason }),
1572    );
1573}
1574
1575/// An undo, a redo or a jump as an agent asks it (the `history.undo`,
1576/// `history.redo` and `history.jump` commands): in `request.scope`, or
1577/// where the keys go when it is `None`; refused unless the scope's
1578/// revision is still `if_rev`; with `dry_run`, checked and answered,
1579/// nothing changed. It runs through its step like the keys.
1580pub fn ask(
1581    app: &AppHandle,
1582    what: Walk,
1583    scope: Option<&ScopeId>,
1584    if_rev: Option<u64>,
1585    dry_run: bool,
1586    origin: &Origin,
1587) -> Outcome {
1588    let t = match scope {
1589        Some(s) => Some(scope_target(app, s).unwrap_or_else(|| Target::Owner(s.clone()))),
1590        None => target(app, what == Walk::Redo),
1591    };
1592    let request = Request {
1593        scope: t.as_ref().map_or(APP, Target::scope),
1594        if_rev,
1595        dry_run,
1596    };
1597    run(app, t, what, Some(request), origin)
1598}
1599
1600/// Runs a walk through its step: its hooks may veto it, or redirect it
1601/// by naming another `scope` in its arguments.
1602fn run(
1603    app: &AppHandle,
1604    target: Option<Target>,
1605    what: Walk,
1606    asked: Option<Request>,
1607    origin: &Origin,
1608) -> Outcome {
1609    let (if_rev, dry_run) = asked.map_or((None, false), |r| (r.if_rev, r.dry_run));
1610    let (step, key, done, failed) = match what {
1611        Walk::Undo => (&STEP_UNDO, "undone", "edit.undone", "edit.undo_failed"),
1612        Walk::Redo => (&STEP_REDO, "redone", "edit.redone", "edit.redo_failed"),
1613        Walk::Jump(_) => (&STEP_JUMP, "jumped", "edit.jumped", "edit.jump_failed"),
1614        Walk::Restore(_) => (
1615            &STEP_RESTORE,
1616            "restored",
1617            "edit.restored",
1618            "edit.restore_failed",
1619        ),
1620        Walk::UndoStep(_) => (
1621            &STEP_UNDO_STEP,
1622            "undone",
1623            "edit.step_undone",
1624            "edit.undo_step_failed",
1625        ),
1626    };
1627    let ctx = app.egui();
1628    let line = target.as_ref().and_then(|t| t.line(app));
1629    let label = match what {
1630        Walk::Restore(id) => target
1631            .as_ref()
1632            .map(Target::scope)
1633            .and_then(|s| snapshots(app, &s).into_iter().find(|x| x.id == id))
1634            .map(|x| x.name),
1635        _ => line
1636            .as_ref()
1637            .and_then(|l| match what {
1638                Walk::Undo => l.head(),
1639                Walk::Redo => l.next(),
1640                Walk::UndoStep(id) => l.undo.iter().find(|s| s.id == id),
1641                _ => None,
1642            })
1643            .map(|s| label_text(&ctx, &s.label)),
1644    };
1645    let scope = target.as_ref().map(Target::scope);
1646    let mut args = json!({
1647        "label": label,
1648        "origin": source_of(origin),
1649        "scope": scope,
1650    });
1651    match what {
1652        Walk::Jump(to) => args["to"] = json!(to),
1653        Walk::Restore(id) => args["snapshot"] = json!(id),
1654        Walk::UndoStep(id) => args["step"] = json!(id),
1655        Walk::Undo | Walk::Redo => {}
1656    }
1657    if let Some(rev) = if_rev {
1658        args["if_rev"] = json!(rev);
1659    }
1660    if dry_run {
1661        args["dry_run"] = json!(true);
1662    }
1663    let refusal: Rc<RefCell<Option<Refusal>>> = Rc::default();
1664    let walked: Rc<RefCell<Option<Walked>>> = Rc::default();
1665    let (r2, w2) = (refusal.clone(), walked.clone());
1666    let who = origin.clone();
1667    let outcome = app.step(step, args, move |app, args| {
1668        // A before-hook may have named another scope.
1669        let asked = args
1670            .get("scope")
1671            .and_then(Json::as_str)
1672            .and_then(|s| ScopeId::new(s).ok());
1673        let target = match (&asked, target) {
1674            (Some(a), Some(t)) if t.scope() == *a => Some(t),
1675            (Some(a), _) => scope_target(app, a),
1676            (None, t) => t,
1677        };
1678        let Some(target) = target else {
1679            return Ok(json!({ key: Json::Null }));
1680        };
1681        let mut request = Request::new(target.scope());
1682        request.if_rev = if_rev;
1683        request.dry_run = dry_run;
1684        match walk(app, &target, what, &request, &who) {
1685            Ok(Some(w)) => {
1686                let name = w.steps.last().map(|s| label_text(&app.egui(), &s.label));
1687                // The values it left with a change made outside the
1688                // history since (the value store's rule, ADR 0014).
1689                let skipped = lock(&app.store()).take_skipped_in(&w.scope);
1690                let mut out = json!({
1691                    key: name,
1692                    "scope": w.scope,
1693                    "steps": w.steps,
1694                    "rev": w.rev,
1695                    "head": w.head,
1696                });
1697                if w.dry_run {
1698                    out["dry_run"] = json!(true);
1699                }
1700                if !skipped.is_empty() {
1701                    out["skipped"] = json!(skipped);
1702                }
1703                *w2.borrow_mut() = Some(w);
1704                Ok(out)
1705            }
1706            Ok(None) => Ok(json!({ key: Json::Null, "scope": target.scope(), "pending": true })),
1707            Err(r) => {
1708                let reason = r.reason.clone();
1709                *r2.borrow_mut() = Some(r);
1710                Err(reason)
1711            }
1712        }
1713    });
1714    let source = source_of(origin);
1715    let skipped: Vec<String> = match &outcome {
1716        Outcome::Done(Ok(v)) => serde_json::from_value(v["skipped"].clone()).unwrap_or_default(),
1717        _ => Vec::new(),
1718    };
1719    match &outcome {
1720        Outcome::Done(Ok(v)) => {
1721            if !v[key].is_null() && !dry_run {
1722                app.publish(
1723                    &source,
1724                    None,
1725                    done,
1726                    json!({ "label": v[key], "scope": v["scope"] }),
1727                );
1728            }
1729        }
1730        Outcome::Done(Err(e)) => {
1731            app.publish(&source, None, failed, json!({ "label": label, "error": e }));
1732        }
1733        Outcome::Vetoed { by, reason } => {
1734            app.publish(
1735                &source,
1736                None,
1737                failed,
1738                json!({ "label": label, "vetoed_by": by, "reason": reason }),
1739            );
1740            *refusal.borrow_mut() = Some(Refusal::new(RefusalKind::Vetoed, reason.clone()));
1741        }
1742    }
1743    if let Some(r) = refusal.borrow_mut().take() {
1744        app.publish(
1745            &source,
1746            None,
1747            "history.refused",
1748            json!({ "scope": scope, "kind": r.kind, "reason": r.reason }),
1749        );
1750    }
1751    if let Some(w) = walked.borrow_mut().take()
1752        && !w.dry_run
1753        && !w.steps.is_empty()
1754    {
1755        let kept = app.local::<Kept>();
1756        {
1757            let mut undone = kept.undone.borrow_mut();
1758            undone.retain(|s| *s != w.scope);
1759            if matches!(what, Walk::Undo | Walk::Jump(_)) {
1760                undone.push(w.scope.clone());
1761            }
1762        }
1763        kept.revs.borrow_mut().insert(w.scope.clone(), w.rev);
1764        changed(app, &w.scope, w.rev, w.head, &skipped);
1765    }
1766    outcome
1767}
1768
1769/// `history.changed`: the scope, its revision and head, and the values
1770/// the move left with a change made outside the history (`skipped`,
1771/// only when there are some).
1772fn changed(app: &AppHandle, scope: &ScopeId, rev: u64, head: u64, skipped: &[String]) {
1773    let mut data = json!({ "scope": scope, "rev": rev, "head": head });
1774    if !skipped.is_empty() {
1775        data["skipped"] = json!(skipped);
1776    }
1777    app.publish("egui_pop", None, "history.changed", data);
1778}
1779
1780/// Each pass: the store's clock moved to the interface's time, merging
1781/// sealed when the focus moved, and `history.changed` for the owner's
1782/// scopes whose revision moved since last published.
1783pub(crate) fn pass(app: &AppHandle) {
1784    let ctx = app.egui();
1785    let kept = app.local::<Kept>();
1786    let store = app.store();
1787    {
1788        let mut clock = kept.clock.borrow_mut();
1789        let mut s = lock(&store);
1790        if clock.is_none() && !s.has_clock() {
1791            let c = ManualClock::default();
1792            s.set_clock(Some(c.shared()));
1793            *clock = Some(c);
1794        }
1795        if let Some(c) = clock.as_ref() {
1796            c.set(ctx.input(|i| i.time));
1797        }
1798        let focused = focus::focused(&ctx);
1799        if kept.focused.replace(focused) != focused {
1800            s.seal();
1801        }
1802    }
1803    // The scope focused last, kept per window while the focus goes where
1804    // no scope is named (the menu bar, an empty spot): Ctrl+Z there still
1805    // goes to it.
1806    if kept.routing.get() == Routing::Focus
1807        && let Some(s) = focused_scope(app)
1808    {
1809        keep_focused(app, s);
1810    }
1811    // Values a group cancelled since left with an outside change.
1812    let mut skipped: BTreeMap<ScopeId, Vec<String>> = BTreeMap::new();
1813    for s in lock(&store).take_skipped() {
1814        skipped.entry(s.history).or_default().push(s.path);
1815    }
1816    let moved: Vec<(ScopeId, u64, u64)> = {
1817        let revs = kept.revs.borrow();
1818        with_owner(app, |h| {
1819            h.scopes()
1820                .into_iter()
1821                .filter_map(|s| {
1822                    let rev = h.rev(&s.id);
1823                    (revs.get(&s.id).copied().unwrap_or(0) != rev || skipped.contains_key(&s.id))
1824                        .then(|| (s.id.clone(), rev, h.line(&s.id).map_or(0, |l| l.head_id())))
1825                })
1826                .collect()
1827        })
1828        .unwrap_or_default()
1829    };
1830    for (id, rev, head) in moved {
1831        kept.revs.borrow_mut().insert(id.clone(), rev);
1832        let paths = skipped.remove(&id).unwrap_or_default();
1833        changed(app, &id, rev, head, &paths);
1834    }
1835    // The store's other histories (a local scope's, such as the
1836    // settings window's) say it too.
1837    for (id, paths) in skipped {
1838        let (rev, head) = {
1839            let s = lock(&store);
1840            (s.history_rev(&id), store_line(&s, &id).head_id())
1841        };
1842        changed(app, &id, rev, head, &paths);
1843    }
1844    // A preview no row asked for in the whole last pass: the rows that
1845    // asked are no longer drawn (or never say when they are, see
1846    // `rows_drawn`). No repaint is asked for here: a pointer resting on
1847    // a row must let the window idle, and a pointer moving away draws
1848    // the window again anyway.
1849    let stale = kept
1850        .previewing
1851        .borrow()
1852        .as_ref()
1853        .is_some_and(|p| p.pass + 1 < ctx.cumulative_pass_nr());
1854    if stale {
1855        end_preview(app);
1856    }
1857}
1858
1859/// The `history` collector's snapshot: the scopes, which is active,
1860/// where Ctrl+Z and Ctrl+Shift+Z go and what they would do.
1861pub(crate) fn snapshot(app: &AppHandle) -> Json {
1862    let active = active(app);
1863    let scopes: Vec<Json> = scopes(app)
1864        .into_iter()
1865        .map(|s| {
1866            let l = line(app, &s.id).unwrap_or_default();
1867            json!({
1868                "scope": s,
1869                "active": s.local || active.contains(&s.id),
1870                "rev": l.rev,
1871                "head": l.head_id(),
1872                "undo": l.undo.len(),
1873                "redo": l.redo.len(),
1874            })
1875        })
1876        .collect();
1877    json!({
1878        "can_undo": can_undo(app),
1879        "undo": undo_label(app),
1880        "undo_scope": target(app, false).map(|t| t.scope()),
1881        "can_redo": can_redo(app),
1882        "redo": redo_label(app),
1883        "redo_scope": target(app, true).map(|t| t.scope()),
1884        "routing": routing(app),
1885        "last_focused": last_focused(app),
1886        "scopes": scopes,
1887    })
1888}