Skip to main content

egui_pop_model/values/
points.rs

1//! The store's histories beyond undo, redo and jump (ADR 0014): the
2//! snapshots pinned in a history, the redo lists new steps dropped
3//! (replaced lines, reachable by a jump), undoing one step out of order,
4//! and the values at a point, for a preview.
5
6use std::collections::BTreeMap;
7
8use super::{Origin, Refused, Step, Store, Value};
9use crate::history::{At, Refusal, RefusalKind, ScopeId, Snapshot, may_undo_out_of_order};
10
11/// A redo list a new step dropped.
12#[derive(Clone, Debug)]
13pub(super) struct Branch {
14    /// The step it came after (0: the start).
15    pub(super) after: u64,
16    /// Its steps, oldest first.
17    pub(super) steps: Vec<Step>,
18}
19
20/// A snapshot, with the values it pins.
21#[derive(Clone, Debug)]
22pub(super) struct Snap {
23    pub(super) info: Snapshot,
24    /// Each path the history touched, with its value when the snapshot
25    /// was taken; a path first changed later is added by that step.
26    pub(super) values: BTreeMap<String, Value>,
27}
28
29fn paths_of(s: &Step) -> Vec<&String> {
30    s.changes.iter().map(|(p, _, _)| p).collect()
31}
32
33fn held(r: Refused) -> Refusal {
34    let kind = match r {
35        Refused::Held { .. } => RefusalKind::Held,
36        _ => RefusalKind::Owner,
37    };
38    Refusal::new(kind, r.to_string())
39}
40
41impl Store {
42    fn no_gesture(&self, history: &ScopeId) -> Result<(), Refusal> {
43        match self.gesture_open(history) {
44            Some(label) => Err(Refusal::new(
45                RefusalKind::Held,
46                format!("“{label}” is in progress"),
47            )),
48            None => Ok(()),
49        }
50    }
51
52    /// A history's snapshots, oldest first.
53    ///
54    /// <div class="warning">Experimental: may change in any release
55    /// (docs/stability.md).</div>
56    pub fn snapshots_in(&self, history: &ScopeId) -> Vec<Snapshot> {
57        self.histories
58            .get(history)
59            .map(|h| h.snapshots.iter().map(|s| s.info.clone()).collect())
60            .unwrap_or_default()
61    }
62
63    /// Pins the history's current state under `name`: the value of every
64    /// path its steps touched. Never dropped by the cap. With `dry_run`,
65    /// the snapshot it would take (id 0), nothing kept.
66    ///
67    /// <div class="warning">Experimental: may change in any release
68    /// (docs/stability.md).</div>
69    pub fn take_snapshot(
70        &mut self,
71        history: &ScopeId,
72        name: &str,
73        origin: &Origin,
74        dry_run: bool,
75    ) -> Result<Snapshot, Refusal> {
76        self.no_gesture(history)?;
77        let name = name.trim();
78        if name.is_empty() {
79            return Err(Refusal::new(RefusalKind::Owner, "a snapshot needs a name"));
80        }
81        let h = self.histories.get(history);
82        let step = h.and_then(|h| h.undo.last()).map_or(0, |s| s.id);
83        let mut info = Snapshot {
84            id: 0,
85            scope: history.clone(),
86            name: name.into(),
87            step,
88            origin: origin.clone(),
89            at: self.now(),
90            pending: false,
91        };
92        if dry_run {
93            return Ok(info);
94        }
95        let mut values = BTreeMap::new();
96        if let Some(h) = h {
97            let all = h
98                .undo
99                .iter()
100                .chain(&h.redo)
101                .chain(h.replaced.iter().flat_map(|b| &b.steps));
102            for s in all {
103                for (path, _, _) in &s.changes {
104                    if let Some(e) = self.entries.get(path) {
105                        values.insert(path.clone(), e.value.clone());
106                    }
107                }
108            }
109        }
110        self.next_snapshot += 1;
111        info.id = self.next_snapshot;
112        self.histories
113            .entry(history.clone())
114            .or_default()
115            .snapshots
116            .push(Snap {
117                info: info.clone(),
118                values,
119            });
120        Ok(info)
121    }
122
123    /// Deletes a snapshot; `false` when there was none.
124    pub fn forget_snapshot(&mut self, history: &ScopeId, id: u64) -> bool {
125        let Some(h) = self.histories.get_mut(history) else {
126            return false;
127        };
128        let n = h.snapshots.len();
129        h.snapshots.retain(|s| s.info.id != id);
130        h.snapshots.len() != n
131    }
132
133    fn snap(&self, history: &ScopeId, id: u64) -> Result<&Snap, Refusal> {
134        self.histories
135            .get(history)
136            .and_then(|h| h.snapshots.iter().find(|s| s.info.id == id))
137            .ok_or_else(|| {
138                Refusal::new(
139                    RefusalKind::Nothing,
140                    format!("no snapshot {id} in `{history}`"),
141                )
142            })
143    }
144
145    /// Brings the history back to a snapshot's state, as one new step
146    /// ("Restore “name”") that an undo takes back. `None`: the state is
147    /// already the snapshot's. With `dry_run`, the step it would make
148    /// (id 0), nothing changed.
149    ///
150    /// <div class="warning">Experimental: may change in any release
151    /// (docs/stability.md).</div>
152    pub fn restore_snapshot(
153        &mut self,
154        history: &ScopeId,
155        id: u64,
156        origin: &Origin,
157        dry_run: bool,
158    ) -> Result<Option<Step>, Refusal> {
159        self.no_gesture(history)?;
160        let snap = self.snap(history, id)?;
161        let label = format!("Restore “{}”", snap.info.name);
162        let changes: Vec<(String, Value, Value)> = snap
163            .values
164            .iter()
165            .filter_map(|(p, v)| {
166                let e = self.entries.get(p)?;
167                (e.value != *v).then(|| (p.clone(), e.value.clone(), v.clone()))
168            })
169            .collect();
170        if changes.is_empty() {
171            return Ok(None);
172        }
173        self.write_step(history, label, origin, changes, dry_run)
174            .map(Some)
175    }
176
177    /// Writes `changes` (path, old, new) as one new step of `history`,
178    /// checked first; with `dry_run`, only the step it would be (id 0).
179    fn write_step(
180        &mut self,
181        history: &ScopeId,
182        label: String,
183        origin: &Origin,
184        changes: Vec<(String, Value, Value)>,
185        dry_run: bool,
186    ) -> Result<Step, Refusal> {
187        let mut step = Step {
188            id: 0,
189            label,
190            origin: origin.clone(),
191            changes,
192            at: self.now(),
193            place: self.place.clone(),
194            merge: None,
195            group: None,
196        };
197        self.can_replay(&step).map_err(held)?;
198        // Written by the origin's writer: the user's is the framework, an
199        // agent's is held to the paths' writers, all or nothing.
200        let by = origin.writer();
201        for (path, _, _) in &step.changes {
202            self.check_writer(path, Some(&by)).map_err(held)?;
203        }
204        if dry_run {
205            return Ok(step);
206        }
207        for (path, _, new) in &step.changes {
208            if self.entries[path].value != *new {
209                self.write(path, new.clone(), origin, Some(by.clone()));
210            }
211        }
212        self.next_step += 1;
213        step.id = self.next_step;
214        if let Some(h) = self.histories.get_mut(history) {
215            h.sealed = true;
216        }
217        self.push_step(history, step.clone());
218        Ok(step)
219    }
220
221    /// Undoes one step out of order (VS Code's rule): the head as an undo
222    /// does; an older step by a new step ("Undo “label”") putting back
223    /// the values it changed, refused when a later step changed one of
224    /// them. The step undone; with `dry_run`, checked only.
225    ///
226    /// <div class="warning">Experimental: may change in any release
227    /// (docs/stability.md).</div>
228    pub fn undo_step_in(
229        &mut self,
230        history: &ScopeId,
231        id: u64,
232        origin: &Origin,
233        dry_run: bool,
234    ) -> Result<Step, Refusal> {
235        self.no_gesture(history)?;
236        let nothing = |why: String| Refusal::new(RefusalKind::Nothing, why);
237        let h = self
238            .histories
239            .get(history)
240            .ok_or_else(|| nothing(format!("no step {id} in `{history}`")))?;
241        let Some(i) = h.undo.iter().position(|s| s.id == id) else {
242            let why = if h.redo.iter().any(|s| s.id == id) {
243                format!("step {id} is undone already")
244            } else {
245                format!("no step {id} in `{history}`")
246            };
247            return Err(nothing(why));
248        };
249        let step = h.undo[i].clone();
250        if i + 1 == h.undo.len() {
251            if dry_run {
252                self.can_replay(&step).map_err(held)?;
253                // As the undo checks it: the origin's writer, every path.
254                let by = origin.writer();
255                if let Some((path, e)) = step
256                    .changes
257                    .iter()
258                    .find(|(p, _, _)| !self.may_write(p, &by))
259                    .and_then(|(p, _, _)| self.entries.get(p).map(|e| (p, e)))
260                {
261                    return Err(held(Refused::NotWriter {
262                        path: path.clone(),
263                        by,
264                        owner: e.owner.clone(),
265                        current: e.value.clone(),
266                    }));
267                }
268                return Ok(step);
269            }
270            return self
271                .undo_in_by(history, origin, &origin.writer())
272                .map_err(held)?
273                .ok_or_else(|| nothing(format!("no step {id} in `{history}`")));
274        }
275        if let Err((later, path)) = may_undo_out_of_order(&h.undo, i, paths_of) {
276            return Err(Refusal::new(
277                RefusalKind::Owner,
278                format!(
279                    "a later step, “{}”, changed `{path}` too: undo it first",
280                    h.undo[later].label
281                ),
282            ));
283        }
284        // Back to the values it found, from what they are now; a value
285        // changed outside the history since keeps that change.
286        let mut changes: Vec<(String, Value, Value)> = Vec::new();
287        let mut skipped = Vec::new();
288        for (path, old, new) in super::net(&step.changes).into_iter().rev() {
289            let Some(e) = self.entries.get(&path) else {
290                return Err(held(Refused::Unknown { path }));
291            };
292            if e.value == old {
293                continue;
294            }
295            if e.value != new {
296                skipped.push(path);
297                continue;
298            }
299            changes.push((path, e.value.clone(), old));
300        }
301        if changes.is_empty() && !skipped.is_empty() {
302            return Err(Refusal::new(
303                RefusalKind::Owner,
304                format!(
305                    "every value it changed was changed outside its history since: `{}`",
306                    skipped.join("`, `")
307                ),
308            ));
309        }
310        self.write_step(
311            history,
312            format!("Undo “{}”", step.label),
313            origin,
314            changes,
315            dry_run,
316        )?;
317        if !dry_run {
318            self.skipped
319                .extend(skipped.into_iter().map(|path| super::Skipped {
320                    history: history.clone(),
321                    path,
322                }));
323        }
324        Ok(step)
325    }
326
327    /// A history's replaced steps, each with the step its line left
328    /// after (0: the start), oldest line first, each line oldest first.
329    pub fn replaced_in(&self, history: &ScopeId) -> Vec<(u64, &Step)> {
330        self.histories
331            .get(history)
332            .map(|h| {
333                h.replaced
334                    .iter()
335                    .flat_map(|b| b.steps.iter().map(move |s| (b.after, s)))
336                    .collect()
337            })
338            .unwrap_or_default()
339    }
340
341    /// Brings a history to a replaced step: back (or forward) to where its
342    /// line left, then along it; the current redo list becomes a
343    /// replaced line in its place. All or nothing. The steps walked, in
344    /// order; `None` when `to` is not a replaced step, or when its line
345    /// left from a step that is itself replaced (go to that line first).
346    /// With `dry_run`, checked and answered, nothing changed.
347    pub fn jump_replaced(
348        &mut self,
349        history: &ScopeId,
350        to: u64,
351        origin: &Origin,
352        dry_run: bool,
353    ) -> Result<Option<Vec<Step>>, Refused> {
354        let Some(h) = self.histories.get(history) else {
355            return Ok(None);
356        };
357        let Some((b, pos)) = h.replaced.iter().enumerate().find_map(|(b, line)| {
358            line.steps
359                .iter()
360                .position(|s| s.id == to)
361                .map(|pos| (b, pos))
362        }) else {
363            return Ok(None);
364        };
365        let after = h.replaced[b].after;
366        let Some((redo, count)) = self.plan_jump(history, after) else {
367            return Ok(None);
368        };
369        let back: Vec<Step> = {
370            let list = if redo { &h.redo } else { &h.undo };
371            list.iter().rev().take(count).cloned().collect()
372        };
373        let along: Vec<Step> = h.replaced[b].steps[..=pos].to_vec();
374        for s in back.iter().chain(&along) {
375            self.can_replay(s)?;
376        }
377        // Walked by the origin's writer, every path checked first.
378        let by = origin.writer();
379        let barred = back
380            .iter()
381            .chain(&along)
382            .flat_map(|s| s.changes.iter().map(|(p, _, _)| p))
383            .find(|p| !self.may_write(p, &by))
384            .cloned();
385        if let Some(path) = barred {
386            self.check_writer(&path, Some(&by))?;
387        }
388        let walked: Vec<Step> = back.into_iter().chain(along).collect();
389        if dry_run {
390            return Ok(Some(walked));
391        }
392        for _ in 0..count {
393            self.walk(history, origin, redo, Some(&by))?;
394        }
395        let h = self.histories.get_mut(history).expect("still there");
396        let line = h.replaced.remove(b);
397        let old: Vec<Step> = h.redo.drain(..).rev().collect();
398        if !old.is_empty() {
399            h.replaced.push(Branch { after, steps: old });
400        }
401        h.redo = line.steps.into_iter().rev().collect();
402        h.rev += 1;
403        for _ in 0..=pos {
404            self.walk(history, origin, true, Some(&by))?;
405        }
406        Ok(Some(walked))
407    }
408
409    /// The values that would differ at a point of a history (a step, 0
410    /// the start, a replaced step, or a snapshot): each path with its
411    /// value now and its value there. `None`: no such point.
412    ///
413    /// <div class="warning">Experimental: may change in any release
414    /// (docs/stability.md).</div>
415    pub fn values_at(&self, history: &ScopeId, at: At) -> Option<Vec<(String, Value, Value)>> {
416        let then = match at {
417            At::Snapshot(id) => self.snap(history, id).ok()?.values.clone(),
418            At::Step(to) => self.state_at(history, to)?,
419        };
420        Some(
421            then.into_iter()
422                .filter_map(|(p, v)| {
423                    let e = self.entries.get(&p)?;
424                    (e.value != v).then(|| (p, e.value.clone(), v))
425                })
426                .collect(),
427        )
428    }
429
430    /// The paths a walk to `to` would write, with the values they would
431    /// get.
432    fn state_at(&self, history: &ScopeId, to: u64) -> Option<BTreeMap<String, Value>> {
433        let mut out = BTreeMap::new();
434        if let Some((redo, count)) = self.plan_jump(history, to) {
435            let Some(h) = self.histories.get(history) else {
436                return Some(out);
437            };
438            let list = if redo { &h.redo } else { &h.undo };
439            for s in list.iter().rev().take(count) {
440                if redo {
441                    for (p, _, new) in &s.changes {
442                        out.insert(p.clone(), new.clone());
443                    }
444                } else {
445                    for (p, old, _) in s.changes.iter().rev() {
446                        out.insert(p.clone(), old.clone());
447                    }
448                }
449            }
450            return Some(out);
451        }
452        let h = self.histories.get(history)?;
453        let (line, pos) = h.replaced.iter().find_map(|line| {
454            line.steps
455                .iter()
456                .position(|s| s.id == to)
457                .map(|pos| (line, pos))
458        })?;
459        let mut out = self.state_at(history, line.after)?;
460        for s in &line.steps[..=pos] {
461            for (p, _, new) in &s.changes {
462                out.insert(p.clone(), new.clone());
463            }
464        }
465        Some(out)
466    }
467}