1use std::collections::BTreeMap;
47use std::fmt;
48
49use serde::{Deserialize, Serialize};
50
51use crate::commands::Origin;
52use crate::context::Entry;
53pub use crate::ids::ScopeId;
54
55pub const APP: ScopeId = ScopeId::from_static("app");
57
58pub const SETTINGS: ScopeId = ScopeId::from_static("settings");
60
61pub const CAP: usize = 500;
63
64pub const MERGE_WINDOW: f64 = 1.0;
67
68#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
72pub struct Label {
73 pub text: String,
75 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub key: Option<String>,
78 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
80 pub args: BTreeMap<String, String>,
81}
82
83impl Label {
84 pub fn text(text: impl Into<String>) -> Self {
86 Self {
87 text: text.into(),
88 ..Self::default()
89 }
90 }
91
92 pub fn message(key: &str, english: &str, args: &[(&str, &str)]) -> Self {
97 let args: BTreeMap<String, String> = args
98 .iter()
99 .map(|(k, v)| (k.to_string(), v.to_string()))
100 .collect();
101 let mut text = english.to_string();
102 for (k, v) in &args {
103 text = text.replace(&format!("{{ ${k} }}"), v);
104 }
105 Self {
106 text,
107 key: Some(key.into()),
108 args,
109 }
110 }
111}
112
113impl fmt::Display for Label {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.write_str(&self.text)
116 }
117}
118
119#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
121pub struct StepInfo {
122 pub id: u64,
124 pub scope: ScopeId,
125 pub label: Label,
126 pub origin: Origin,
127 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub group: Option<u64>,
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 pub place: Vec<Entry>,
134 #[serde(default)]
136 pub at: f64,
137 #[serde(default)]
139 pub in_progress: bool,
140}
141
142impl StepInfo {
143 pub fn new(id: u64, scope: ScopeId, label: Label, origin: Origin) -> Self {
145 Self {
146 id,
147 scope,
148 label,
149 origin,
150 group: None,
151 place: Vec::new(),
152 at: 0.0,
153 in_progress: false,
154 }
155 }
156}
157
158#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
160pub struct ScopeInfo {
161 pub id: ScopeId,
162 pub title: String,
164 #[serde(default, skip_serializing_if = "Vec::is_empty")]
167 pub focus: Vec<String>,
168 #[serde(default)]
170 pub durable: bool,
171 pub cap: usize,
173 #[serde(default)]
176 pub local: bool,
177}
178
179impl ScopeInfo {
180 pub fn new(id: ScopeId, title: &str) -> Self {
182 Self {
183 id,
184 title: title.into(),
185 focus: Vec::new(),
186 durable: false,
187 cap: CAP,
188 local: false,
189 }
190 }
191
192 pub fn active<S: AsRef<str>>(&self, shown: &[S]) -> bool {
194 self.focus.is_empty()
195 || self
196 .focus
197 .iter()
198 .any(|f| shown.iter().any(|s| s.as_ref() == f))
199 }
200}
201
202#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
204pub struct Line {
205 pub undo: Vec<StepInfo>,
207 pub redo: Vec<StepInfo>,
209 pub rev: u64,
211}
212
213impl Line {
214 pub fn head(&self) -> Option<&StepInfo> {
216 self.undo.last()
217 }
218
219 pub fn next(&self) -> Option<&StepInfo> {
221 self.redo.last()
222 }
223
224 pub fn head_id(&self) -> u64 {
226 self.head().map_or(0, |s| s.id)
227 }
228}
229
230#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
232pub struct Request {
233 pub scope: ScopeId,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub if_rev: Option<u64>,
237 #[serde(default)]
239 pub dry_run: bool,
240}
241
242impl Request {
243 pub fn new(scope: ScopeId) -> Self {
244 Self {
245 scope,
246 if_rev: None,
247 dry_run: false,
248 }
249 }
250
251 pub fn if_rev(mut self, rev: u64) -> Self {
252 self.if_rev = Some(rev);
253 self
254 }
255
256 pub fn dry_run(mut self) -> Self {
257 self.dry_run = true;
258 self
259 }
260
261 pub fn check(&self, rev: u64) -> Result<(), Refusal> {
263 match self.if_rev {
264 Some(r) if r != rev => Err(Refusal::new(
265 RefusalKind::Stale,
266 format!("the history moved on (revision {rev}, not {r})"),
267 )),
268 _ => Ok(()),
269 }
270 }
271}
272
273#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(rename_all = "snake_case")]
276pub enum RefusalKind {
277 Nothing,
279 Unknown,
281 Stale,
283 Held,
285 Vetoed,
287 Owner,
290 Unsupported,
293}
294
295#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
297pub struct Refusal {
298 pub kind: RefusalKind,
299 pub reason: String,
300}
301
302impl Refusal {
303 pub fn new(kind: RefusalKind, reason: impl Into<String>) -> Self {
304 Self {
305 kind,
306 reason: reason.into(),
307 }
308 }
309}
310
311impl fmt::Display for Refusal {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 f.write_str(&self.reason)
314 }
315}
316
317impl std::error::Error for Refusal {}
318
319#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
322pub struct Snapshot {
323 pub id: u64,
325 pub scope: ScopeId,
326 pub name: String,
327 pub step: u64,
329 pub origin: Origin,
331 #[serde(default)]
333 pub at: f64,
334 #[serde(default)]
338 pub pending: bool,
339}
340
341#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
345pub struct Replaced {
346 pub step: StepInfo,
347 pub after: u64,
350}
351
352#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
356pub enum At {
357 Step(u64),
358 Snapshot(u64),
359}
360
361#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
366pub struct Preview {
367 #[serde(default)]
369 pub shown: bool,
370 #[serde(default, skip_serializing_if = "Vec::is_empty")]
372 pub changes: Vec<PreviewChange>,
373}
374
375#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
377pub struct PreviewChange {
378 pub what: String,
380 pub then: String,
382 pub now: String,
384}
385
386#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
389#[non_exhaustive]
390pub struct Features {
391 pub snapshots: bool,
393 pub undo_step: bool,
395}
396
397impl Features {
398 pub fn all() -> Self {
400 Self {
401 snapshots: true,
402 undo_step: true,
403 }
404 }
405}
406
407pub fn may_undo_out_of_order<'a, T: PartialEq + 'a, S>(
412 undo: &'a [S],
413 step: usize,
414 targets_of: impl Fn(&'a S) -> Vec<&'a T>,
415) -> Result<(), (usize, &'a T)> {
416 let Some(s) = undo.get(step) else {
417 return Ok(());
418 };
419 let mine = targets_of(s);
420 for (i, later) in undo.iter().enumerate().skip(step + 1) {
421 if let Some(t) = targets_of(later).into_iter().find(|t| mine.contains(t)) {
422 return Err((i, t));
423 }
424 }
425 Ok(())
426}
427
428#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
431pub struct MergeMark {
432 pub key: String,
433 pub origin: Origin,
434 pub at: f64,
435}
436
437impl MergeMark {
438 pub fn new(key: &str, origin: Origin, at: f64) -> Self {
439 Self {
440 key: key.into(),
441 origin,
442 at,
443 }
444 }
445}
446
447pub fn merges(prev: &MergeMark, next: &MergeMark) -> bool {
451 let gap = next.at - prev.at;
452 prev.key == next.key && prev.origin == next.origin && (0.0..MERGE_WINDOW).contains(&gap)
453}
454
455pub fn newest<'a>(lines: impl IntoIterator<Item = &'a Line>) -> Option<&'a ScopeId> {
459 lines
460 .into_iter()
461 .filter_map(Line::head)
462 .filter(|s| !s.in_progress)
463 .fold(None::<&StepInfo>, |best, s| match best {
464 Some(b) if (b.at, b.id) > (s.at, s.id) => Some(b),
465 _ => Some(s),
466 })
467 .map(|s| &s.scope)
468}
469
470#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
472pub struct Jump {
473 pub redo: bool,
475 pub count: usize,
477}
478
479pub fn plan_jump(line: &Line, to: u64) -> Result<Jump, Refusal> {
482 if to == 0 {
483 return Ok(Jump {
484 redo: false,
485 count: line.undo.len(),
486 });
487 }
488 if let Some(i) = line.undo.iter().position(|s| s.id == to) {
489 return Ok(Jump {
490 redo: false,
491 count: line.undo.len() - 1 - i,
492 });
493 }
494 if let Some(i) = line.redo.iter().position(|s| s.id == to) {
495 return Ok(Jump {
496 redo: true,
497 count: line.redo.len() - i,
498 });
499 }
500 Err(Refusal::new(
501 RefusalKind::Nothing,
502 format!("no step {to} in `{}`", scope_of(line)),
503 ))
504}
505
506fn scope_of(line: &Line) -> String {
507 line.undo
508 .first()
509 .or(line.redo.first())
510 .map_or_else(String::new, |s| s.scope.to_string())
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[test]
518 fn a_snapshot_from_an_older_owner_is_not_pending() {
519 let mut snap = Snapshot {
520 id: 1,
521 scope: ScopeId::from_static("app"),
522 name: "Before".into(),
523 step: 2,
524 origin: crate::commands::Origin::User,
525 at: 0.0,
526 pending: true,
527 };
528 let back: Snapshot = serde_json::from_value(serde_json::to_value(&snap).unwrap()).unwrap();
529 assert_eq!(back, snap);
530 let mut old = serde_json::to_value(&snap).unwrap();
532 old.as_object_mut().unwrap().remove("pending");
533 snap.pending = false;
534 assert_eq!(serde_json::from_value::<Snapshot>(old).unwrap(), snap);
535 }
536
537 fn step(id: u64, scope: &'static str, at: f64) -> StepInfo {
538 let mut s = StepInfo::new(
539 id,
540 ScopeId::from_static(scope),
541 Label::text("x"),
542 Origin::User,
543 );
544 s.at = at;
545 s
546 }
547
548 #[test]
549 fn repeats_merge_within_the_window_on_one_key_and_origin() {
550 let a = MergeMark::new("k", Origin::User, 5.0);
551 assert!(merges(&a, &MergeMark::new("k", Origin::User, 5.99)));
552 assert!(!merges(&a, &MergeMark::new("k", Origin::User, 6.0)));
553 assert!(!merges(&a, &MergeMark::new("other", Origin::User, 5.1)));
554 assert!(!merges(
555 &a,
556 &MergeMark::new("k", Origin::Agent("a".into()), 5.1)
557 ));
558 assert!(!merges(&a, &MergeMark::new("k", Origin::User, 4.0)));
560 }
561
562 #[test]
563 fn the_newest_head_among_active_scopes_wins() {
564 let a = Line {
565 undo: vec![step(1, "a", 1.0), step(4, "a", 3.0)],
566 ..Line::default()
567 };
568 let b = Line {
569 undo: vec![step(2, "b", 2.0)],
570 ..Line::default()
571 };
572 assert_eq!(newest([&a, &b]).unwrap().as_str(), "a");
573 let c = Line {
574 undo: vec![step(5, "c", 3.0)],
575 ..Line::default()
576 };
577 assert_eq!(newest([&a, &b, &c]).unwrap().as_str(), "c");
579 let mut d = step(9, "d", 9.0);
581 d.in_progress = true;
582 let d = Line {
583 undo: vec![d],
584 ..Line::default()
585 };
586 assert_eq!(newest([&a, &d]).unwrap().as_str(), "a");
587 assert_eq!(newest([&Line::default()]), None);
588 }
589
590 #[test]
591 fn a_jump_is_undos_or_redos_to_the_step() {
592 let line = Line {
593 undo: vec![step(1, "a", 0.0), step(2, "a", 0.0), step(3, "a", 0.0)],
594 redo: vec![step(5, "a", 0.0), step(4, "a", 0.0)],
595 rev: 7,
596 };
597 assert_eq!(
598 plan_jump(&line, 3).unwrap(),
599 Jump {
600 redo: false,
601 count: 0
602 }
603 );
604 assert_eq!(
605 plan_jump(&line, 1).unwrap(),
606 Jump {
607 redo: false,
608 count: 2
609 }
610 );
611 assert_eq!(
612 plan_jump(&line, 0).unwrap(),
613 Jump {
614 redo: false,
615 count: 3
616 }
617 );
618 assert_eq!(
619 plan_jump(&line, 4).unwrap(),
620 Jump {
621 redo: true,
622 count: 1
623 }
624 );
625 assert_eq!(
626 plan_jump(&line, 5).unwrap(),
627 Jump {
628 redo: true,
629 count: 2
630 }
631 );
632 assert_eq!(plan_jump(&line, 9).unwrap_err().kind, RefusalKind::Nothing);
633 }
634
635 #[test]
636 fn a_request_holds_while_the_revision_does() {
637 let r = Request::new(APP).if_rev(3);
638 assert!(r.check(3).is_ok());
639 assert_eq!(r.check(4).unwrap_err().kind, RefusalKind::Stale);
640 assert!(Request::new(APP).check(9).is_ok());
641 }
642
643 #[test]
644 fn a_label_fills_its_arguments_and_keeps_its_message() {
645 let l = Label::message("exposure", "Exposure { $ev } EV", &[("ev", "+0.30")]);
646 assert_eq!(l.text, "Exposure +0.30 EV");
647 assert_eq!(l.key.as_deref(), Some("exposure"));
648 let json = serde_json::to_value(&l).unwrap();
649 assert_eq!(json["args"]["ev"], "+0.30");
650 assert_eq!(
651 serde_json::to_value(Label::text("x")).unwrap(),
652 serde_json::json!({ "text": "x" })
653 );
654 }
655
656 #[test]
657 fn one_step_is_undone_out_of_order_unless_a_later_one_shares_a_target() {
658 fn targets<'a>(s: &'a [&'static str; 2]) -> Vec<&'a &'static str> {
659 s.iter().filter(|t| !t.is_empty()).collect()
660 }
661 let steps = [["a", ""], ["b", ""], ["a", "c"]];
662 assert_eq!(may_undo_out_of_order(&steps, 0, targets), Err((2, &"a")));
663 assert_eq!(may_undo_out_of_order(&steps, 1, targets), Ok(()));
664 assert_eq!(may_undo_out_of_order(&steps, 2, targets), Ok(()));
665 }
666
667 #[test]
668 fn a_scope_is_active_while_one_of_its_targets_is_shown() {
669 let mut s = ScopeInfo::new(APP, "Application");
670 assert!(s.active::<&str>(&[]));
671 s.focus = vec!["viewer".into()];
672 assert!(!s.active(&["library"]));
673 assert!(s.active(&["library", "viewer"]));
674 }
675}