Scripts: retrace refuses a tracing that holds artwork its trace did not make

imageTrace.make records the ids of the objects it made in the tracing's
trace settings as `made`, and copying the tracing records the ids of their
copies. Tracing again through the scripting API throws, with nothing
changed, when the tracing holds any other object, whether it was added in
this run, an earlier run or by a command. A tracing saved without `made`
is checked only for objects added in the same run, as before.
This commit is contained in:
dotCooCoo committed 2026-11-30 17:54:54 -08:00
1 parent 374b31b6f6
commit 795bef8b29
8 files changed
+284 -6

No files matched your search

+10
View File
@@ -757,6 +757,16 @@ impl Document {
{
on_path.rename(&renamed);
}
// An Image Trace object names the objects its trace made by id: the copy names the copies of
// those objects, and no other object.
if let Some(made) = node.trace_made() {
let mut old = vec![];
node.walk(&mut |d| old.push(d.id));
let mut new = vec![];
n.walk(&mut |d| new.push(d.id));
let copies = old.into_iter().zip(new).skip(1).filter(|(o, _)| made.contains(*o)).map(|(_, c)| c);
n.set_trace_made(&crate::TraceMade::of(copies));
}
n
}
}
+1 -1
View File
@@ -142,7 +142,7 @@ pub use text::{
TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
};
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
pub use trace::TraceView;
pub use trace::{TraceMade, TraceView};
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
pub use vectorcraft_color as color;
pub use vectorcraft_geom as geom;
+22
View File
@@ -822,6 +822,28 @@ fn reid_gives_fresh_ids() {
assert!(!ids.contains(&a) && !ids.contains(&b));
}
/// A copy of an Image Trace object records the copies of the objects its trace made, nested ones
/// included, and not the copy of an object added to it later.
#[test]
fn reid_remaps_what_a_tracing_records_it_made() {
let (mut d, a, b) = doc_with_rects();
let na = (*d.remove(a).unwrap()).clone();
let nb = (*d.remove(b).unwrap()).clone();
let inner = d.alloc_id();
let inner = Node::group(inner, vec![Arc::new(na)]);
let mut tracing = Node::group(d.alloc_id(), vec![Arc::new(inner.clone()), Arc::new(nb)]);
tracing.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
tracing.set_trace_made(&crate::TraceMade::of([inner.id, a]));
let copy = d.reid(&tracing);
let made = copy.trace_made().unwrap();
let ch = copy.children().unwrap();
let (inner_copy, added_copy) = (&ch[0], &ch[1]);
let a_copy = inner_copy.children().unwrap()[0].id;
assert!(made.contains(inner_copy.id) && made.contains(a_copy));
assert!(!made.contains(added_copy.id) && !made.contains(inner.id) && !made.contains(a) && !made.contains(b));
assert_eq!(made, crate::TraceMade::of([inner_copy.id, a_copy]));
}
/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
/// another document with the same id does not.
#[test]
+103 -2
View File
@@ -1,11 +1,64 @@
//! Image Trace objects' View: how a live trace draws on screen.
//!
//! An Image Trace object is a group whose `trace` holds `{preset, params, view}` (see
//! An Image Trace object is a group whose `trace` holds `{preset, params, view, made}` (see
//! `imageTrace.make`). The view is a viewing aid only: exports, printing and Expand always use the
//! tracing result, whatever it is set to.
//! tracing result, whatever it is set to. `made` names the objects the trace made ([`TraceMade`]).
use crate::NodeId;
use crate::node::Node;
/// The key of an Image Trace object's `trace` settings that names the objects its trace made.
pub const TRACE_MADE: &str = "made";
/// The objects the trace of an Image Trace object made, by id: the ranges `[first, last]` of their
/// ids, ascending and apart. A trace gives out its ids one after the other, so a trace of any size
/// is a few ranges.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TraceMade(Vec<(u64, u64)>);
impl TraceMade {
/// The objects `ids` name.
pub fn of(ids: impl IntoIterator<Item = NodeId>) -> Self {
let mut ids: Vec<u64> = ids.into_iter().map(|i| i.0).collect();
ids.sort_unstable();
ids.dedup();
let mut ranges: Vec<(u64, u64)> = vec![];
for id in ids {
match ranges.last_mut() {
Some((_, last)) if last.checked_add(1) == Some(id) => *last = id,
_ => ranges.push((id, id)),
}
}
Self(ranges)
}
/// Whether the trace made the object `id`.
pub fn contains(&self, id: NodeId) -> bool {
let i = self.0.partition_point(|(_, last)| *last < id.0);
self.0.get(i).is_some_and(|(first, _)| *first <= id.0)
}
/// The ranges as the `trace` settings save them: `[[first, last], ...]`.
pub fn to_json(&self) -> serde_json::Value {
serde_json::Value::Array(self.0.iter().map(|(a, b)| serde_json::json!([a, b])).collect())
}
/// The ranges `v` saves, or `None` when it is not a list of `[first, last]` pairs of whole
/// numbers, ascending and apart.
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
let mut ranges: Vec<(u64, u64)> = vec![];
for r in v.as_array()? {
let [a, b] = r.as_array()?.as_slice() else { return None };
let (a, b) = (a.as_u64()?, b.as_u64()?);
if a > b || ranges.last().is_some_and(|(_, last)| *last >= a) {
return None;
}
ranges.push((a, b));
}
Some(Self(ranges))
}
}
/// Image Trace › View.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TraceView {
@@ -90,6 +143,21 @@ impl Node {
pub fn trace_split(&self) -> f64 {
self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of)
}
/// The objects the trace of this Image Trace object made ([`TRACE_MADE`]), or `None` when its
/// `trace` settings name none, as in a tracing saved before they did, or name them in any other
/// form than [`TraceMade::to_json`]'s.
pub fn trace_made(&self) -> Option<TraceMade> {
self.extras().trace.as_deref().and_then(|t| t.get(TRACE_MADE)).and_then(TraceMade::from_json)
}
/// Records `made` as the objects the trace of this Image Trace object made, when its `trace`
/// settings are an object.
pub fn set_trace_made(&mut self, made: &TraceMade) {
if let Some(t) = self.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(serde_json::Value::as_object_mut) {
t.insert(TRACE_MADE.into(), made.to_json());
}
}
}
#[cfg(test)]
@@ -111,6 +179,39 @@ mod tests {
assert_eq!(g.trace_view(), TraceView::Result);
}
#[test]
fn trace_made_keeps_ranges_and_reads_only_well_formed_ones() {
let ids = [7, 3, 4, 5, 9, 3, u64::MAX].map(crate::NodeId);
let made = TraceMade::of(ids);
assert_eq!(made.to_json(), serde_json::json!([[3, 5], [7, 7], [9, 9], [u64::MAX, u64::MAX]]));
for id in 0..12 {
assert_eq!(made.contains(crate::NodeId(id)), ids.contains(&crate::NodeId(id)), "{id}");
}
assert!(made.contains(crate::NodeId(u64::MAX)));
assert_eq!(TraceMade::from_json(&made.to_json()), Some(made.clone()));
assert_eq!(TraceMade::from_json(&serde_json::json!([])), Some(TraceMade::default()));
for bad in [
serde_json::json!({}),
serde_json::json!([[5, 3]]),
serde_json::json!([[1, 4], [4, 6]]),
serde_json::json!([[6, 7], [1, 2]]),
serde_json::json!([[1]]),
serde_json::json!([[1, 2, 3]]),
serde_json::json!([[-1, 2]]),
serde_json::json!([[1.5, 2]]),
serde_json::json!(["1", "2"]),
] {
assert_eq!(TraceMade::from_json(&bad), None, "{bad}");
}
let mut g = Node::group(crate::NodeId(1), vec![]);
g.set_trace_made(&made);
assert_eq!(g.trace_made(), None, "a group with no trace settings records nothing");
g.extras_mut().trace = Some(Box::new(serde_json::json!({"preset": "Default"})));
assert_eq!(g.trace_made(), None);
g.set_trace_made(&made);
assert_eq!(g.trace_made(), Some(made));
}
#[test]
fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() {
let mut g = Node::group(crate::NodeId(1), vec![]);
+4
View File
@@ -1234,6 +1234,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
t["split"] = split.clone();
}
g.extras_mut().trace = Some(Box::new(t));
// Records the objects this trace made: every object in the tracing.
let mut made = vec![];
g.walk(&mut |n| made.push(n.id));
g.set_trace_made(&vectorcraft_doc::TraceMade::of(made.into_iter().filter(|i| *i != gid)));
}
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
d.remove(target)?;
+13 -2
View File
@@ -24,6 +24,10 @@
//! so. Tracing again makes a new object: the `PluginItem`, its `TracingObject` and its
//! `TracingOptions` follow it. A tracing that another command traced again, expanded or
//! released, or whose source image was deleted, is stale.
//! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object
//! its trace did not make, whether this run, an earlier run or a command added it. The tracing records the
//! objects its trace made ([`crate::doc::TraceMade`]), and a copy of it records their copies. A
//! tracing saved without that record is checked only for objects added in this run.
//! - `palette` is `""` for the automatic palette, or `"Limited"`, `"Full Tone"` or
//! `"Document Library"`. `minArea` is the Noise setting in pixels: an area smaller than it is not
//! traced. `tracingMode` has no value for the Flat Logo mode. The options with no VectorCraft
@@ -50,6 +54,8 @@ use crate::{NodeId, NodeKind};
/// The error of `trace()` on an image that is the source of a tracing.
pub const ALREADY_TRACED: &str = "The image is the source art of a tracing";
/// The error of tracing again a tracing that holds an object its trace did not make.
pub const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork";
/// The error of options that trace with neither fills nor strokes.
pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes";
/// The error of `expandTracing(true)`.
@@ -286,10 +292,15 @@ fn retrace(h: &Host, item: Item, mut params: Map<String, Value>) -> Result<(), H
remember_source(h, item.doc.uid, group);
let descendants = h.dom.tracing.descendants.borrow();
let ids = descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?;
// 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.
let made = group.trace_made();
let mut added = false;
group.walk(&mut |n| added |= n.id != group.id && !ids.contains(&n.id));
group.walk(&mut |n| {
added |= n.id != group.id && made.as_ref().map_or(!ids.contains(&n.id), |m| !m.contains(n.id));
});
if added {
return Err(HostError::Error("Cannot retrace a tracing containing added artwork".into()));
return Err(HostError::Error(ADDED_ARTWORK.into()));
}
Ok(())
})?;
@@ -380,6 +380,132 @@ fn copied_traces_remap_child_records_without_accepting_added_artwork() {
let _ = std::fs::remove_dir_all(base);
}
/// The objects in the object `id` of the active document, without it, in order.
fn members(s: &Session, id: NodeId) -> Vec<NodeId> {
let mut out = vec![];
if let Some(n) = s.active().unwrap().doc.node(id) {
n.walk(&mut |m| {
if m.id != id {
out.push(m.id);
}
});
}
out
}
/// A new session with the active document of `s`, saved and opened again.
fn reopened(s: &Session) -> Session {
let bytes = vectorcraft_format::save(&s.active().unwrap().doc, false);
let mut o = Session::new();
o.execute("document.open", &json!({"name": "traced.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
o
}
/// Traces the Image Trace object `index` of the active document's page items again with a
/// threshold of 90, and logs the error, or `""`.
fn retrace_item(index: usize) -> String {
format!(
"(function () {{ var items = app.activeDocument.pageItems, found = [];\
for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') found.push(items[i]);\
var o = found[{index}].tracing.tracingOptions, m = '';\
try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }} vc.log(m); }})();"
)
}
const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork";
#[test]
fn retrace_refuses_artwork_added_before_the_run() {
let base = folder("retrace-earlier-artwork");
for by_command in [false, true] {
for reopen in [false, true] {
let (mut s, image) = session(&base, false);
let trace = if by_command {
s.execute("imageTrace.make", &json!({"id": image.0})).unwrap();
"var p = app.activeDocument.pageItems[0];"
} else {
"var p = app.activeDocument.rasterItems[0].trace();"
};
log(&mut s, &base, &format!("{trace} app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);"));
let mut s = if reopen { reopened(&s) } else { s };
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
let steps = undo_steps(&s);
let out = log(&mut s, &base, &retrace_item(0));
assert_eq!(out, [json!(ADDED_ARTWORK)], "by command: {by_command}, reopened: {reopen}");
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "by command: {by_command}, reopened: {reopen}");
assert_eq!(undo_steps(&s), steps);
}
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn retrace_takes_a_tracing_whose_traced_objects_were_edited() {
let base = folder("retrace-edited-artwork");
for reopen 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 made = s.active().unwrap().doc.node(group).and_then(|g| g.trace_made()).expect("the trace records what it made");
let held = members(&s, group);
assert!(held.len() > 1 && held.iter().all(|m| made.contains(*m)), "{held:?} {made:?}");
assert!(!made.contains(group));
let path = held[held.len() - 1];
s.execute("object.move", &json!({"ids": [path.0], "dx": 5, "dy": 0})).unwrap();
let mut s = if reopen { reopened(&s) } else { s };
let out = log(&mut s, &base, &format!("{} vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.threshold);", retrace_item(0)));
assert_eq!(out, [json!(""), json!(90)], "reopened: {reopen}");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_copied_tracing_retraces_in_a_later_run() {
let base = folder("retrace-copy-later");
for added in [false, true] {
for reopen in [false, true] {
let (mut s, _) = session(&base, false);
let artwork = if added { "app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" };
log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(), copy = p.duplicate(); {artwork}"));
let groups = traces(&s);
assert_eq!(groups.len(), 2);
let records: Vec<_> = groups.iter().map(|g| s.active().unwrap().doc.node(*g).and_then(|n| n.trace_made()).unwrap()).collect();
for (k, g) in groups.iter().enumerate() {
assert!(members(&s, *g).iter().all(|m| !records[1 - k].contains(*m)), "a tracing records none of the other's objects");
}
let mut s = if reopen { reopened(&s) } else { s };
let out = log(&mut s, &base, &format!("{} {}", retrace_item(0), retrace_item(1)));
let message = if added { ADDED_ARTWORK } else { "" };
assert_eq!(out, [json!(message), json!("")], "added: {added}, reopened: {reopen}");
}
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() {
let base = folder("retrace-legacy");
for same_run 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);
let add = "var r = app.activeDocument.pathItems.rectangle(20, 20, 10, 10); r.name = 'added'; r.move(app.activeDocument.pageItems[1], ElementPlacement.PLACEATEND);";
let out = if same_run {
log(&mut s, &base, &format!("{add} {}", retrace_item(0)))
} else {
log(&mut s, &base, add);
log(&mut s, &base, &retrace_item(0))
};
let message = if same_run { ADDED_ARTWORK } else { "" };
assert_eq!(out, [json!(message)], "same run: {same_run}");
let mut named = false;
s.active().unwrap().doc.walk(|n| named |= n.name.as_deref() == Some("added"));
assert_eq!(named, same_run, "tracing again drops what was added, as before");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn engine_trace_can_be_retraced_by_a_script() {
let base = folder("retrace-engine-artwork");
+5 -1
View File
@@ -3243,7 +3243,11 @@ through `$`:
across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the
source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or
`viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject`
and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole
and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. Tracing again throws
`Cannot retrace a tracing containing added artwork`, with nothing changed, when the tracing holds an object its trace
did not make, whether this run, an earlier run or a command added it. `imageTrace.make` records the objects it made in
the tracing's `trace` settings as `made`, ranges of ids `[[first, last], ...]`, and a copy of the tracing records
their copies. A tracing saved without `made` is checked only for objects added in the same run. `threshold` takes a whole
number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest
image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`,
`"Full Tone"` or `"Document Library"`; `viewRaster` and `viewVector` take only the pairs that match an Image Trace