Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Engine: a cancelled gesture puts back the revision it began at

aiongg6dda09539623
diff --git a/crates/engine/src/cmd/datamerge/mod.rs b/crates/engine/src/cmd/datamerge/mod.rs
index 3b3e1dd3b..474811f3a 100644
--- a/crates/engine/src/cmd/datamerge/mod.rs
+++ b/crates/engine/src/cmd/datamerge/mod.rs
@@ -197,7 +197,7 @@ fn preview_cmd(s: &mut Session, p: &Value) -> Result<Value> {
fill_row(&mut doc, &source.fields, &row, record as u32, &options, &maps, data_dir.as_deref(), doc_dir.as_deref());
st.doc = Arc::new(doc);
st.preview_record = Some(record as u32);
- st.revision = st.revision.saturating_add(1);
+ st.bump_revision();
Ok(json!({"record": record}))
}
@@ -709,7 +709,7 @@ fn remember_source_status(s: &mut Session, status: SourceStatus) {
return;
}
st.doc = Arc::new(doc);
- st.revision = st.revision.saturating_add(1);
+ st.bump_revision();
}
fn load_inline(p: &Value) -> std::result::Result<(Table, Option<PathBuf>), String> {
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index e7190acb4..b553620c7 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
st.history.redo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
st.doc = e.doc;
st.selection = e.selection;
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"undone": e.label}))
}),
cmd!(noundo "edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| {
@@ -118,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
st.history.undo.push(HistoryEntry { label: e.label.clone(), doc: st.doc.clone(), selection: st.selection.clone() });
st.doc = e.doc;
st.selection = e.selection;
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"redone": e.label}))
}),
cmd!(noundo "selection.set", "Select", [], None, "{ids: [id], add?: bool, content?: bool}", has_doc, |s, p| {
@@ -138,7 +138,7 @@ pub fn specs() -> Vec<CommandSpec> {
}
st.selection.text = None;
st.selection.cells = None;
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!(noundo "selection.toggle", "Toggle Selection", [], None, "{id}", has_doc, |s, p| {
@@ -151,7 +151,7 @@ pub fn specs() -> Vec<CommandSpec> {
} else {
st.selection.items.push(id);
}
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!(noundo "edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{} — all items on the active spreads, or all text in the story", has_doc, |s, _| {
@@ -175,13 +175,13 @@ pub fn specs() -> Vec<CommandSpec> {
}
st.selection = Selection::items(ids);
}
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!(noundo "edit.deselectAll", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", has_doc, |s, _| {
let st = s.doc_mut()?;
st.selection = Selection::default();
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{ids?} — delete selected items (or the selected text)", has_doc, |s, p| {
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 9f15727cd..6cde2d33b 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -242,7 +242,7 @@ fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
super::datamerge::refresh_relative_paths(&mut d, std::path::Path::new(&path));
if d.data_merge != st.doc.data_merge {
st.doc = Arc::new(d);
- st.revision = st.revision.saturating_add(1);
+ st.bump_revision();
}
}
let bytes = to_bytes(&st.doc);
@@ -649,7 +649,6 @@ fn file_revert(s: &mut Session, _: &Value) -> Result<Value> {
let mut fresh = DocState::new(d, Some(path.clone()));
fresh.fonts = fonts;
fresh.uid = uid;
- fresh.revision = st.revision + 1;
*st = fresh;
if let Some(dir) = &s.recovery_dir {
crate::recovery::discard(dir, uid);
diff --git a/crates/engine/src/cmd/find.rs b/crates/engine/src/cmd/find.rs
index 878160400..241feb4b6 100644
--- a/crates/engine/src/cmd/find.rs
+++ b/crates/engine/src/cmd/find.rs
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
if p.get("select").and_then(Value::as_bool).unwrap_or(true) && !ids.is_empty() {
let st = s.doc_mut()?;
st.selection = designcraft_doc::Selection::items(ids.clone());
- st.revision += 1;
+ st.bump_revision();
}
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
}),
diff --git a/crates/engine/src/cmd/interactive.rs b/crates/engine/src/cmd/interactive.rs
index 276b0211b..32562737c 100644
--- a/crates/engine/src/cmd/interactive.rs
+++ b/crates/engine/src/cmd/interactive.rs
@@ -51,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
designcraft_doc::Selection::text(designcraft_doc::TextSel { story, anchor: start, focus: end, frame, cell: None })
}
};
- st.revision += 1;
+ st.bump_revision();
Ok(Value::Null)
}),
cmd!("bookmark.rename", "Rename Bookmark", [], None, "{index, name}", has_doc, |s, p| {
diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs
index bd5320799..8ec59862c 100644
--- a/crates/engine/src/cmd/layout.rs
+++ b/crates/engine/src/cmd/layout.rs
@@ -183,7 +183,7 @@ pub fn specs() -> Vec<CommandSpec> {
let st = s.doc_mut()?;
st.editing_parents = p.get("on").and_then(Value::as_bool).unwrap_or(!st.editing_parents);
st.selection = Default::default();
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!(
@@ -448,7 +448,7 @@ pub fn specs() -> Vec<CommandSpec> {
let st = s.doc_mut()?;
let ids: Vec<_> = st.doc.spreads.iter().flat_map(|sp| sp.items.iter().filter(|i| i.layer == id && !i.locked).map(|i| i.id)).collect();
st.selection = designcraft_doc::Selection::items(ids);
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!("layer.new", "New Layer…", [], None, "{name?}", has_doc, |s, p| {
@@ -603,7 +603,7 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad("layer.activate", "no such layer"));
}
st.active_layer = id;
- st.revision += 1;
+ st.bump_revision();
ok()
}),
]
diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs
index c05c6dad9..ee906935b 100644
--- a/crates/engine/src/cmd/links.rs
+++ b/crates/engine/src/cmd/links.rs
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
return Err(bad("links.goTo", "the graphic isn't placed"));
}
st.selection = Selection::items(ids.clone());
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
}),
]
diff --git a/crates/engine/src/cmd/notes.rs b/crates/engine/src/cmd/notes.rs
index 4d7b0f13f..920410485 100644
--- a/crates/engine/src/cmd/notes.rs
+++ b/crates/engine/src/cmd/notes.rs
@@ -161,7 +161,7 @@ fn go_to_reference(s: &mut Session, _: &Value) -> Result<Value> {
let at = st.doc.story(t.story).and_then(|x| x.note_anchor(id)).ok_or_else(|| bad("footnote.goToReference", "footnote not found"))?;
let pos = at + designcraft_doc::FOOTNOTE_REF.len_utf8();
st.selection.text = Some(TextSel { anchor: pos, focus: pos, cell: None, ..t });
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"story": t.story.0, "pos": pos}))
}
diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs
index 0d09ac869..0f77d5372 100644
--- a/crates/engine/src/cmd/select.rs
+++ b/crates/engine/src/cmd/select.rs
@@ -72,7 +72,7 @@ fn select_stacked(s: &mut Session, how: Step) -> Result<Value> {
(Step::Down, Some(i)) => i.saturating_sub(1),
};
st.selection = Selection::items(vec![order[i]]);
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"id": order[i].0}))
}
@@ -90,7 +90,7 @@ fn select_container(s: &mut Session) -> Result<Value> {
} else {
return ok();
}
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"id": st.selection.items[0].0}))
}
@@ -105,7 +105,7 @@ fn select_content(s: &mut Session) -> Result<Value> {
} else {
return ok();
}
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"id": st.selection.items[0].0}))
}
@@ -125,7 +125,7 @@ fn select_sibling(s: &mut Session, dir: isize) -> Result<Value> {
let j = (i as isize - dir).rem_euclid(n) as usize;
let Some(next) = kids.get(j).map(|k| k.id) else { return ok() };
st.selection = Selection::items(vec![next]);
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"id": next.0}))
}
diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs
index 028971e97..f0cb073de 100644
--- a/crates/engine/src/cmd/table.rs
+++ b/crates/engine/src/cmd/table.rs
@@ -976,7 +976,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
text: Some(TextSel { story: g.story, anchor: 0, focus: 0, frame, cell: Some(CellAddr { table: g.table, row: r.r0, col: r.c0 }) }),
..Default::default()
};
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"story": g.story.0, "table": g.table, "range": r}))
}
@@ -1008,7 +1008,7 @@ pub(crate) fn step_cell(s: &mut Session, forward: bool) -> Result<Value> {
let st = s.doc_mut()?;
let len = st.doc.text_story(t.story, Some(CellAddr { table: c.table, row, col })).map_or(0, |x| x.len());
st.selection = Selection::text(TextSel { anchor: 0, focus: len, cell: Some(CellAddr { table: c.table, row, col }), ..t });
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"row": row, "col": col}))
}
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index 62ce87683..c7b30c1f0 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
let a = floor_char_boundary(text, p.get("anchor").and_then(Value::as_u64).unwrap_or(0) as usize);
let f = floor_char_boundary(text, p.get("focus").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(a));
st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: f, frame: None, cell: None });
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!("text.insert", "Type", [], None, "{text, raw?: bool (no typographer's quotes)} — replaces the selected text", has_text, insert),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
st.selection.items = f.into_iter().collect();
}
st.selection.cells = None;
- st.revision += 1;
+ st.bump_revision();
ok()
}),
cmd!(
@@ -342,7 +342,7 @@ fn select_at(s: &mut Session, p: &Value, unit: &str) -> Result<Value> {
s.text_drag = false;
let st = s.doc_mut()?;
st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: e, frame: Some(frame), cell });
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"story": sid.0, "anchor": a, "focus": e}))
}
@@ -408,7 +408,7 @@ fn place(s: &mut Session, p: &Value, extend: bool) -> Result<Value> {
{
let range = designcraft_doc::CellRange::new(a.row, a.col, c.row, c.col);
st.selection.cells = Some(designcraft_doc::TableSel { story: sid, table: c.table, range });
- st.revision += 1;
+ st.bump_revision();
return Ok(json!({"story": sid.0, "cells": range}));
}
let t = match (extend, st.selection.text) {
@@ -416,7 +416,7 @@ fn place(s: &mut Session, p: &Value, extend: bool) -> Result<Value> {
_ => TextSel { story: sid, anchor: b, focus: b, frame: Some(frame), cell },
};
st.selection = Selection::text(t);
- st.revision += 1;
+ st.bump_revision();
Ok(json!({"story": sid.0, "pos": b, "cell": cell}))
}
diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs
index 9a1df3eef..4e4c9c030 100644
--- a/crates/engine/src/guard.rs
+++ b/crates/engine/src/guard.rs
@@ -35,19 +35,19 @@ pub fn install_panic_hook() {
impl Session {
/// Run command `id` (`f`) inside the guard.
pub(crate) fn guarded(&mut self, id: &str, f: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
- let before = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone(), d.revision));
+ let before = self.active().map(|d| (d.uid, d.doc.clone(), d.selection.clone()));
match catch_unwind(AssertUnwindSafe(|| f(self))) {
Ok(r) => r,
Err(payload) => {
let msg = panic_message(payload.as_ref());
// Keep the document as it was before the command.
- if let (Some((uid, doc, selection, revision)), Some(st)) = (before, self.active_mut())
+ if let (Some((uid, doc, selection)), Some(st)) = (before, self.active_mut())
&& st.uid == uid
{
st.doc = doc;
st.selection = selection;
st.interaction = None;
- st.revision = revision.max(st.revision).saturating_add(1);
+ st.bump_revision();
}
if let Some(dir) = self.recovery_dir.clone()
&& let Err(e) = crate::recovery::save(self, &dir)
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index de10b0a8d..8bdd47fb4 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -74,6 +74,8 @@ pub struct Interaction {
pub doc: Arc<Document>,
pub selection: Selection,
pub preview: Option<(String, Value)>,
+ /// The document's revision when the gesture began: a cancel puts it back.
+ pub revision: u64,
}
#[derive(Clone, Debug)]
@@ -82,6 +84,8 @@ pub struct DocState {
pub selection: Selection,
pub history: History,
pub path: Option<String>,
+ /// Names the document state for caches keyed `(uid, revision)` (see
+ /// [`DocState::bump_revision`]).
pub revision: u64,
pub saved_revision: u64,
/// The document as last saved (dirty = the current document is a different allocation).
@@ -112,19 +116,25 @@ impl Drop for FontScope {
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+static NEXT_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
+fn next_revision() -> u64 {
+ NEXT_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+}
impl DocState {
pub fn new(doc: Document, path: Option<String>) -> Self {
let active_layer = doc.default_layer();
let doc = Arc::new(doc);
+ let revision = next_revision();
DocState {
saved_doc: doc.clone(),
doc,
selection: Selection::default(),
history: History { limit: 1000, ..Default::default() },
path,
- revision: 1,
- saved_revision: 1,
+ revision,
+ saved_revision: revision,
active_layer,
interaction: None,
editing_parents: false,
@@ -134,6 +144,12 @@ impl DocState {
fonts: None,
}
}
+ /// The document changed: it gets a revision no document state had before. A cancelled
+ /// gesture puts back the revision it began at, so the numbers its previews used are never
+ /// handed out again (a cache entry for one would show the cancelled preview).
+ pub fn bump_revision(&mut self) {
+ self.revision = next_revision();
+ }
pub fn is_dirty(&self) -> bool {
!Arc::ptr_eq(&self.doc, &self.saved_doc)
}
@@ -377,7 +393,7 @@ impl Session {
st.preview_record = None;
let Some(stash) = st.preview_stash.take() else { return };
st.doc = stash;
- st.revision = st.revision.saturating_add(1);
+ st.bump_revision();
}
pub fn close_document(&mut self, i: usize) {
if self.active == Some(i) {
@@ -505,7 +521,7 @@ impl Session {
}
if let Some(st) = self.active_mut() {
st.doc = Arc::new(d);
- st.revision += 1;
+ st.bump_revision();
}
}
@@ -547,7 +563,7 @@ impl Session {
doc.sync_endnote_story();
st.doc = Arc::new(doc);
st.selection = sel;
- st.revision += 1;
+ st.bump_revision();
Ok(r)
}
}
diff --git a/crates/engine/src/recovery.rs b/crates/engine/src/recovery.rs
index a038c2d27..1011e1396 100644
--- a/crates/engine/src/recovery.rs
+++ b/crates/engine/src/recovery.rs
@@ -229,7 +229,7 @@ pub fn open(s: &mut Session, dir: &Path) -> Result<Vec<usize>> {
st.fonts = fonts;
// Unsaved: the copy on disk (if any) is older than what was recovered.
st.saved_doc = std::sync::Arc::new((*st.doc).clone());
- st.revision += 1;
+ st.bump_revision();
opened.push(s.add_document(st));
discard(dir, uid);
}
diff --git a/crates/engine/src/tests_ime.rs b/crates/engine/src/tests_ime.rs
index 66a908e64..266470914 100644
--- a/crates/engine/src/tests_ime.rs
+++ b/crates/engine/src/tests_ime.rs
@@ -145,3 +145,37 @@ fn an_ime_commit_takes_the_format_chosen_at_the_caret() {
s.execute("text.select", &json!({"story": sid, "anchor": 1, "focus": 7})).unwrap();
assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], 24.0);
}
+
+#[test]
+fn a_cancelled_gesture_puts_back_the_revision_and_leaves_a_saved_document_saved() {
+ let mut s = session();
+ let v = ViewInfo::default();
+ let sid = typing_into(&mut s, "雅");
+ // As if just saved.
+ let st = s.doc_mut().unwrap();
+ st.saved_doc = st.doc.clone();
+ let before = st.revision;
+ let mut seen = vec![before];
+ // A cancelled composition…
+ for t in ["が", "がく"] {
+ s.tool_preedit(t, None, v).unwrap();
+ seen.push(s.doc().unwrap().revision);
+ }
+ s.tool_preedit("", None, v).unwrap();
+ assert_eq!(s.doc().unwrap().revision, before);
+ assert!(!s.doc().unwrap().is_dirty());
+ // …and any other cancelled gesture.
+ let preview = |t: &str| designcraft_tools::Action::Preview("text.insert".into(), json!({"text": t, "raw": true}));
+ s.run_actions(vec![designcraft_tools::Action::Begin("Type".into()), preview("x")]).unwrap();
+ seen.push(s.doc().unwrap().revision);
+ s.run_actions(vec![preview("xy"), designcraft_tools::Action::Cancel]).unwrap();
+ assert_eq!(s.doc().unwrap().revision, before);
+ assert!(!s.doc().unwrap().is_dirty());
+ assert_eq!(text(&mut s, sid), "雅");
+ // The next change gets a revision no preview had: caches keyed by revision never show a
+ // cancelled preview.
+ s.execute("text.insert", &json!({"text": "楽"})).unwrap();
+ let after = s.doc().unwrap().revision;
+ assert!(!seen.contains(&after), "{after} in {seen:?}");
+ assert!(s.doc().unwrap().is_dirty());
+}
diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs
index a294aedd4..440eee8db 100644
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@ -207,7 +207,8 @@ impl Session {
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
let st = self.doc_mut()?;
- st.interaction = Some(Interaction { label: label.into(), doc: st.doc.clone(), selection: st.selection.clone(), preview: None });
+ st.interaction =
+ Some(Interaction { label: label.into(), doc: st.doc.clone(), selection: st.selection.clone(), preview: None, revision: st.revision });
Ok(())
}
@@ -250,9 +251,10 @@ impl Session {
if let Some(st) = self.active_mut()
&& let Some(it) = st.interaction.take()
{
+ // Nothing changed: the document goes back to the state and revision it began with.
st.doc = it.doc;
st.selection = it.selection;
- st.revision += 1;
+ st.revision = it.revision;
if self.transforms.2 {
self.transforms.0.pop();
self.transforms.2 = false;