From cdbd288f3c230a049a07221793348fe48bdbf863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:40:50 -0800 Subject: [PATCH] Scripts: tracings saved without their record catch artwork added before the script reaches them A tracing saved without the record of the objects its trace made was checked against a snapshot taken when the script first got its PluginItem. A script that reached the tracing's paths first (through pathItems or the selection) and added artwork beside them had that artwork in the snapshot, so tracing again or releasing the tracing discarded it without an error. - Before each command a script runs, the run notes the id the active document gives its next object. An object the run made since then counts as added to an older tracing saved without its record. - After file.revert the note moves to the reloaded document's next id, so objects read back from the file are not counted as added. The snapshot check comes from 466debdc (Scripts: tracing refuses protected art). --- crates/engine/src/script/dom.rs | 1 + crates/engine/src/script/dom/tracing.rs | 52 +++++++++++++++++-- crates/engine/src/tests/script_dom_tracing.rs | 51 ++++++++++++++++++ 3 files changed, 99 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4e50da3b48..8bc2329a92 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -110,6 +110,7 @@ pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + tracing::before_command(h); variables::before_command(h, id) } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index a37a062849..22a1e36f1d 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -128,6 +128,10 @@ pub(super) struct State { prev: RefCell>, sources: RefCell>, descendants: RefCell>>, + /// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`]) + /// and the lowest id the run could allocate after the first note or the latest revert + /// ([`note_document`]). + marks: RefCell>, retraces: Cell, } @@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { }); } +/// Before each command a script runs: notes the active document ([`note_document`]). +pub(super) fn before_command(h: &Host) { + let s = h.session.borrow(); + if let Some(st) = s.active() { + note_document(h, st); + } +} + +/// Records the next object id when the run first notes the document `st`. A revert resets +/// the mark to the reloaded document's next object id and keeps the descendant snapshots. +/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it. +fn note_document(h: &Host, st: &crate::DocState) { + let mut marks = h.dom.tracing.marks.borrow_mut(); + match marks.get_mut(&st.uid) { + Some((reverts, _)) if *reverts == st.reverts => {} + Some((reverts, mark)) => { + *reverts = st.reverts; + *mark = st.doc.peek_next_id(); + } + None => { + marks.insert(st.uid, (st.reverts, st.doc.peek_next_id())); + } + } +} + +/// Returns the lowest id the run could allocate in document `uid` after its first note or latest +/// revert ([`note_document`]). +fn mark(h: &Host, uid: u64) -> Option { + h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark) +} + pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) @@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< /// and "Cannot edit page item" when it holds a locked object other than its source image, which /// the replacement would discard. The objects looked at are charged to the run either way. fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { - let (visited, result) = read_group(h, item, |_, group| { + let (visited, result) = read_group(h, item, |st, group| { + note_document(h, st); remember_source(h, item.doc.uid, group); - // The objects the trace made, as the tracing records them; a tracing saved without that - // record is checked against the objects it held when this run first saw it. + // A tracing with a record is checked against the objects its trace made. A tracing without + // a record is checked against its first descendant snapshot, which survives reverts. + // If the group id is below the document's mark, members at or above the mark are also added. + // A revert resets the mark to the reloaded document's next object id. let made = group.trace_made(); let descendants = h.dom.tracing.descendants.borrow(); let ids = match made { Some(_) => None, - None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?), + None => descendants.get(&(item.doc.uid, item.id.0)), + }; + let newer = match made { + Some(_) => None, + None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m), }; let source = group.children().and_then(|c| c.first()).map(|n| n.id); let mut visited = 0u64; @@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { (Some(m), _) => !m.contains(n.id), (None, Some(ids)) => !ids.contains(&n.id), (None, None) => false, - }; + } || newer.is_some_and(|m| n.id.0 >= m); // Added artwork is reported before a locked object, whichever comes first. if added { return Ok((visited, Err(HostError::Error(refusal.into())))); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..5949e019fc 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -506,6 +506,57 @@ fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() { + let base = folder("retrace-legacy-paths"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let held = members(&s, group); + // The script reaches the tracing's paths before the tracing itself. + let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);"; + let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0))); + assert_eq!(out, [json!(ADDED_ARTWORK)]); + assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() { + let base = folder("retrace-legacy-revert"); + let path = base.join("main/legacy.vectorcraft"); + for seen_first in [false, true] { + for added in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = members(&s, group); + s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap(); + let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" }; + let add = if added { + format!( + "var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';", + json!(path.to_string_lossy()) + ) + } else { + String::new() + }; + let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0))); + // A revert keeps the snapshot taken before it. + let message = if added || seen_first { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn engine_trace_can_be_retraced_by_a_script() { let base = folder("retrace-engine-artwork");