diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index 7c96cc6104..77b9a4c747 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -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 } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 6a331c6b77..cb8f077dae 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -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; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index a39260ee91..c83f43fe56 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -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] diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index a2d17cc990..69bc50b5d0 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -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) -> Self { + let mut ids: Vec = 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 { + 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 { + 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![]); diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 5d27feacd9..ff99c44bb2 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -1234,6 +1234,10 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result) -> 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(()) })?; diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index d9aebe728f..6b891aadc0 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -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 { + 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"); diff --git a/docs/mcp.md b/docs/mcp.md index e1cee3b3ae..4e37a4d5de 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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