Skip to main content

egui_pop_model/values/
mod.rs

1//! The value store: every value a widget, a setting or an agent edits
2//! lives here at a stable path (`settings/theme`, `view/zoom`), never in a
3//! widget.
4//!
5//! - Each path has a [`Descriptor`]: type, hard and soft range, fine and
6//!   coarse steps, unit, display scale and precision, default, label,
7//!   choices.
8//! - Every write is a [`Set`]: an absolute value, a relative step, reset,
9//!   top or bottom, with its [`Origin`]. The answer says what was applied
10//!   and whether it was clamped; a refusal says why and gives the current
11//!   value.
12//! - During a gesture (a drag), the paths it touched belong to it: a write
13//!   from another origin is refused. Otherwise the last writer wins; a
14//!   writer may ask to write only if nothing changed since it read
15//!   (`if_seq`).
16//! - Every change is told to the listeners of its path and kept in a
17//!   short journal ([`Changed`]: path, old, new, origin, sequence); a write
18//!   equal to the value changes nothing and tells nothing, so a change
19//!   never loops back.
20//! - Undo: one step per gesture or group, else one per write; the newest
21//!   [`HISTORY_CAP`] steps are kept unless the host sets another cap. An
22//!   undo or a redo never writes into a drag still going, the dragger's
23//!   own included. Steps go to a history by scope (ADR 0014): the
24//!   application's ([`APP`]) unless the write names another
25//!   ([`Set::history`], or the one [`enter_history`] set, such as the
26//!   settings window's). Each step has an id, its time on the store's
27//!   clock ([`Store::set_clock`]) and the place it was made in
28//!   ([`Store::set_place`]); writes carrying the same merge key
29//!   ([`Set::merge`]) from one origin less than a second apart are one
30//!   step, until [`Store::seal`] (the focus left).
31//! - A history also keeps its snapshots ([`Store::take_snapshot`],
32//!   restored as a new step), the redo lists new steps dropped
33//!   ([`Store::replaced_in`], reachable by [`Store::jump_in`]), and
34//!   undoes one step out of order unless a later step changed the same
35//!   path ([`Store::undo_step_in`]); [`Store::values_at`] says what
36//!   differs at a point, for a preview.
37//! - A value changed outside a history since its step (an untracked
38//!   write, [`Store::import`], another history) keeps that change: undo,
39//!   redo, jumps and cancels leave it and list it
40//!   ([`Store::take_skipped`]). A group's step goes before the steps
41//!   made after its first write.
42//! - Paths are owned: a plugin's settings and listeners go with it.
43//! - One writer per value: a write names the scope issuing it
44//!   ([`Set::by`], or the scope [`enter_scope`] set, such as the plugin
45//!   whose command runs). A scope that is not the path's owner, not one
46//!   of its [`Writers`] and not the framework (acting for a person: the
47//!   settings form, a bound widget, the user's `value.set`) is refused,
48//!   or only warned about under [`WriterCheck::Warn`]. An agent or a
49//!   script writes as itself ([`Origin::writer`](crate::commands::Origin::writer)).
50//!   A write naming no scope is the application's own and is not
51//!   checked; undo, redo and restoring saved values are never refused,
52//!   but for an undo or redo issued by a writer ([`Store::undo_by`]).
53//!
54//! ```
55//! use egui_pop_model::commands::Origin;
56//! use egui_pop_model::ids::OwnerId;
57//! use egui_pop_model::values::{Change, Descriptor, Set, Store, Value};
58//!
59//! let mut store = Store::new();
60//! store
61//!     .declare(&OwnerId::FRAMEWORK, "settings/volume", Descriptor::float("Volume", 0.0, 1.0, 0.5))
62//!     .unwrap();
63//! let applied = store
64//!     .set(Set::new("settings/volume", Change::To(Value::Float(2.0)), Origin::User))
65//!     .unwrap();
66//! assert_eq!(applied.value, Value::Float(1.0)); // clamped to the range
67//! ```
68
69mod commands;
70mod points;
71mod value;
72
73pub use commands::{register, register_with};
74pub use value::{Descriptor, PathHint, PathKind, Type, Value, Writers};
75
76use std::cell::RefCell;
77use std::collections::{BTreeMap, BTreeSet, VecDeque};
78use std::fmt;
79
80use serde::{Deserialize, Serialize};
81use serde_json::Value as Json;
82
83use crate::clock::SharedClock;
84use crate::commands::Origin;
85use crate::context::Entry as Place;
86use crate::diagnostics::Diagnostics;
87use crate::doc::{Schema, same};
88pub use crate::history::{APP, SETTINGS};
89use crate::history::{MergeMark, ScopeId, merges};
90use crate::ids::{OwnerId, check};
91
92/// A value at its path.
93#[derive(Clone, Debug, PartialEq, Serialize)]
94pub struct Entry {
95    pub descriptor: Descriptor,
96    pub value: Value,
97    /// The store's sequence number when it last changed (0: never).
98    pub seq: u64,
99    /// Who changed it last; `None` until someone does.
100    pub origin: Option<Origin>,
101    /// The order it was declared in.
102    pub order: u64,
103    /// Who declared it.
104    pub owner: OwnerId,
105    /// The scope of the last write that changed it, when it named one.
106    pub writer: Option<OwnerId>,
107}
108
109/// What a write asks for.
110#[derive(Clone, Debug, PartialEq)]
111pub enum Change {
112    To(Value),
113    /// So many fine steps (negative: down).
114    Step(i64),
115    /// So many coarse steps.
116    Coarse(i64),
117    Reset,
118    Top,
119    Bottom,
120}
121
122/// A write.
123#[derive(Clone, Debug, PartialEq)]
124pub struct Set {
125    pub path: String,
126    pub change: Change,
127    pub origin: Origin,
128    /// Past the soft range, up to the hard one.
129    pub force: bool,
130    pub gesture: Option<GestureId>,
131    /// Only if the value has not changed since this sequence number.
132    pub if_seq: Option<u64>,
133    /// Not an undo step (state the application keeps for itself, such as
134    /// the window's place).
135    pub untracked: bool,
136    /// The scope issuing it (a plugin, the plugin whose command runs, the
137    /// framework); `None`: the one [`enter_scope`] set, else the
138    /// application's own code, not checked.
139    pub by: Option<OwnerId>,
140    /// Repeats with the same key are one undo step while they come less
141    /// than a second apart ([`crate::history::merges`]).
142    pub merge: Option<String>,
143    /// The history its step goes to; `None`: the one [`enter_history`]
144    /// set, else [`APP`].
145    pub history: Option<ScopeId>,
146}
147
148impl Set {
149    pub fn new(path: &str, change: Change, origin: Origin) -> Self {
150        Self {
151            path: path.into(),
152            change,
153            origin,
154            force: false,
155            gesture: None,
156            if_seq: None,
157            untracked: false,
158            by: None,
159            merge: None,
160            history: None,
161        }
162    }
163
164    /// Merged with the previous step when it carries the same key, comes
165    /// from the same origin less than a second before, and the history
166    /// was not sealed since (a held arrow, a wheel's notches).
167    pub fn merge(mut self, key: &str) -> Self {
168        self.merge = Some(key.into());
169        self
170    }
171
172    /// Its step goes to this history.
173    pub fn history(mut self, scope: &ScopeId) -> Self {
174        self.history = Some(scope.clone());
175        self
176    }
177
178    /// Issued by this scope (checked against the path's writers).
179    pub fn by(mut self, scope: &OwnerId) -> Self {
180        self.by = Some(scope.clone());
181        self
182    }
183
184    /// Leaves no undo step.
185    pub fn untracked(mut self) -> Self {
186        self.untracked = true;
187        self
188    }
189
190    pub fn force(mut self) -> Self {
191        self.force = true;
192        self
193    }
194
195    pub fn gesture(mut self, gesture: GestureId) -> Self {
196        self.gesture = Some(gesture);
197        self
198    }
199
200    pub fn if_seq(mut self, seq: u64) -> Self {
201        self.if_seq = Some(seq);
202        self
203    }
204}
205
206/// Which range held a write back.
207#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
208#[serde(rename_all = "lowercase")]
209pub enum Clamped {
210    None,
211    Soft,
212    Hard,
213}
214
215/// What a write did.
216#[derive(Clone, Debug, PartialEq, Serialize)]
217pub struct Applied {
218    pub value: Value,
219    pub clamped: Clamped,
220    /// The value's sequence number now.
221    pub seq: u64,
222    /// False when the value was already that.
223    pub changed: bool,
224}
225
226/// Why a write was refused; each gives the current value.
227#[derive(Clone, Debug, PartialEq, Serialize)]
228#[serde(tag = "refused", rename_all = "snake_case")]
229pub enum Refused {
230    Unknown {
231        path: String,
232    },
233    Invalid {
234        reason: String,
235        current: Value,
236    },
237    /// It changed since the writer read it.
238    Stale {
239        current: Value,
240        seq: u64,
241    },
242    /// Someone else's gesture holds it.
243    Held {
244        current: Value,
245        by: Origin,
246    },
247    /// The scope issuing it is not one of the path's writers.
248    NotWriter {
249        path: String,
250        by: OwnerId,
251        owner: OwnerId,
252        current: Value,
253    },
254}
255
256impl fmt::Display for Refused {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        match self {
259            Refused::Unknown { path } => write!(f, "no value at `{path}`"),
260            Refused::Invalid { reason, current } => {
261                write!(f, "{reason} (the value stays {current:?})")
262            }
263            Refused::Stale { current, seq } => write!(
264                f,
265                "it changed since it was read (now {current:?}, sequence {seq})"
266            ),
267            Refused::Held { current, by } => write!(
268                f,
269                "a gesture of {by:?} holds it (the value stays {current:?})"
270            ),
271            Refused::NotWriter {
272                path,
273                by,
274                owner,
275                current,
276            } => write!(
277                f,
278                "`{by}` may not write `{path}`, owned by `{owner}` (the value stays {current:?})"
279            ),
280        }
281    }
282}
283
284impl std::error::Error for Refused {}
285
286/// A refusal as its message, so `?` turns it into the `String` error a
287/// command handler returns.
288impl From<Refused> for String {
289    fn from(r: Refused) -> Self {
290        r.to_string()
291    }
292}
293
294/// Why a path could not be declared.
295#[derive(Clone, Debug, PartialEq, Eq)]
296pub enum DeclareError {
297    BadPath {
298        path: String,
299        reason: &'static str,
300    },
301    /// Another owner declared it.
302    Taken {
303        path: String,
304        by: OwnerId,
305    },
306    /// The default does not fit the descriptor.
307    BadDefault {
308        path: String,
309        reason: String,
310    },
311}
312
313impl fmt::Display for DeclareError {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        match self {
316            DeclareError::BadPath { path, reason } => write!(f, "`{path}` is not a path: {reason}"),
317            DeclareError::Taken { path, by } => write!(f, "`{path}` is already declared by `{by}`"),
318            DeclareError::BadDefault { path, reason } => {
319                write!(f, "`{path}`: its default does not fit: {reason}")
320            }
321        }
322    }
323}
324
325impl std::error::Error for DeclareError {}
326
327/// A value changed.
328#[derive(Clone, Debug, PartialEq, Serialize)]
329pub struct Changed {
330    pub path: String,
331    pub old: Value,
332    pub new: Value,
333    pub origin: Origin,
334    pub seq: u64,
335}
336
337#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
338pub struct GestureId(pub u64);
339
340/// A change listener, by id.
341#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
342pub struct ListenerId(pub u64);
343
344type Listener = Box<dyn FnMut(&Changed) + Send>;
345
346struct ListenerSlot {
347    owner: OwnerId,
348    prefix: String,
349    f: Listener,
350}
351
352#[derive(Debug)]
353struct Gesture {
354    origin: Origin,
355    label: String,
356    /// The history its step goes to.
357    history: ScopeId,
358    /// Whether the paths it touched are held against other origins: a
359    /// drag holds them, a group of an agent's writes does not.
360    holds: bool,
361    paths: BTreeSet<String>,
362    changes: Vec<(String, Value, Value)>,
363    /// The store's last step id when it first wrote: steps with a higher
364    /// id were made after it began, so its own step goes before them.
365    mark: Option<u64>,
366}
367
368/// What [`Store::remove_owner_report`] removed with an owner.
369#[derive(Clone, Debug, Default, PartialEq, Eq)]
370pub struct OwnerRemoval {
371    /// The owner's paths, removed (their changed values kept pending).
372    pub paths: Vec<String>,
373    /// Per history, the undo steps dropped; only histories that lost
374    /// some.
375    pub dropped: Vec<DroppedSteps>,
376}
377
378/// The undo steps one history lost when an owner went: those changing
379/// one of its paths, undo, redo and kept branches alike.
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct DroppedSteps {
382    pub history: ScopeId,
383    /// Steps dropped.
384    pub steps: usize,
385    /// Of those, the steps that also changed values of other owners.
386    pub mixed: usize,
387}
388
389/// One undo step.
390#[derive(Clone, Debug, PartialEq, Serialize)]
391pub struct Step {
392    /// Unique in the store, from 1.
393    pub id: u64,
394    pub label: String,
395    pub origin: Origin,
396    /// Path, old value, new value, in the order written.
397    pub changes: Vec<(String, Value, Value)>,
398    /// When it was made (its last merged write), on the store's clock.
399    pub at: f64,
400    /// The place of the context stack it was made in.
401    ///
402    /// <div class="warning">Experimental: may change in any release
403    /// (docs/stability.md).</div>
404    pub place: Vec<Place>,
405    /// Its merge key, when its writes merge with the next.
406    pub merge: Option<String>,
407    /// The gesture or group it was made of.
408    pub group: Option<u64>,
409}
410
411/// One history of the store: its undo and redo steps.
412#[derive(Clone, Debug, Default)]
413struct History {
414    undo: Vec<Step>,
415    redo: Vec<Step>,
416    /// Undo and redo steps the cap dropped so far.
417    dropped: (u64, u64),
418    /// Moves on with every change of either list.
419    rev: u64,
420    /// The next step does not merge with the head.
421    sealed: bool,
422    /// Redo lists new steps dropped, oldest first: shown as "replaced"
423    /// steps, reachable by a jump.
424    replaced: Vec<points::Branch>,
425    /// Named states pinned in it, oldest first.
426    snapshots: Vec<points::Snap>,
427}
428
429/// How many changes the journal keeps.
430pub const JOURNAL: usize = 1024;
431
432/// What a write from a scope that is not one of a path's writers gets.
433#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
434#[serde(rename_all = "lowercase")]
435pub enum WriterCheck {
436    /// Refused, with a diagnostic (the default).
437    #[default]
438    Refuse,
439    /// Applied, with a warning: to migrate plugins written before the
440    /// check.
441    Warn,
442}
443
444/// The diagnostic code of a write from a scope that is not a writer.
445pub const NOT_A_WRITER: &str = "not-a-writer";
446
447thread_local! {
448    static SCOPES: RefCell<Vec<OwnerId>> = const { RefCell::new(Vec::new()) };
449    static HISTORIES: RefCell<Vec<ScopeId>> = const { RefCell::new(Vec::new()) };
450}
451
452/// Steps made on this thread go to `scope`'s history while the guard
453/// lives, unless a write names its own ([`Set::history`]); a gesture or a
454/// group keeps the history it was opened in. The settings window enters
455/// [`SETTINGS`] while it draws its form. Histories nest.
456pub fn enter_history(scope: &ScopeId) -> HistoryGuard {
457    HISTORIES.with(|s| s.borrow_mut().push(scope.clone()));
458    HistoryGuard {
459        _not_send: std::marker::PhantomData,
460    }
461}
462
463/// The history [`enter_history`] set on this thread, else [`APP`].
464pub fn current_history() -> ScopeId {
465    HISTORIES
466        .with(|s| s.borrow().last().cloned())
467        .unwrap_or(APP)
468}
469
470/// Leaves the history [`enter_history`] entered when dropped.
471#[must_use = "the history is left when the guard is dropped"]
472#[derive(Debug)]
473pub struct HistoryGuard {
474    _not_send: std::marker::PhantomData<*const ()>,
475}
476
477impl Drop for HistoryGuard {
478    fn drop(&mut self) {
479        HISTORIES.with(|s| s.borrow_mut().pop());
480    }
481}
482
483/// Writes on this thread that name no scope are issued by `scope` while
484/// the guard lives (the application sets the plugin connecting, the
485/// owner of the command running, the plugin a lifecycle hook belongs
486/// to). Scopes nest.
487pub fn enter_scope(scope: &OwnerId) -> ScopeGuard {
488    SCOPES.with(|s| s.borrow_mut().push(scope.clone()));
489    ScopeGuard {
490        _not_send: std::marker::PhantomData,
491    }
492}
493
494/// The scope [`enter_scope`] set on this thread, if any.
495pub fn current_scope() -> Option<OwnerId> {
496    SCOPES.with(|s| s.borrow().last().cloned())
497}
498
499/// Leaves the scope [`enter_scope`] entered when dropped.
500#[must_use = "the scope is left when the guard is dropped"]
501#[derive(Debug)]
502pub struct ScopeGuard {
503    _not_send: std::marker::PhantomData<*const ()>,
504}
505
506impl Drop for ScopeGuard {
507    fn drop(&mut self) {
508        SCOPES.with(|s| s.borrow_mut().pop());
509    }
510}
511
512/// A write from a scope that is not one of a path's writers.
513#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
514pub struct StrayWrite {
515    pub path: String,
516    pub by: OwnerId,
517    pub owner: OwnerId,
518    /// Whether it was refused (else applied, under [`WriterCheck::Warn`]).
519    pub refused: bool,
520}
521
522/// How many undo steps a store keeps by default, the oldest dropped
523/// first ([`Store::set_history_cap`]).
524pub const HISTORY_CAP: usize = 500;
525
526/// The store.
527#[derive(Default)]
528pub struct Store {
529    entries: BTreeMap<String, Entry>,
530    seq: u64,
531    next_order: u64,
532    gestures: BTreeMap<GestureId, Gesture>,
533    next_gesture: u64,
534    /// The histories, by scope ([`APP`] first made).
535    histories: BTreeMap<ScopeId, History>,
536    next_step: u64,
537    next_snapshot: u64,
538    /// The host's cap on each history; [`HISTORY_CAP`] when unset.
539    history_cap: Option<usize>,
540    /// Where steps take their time from; none: 0, and nothing merges.
541    clock: Option<SharedClock>,
542    /// The place new steps are made in.
543    place: Vec<Place>,
544    listeners: BTreeMap<ListenerId, ListenerSlot>,
545    next_listener: u64,
546    journal: VecDeque<Changed>,
547    /// Saved values for paths not declared yet (a plugin not connected).
548    pending: BTreeMap<String, Json>,
549    check: WriterCheck,
550    /// Writes from scopes that are not writers, each path and scope once.
551    stray: Vec<StrayWrite>,
552    diagnostics: Diagnostics,
553    /// Values an undo, a redo or a cancel left alone because they were
554    /// changed outside the history since ([`Store::take_skipped`]).
555    skipped: Vec<Skipped>,
556}
557
558/// A value an undo, a redo, a jump or a cancel left as it was: it was
559/// changed outside the history since the step (an untracked write, a
560/// settings file read back, another history), so the outside change is
561/// kept.
562#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
563pub struct Skipped {
564    /// The history walked (or the group's).
565    pub history: ScopeId,
566    pub path: String,
567}
568
569impl fmt::Debug for Store {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        f.debug_struct("Store")
572            .field("paths", &self.entries.len())
573            .field("seq", &self.seq)
574            .field("listeners", &self.listeners.len())
575            .field("gestures", &self.gestures)
576            .finish()
577    }
578}
579
580fn clamp(v: f64, range: Option<(f64, f64)>, soft: bool) -> (f64, Clamped) {
581    match range {
582        Some((lo, hi)) if v < lo || v > hi => (
583            v.clamp(lo, hi),
584            if soft { Clamped::Soft } else { Clamped::Hard },
585        ),
586        _ => (v, Clamped::None),
587    }
588}
589
590/// A step's changes per path, in the order first written: the value
591/// before the first write, the value after the last.
592fn net(changes: &[(String, Value, Value)]) -> Vec<(String, Value, Value)> {
593    let mut out: Vec<(String, Value, Value)> = Vec::new();
594    for (path, old, new) in changes {
595        match out.iter_mut().find(|(p, _, _)| p == path) {
596            Some(c) => c.2 = new.clone(),
597            None => out.push((path.clone(), old.clone(), new.clone())),
598        }
599    }
600    out
601}
602
603/// Checks a path: segments with the id syntax, separated by `/`.
604pub fn check_path(path: &str) -> Result<(), &'static str> {
605    check(path)?;
606    if path.split('/').any(str::is_empty) {
607        return Err("it has an empty segment");
608    }
609    Ok(())
610}
611
612/// The `settings` document: the values that differ from their default.
613#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
614pub struct SettingsDoc {
615    pub values: BTreeMap<String, Json>,
616}
617
618/// The `settings` document's schema. Version 2 reads a retired pointer
619/// profile id as the profile it names (`adobe` as `lightroom`); version 3
620/// reads the file picker's views as the file browser's modes (`list` as
621/// `details`, `grid` as `thumbnails`).
622pub fn settings_schema() -> Schema {
623    Schema::new("settings", 3)
624        .migration(0, same)
625        .migration(1, crate::pointer::settings_profile_aliases)
626        .migration(2, file_views_as_modes)
627}
628
629/// `settings/files.view`: the picker's views became the file browser's
630/// modes.
631fn file_views_as_modes(mut json: serde_json::Value) -> Result<serde_json::Value, String> {
632    if let Some(v) = json
633        .get_mut("values")
634        .and_then(|values| values.get_mut("settings/files.view"))
635    {
636        let to = match v.as_str() {
637            Some("list") => "details",
638            Some("grid") => "thumbnails",
639            _ => return Ok(json),
640        };
641        *v = serde_json::Value::String(to.into());
642    }
643    Ok(json)
644}
645
646impl Store {
647    pub fn new() -> Self {
648        Self::default()
649    }
650
651    /// Declares a path at its default value. The same owner may declare a
652    /// path again (its descriptor is replaced, its value kept when it
653    /// still fits); another owner may not.
654    pub fn declare(
655        &mut self,
656        owner: &OwnerId,
657        path: &str,
658        descriptor: Descriptor,
659    ) -> Result<(), DeclareError> {
660        let value = descriptor.default.clone();
661        self.declare_with(owner, path, descriptor, value)
662    }
663
664    /// Declares a path at a value.
665    pub fn declare_with(
666        &mut self,
667        owner: &OwnerId,
668        path: &str,
669        descriptor: Descriptor,
670        value: Value,
671    ) -> Result<(), DeclareError> {
672        check_path(path).map_err(|reason| DeclareError::BadPath {
673            path: path.into(),
674            reason,
675        })?;
676        let probe = Entry {
677            descriptor: descriptor.clone(),
678            value: descriptor.default.clone(),
679            seq: 0,
680            origin: None,
681            order: 0,
682            owner: owner.clone(),
683            writer: None,
684        };
685        let default = Set::new(path, Change::To(descriptor.default.clone()), Origin::User).force();
686        match Self::target(&probe, &default) {
687            Ok((_, Clamped::None)) => {}
688            Ok(_) => {
689                return Err(DeclareError::BadDefault {
690                    path: path.into(),
691                    reason: "it is out of range".into(),
692                });
693            }
694            Err(reason) => {
695                return Err(DeclareError::BadDefault {
696                    path: path.into(),
697                    reason,
698                });
699            }
700        }
701        let (order, mut value) = match self.entries.get(path) {
702            Some(e) if e.owner != *owner => {
703                return Err(DeclareError::Taken {
704                    path: path.into(),
705                    by: e.owner.clone(),
706                });
707            }
708            Some(e) => (e.order, e.value.clone()),
709            None => {
710                self.next_order += 1;
711                (self.next_order, value)
712            }
713        };
714        let mut entry = Entry {
715            descriptor,
716            value: value.clone(),
717            seq: 0,
718            origin: None,
719            order,
720            owner: owner.clone(),
721            writer: None,
722        };
723        // A saved value waiting for this path, or the kept one: only if
724        // it fits.
725        if let Some(saved) = self.pending.remove(path)
726            && let Ok(v) = Value::from_json(entry.descriptor.ty, &saved)
727        {
728            value = v;
729        }
730        let check = Set::new(path, Change::To(value), Origin::User).force();
731        entry.value = Self::target(&entry, &check)
732            .map(|(v, _)| v)
733            .unwrap_or_else(|_| entry.descriptor.default.clone());
734        self.entries.insert(path.into(), entry);
735        Ok(())
736    }
737
738    pub fn get(&self, path: &str) -> Option<&Entry> {
739        self.entries.get(path)
740    }
741
742    /// The paths under a prefix (`settings/`), by path.
743    pub fn list(&self, prefix: &str) -> Vec<(&str, &Entry)> {
744        self.entries
745            .range(prefix.to_string()..)
746            .take_while(|(p, _)| p.starts_with(prefix))
747            .map(|(p, e)| (p.as_str(), e))
748            .collect()
749    }
750
751    /// The paths under a prefix, in declaration order.
752    pub fn list_in_order(&self, prefix: &str) -> Vec<(&str, &Entry)> {
753        let mut v = self.list(prefix);
754        v.sort_by_key(|(_, e)| e.order);
755        v
756    }
757
758    /// The store's sequence number: the last change's.
759    pub fn seq(&self) -> u64 {
760        self.seq
761    }
762
763    /// What a change makes of the value, before ranges are checked.
764    fn target(entry: &Entry, set: &Set) -> Result<(Value, Clamped), String> {
765        let d = &entry.descriptor;
766        let range = d.range(set.force);
767        let soft = !set.force && d.soft.is_some();
768        let number = |v: f64| -> Result<(Value, Clamped), String> {
769            if !v.is_finite() {
770                return Err(format!("{v} is not a number"));
771            }
772            let (v, c) = clamp(v, range, soft);
773            Ok(match d.ty {
774                Type::Int => (Value::Int(v.round() as i64), c),
775                _ => (Value::Float(v), c),
776            })
777        };
778        let current = entry.value.as_f64();
779        match (&set.change, d.ty) {
780            (Change::Reset, _) => Ok((d.default.clone(), Clamped::None)),
781            (Change::To(Value::Float(v)), Type::Float | Type::Int) => number(*v),
782            (Change::To(Value::Int(v)), Type::Float | Type::Int) => number(*v as f64),
783            (Change::To(Value::Floats(v)), Type::Floats) => {
784                if let Some(n) = d.count
785                    && v.len() > n as usize
786                {
787                    return Err(format!("{} values, at most {n}", v.len()));
788                }
789                let mut clamped = Clamped::None;
790                let mut out = Vec::with_capacity(v.len());
791                for x in v {
792                    if !x.is_finite() {
793                        return Err(format!("{x} is not a number"));
794                    }
795                    let (x, c) = clamp(*x, d.hard, false);
796                    if c != Clamped::None {
797                        clamped = c;
798                    }
799                    out.push(x);
800                }
801                Ok((Value::Floats(out), clamped))
802            }
803            (Change::To(Value::Ints(v)), Type::Ints) => {
804                if let Some(n) = d.count
805                    && v.len() > n as usize
806                {
807                    return Err(format!("{} values, at most {n}", v.len()));
808                }
809                let mut clamped = Clamped::None;
810                let out = v
811                    .iter()
812                    .map(|x| {
813                        let (x, c) = clamp(*x as f64, d.hard, false);
814                        if c != Clamped::None {
815                            clamped = c;
816                        }
817                        x as i64
818                    })
819                    .collect();
820                Ok((Value::Ints(out), clamped))
821            }
822            (Change::To(Value::Bool(b)), Type::Bool) => Ok((Value::Bool(*b), Clamped::None)),
823            (Change::To(Value::Choice(c)), Type::Choice) => {
824                if d.choices.contains(c) {
825                    Ok((Value::Choice(c.clone()), Clamped::None))
826                } else {
827                    Err(format!("`{c}` is not one of {}", d.choices.join(", ")))
828                }
829            }
830            (Change::To(Value::Text(t)), Type::Text) => match d.capacity {
831                Some(n) if t.len() > n as usize => Err(format!("{} bytes, at most {n}", t.len())),
832                _ => Ok((Value::Text(t.clone()), Clamped::None)),
833            },
834            (Change::To(v), _) => Err(format!("{v:?} is not a {:?}", d.ty)),
835            (Change::Step(n) | Change::Coarse(n), Type::Float | Type::Int) => {
836                let step = if matches!(set.change, Change::Coarse(_)) {
837                    d.coarse
838                } else {
839                    d.step
840                };
841                number(current.unwrap_or(0.0) + *n as f64 * step)
842            }
843            (Change::Step(n) | Change::Coarse(n), Type::Bool) => {
844                let b = entry.value.as_bool().unwrap_or(false);
845                Ok((Value::Bool(b ^ (n % 2 != 0)), Clamped::None))
846            }
847            (Change::Step(n) | Change::Coarse(n), Type::Choice) => {
848                if d.choices.is_empty() {
849                    return Err("no choices to step through".into());
850                }
851                let at = entry
852                    .value
853                    .as_choice()
854                    .and_then(|c| d.choices.iter().position(|o| o == c))
855                    .unwrap_or(0) as i64;
856                let last = d.choices.len() as i64 - 1;
857                let to = at + n;
858                let clamped = if to < 0 || to > last {
859                    Clamped::Hard
860                } else {
861                    Clamped::None
862                };
863                Ok((
864                    Value::Choice(d.choices[to.clamp(0, last) as usize].clone()),
865                    clamped,
866                ))
867            }
868            (Change::Top | Change::Bottom, Type::Float | Type::Int) => {
869                let (lo, hi) = range.ok_or("no range to go to the end of")?;
870                number(if set.change == Change::Top { hi } else { lo })
871            }
872            (Change::Top | Change::Bottom, Type::Bool) => {
873                Ok((Value::Bool(set.change == Change::Top), Clamped::None))
874            }
875            (Change::Top | Change::Bottom, Type::Choice) => {
876                let c = if set.change == Change::Top {
877                    d.choices.last()
878                } else {
879                    d.choices.first()
880                };
881                Ok((Value::Choice(c.cloned().unwrap_or_default()), Clamped::None))
882            }
883            (_, ty) => Err(format!("a {ty:?} cannot be stepped")),
884        }
885    }
886
887    /// The origin of the gesture holding a path, if one does: a widget
888    /// shows it, an agent knows to wait.
889    pub fn held_by(&self, path: &str) -> Option<&Origin> {
890        self.gestures
891            .values()
892            .find(|g| g.holds && g.paths.contains(path))
893            .map(|g| &g.origin)
894    }
895
896    /// Who holds a path against `origin`, if anyone.
897    fn holder(&self, path: &str, origin: &Origin, gesture: Option<GestureId>) -> Option<&Origin> {
898        self.gestures
899            .iter()
900            .find(|(id, g)| {
901                g.holds && Some(**id) != gesture && g.origin != *origin && g.paths.contains(path)
902            })
903            .map(|(_, g)| &g.origin)
904    }
905
906    /// What a write from a scope that is not a writer gets: refused or
907    /// warned about, as [`WriterCheck`] says; each path and scope is
908    /// reported once.
909    pub fn set_writer_check(&mut self, check: WriterCheck) {
910        self.check = check;
911    }
912
913    pub fn writer_check(&self) -> WriterCheck {
914        self.check
915    }
916
917    /// The writes from scopes that are not writers so far, each path and
918    /// scope once: what a test of a plugin set expects empty.
919    pub fn stray_writes(&self) -> &[StrayWrite] {
920        &self.stray
921    }
922
923    /// The store's diagnostics: writes from scopes that are not writers.
924    pub fn diagnostics(&self) -> &Diagnostics {
925        &self.diagnostics
926    }
927
928    /// Whether a scope may write a path (an unknown path: no).
929    pub fn may_write(&self, path: &str, scope: &OwnerId) -> bool {
930        self.entries
931            .get(path)
932            .is_some_and(|e| e.descriptor.writers.allow(&e.owner, scope))
933    }
934
935    /// Checks a write's scope; `Err` when it is refused.
936    fn check_writer(&mut self, path: &str, scope: Option<&OwnerId>) -> Result<(), Refused> {
937        let (Some(scope), Some(e)) = (scope, self.entries.get(path)) else {
938            return Ok(());
939        };
940        if e.descriptor.writers.allow(&e.owner, scope) {
941            return Ok(());
942        }
943        let refused = self.check == WriterCheck::Refuse;
944        let (owner, current) = (e.owner.clone(), e.value.clone());
945        if !self
946            .stray
947            .iter()
948            .any(|s| s.path == path && s.by == *scope && s.refused == refused)
949        {
950            self.stray.push(StrayWrite {
951                path: path.into(),
952                by: scope.clone(),
953                owner: owner.clone(),
954                refused,
955            });
956            let message = format!(
957                "`{scope}` is not one of its writers (its owner is `{owner}`): {}",
958                if refused {
959                    "the write is refused; declare the writer (`Descriptor::writers`)"
960                } else {
961                    "the write is applied (the check only warns)"
962                }
963            );
964            if refused {
965                self.diagnostics
966                    .error(NOT_A_WRITER, Some(scope), path, message);
967            } else {
968                self.diagnostics
969                    .warn(NOT_A_WRITER, Some(scope), path, message);
970            }
971        }
972        if refused {
973            return Err(Refused::NotWriter {
974                path: path.into(),
975                by: scope.clone(),
976                owner,
977                current,
978            });
979        }
980        Ok(())
981    }
982
983    /// Writes a value already checked; tells the listeners.
984    fn write(
985        &mut self,
986        path: &str,
987        value: Value,
988        origin: &Origin,
989        by: Option<OwnerId>,
990    ) -> (Value, u64) {
991        self.seq += 1;
992        let seq = self.seq;
993        let entry = self.entries.get_mut(path).expect("a declared path");
994        let old = std::mem::replace(&mut entry.value, value.clone());
995        entry.seq = seq;
996        entry.origin = Some(origin.clone());
997        entry.writer = by;
998        let event = Changed {
999            path: path.into(),
1000            old: old.clone(),
1001            new: value,
1002            origin: origin.clone(),
1003            seq,
1004        };
1005        for l in self.listeners.values_mut() {
1006            if path.starts_with(&l.prefix) {
1007                (l.f)(&event);
1008            }
1009        }
1010        if self.journal.len() == JOURNAL {
1011            self.journal.pop_front();
1012        }
1013        self.journal.push_back(event);
1014        (old, seq)
1015    }
1016
1017    /// Applies a write. Its scope ([`Set::by`], else [`current_scope`])
1018    /// must be one of the path's writers: its owner, one its descriptor
1019    /// names ([`Writers`]), or the framework; a write naming none is not
1020    /// checked.
1021    pub fn set(&mut self, set: Set) -> Result<Applied, Refused> {
1022        if !self.entries.contains_key(&set.path) {
1023            return Err(Refused::Unknown {
1024                path: set.path.clone(),
1025            });
1026        }
1027        let scope = set.by.clone().or_else(current_scope);
1028        self.check_writer(&set.path, scope.as_ref())?;
1029        let entry = &self.entries[&set.path];
1030        let current = entry.value.clone();
1031        if let Some(seq) = set.if_seq
1032            && entry.seq != seq
1033        {
1034            return Err(Refused::Stale {
1035                current,
1036                seq: entry.seq,
1037            });
1038        }
1039        if let Some(by) = self.holder(&set.path, &set.origin, set.gesture) {
1040            return Err(Refused::Held {
1041                current,
1042                by: by.clone(),
1043            });
1044        }
1045        if let Some(g) = set.gesture
1046            && !self.gestures.contains_key(&g)
1047        {
1048            return Err(Refused::Invalid {
1049                reason: format!("no gesture {}", g.0),
1050                current,
1051            });
1052        }
1053        let (value, clamped) = Self::target(entry, &set).map_err(|reason| Refused::Invalid {
1054            reason,
1055            current: current.clone(),
1056        })?;
1057        if value == current {
1058            return Ok(Applied {
1059                value,
1060                clamped,
1061                seq: entry.seq,
1062                changed: false,
1063            });
1064        }
1065        let (old, seq) = self.write(&set.path, value.clone(), &set.origin, scope);
1066        let change = (set.path.clone(), old, value.clone());
1067        let last_step = self.next_step;
1068        match set.gesture.and_then(|g| self.gestures.get_mut(&g)) {
1069            _ if set.untracked => {}
1070            Some(g) => {
1071                g.mark.get_or_insert(last_step);
1072                g.paths.insert(set.path.clone());
1073                g.changes.push(change);
1074            }
1075            None => {
1076                let history = set.history.clone().unwrap_or_else(current_history);
1077                let step = self.new_step(
1078                    format!("set {}", set.path),
1079                    set.origin,
1080                    vec![change],
1081                    set.merge.clone(),
1082                    None,
1083                );
1084                self.push_step(&history, step);
1085            }
1086        }
1087        Ok(Applied {
1088            value,
1089            clamped,
1090            seq,
1091            changed: true,
1092        })
1093    }
1094
1095    fn new_step(
1096        &mut self,
1097        label: String,
1098        origin: Origin,
1099        changes: Vec<(String, Value, Value)>,
1100        merge: Option<String>,
1101        group: Option<u64>,
1102    ) -> Step {
1103        self.next_step += 1;
1104        Step {
1105            id: self.next_step,
1106            label,
1107            origin,
1108            changes,
1109            at: self.now(),
1110            place: self.place.clone(),
1111            merge,
1112            group,
1113        }
1114    }
1115
1116    /// The store's clock now (0 without one).
1117    pub fn now(&self) -> f64 {
1118        self.clock.as_ref().map_or(0.0, |c| c.now())
1119    }
1120
1121    /// Where steps take their time from (the interface's clock); without
1122    /// one, steps are made at 0 and writes never merge.
1123    pub fn set_clock(&mut self, clock: Option<SharedClock>) {
1124        self.clock = clock;
1125    }
1126
1127    /// Whether the store has a clock.
1128    pub fn has_clock(&self) -> bool {
1129        self.clock.is_some()
1130    }
1131
1132    /// The place of the context stack new steps are made in (the
1133    /// interface follows the stack), root first.
1134    ///
1135    /// <div class="warning">Experimental: may change in any release
1136    /// (docs/stability.md).</div>
1137    pub fn set_place(&mut self, place: Vec<Place>) {
1138        self.place = place;
1139    }
1140
1141    /// The next step of every history starts a new one, even with the
1142    /// head's merge key (the focus left the target).
1143    pub fn seal(&mut self) {
1144        for h in self.histories.values_mut() {
1145            h.sealed = true;
1146        }
1147    }
1148
1149    fn push_step(&mut self, history: &ScopeId, step: Step) {
1150        self.push_step_after(history, step, None);
1151    }
1152
1153    /// Pushes a step; with `mark`, before the undo steps made after that
1154    /// step id (a group or a gesture that began before them).
1155    fn push_step_after(&mut self, history: &ScopeId, step: Step, mark: Option<u64>) {
1156        let clocked = self.clock.is_some();
1157        let h = self.histories.entry(history.clone()).or_default();
1158        h.rev += 1;
1159        // A snapshot keeps the value each path had when it was taken: a
1160        // path changed for the first time since is recorded now.
1161        for snap in &mut h.snapshots {
1162            for (path, old, _) in &step.changes {
1163                snap.values
1164                    .entry(path.clone())
1165                    .or_insert_with(|| old.clone());
1166            }
1167        }
1168        // Begun before steps made since: it goes before them, so undoing
1169        // them all comes back to where it began.
1170        if let Some(i) = mark.and_then(|m| h.undo.iter().position(|s| s.id > m)) {
1171            h.undo.insert(i, step);
1172            self.trim_history();
1173            return;
1174        }
1175        let joins = clocked && !h.sealed && h.redo.is_empty();
1176        let head = h.undo.last_mut().filter(|_| joins);
1177        if let (Some(head), Some(key)) = (head, &step.merge)
1178            && let Some(prev) = &head.merge
1179            && merges(
1180                &MergeMark::new(prev, head.origin.clone(), head.at),
1181                &MergeMark::new(key, step.origin.clone(), step.at),
1182            )
1183        {
1184            for (path, old, new) in step.changes {
1185                match head.changes.iter_mut().find(|(p, _, _)| *p == path) {
1186                    Some(c) => c.2 = new,
1187                    None => head.changes.push((path, old, new)),
1188                }
1189            }
1190            head.at = step.at;
1191            head.label = step.label;
1192            return;
1193        }
1194        h.sealed = false;
1195        // The redo list a new step drops is kept, as a replaced line.
1196        let after = h.undo.last().map_or(0, |s| s.id);
1197        let dropped: Vec<Step> = h.redo.drain(..).rev().collect();
1198        if !dropped.is_empty() {
1199            h.replaced.push(points::Branch {
1200                after,
1201                steps: dropped,
1202            });
1203        }
1204        h.undo.push(step);
1205        self.trim_history();
1206    }
1207
1208    /// How many undo steps the store keeps: [`HISTORY_CAP`] unless the
1209    /// host set another cap.
1210    pub fn history_cap(&self) -> usize {
1211        self.history_cap.unwrap_or(HISTORY_CAP)
1212    }
1213
1214    /// Keeps at most `cap` undo steps (and as many redo steps), dropping
1215    /// the oldest now and whenever a new step goes over it. 0 keeps none.
1216    pub fn set_history_cap(&mut self, cap: usize) {
1217        self.history_cap = Some(cap);
1218        self.trim_history();
1219    }
1220
1221    fn trim_history(&mut self) {
1222        let cap = self.history_cap();
1223        for h in self.histories.values_mut() {
1224            for (steps, dropped) in [
1225                (&mut h.undo, &mut h.dropped.0),
1226                (&mut h.redo, &mut h.dropped.1),
1227            ] {
1228                // The oldest undo step and the farthest redo step come first.
1229                let over = steps.len().saturating_sub(cap);
1230                if over > 0 {
1231                    steps.drain(..over);
1232                    *dropped += over as u64;
1233                    h.rev += 1;
1234                }
1235            }
1236            // Replaced lines: the oldest go first.
1237            while h.replaced.iter().map(|b| b.steps.len()).sum::<usize>() > cap {
1238                h.replaced.remove(0);
1239                h.rev += 1;
1240            }
1241        }
1242    }
1243
1244    /// How many undo steps and redo steps the cap dropped from the
1245    /// application's history ([`APP`]) since the store began, each from
1246    /// the front of its list.
1247    pub fn dropped_steps(&self) -> (u64, u64) {
1248        self.dropped_steps_in(&APP)
1249    }
1250
1251    /// How many steps the cap dropped from a history.
1252    pub fn dropped_steps_in(&self, history: &ScopeId) -> (u64, u64) {
1253        self.histories.get(history).map_or((0, 0), |h| h.dropped)
1254    }
1255
1256    /// The histories that have had a step, by scope.
1257    pub fn histories(&self) -> Vec<ScopeId> {
1258        self.histories.keys().cloned().collect()
1259    }
1260
1261    /// A history's revision: it moves on with every change of its lists.
1262    pub fn history_rev(&self, history: &ScopeId) -> u64 {
1263        self.histories.get(history).map_or(0, |h| h.rev)
1264    }
1265
1266    fn open(&mut self, origin: Origin, label: &str, holds: bool) -> GestureId {
1267        self.next_gesture += 1;
1268        let id = GestureId(self.next_gesture);
1269        self.gestures.insert(
1270            id,
1271            Gesture {
1272                origin,
1273                label: label.into(),
1274                history: current_history(),
1275                holds,
1276                paths: BTreeSet::new(),
1277                changes: Vec::new(),
1278                mark: None,
1279            },
1280        );
1281        id
1282    }
1283
1284    /// Starts a gesture (a drag): its writes are one undo step, and the
1285    /// paths it touches are held against other origins until it ends.
1286    pub fn begin_gesture(&mut self, origin: Origin, label: &str) -> GestureId {
1287        self.open(origin, label, true)
1288    }
1289
1290    /// Starts a group: its writes are one undo step, nothing is held.
1291    pub fn begin_group(&mut self, origin: Origin, label: &str) -> GestureId {
1292        self.open(origin, label, false)
1293    }
1294
1295    /// Ends a gesture or a group; what it changed becomes one undo step.
1296    /// Ending one that is not open is reported as `false`.
1297    pub fn end(&mut self, id: GestureId) -> bool {
1298        let Some(g) = self.gestures.remove(&id) else {
1299            return false;
1300        };
1301        if !g.changes.is_empty() {
1302            let step = self.new_step(g.label, g.origin, g.changes, None, Some(id.0));
1303            self.push_step_after(&g.history, step, g.mark);
1304        }
1305        true
1306    }
1307
1308    /// The label of a gesture still going (a drag) whose writes would go
1309    /// to `history`: an undo there waits for it.
1310    pub fn gesture_open(&self, history: &ScopeId) -> Option<&str> {
1311        self.gestures
1312            .values()
1313            .find(|g| g.holds && g.history == *history)
1314            .map(|g| g.label.as_str())
1315    }
1316
1317    /// Cancels a gesture or a group: what it changed is put back as it
1318    /// was (listeners are told), and no undo step is left. Cancelling one
1319    /// that is not open is reported as `false`.
1320    pub fn cancel(&mut self, id: GestureId) -> bool {
1321        let Some(g) = self.gestures.remove(&id) else {
1322            return false;
1323        };
1324        for (path, old, new) in net(&g.changes).into_iter().rev() {
1325            let Some(e) = self.entries.get(&path) else {
1326                continue;
1327            };
1328            if e.value == new {
1329                self.write(&path, old, &g.origin, Some(OwnerId::FRAMEWORK));
1330            } else if e.value != old {
1331                // Changed outside the group since: the outside change
1332                // stays, and the first step made since on it now starts
1333                // from the value before the group, so undoing it comes
1334                // back there.
1335                let mark = g.mark.unwrap_or(0);
1336                for h in self.histories.values_mut() {
1337                    let later = h
1338                        .undo
1339                        .iter_mut()
1340                        .chain(h.redo.iter_mut().rev())
1341                        .filter(|s| s.id > mark)
1342                        .find_map(|s| s.changes.iter_mut().find(|(p, _, _)| *p == path));
1343                    if let Some(c) = later {
1344                        c.1 = old.clone();
1345                        h.rev += 1;
1346                    }
1347                }
1348                self.skipped.push(Skipped {
1349                    history: g.history.clone(),
1350                    path,
1351                });
1352            }
1353        }
1354        true
1355    }
1356
1357    /// The values the undos, redos, jumps and cancels since the last call
1358    /// left alone because they had been changed outside the history,
1359    /// each kept with the outside change; the list is emptied.
1360    pub fn take_skipped(&mut self) -> Vec<Skipped> {
1361        self.take_skipped_where(|_| true)
1362    }
1363
1364    /// [`Store::take_skipped`] for one history: its skipped values are
1365    /// taken, the other histories' stay.
1366    pub fn take_skipped_in(&mut self, history: &ScopeId) -> Vec<String> {
1367        self.take_skipped_where(|s| s.history == *history)
1368            .into_iter()
1369            .map(|s| s.path)
1370            .collect()
1371    }
1372
1373    fn take_skipped_where(&mut self, f: impl Fn(&Skipped) -> bool) -> Vec<Skipped> {
1374        let (mut out, keep): (Vec<Skipped>, Vec<Skipped>) =
1375            std::mem::take(&mut self.skipped).into_iter().partition(f);
1376        self.skipped = keep;
1377        let mut seen = BTreeSet::new();
1378        out.retain(|s| seen.insert((s.history.clone(), s.path.clone())));
1379        out
1380    }
1381
1382    /// The application's undo steps ([`APP`]), oldest first.
1383    pub fn undo_steps(&self) -> &[Step] {
1384        self.undo_steps_in(&APP)
1385    }
1386
1387    /// The application's redo steps, the next one last.
1388    pub fn redo_steps(&self) -> &[Step] {
1389        self.redo_steps_in(&APP)
1390    }
1391
1392    /// A history's undo steps, oldest first.
1393    pub fn undo_steps_in(&self, history: &ScopeId) -> &[Step] {
1394        self.histories.get(history).map_or(&[], |h| &h.undo)
1395    }
1396
1397    /// A history's redo steps, the next one last.
1398    pub fn redo_steps_in(&self, history: &ScopeId) -> &[Step] {
1399        self.histories.get(history).map_or(&[], |h| &h.redo)
1400    }
1401
1402    /// Whether a step can be put back (`back`) or made again: its paths
1403    /// exist and no drag still going holds one.
1404    fn can_replay(&self, step: &Step) -> Result<(), Refused> {
1405        for (path, _, _) in &step.changes {
1406            let current = self
1407                .entries
1408                .get(path)
1409                .map(|e| e.value.clone())
1410                .ok_or_else(|| Refused::Unknown { path: path.clone() })?;
1411            // A drag still going holds its paths against every undo and
1412            // redo, the dragger's own included: its step is not made yet.
1413            if let Some(by) = self.held_by(path) {
1414                return Err(Refused::Held {
1415                    current,
1416                    by: by.clone(),
1417                });
1418            }
1419        }
1420        Ok(())
1421    }
1422
1423    /// Puts back the values a step changed, as a write by `origin`;
1424    /// `by`, every path is checked against its writers first (all or
1425    /// nothing), else the framework replays it.
1426    ///
1427    /// A value no longer as the step left it (`back`) or found it was
1428    /// changed outside the history since: it keeps that change and is
1429    /// listed as skipped ([`Store::take_skipped`]).
1430    fn replay(
1431        &mut self,
1432        history: &ScopeId,
1433        step: &Step,
1434        origin: &Origin,
1435        back: bool,
1436        by: Option<&OwnerId>,
1437    ) -> Result<(), Refused> {
1438        self.can_replay(step)?;
1439        if let Some(by) = by {
1440            for (path, _, _) in &step.changes {
1441                self.check_writer(path, Some(by))?;
1442            }
1443        }
1444        let mut changes = net(&step.changes);
1445        if back {
1446            changes.reverse();
1447        }
1448        for (path, old, new) in changes {
1449            let (expect, to) = if back { (new, old) } else { (old, new) };
1450            let now = &self.entries[&path].value;
1451            if *now == to {
1452                continue;
1453            }
1454            if *now != expect {
1455                self.skipped.push(Skipped {
1456                    history: history.clone(),
1457                    path,
1458                });
1459                continue;
1460            }
1461            self.write(
1462                &path,
1463                to,
1464                origin,
1465                Some(by.cloned().unwrap_or(OwnerId::FRAMEWORK)),
1466            );
1467        }
1468        Ok(())
1469    }
1470
1471    /// Undoes the application's last step ([`APP`]); its label, or
1472    /// `None` when there is none.
1473    pub fn undo(&mut self, origin: &Origin) -> Result<Option<String>, Refused> {
1474        Ok(self.undo_in(&APP, origin)?.map(|s| s.label))
1475    }
1476
1477    /// Redoes the application's last undone step.
1478    pub fn redo(&mut self, origin: &Origin) -> Result<Option<String>, Refused> {
1479        Ok(self.redo_in(&APP, origin)?.map(|s| s.label))
1480    }
1481
1482    /// As [`Store::undo`], written by `by` (`Origin::writer`): refused,
1483    /// as a write is, when `by` is not one of the writers of every path
1484    /// the step changed. What an agent's undo goes through.
1485    pub fn undo_by(&mut self, origin: &Origin, by: &OwnerId) -> Result<Option<String>, Refused> {
1486        Ok(self.walk(&APP, origin, false, Some(by))?.map(|s| s.label))
1487    }
1488
1489    /// As [`Store::redo`], written by `by`.
1490    pub fn redo_by(&mut self, origin: &Origin, by: &OwnerId) -> Result<Option<String>, Refused> {
1491        Ok(self.walk(&APP, origin, true, Some(by))?.map(|s| s.label))
1492    }
1493
1494    /// Undoes a history's last step; the step, or `None` when there is
1495    /// none.
1496    pub fn undo_in(&mut self, history: &ScopeId, origin: &Origin) -> Result<Option<Step>, Refused> {
1497        self.walk(history, origin, false, None)
1498    }
1499
1500    /// Redoes a history's last undone step.
1501    pub fn redo_in(&mut self, history: &ScopeId, origin: &Origin) -> Result<Option<Step>, Refused> {
1502        self.walk(history, origin, true, None)
1503    }
1504
1505    /// As [`Store::undo_in`], written by `by` (`Origin::writer`): refused
1506    /// when `by` is not one of the writers of every path of the step.
1507    pub fn undo_in_by(
1508        &mut self,
1509        history: &ScopeId,
1510        origin: &Origin,
1511        by: &OwnerId,
1512    ) -> Result<Option<Step>, Refused> {
1513        self.walk(history, origin, false, Some(by))
1514    }
1515
1516    /// As [`Store::redo_in`], written by `by`.
1517    pub fn redo_in_by(
1518        &mut self,
1519        history: &ScopeId,
1520        origin: &Origin,
1521        by: &OwnerId,
1522    ) -> Result<Option<Step>, Refused> {
1523        self.walk(history, origin, true, Some(by))
1524    }
1525
1526    /// Whether an undo (or a redo) of a history would be refused, without
1527    /// making it: the step it would take, or `None` when there is none.
1528    pub fn check_walk(&self, history: &ScopeId, redo: bool) -> Result<Option<&Step>, Refused> {
1529        let Some(h) = self.histories.get(history) else {
1530            return Ok(None);
1531        };
1532        let Some(step) = (if redo { h.redo.last() } else { h.undo.last() }) else {
1533            return Ok(None);
1534        };
1535        self.can_replay(step)?;
1536        Ok(Some(step))
1537    }
1538
1539    /// Brings a history to step `to` (0: everything undone) by undos or
1540    /// redos, all or none: every step on the way is checked first. How
1541    /// many steps it walked, or `None` when `to` is not in the history.
1542    pub fn jump_in(
1543        &mut self,
1544        history: &ScopeId,
1545        to: u64,
1546        origin: &Origin,
1547    ) -> Result<Option<usize>, Refused> {
1548        self.jump_in_with(history, to, origin, None)
1549    }
1550
1551    /// As [`Store::jump_in`], written by `by`: every step on the way is
1552    /// checked against the writers of its paths first.
1553    pub fn jump_in_by(
1554        &mut self,
1555        history: &ScopeId,
1556        to: u64,
1557        origin: &Origin,
1558        by: &OwnerId,
1559    ) -> Result<Option<usize>, Refused> {
1560        self.jump_in_with(history, to, origin, Some(by))
1561    }
1562
1563    fn jump_in_with(
1564        &mut self,
1565        history: &ScopeId,
1566        to: u64,
1567        origin: &Origin,
1568        by: Option<&OwnerId>,
1569    ) -> Result<Option<usize>, Refused> {
1570        let Some((redo, count)) = self.plan_jump(history, to) else {
1571            // A replaced step: back to where its line left, then along it.
1572            return Ok(self
1573                .jump_replaced(history, to, origin, false)?
1574                .map(|steps| steps.len()));
1575        };
1576        let mut barred = None;
1577        {
1578            let h = &self.histories[history];
1579            let list = if redo { &h.redo } else { &h.undo };
1580            for step in list.iter().rev().take(count) {
1581                self.can_replay(step)?;
1582                if let Some(by) = by
1583                    && barred.is_none()
1584                {
1585                    barred = step
1586                        .changes
1587                        .iter()
1588                        .find(|(p, _, _)| !self.may_write(p, by))
1589                        .map(|(p, _, _)| p.clone());
1590                }
1591            }
1592        }
1593        if let Some(path) = barred {
1594            // Said as a write would be: refused, in the diagnostics.
1595            self.check_writer(&path, by)?;
1596        }
1597        for _ in 0..count {
1598            self.walk(history, origin, redo, by)?;
1599        }
1600        Ok(Some(count))
1601    }
1602
1603    /// Redos (`true`) or undos, and how many, to bring a history to `to`.
1604    pub fn plan_jump(&self, history: &ScopeId, to: u64) -> Option<(bool, usize)> {
1605        let h = self.histories.get(history);
1606        if to == 0 {
1607            return Some((false, h.map_or(0, |h| h.undo.len())));
1608        }
1609        let h = h?;
1610        if let Some(i) = h.undo.iter().position(|s| s.id == to) {
1611            return Some((false, h.undo.len() - 1 - i));
1612        }
1613        h.redo
1614            .iter()
1615            .position(|s| s.id == to)
1616            .map(|i| (true, h.redo.len() - i))
1617    }
1618
1619    fn walk(
1620        &mut self,
1621        history: &ScopeId,
1622        origin: &Origin,
1623        redo: bool,
1624        by: Option<&OwnerId>,
1625    ) -> Result<Option<Step>, Refused> {
1626        let Some(h) = self.histories.get_mut(history) else {
1627            return Ok(None);
1628        };
1629        let Some(step) = (if redo { h.redo.pop() } else { h.undo.pop() }) else {
1630            return Ok(None);
1631        };
1632        let replayed = self.replay(history, &step, origin, !redo, by);
1633        let h = self.histories.get_mut(history).expect("still there");
1634        let (from, to) = if redo {
1635            (&mut h.redo, &mut h.undo)
1636        } else {
1637            (&mut h.undo, &mut h.redo)
1638        };
1639        if let Err(e) = replayed {
1640            from.push(step);
1641            return Err(e);
1642        }
1643        to.push(step.clone());
1644        h.rev += 1;
1645        // What comes next never merges with a step walked over.
1646        h.sealed = true;
1647        Ok(Some(step))
1648    }
1649
1650    /// Calls `f` after every change of a path starting with `prefix`
1651    /// (empty: every path), until removed.
1652    pub fn listen(
1653        &mut self,
1654        owner: &OwnerId,
1655        prefix: &str,
1656        f: impl FnMut(&Changed) + Send + 'static,
1657    ) -> ListenerId {
1658        self.next_listener += 1;
1659        let id = ListenerId(self.next_listener);
1660        self.listeners.insert(
1661            id,
1662            ListenerSlot {
1663                owner: owner.clone(),
1664                prefix: prefix.into(),
1665                f: Box::new(f),
1666            },
1667        );
1668        id
1669    }
1670
1671    /// Removes a listener; `false` when it was not there.
1672    pub fn unlisten(&mut self, id: ListenerId) -> bool {
1673        self.listeners.remove(&id).is_some()
1674    }
1675
1676    /// The listeners, by id: owner and prefix.
1677    pub fn listeners(&self) -> Vec<(ListenerId, &OwnerId, &str)> {
1678        self.listeners
1679            .iter()
1680            .map(|(id, l)| (*id, &l.owner, l.prefix.as_str()))
1681            .collect()
1682    }
1683
1684    /// The changes after a sequence number still in the journal.
1685    pub fn changes_since(&self, seq: u64) -> Vec<&Changed> {
1686        self.journal.iter().filter(|c| c.seq > seq).collect()
1687    }
1688
1689    /// Removes an owner's paths and listeners; their undo steps go too.
1690    /// Changed values of removed paths are kept as pending, so they come
1691    /// back when the owner declares them again. The paths removed;
1692    /// [`Store::remove_owner_report`] also says which steps went.
1693    pub fn remove_owner(&mut self, owner: &OwnerId) -> Vec<String> {
1694        self.remove_owner_report(owner).paths
1695    }
1696
1697    /// [`Store::remove_owner`], saying what went: the paths, and per
1698    /// history the undo steps dropped because they changed one of them,
1699    /// those also changing other owners' values included (ADR 0028).
1700    /// Each history that lost steps logs how many at info level.
1701    pub fn remove_owner_report(&mut self, owner: &OwnerId) -> OwnerRemoval {
1702        let paths: Vec<String> = self
1703            .entries
1704            .iter()
1705            .filter(|(_, e)| e.owner == *owner)
1706            .map(|(p, _)| p.clone())
1707            .collect();
1708        for p in &paths {
1709            if let Some(e) = self.entries.remove(p)
1710                && e.value != e.descriptor.default
1711            {
1712                self.pending.insert(p.clone(), e.value.to_json());
1713            }
1714        }
1715        let gone = |s: &Step| s.changes.iter().any(|(p, _, _)| paths.contains(p));
1716        let mixed = |s: &Step| s.changes.iter().any(|(p, _, _)| !paths.contains(p));
1717        let mut dropped = Vec::new();
1718        for (scope, h) in &mut self.histories {
1719            let mut out = DroppedSteps {
1720                history: scope.clone(),
1721                steps: 0,
1722                mixed: 0,
1723            };
1724            let mut keep = |s: &Step| {
1725                if !gone(s) {
1726                    return true;
1727                }
1728                out.steps += 1;
1729                out.mixed += usize::from(mixed(s));
1730                false
1731            };
1732            let n = h.undo.len() + h.redo.len();
1733            h.undo.retain(&mut keep);
1734            h.redo.retain(&mut keep);
1735            if h.undo.len() + h.redo.len() != n {
1736                h.rev += 1;
1737            }
1738            for b in &mut h.replaced {
1739                b.steps.retain(&mut keep);
1740            }
1741            h.replaced.retain(|b| !b.steps.is_empty());
1742            for snap in &mut h.snapshots {
1743                snap.values.retain(|p, _| !paths.contains(p));
1744            }
1745            if out.steps > 0 {
1746                log::info!(
1747                    target: "egui_pop",
1748                    "history `{scope}`: {} undo step(s) dropped with `{owner}` ({} also changing other values)",
1749                    out.steps,
1750                    out.mixed,
1751                );
1752                dropped.push(out);
1753            }
1754        }
1755        self.listeners.retain(|_, l| l.owner != *owner);
1756        OwnerRemoval { paths, dropped }
1757    }
1758
1759    /// The values under a prefix that differ from their default, and the
1760    /// saved values still waiting for their path: what the `settings`
1761    /// document holds.
1762    pub fn export(&self, prefix: &str) -> SettingsDoc {
1763        let mut values: BTreeMap<String, Json> = self
1764            .pending
1765            .iter()
1766            .filter(|(p, _)| p.starts_with(prefix))
1767            .map(|(p, v)| (p.clone(), v.clone()))
1768            .collect();
1769        for (p, e) in self.list(prefix) {
1770            if e.value != e.descriptor.default {
1771                values.insert(p.into(), e.value.to_json());
1772            }
1773        }
1774        SettingsDoc { values }
1775    }
1776
1777    /// Applies saved values as writes by `origin` (no undo step). A value
1778    /// for a path not declared yet waits for it; one that does not fit its
1779    /// path is skipped and reported.
1780    pub fn import(&mut self, doc: &SettingsDoc, origin: &Origin) -> Diagnostics {
1781        let mut d = Diagnostics::new();
1782        for (path, json) in &doc.values {
1783            let Some(e) = self.entries.get(path) else {
1784                self.pending.insert(path.clone(), json.clone());
1785                continue;
1786            };
1787            let result = Value::from_json(e.descriptor.ty, json).and_then(|v| {
1788                let set = Set::new(path, Change::To(v), origin.clone()).force();
1789                Self::target(e, &set).map(|(v, _)| v)
1790            });
1791            match result {
1792                Ok(v) => {
1793                    if self.entries[path].value != v {
1794                        self.write(path, v, origin, Some(OwnerId::FRAMEWORK));
1795                    }
1796                }
1797                Err(reason) => d.warn(
1798                    "bad-setting",
1799                    None,
1800                    path,
1801                    format!("{reason}: the saved value is skipped, the current one stays"),
1802                ),
1803            }
1804        }
1805        d
1806    }
1807
1808    /// Saved values waiting for their path to be declared.
1809    pub fn pending(&self) -> &BTreeMap<String, Json> {
1810        &self.pending
1811    }
1812}