Skip to main content

egui_pop_model/
history.rs

1//! Undo histories, as the interface sees them (ADR 0014): the pure parts
2//! of the `History` contract.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! - A **scope** ([`ScopeId`], described by [`ScopeInfo`]) is one
8//!   history: a document's edit, a collection's marks, the application's
9//!   values, the settings window. Steps never cross scopes.
10//! - A **step** says what it is, not how to undo it ([`StepInfo`]): its
11//!   id, scope, [`Label`], origin, group, the place of the context stack
12//!   it was made in, its time and whether it is still in progress. The
13//!   inverse stays with the owner.
14//! - A scope's steps are a [`Line`]: what an undo walks back (oldest
15//!   first) and what a redo makes again (the next one last), with the
16//!   scope's revision. Redo is linear: a new step drops the redo list.
17//! - **Merging** ([`merges`]): repeats on one target (held arrows, wheel
18//!   notches, a colour picker's frames) carry the same merge key and are
19//!   one step while they come less than [`MERGE_WINDOW`] apart, from the
20//!   same origin, the focus unchanged.
21//! - **Routing** ([`newest`]): Ctrl+Z, outside a text field and a
22//!   focused local scope, undoes the newest step among the scopes active
23//!   in the window, unless the application routes by focus (the API
24//!   crate's `history::Routing`).
25//! - A **jump** ([`plan_jump`]) is a run of undos or redos to a step.
26//! - Beyond them, as an owner supports them ([`Features`]): a
27//!   [`Snapshot`] (a named state pinned in a scope), a [`Preview`] of a
28//!   point ([`At`]) the pointer is on, the steps a new step dropped from
29//!   the redo list ([`Replaced`]), and one step undone out of order,
30//!   unless a later step shares a target ([`may_undo_out_of_order`]).
31//!
32//! ```
33//! use egui_pop_model::commands::Origin;
34//! use egui_pop_model::history::{Label, Line, MergeMark, ScopeId, StepInfo, merges, plan_jump};
35//!
36//! let a = MergeMark::new("view/zoom", Origin::User, 10.0);
37//! assert!(merges(&a, &MergeMark::new("view/zoom", Origin::User, 10.4)));
38//! assert!(!merges(&a, &MergeMark::new("view/zoom", Origin::User, 11.5)));
39//!
40//! let step = |id| StepInfo::new(id, ScopeId::from_static("app"), Label::text("Zoom"), Origin::User);
41//! let line = Line { undo: vec![step(1), step(2)], redo: vec![step(3)], rev: 4 };
42//! let jump = plan_jump(&line, 3).unwrap();
43//! assert_eq!((jump.redo, jump.count), (true, 1));
44//! ```
45
46use std::collections::BTreeMap;
47use std::fmt;
48
49use serde::{Deserialize, Serialize};
50
51use crate::commands::Origin;
52use crate::context::Entry;
53pub use crate::ids::ScopeId;
54
55/// The application's own history: the value store's steps.
56pub const APP: ScopeId = ScopeId::from_static("app");
57
58/// The settings window's history: the values written from its form.
59pub const SETTINGS: ScopeId = ScopeId::from_static("settings");
60
61/// How many steps a scope keeps by default, the oldest dropped first.
62pub const CAP: usize = 500;
63
64/// How far apart, in seconds, two repeats on one target may come and
65/// still be one step.
66pub const MERGE_WINDOW: f64 = 1.0;
67
68/// What a step is called: a message id and its arguments, rendered in the
69/// interface's language when shown, with its English text for an
70/// interface that does not know the message ("Exposure +0.30 EV").
71#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
72pub struct Label {
73    /// The text in English (or as the owner wrote it).
74    pub text: String,
75    /// The message id, when the label is translated.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub key: Option<String>,
78    /// The message's arguments.
79    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
80    pub args: BTreeMap<String, String>,
81}
82
83impl Label {
84    /// A label without a message id.
85    pub fn text(text: impl Into<String>) -> Self {
86        Self {
87            text: text.into(),
88            ..Self::default()
89        }
90    }
91
92    /// A label from a message id, its English text and its arguments
93    /// (`{ $name }` in the text is filled from them). The arguments are
94    /// text, shown as they are written ("+0.30", a name like "2026"):
95    /// a number is written by the caller.
96    pub fn message(key: &str, english: &str, args: &[(&str, &str)]) -> Self {
97        let args: BTreeMap<String, String> = args
98            .iter()
99            .map(|(k, v)| (k.to_string(), v.to_string()))
100            .collect();
101        let mut text = english.to_string();
102        for (k, v) in &args {
103            text = text.replace(&format!("{{ ${k} }}"), v);
104        }
105        Self {
106            text,
107            key: Some(key.into()),
108            args,
109        }
110    }
111}
112
113impl fmt::Display for Label {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(&self.text)
116    }
117}
118
119/// One step of a history, as the interface sees it.
120#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
121pub struct StepInfo {
122    /// Unique within its owner; never 0 (0 is "before the first step").
123    pub id: u64,
124    pub scope: ScopeId,
125    pub label: Label,
126    pub origin: Origin,
127    /// The group (an import, an agent's request) it was made under.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub group: Option<u64>,
130    /// The place of the context stack it was made in (ADR 0012), root
131    /// first; empty at the root or when the owner does not know.
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub place: Vec<Entry>,
134    /// When it was made, in seconds of the owner's clock.
135    #[serde(default)]
136    pub at: f64,
137    /// A gesture still going: not undoable yet.
138    #[serde(default)]
139    pub in_progress: bool,
140}
141
142impl StepInfo {
143    /// A step made now (`at` 0), at the root, in no group.
144    pub fn new(id: u64, scope: ScopeId, label: Label, origin: Origin) -> Self {
145        Self {
146            id,
147            scope,
148            label,
149            origin,
150            group: None,
151            place: Vec::new(),
152            at: 0.0,
153            in_progress: false,
154        }
155    }
156}
157
158/// A history, described.
159#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
160pub struct ScopeInfo {
161    pub id: ScopeId,
162    /// Its title, as the history panel shows it.
163    pub title: String,
164    /// The focus surfaces and panels that show it: while one of them is
165    /// drawn, the scope is active in the window. Empty: always active.
166    #[serde(default, skip_serializing_if = "Vec::is_empty")]
167    pub focus: Vec<String>,
168    /// Whether it survives a restart.
169    #[serde(default)]
170    pub durable: bool,
171    /// How many steps it keeps in memory.
172    pub cap: usize,
173    /// A component's own history, kept by the interface (the theme
174    /// editor's draft), not the owner's.
175    #[serde(default)]
176    pub local: bool,
177}
178
179impl ScopeInfo {
180    /// An owner's scope, always active, kept for the session.
181    pub fn new(id: ScopeId, title: &str) -> Self {
182        Self {
183            id,
184            title: title.into(),
185            focus: Vec::new(),
186            durable: false,
187            cap: CAP,
188            local: false,
189        }
190    }
191
192    /// Whether it is active, the surfaces and panels `shown` being drawn.
193    pub fn active<S: AsRef<str>>(&self, shown: &[S]) -> bool {
194        self.focus.is_empty()
195            || self
196                .focus
197                .iter()
198                .any(|f| shown.iter().any(|s| s.as_ref() == f))
199    }
200}
201
202/// A scope's steps.
203#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
204pub struct Line {
205    /// What an undo walks back, oldest first.
206    pub undo: Vec<StepInfo>,
207    /// What a redo makes again, the next one last.
208    pub redo: Vec<StepInfo>,
209    /// Moves on with every change of either list.
210    pub rev: u64,
211}
212
213impl Line {
214    /// The step an undo would take back.
215    pub fn head(&self) -> Option<&StepInfo> {
216        self.undo.last()
217    }
218
219    /// The step a redo would make again.
220    pub fn next(&self) -> Option<&StepInfo> {
221        self.redo.last()
222    }
223
224    /// The head's id (0: nothing done).
225    pub fn head_id(&self) -> u64 {
226        self.head().map_or(0, |s| s.id)
227    }
228}
229
230/// An undo, a redo or a jump asked of a scope.
231#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
232pub struct Request {
233    pub scope: ScopeId,
234    /// Refused unless the scope's revision is still this one.
235    #[serde(default, skip_serializing_if = "Option::is_none")]
236    pub if_rev: Option<u64>,
237    /// Checked, answered, but nothing is changed.
238    #[serde(default)]
239    pub dry_run: bool,
240}
241
242impl Request {
243    pub fn new(scope: ScopeId) -> Self {
244        Self {
245            scope,
246            if_rev: None,
247            dry_run: false,
248        }
249    }
250
251    pub fn if_rev(mut self, rev: u64) -> Self {
252        self.if_rev = Some(rev);
253        self
254    }
255
256    pub fn dry_run(mut self) -> Self {
257        self.dry_run = true;
258        self
259    }
260
261    /// Refused when the scope moved since `if_rev`.
262    pub fn check(&self, rev: u64) -> Result<(), Refusal> {
263        match self.if_rev {
264            Some(r) if r != rev => Err(Refusal::new(
265                RefusalKind::Stale,
266                format!("the history moved on (revision {rev}, not {r})"),
267            )),
268            _ => Ok(()),
269        }
270    }
271}
272
273/// Why an undo, a redo or a jump was refused.
274#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(rename_all = "snake_case")]
276pub enum RefusalKind {
277    /// Nothing to undo, redo, or no such step.
278    Nothing,
279    /// No such scope.
280    Unknown,
281    /// `if_rev` no longer holds.
282    Stale,
283    /// A gesture in progress holds what it would change.
284    Held,
285    /// A hook of the interface vetoed it.
286    Vetoed,
287    /// The owner's own reason (another process, a later step on the
288    /// same target).
289    Owner,
290    /// The owner does not support the request (snapshots, undoing one
291    /// step out of order).
292    Unsupported,
293}
294
295/// A refusal, with its reason as the interface shows it.
296#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
297pub struct Refusal {
298    pub kind: RefusalKind,
299    pub reason: String,
300}
301
302impl Refusal {
303    pub fn new(kind: RefusalKind, reason: impl Into<String>) -> Self {
304        Self {
305            kind,
306            reason: reason.into(),
307        }
308    }
309}
310
311impl fmt::Display for Refusal {
312    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313        f.write_str(&self.reason)
314    }
315}
316
317impl std::error::Error for Refusal {}
318
319/// A named state pinned in a scope (ADR 0014): taken by the user or an
320/// agent, never dropped by the cap, restored as a new step.
321#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
322pub struct Snapshot {
323    /// Unique within its owner; never 0.
324    pub id: u64,
325    pub scope: ScopeId,
326    pub name: String,
327    /// The scope's head when it was taken (0: the start).
328    pub step: u64,
329    /// Who took it.
330    pub origin: Origin,
331    /// When it was taken, in seconds of the owner's clock.
332    #[serde(default)]
333    pub at: f64,
334    /// Not kept yet: an owner that keeps a snapshot only once its state
335    /// is saved (at its next save) says so until then; it is lost if the
336    /// application quits first. The history panel marks it.
337    #[serde(default)]
338    pub pending: bool,
339}
340
341/// A step a new step dropped from the redo list, kept by an owner whose
342/// history keeps every state (ADR 0014): the history panel shows it as a
343/// "replaced" row behind a toggle, and a jump reaches it.
344#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
345pub struct Replaced {
346    pub step: StepInfo,
347    /// The step it came after (0: the start): where its line left the
348    /// current one.
349    pub after: u64,
350}
351
352/// A point of a history the panel previews: a step (0: the start, a
353/// replaced step included) or a snapshot.
354#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
356pub enum At {
357    Step(u64),
358    Snapshot(u64),
359}
360
361/// What the owner answers a hover on the history panel: it may show the
362/// state there itself (`shown`: in its own views, the image as it was),
363/// and say what differs from now, which the panel shows beside the row.
364/// Nothing is committed: the hover ending cancels it.
365#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
366pub struct Preview {
367    /// The owner shows the state in its own views.
368    #[serde(default)]
369    pub shown: bool,
370    /// What differs from now, as the panel lists it.
371    #[serde(default, skip_serializing_if = "Vec::is_empty")]
372    pub changes: Vec<PreviewChange>,
373}
374
375/// One thing a preview says differs.
376#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
377pub struct PreviewChange {
378    /// What it is ("Exposure").
379    pub what: String,
380    /// Its value at the point previewed.
381    pub then: String,
382    /// Its value now.
383    pub now: String,
384}
385
386/// What an owner supports beyond undo, redo and jump, per scope; the
387/// history panel offers only these.
388#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
389#[non_exhaustive]
390pub struct Features {
391    /// Snapshots: taken, restored, deleted.
392    pub snapshots: bool,
393    /// Undoing one step out of order ("Undo this step").
394    pub undo_step: bool,
395}
396
397impl Features {
398    /// Everything.
399    pub fn all() -> Self {
400        Self {
401            snapshots: true,
402            undo_step: true,
403        }
404    }
405}
406
407/// Whether undoing `step` out of order is allowed (VS Code's rule): no
408/// later step of `undo` (oldest first) changed one of the same `targets`.
409/// `targets_of` names what a step changes. `Err`: the later step in the
410/// way, and the target it shares.
411pub fn may_undo_out_of_order<'a, T: PartialEq + 'a, S>(
412    undo: &'a [S],
413    step: usize,
414    targets_of: impl Fn(&'a S) -> Vec<&'a T>,
415) -> Result<(), (usize, &'a T)> {
416    let Some(s) = undo.get(step) else {
417        return Ok(());
418    };
419    let mine = targets_of(s);
420    for (i, later) in undo.iter().enumerate().skip(step + 1) {
421        if let Some(t) = targets_of(later).into_iter().find(|t| mine.contains(t)) {
422            return Err((i, t));
423        }
424    }
425    Ok(())
426}
427
428/// What a step carries to be merged with the next: its merge key (the
429/// target path, or the component's own key), origin and time.
430#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
431pub struct MergeMark {
432    pub key: String,
433    pub origin: Origin,
434    pub at: f64,
435}
436
437impl MergeMark {
438    pub fn new(key: &str, origin: Origin, at: f64) -> Self {
439        Self {
440            key: key.into(),
441            origin,
442            at,
443        }
444    }
445}
446
447/// Whether `next` joins the step that ended with `prev`: the same key and
448/// origin, less than [`MERGE_WINDOW`] later. The owner also stops merging
449/// when the focus leaves, after an undo or a redo, and across groups.
450pub fn merges(prev: &MergeMark, next: &MergeMark) -> bool {
451    let gap = next.at - prev.at;
452    prev.key == next.key && prev.origin == next.origin && (0.0..MERGE_WINDOW).contains(&gap)
453}
454
455/// The scope Ctrl+Z undoes among `lines` (the active scopes): the one
456/// whose head is newest, by time then by id; a later scope wins a tie.
457/// `None`: nothing to undo in any of them.
458pub fn newest<'a>(lines: impl IntoIterator<Item = &'a Line>) -> Option<&'a ScopeId> {
459    lines
460        .into_iter()
461        .filter_map(Line::head)
462        .filter(|s| !s.in_progress)
463        .fold(None::<&StepInfo>, |best, s| match best {
464            Some(b) if (b.at, b.id) > (s.at, s.id) => Some(b),
465            _ => Some(s),
466        })
467        .map(|s| &s.scope)
468}
469
470/// A jump, as undos or redos.
471#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
472pub struct Jump {
473    /// Redos (the step is ahead), else undos.
474    pub redo: bool,
475    /// How many (0: already there).
476    pub count: usize,
477}
478
479/// How to bring a scope to step `to`: after it, `to` is the head (0: the
480/// start, everything undone).
481pub fn plan_jump(line: &Line, to: u64) -> Result<Jump, Refusal> {
482    if to == 0 {
483        return Ok(Jump {
484            redo: false,
485            count: line.undo.len(),
486        });
487    }
488    if let Some(i) = line.undo.iter().position(|s| s.id == to) {
489        return Ok(Jump {
490            redo: false,
491            count: line.undo.len() - 1 - i,
492        });
493    }
494    if let Some(i) = line.redo.iter().position(|s| s.id == to) {
495        return Ok(Jump {
496            redo: true,
497            count: line.redo.len() - i,
498        });
499    }
500    Err(Refusal::new(
501        RefusalKind::Nothing,
502        format!("no step {to} in `{}`", scope_of(line)),
503    ))
504}
505
506fn scope_of(line: &Line) -> String {
507    line.undo
508        .first()
509        .or(line.redo.first())
510        .map_or_else(String::new, |s| s.scope.to_string())
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    #[test]
518    fn a_snapshot_from_an_older_owner_is_not_pending() {
519        let mut snap = Snapshot {
520            id: 1,
521            scope: ScopeId::from_static("app"),
522            name: "Before".into(),
523            step: 2,
524            origin: crate::commands::Origin::User,
525            at: 0.0,
526            pending: true,
527        };
528        let back: Snapshot = serde_json::from_value(serde_json::to_value(&snap).unwrap()).unwrap();
529        assert_eq!(back, snap);
530        // Written before the flag: not pending.
531        let mut old = serde_json::to_value(&snap).unwrap();
532        old.as_object_mut().unwrap().remove("pending");
533        snap.pending = false;
534        assert_eq!(serde_json::from_value::<Snapshot>(old).unwrap(), snap);
535    }
536
537    fn step(id: u64, scope: &'static str, at: f64) -> StepInfo {
538        let mut s = StepInfo::new(
539            id,
540            ScopeId::from_static(scope),
541            Label::text("x"),
542            Origin::User,
543        );
544        s.at = at;
545        s
546    }
547
548    #[test]
549    fn repeats_merge_within_the_window_on_one_key_and_origin() {
550        let a = MergeMark::new("k", Origin::User, 5.0);
551        assert!(merges(&a, &MergeMark::new("k", Origin::User, 5.99)));
552        assert!(!merges(&a, &MergeMark::new("k", Origin::User, 6.0)));
553        assert!(!merges(&a, &MergeMark::new("other", Origin::User, 5.1)));
554        assert!(!merges(
555            &a,
556            &MergeMark::new("k", Origin::Agent("a".into()), 5.1)
557        ));
558        // A clock going back never merges.
559        assert!(!merges(&a, &MergeMark::new("k", Origin::User, 4.0)));
560    }
561
562    #[test]
563    fn the_newest_head_among_active_scopes_wins() {
564        let a = Line {
565            undo: vec![step(1, "a", 1.0), step(4, "a", 3.0)],
566            ..Line::default()
567        };
568        let b = Line {
569            undo: vec![step(2, "b", 2.0)],
570            ..Line::default()
571        };
572        assert_eq!(newest([&a, &b]).unwrap().as_str(), "a");
573        let c = Line {
574            undo: vec![step(5, "c", 3.0)],
575            ..Line::default()
576        };
577        // Same time: the higher id.
578        assert_eq!(newest([&a, &b, &c]).unwrap().as_str(), "c");
579        // A gesture in progress is not undoable.
580        let mut d = step(9, "d", 9.0);
581        d.in_progress = true;
582        let d = Line {
583            undo: vec![d],
584            ..Line::default()
585        };
586        assert_eq!(newest([&a, &d]).unwrap().as_str(), "a");
587        assert_eq!(newest([&Line::default()]), None);
588    }
589
590    #[test]
591    fn a_jump_is_undos_or_redos_to_the_step() {
592        let line = Line {
593            undo: vec![step(1, "a", 0.0), step(2, "a", 0.0), step(3, "a", 0.0)],
594            redo: vec![step(5, "a", 0.0), step(4, "a", 0.0)],
595            rev: 7,
596        };
597        assert_eq!(
598            plan_jump(&line, 3).unwrap(),
599            Jump {
600                redo: false,
601                count: 0
602            }
603        );
604        assert_eq!(
605            plan_jump(&line, 1).unwrap(),
606            Jump {
607                redo: false,
608                count: 2
609            }
610        );
611        assert_eq!(
612            plan_jump(&line, 0).unwrap(),
613            Jump {
614                redo: false,
615                count: 3
616            }
617        );
618        assert_eq!(
619            plan_jump(&line, 4).unwrap(),
620            Jump {
621                redo: true,
622                count: 1
623            }
624        );
625        assert_eq!(
626            plan_jump(&line, 5).unwrap(),
627            Jump {
628                redo: true,
629                count: 2
630            }
631        );
632        assert_eq!(plan_jump(&line, 9).unwrap_err().kind, RefusalKind::Nothing);
633    }
634
635    #[test]
636    fn a_request_holds_while_the_revision_does() {
637        let r = Request::new(APP).if_rev(3);
638        assert!(r.check(3).is_ok());
639        assert_eq!(r.check(4).unwrap_err().kind, RefusalKind::Stale);
640        assert!(Request::new(APP).check(9).is_ok());
641    }
642
643    #[test]
644    fn a_label_fills_its_arguments_and_keeps_its_message() {
645        let l = Label::message("exposure", "Exposure { $ev } EV", &[("ev", "+0.30")]);
646        assert_eq!(l.text, "Exposure +0.30 EV");
647        assert_eq!(l.key.as_deref(), Some("exposure"));
648        let json = serde_json::to_value(&l).unwrap();
649        assert_eq!(json["args"]["ev"], "+0.30");
650        assert_eq!(
651            serde_json::to_value(Label::text("x")).unwrap(),
652            serde_json::json!({ "text": "x" })
653        );
654    }
655
656    #[test]
657    fn one_step_is_undone_out_of_order_unless_a_later_one_shares_a_target() {
658        fn targets<'a>(s: &'a [&'static str; 2]) -> Vec<&'a &'static str> {
659            s.iter().filter(|t| !t.is_empty()).collect()
660        }
661        let steps = [["a", ""], ["b", ""], ["a", "c"]];
662        assert_eq!(may_undo_out_of_order(&steps, 0, targets), Err((2, &"a")));
663        assert_eq!(may_undo_out_of_order(&steps, 1, targets), Ok(()));
664        assert_eq!(may_undo_out_of_order(&steps, 2, targets), Ok(()));
665    }
666
667    #[test]
668    fn a_scope_is_active_while_one_of_its_targets_is_shown() {
669        let mut s = ScopeInfo::new(APP, "Application");
670        assert!(s.active::<&str>(&[]));
671        s.focus = vec!["viewer".into()];
672        assert!(!s.active(&["library"]));
673        assert!(s.active(&["library", "viewer"]));
674    }
675}