1mod 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#[derive(Clone, Debug, PartialEq, Serialize)]
94pub struct Entry {
95 pub descriptor: Descriptor,
96 pub value: Value,
97 pub seq: u64,
99 pub origin: Option<Origin>,
101 pub order: u64,
103 pub owner: OwnerId,
105 pub writer: Option<OwnerId>,
107}
108
109#[derive(Clone, Debug, PartialEq)]
111pub enum Change {
112 To(Value),
113 Step(i64),
115 Coarse(i64),
117 Reset,
118 Top,
119 Bottom,
120}
121
122#[derive(Clone, Debug, PartialEq)]
124pub struct Set {
125 pub path: String,
126 pub change: Change,
127 pub origin: Origin,
128 pub force: bool,
130 pub gesture: Option<GestureId>,
131 pub if_seq: Option<u64>,
133 pub untracked: bool,
136 pub by: Option<OwnerId>,
140 pub merge: Option<String>,
143 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 pub fn merge(mut self, key: &str) -> Self {
168 self.merge = Some(key.into());
169 self
170 }
171
172 pub fn history(mut self, scope: &ScopeId) -> Self {
174 self.history = Some(scope.clone());
175 self
176 }
177
178 pub fn by(mut self, scope: &OwnerId) -> Self {
180 self.by = Some(scope.clone());
181 self
182 }
183
184 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
208#[serde(rename_all = "lowercase")]
209pub enum Clamped {
210 None,
211 Soft,
212 Hard,
213}
214
215#[derive(Clone, Debug, PartialEq, Serialize)]
217pub struct Applied {
218 pub value: Value,
219 pub clamped: Clamped,
220 pub seq: u64,
222 pub changed: bool,
224}
225
226#[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 Stale {
239 current: Value,
240 seq: u64,
241 },
242 Held {
244 current: Value,
245 by: Origin,
246 },
247 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
286impl From<Refused> for String {
289 fn from(r: Refused) -> Self {
290 r.to_string()
291 }
292}
293
294#[derive(Clone, Debug, PartialEq, Eq)]
296pub enum DeclareError {
297 BadPath {
298 path: String,
299 reason: &'static str,
300 },
301 Taken {
303 path: String,
304 by: OwnerId,
305 },
306 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#[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#[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 history: ScopeId,
358 holds: bool,
361 paths: BTreeSet<String>,
362 changes: Vec<(String, Value, Value)>,
363 mark: Option<u64>,
366}
367
368#[derive(Clone, Debug, Default, PartialEq, Eq)]
370pub struct OwnerRemoval {
371 pub paths: Vec<String>,
373 pub dropped: Vec<DroppedSteps>,
376}
377
378#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct DroppedSteps {
382 pub history: ScopeId,
383 pub steps: usize,
385 pub mixed: usize,
387}
388
389#[derive(Clone, Debug, PartialEq, Serialize)]
391pub struct Step {
392 pub id: u64,
394 pub label: String,
395 pub origin: Origin,
396 pub changes: Vec<(String, Value, Value)>,
398 pub at: f64,
400 pub place: Vec<Place>,
405 pub merge: Option<String>,
407 pub group: Option<u64>,
409}
410
411#[derive(Clone, Debug, Default)]
413struct History {
414 undo: Vec<Step>,
415 redo: Vec<Step>,
416 dropped: (u64, u64),
418 rev: u64,
420 sealed: bool,
422 replaced: Vec<points::Branch>,
425 snapshots: Vec<points::Snap>,
427}
428
429pub const JOURNAL: usize = 1024;
431
432#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
434#[serde(rename_all = "lowercase")]
435pub enum WriterCheck {
436 #[default]
438 Refuse,
439 Warn,
442}
443
444pub 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
452pub 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
463pub fn current_history() -> ScopeId {
465 HISTORIES
466 .with(|s| s.borrow().last().cloned())
467 .unwrap_or(APP)
468}
469
470#[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
483pub 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
494pub fn current_scope() -> Option<OwnerId> {
496 SCOPES.with(|s| s.borrow().last().cloned())
497}
498
499#[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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
514pub struct StrayWrite {
515 pub path: String,
516 pub by: OwnerId,
517 pub owner: OwnerId,
518 pub refused: bool,
520}
521
522pub const HISTORY_CAP: usize = 500;
525
526#[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 histories: BTreeMap<ScopeId, History>,
536 next_step: u64,
537 next_snapshot: u64,
538 history_cap: Option<usize>,
540 clock: Option<SharedClock>,
542 place: Vec<Place>,
544 listeners: BTreeMap<ListenerId, ListenerSlot>,
545 next_listener: u64,
546 journal: VecDeque<Changed>,
547 pending: BTreeMap<String, Json>,
549 check: WriterCheck,
550 stray: Vec<StrayWrite>,
552 diagnostics: Diagnostics,
553 skipped: Vec<Skipped>,
556}
557
558#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
563pub struct Skipped {
564 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
590fn 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
603pub 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
614pub struct SettingsDoc {
615 pub values: BTreeMap<String, Json>,
616}
617
618pub 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
629fn 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 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 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 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 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 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 pub fn seq(&self) -> u64 {
760 self.seq
761 }
762
763 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 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 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 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 pub fn stray_writes(&self) -> &[StrayWrite] {
920 &self.stray
921 }
922
923 pub fn diagnostics(&self) -> &Diagnostics {
925 &self.diagnostics
926 }
927
928 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 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 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 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 pub fn now(&self) -> f64 {
1118 self.clock.as_ref().map_or(0.0, |c| c.now())
1119 }
1120
1121 pub fn set_clock(&mut self, clock: Option<SharedClock>) {
1124 self.clock = clock;
1125 }
1126
1127 pub fn has_clock(&self) -> bool {
1129 self.clock.is_some()
1130 }
1131
1132 pub fn set_place(&mut self, place: Vec<Place>) {
1138 self.place = place;
1139 }
1140
1141 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 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 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 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 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 pub fn history_cap(&self) -> usize {
1211 self.history_cap.unwrap_or(HISTORY_CAP)
1212 }
1213
1214 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 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 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 pub fn dropped_steps(&self) -> (u64, u64) {
1248 self.dropped_steps_in(&APP)
1249 }
1250
1251 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 pub fn histories(&self) -> Vec<ScopeId> {
1258 self.histories.keys().cloned().collect()
1259 }
1260
1261 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 pub fn begin_gesture(&mut self, origin: Origin, label: &str) -> GestureId {
1287 self.open(origin, label, true)
1288 }
1289
1290 pub fn begin_group(&mut self, origin: Origin, label: &str) -> GestureId {
1292 self.open(origin, label, false)
1293 }
1294
1295 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 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 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 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 pub fn take_skipped(&mut self) -> Vec<Skipped> {
1361 self.take_skipped_where(|_| true)
1362 }
1363
1364 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 pub fn undo_steps(&self) -> &[Step] {
1384 self.undo_steps_in(&APP)
1385 }
1386
1387 pub fn redo_steps(&self) -> &[Step] {
1389 self.redo_steps_in(&APP)
1390 }
1391
1392 pub fn undo_steps_in(&self, history: &ScopeId) -> &[Step] {
1394 self.histories.get(history).map_or(&[], |h| &h.undo)
1395 }
1396
1397 pub fn redo_steps_in(&self, history: &ScopeId) -> &[Step] {
1399 self.histories.get(history).map_or(&[], |h| &h.redo)
1400 }
1401
1402 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 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 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 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 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 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 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 pub fn undo_in(&mut self, history: &ScopeId, origin: &Origin) -> Result<Option<Step>, Refused> {
1497 self.walk(history, origin, false, None)
1498 }
1499
1500 pub fn redo_in(&mut self, history: &ScopeId, origin: &Origin) -> Result<Option<Step>, Refused> {
1502 self.walk(history, origin, true, None)
1503 }
1504
1505 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 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 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 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 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 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 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 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 h.sealed = true;
1647 Ok(Some(step))
1648 }
1649
1650 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 pub fn unlisten(&mut self, id: ListenerId) -> bool {
1673 self.listeners.remove(&id).is_some()
1674 }
1675
1676 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 pub fn changes_since(&self, seq: u64) -> Vec<&Changed> {
1686 self.journal.iter().filter(|c| c.seq > seq).collect()
1687 }
1688
1689 pub fn remove_owner(&mut self, owner: &OwnerId) -> Vec<String> {
1694 self.remove_owner_report(owner).paths
1695 }
1696
1697 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 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 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 pub fn pending(&self) -> &BTreeMap<String, Json> {
1810 &self.pending
1811 }
1812}