From 4edede500d116d6ce894d77bee26c63bf2384089 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:07:40 -0800 Subject: [PATCH] Scripts: retracing refuses added artwork; PlacedItem.file resolves linked paths - Retracing a tracing that holds artwork added after the trace throws before the document changes; the retrace limit counts retraces, not mappings. - Image Trace warnings from trace and option changes go to the console. - PlacedItem.file resolves the link against the document's folder. - saveAs picks the format from the name it was given before resolving aliases. - controlBounds includes handles inside blends, envelopes and other containers. --- crates/engine/src/cmd/links.rs | 4 + crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/images.rs | 9 +- crates/engine/src/script/dom/save_open.rs | 2 + crates/engine/src/script/dom/tracing.rs | 34 ++++- crates/engine/src/tests/script_dom.rs | 26 ++++ crates/engine/src/tests/script_dom_images.rs | 30 ++++ crates/engine/src/tests/script_dom_tracing.rs | 135 ++++++++++++++++++ crates/engine/src/tests/script_save_open.rs | 19 +++ 9 files changed, 258 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 65f268f2b0..406a41c971 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -415,6 +415,10 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option { Some(f) } +pub(crate) fn located_path(link: &LinkInfo, base: LinkBase) -> Option { + locate(link, base).map(|f| f.path) +} + /// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`] /// finds each linked image's and placed document's file from `base` and from no document (as /// output reads them, [`full_linked_images`]), the plate files of their own of images placed from diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6ba1934af1..83b23c6fa2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2388,16 +2388,12 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { } /// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown -/// paths in a group or compound path (a clip group's from its clipping path). `None` for other -/// objects. +/// paths in its children (a clip group's from its clipping path). fn handle_bounds(n: &crate::doc::Node) -> Option { match &n.kind { NodeKind::Path { path, .. } => path.control_bounds(), NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), - NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { - children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b)) - } - _ => None, + _ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))), } } diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index d3d8c997b4..1fe29e4314 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -358,7 +358,14 @@ fn placed_file(h: &Host, a: &[Data]) -> Answer { return Ok(Data::Null); } } - let path = read_image(h, a, "PlacedItem", |_, _, im| Ok(text(im.link.as_ref().map(|l| l.path.clone()).unwrap_or_default())))?; + let path = read_image(h, a, "PlacedItem", |st, _, im| { + let path = im.link.as_ref().and_then(|link| { + let base = crate::cmd::links::LinkBase::of(st); + crate::cmd::links::located_path(link, base).or_else(|| crate::cmd::fileio::document_path(&link.path, base.doc).ok()) + }); + let path = path.ok_or_else(|| HostError::Error(super::super::files::ACCESS_DENIED.into()))?; + Ok(text(path)) + })?; let Data::String(path) = path else { return Ok(Data::Null) }; if !may_read(h, &path) { return Err(HostError::Error(super::super::files::ACCESS_DENIED.into())); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f8c0cb5d16..26df5be327 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -665,6 +665,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } else if !q.is_empty() { p.insert("options".into(), Value::Object(q)); } + } else if let Some(format) = crate::cmd::fileio::format_for_name(path) { + p.insert("format".into(), json!(format.id)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; if given_options.is_none() && extension.as_deref().is_some_and(|e| !e.is_empty()) && crate::cmd::fileio::format_for_name(path).is_none() { diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index e2c3708000..fd1783c6c8 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -34,7 +34,7 @@ //! the saved presets, so any other name throws. A preset name has at most [`MAX_PRESET_NAME`] //! bytes and none of `/`, `\`, `:` or control characters. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -116,6 +116,8 @@ const NOT_IMPLEMENTED: &[&str] = &[ pub(super) struct State { next: RefCell>, sources: RefCell>, + descendants: RefCell>>, + retraces: Cell, } /// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put @@ -150,6 +152,15 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { if let Some(source) = group.children().and_then(|c| c.first()) { h.dom.tracing.sources.borrow_mut().entry((uid, group.id.0)).or_insert(source.id); } + h.dom.tracing.descendants.borrow_mut().entry((uid, group.id.0)).or_insert_with(|| { + let mut ids = HashSet::new(); + group.walk(&mut |n| { + if n.id != group.id { + ids.insert(n.id); + } + }); + ids + }); } pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { @@ -242,6 +253,9 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< let mut before = with_doc(h, item.doc, |_, st| st.selection.clone()); on_doc(h, item.doc.uid, false, |h| { let (_, r) = command_value(h, id, params)?; + for w in r.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{id}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?; let remap = |i: NodeId| if i == item.id { new } else { i }; before.objects = before.objects.into_iter().map(remap).collect(); @@ -265,11 +279,27 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< /// Traces the Image Trace object of `item` again with `params` (`id` is added) and makes its /// script objects follow the new one. fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), HostError> { - if h.dom.tracing.next.borrow().len() >= MAX_RETRACES { + if h.dom.tracing.retraces.get() >= MAX_RETRACES { return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); } + read_group(h, item, |_, group| { + 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)?; + let mut added = false; + group.walk(&mut |n| added |= n.id != group.id && !ids.contains(&n.id)); + if added { + return Err(HostError::Error("Cannot retrace a tracing containing added artwork".into())); + } + Ok(()) + })?; params.insert("id".into(), json!(item.id.0)); let new = replace(h, item, "imageTrace.make", &Value::Object(params), "id")?; + read_group(h, Item { id: new, ..item }, |_, group| { + remember_source(h, item.doc.uid, group); + Ok(()) + })?; + h.dom.tracing.retraces.set(h.dom.tracing.retraces.get() + 1); replaced(h, item.doc.uid, item.id, new); Ok(()) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index dd10c77ad6..1d64aebc86 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -148,6 +148,32 @@ fn page_item_control_bounds_take_in_the_handles() { assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}"); } +#[test] +fn control_bounds_include_handles_inside_live_containers() { + for command in ["object.blend.make", "object.envelope.makeWithMesh", "object.repeat.grid", "object.intertwine.make"] { + let (mut s, _, _) = doc(); + let path = s + .execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})) + .unwrap()["id"] + .as_u64() + .unwrap(); + let other = rect(&mut s, 210.0, 10.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [path, other.0]})).unwrap(); + let params = match command { + "object.blend.make" => json!({"steps": 2}), + "object.envelope.makeWithMesh" | "object.repeat.grid" => json!({"rows": 1, "cols": 1}), + _ => json!({}), + }; + s.execute(command, ¶ms).unwrap(); + let out = log( + &mut s, + "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.selection[0];\ + vc.log(p.controlBounds[1] < p.visibleBounds[1]);", + ); + assert_eq!(out, [json!(true)], "{command}"); + } +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 6628e48bdc..2e7e23044a 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -485,6 +485,36 @@ fn image_file_getter_hides_out_of_scope_link() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_file_getter_resolves_document_relative_and_fallback_paths() { + let base = folder("resolved-file"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + for (stored, relative) in [ + ("a.png".to_string(), None), + (base.join("missing/a.png").to_string_lossy().into_owned(), None), + (base.join("missing/old.png").to_string_lossy().into_owned(), Some("a.png".to_string())), + ] { + let mut s = session(); + let image = place(&mut s, &png, true); + s.doc_mut().unwrap().path = Some(base.join("main/page.vectorcraft").to_string_lossy().into_owned()); + if relative.is_some() { + s.doc_mut().unwrap().path = Some(base.join("main/saved/page.vectorcraft").to_string_lossy().into_owned()); + s.doc_mut().unwrap().links_from = Some(base.join("main/original.vectorcraft").to_string_lossy().into_owned()); + } + s.edit("Set linked path", |d, _| { + let NodeKind::Image(im) = &mut d.node_mut(image).unwrap().kind else { panic!("not an image") }; + im.link.as_mut().unwrap().path = stored.clone(); + im.link.as_mut().unwrap().relative = relative.clone(); + Ok(()) + }) + .unwrap(); + let out = log(&mut s, &base, &format!("vc.log(app.activeDocument.placedItems[0].file.fsName === new File('{}').fsName);", js_path(&png))); + assert_eq!(out, [json!(true)], "{stored}"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() { let base = folder("hidedoc"); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 523c70e5b2..aa43c63696 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -292,6 +292,141 @@ fn tracing_replacements_refuse_protected_artwork() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn retrace_refuses_added_artwork_before_changing_the_document() { + let base = folder("retrace-added-artwork"); + for artwork in [ + "r.move(p, ElementPlacement.PLACEATEND);", + "r.duplicate(p, ElementPlacement.PLACEATEND);", + "d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ] { + for action in ["o.threshold = 90;", "o.loadFromPreset('Silhouettes');"] { + let (mut s, _) = session(&base, false); + s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap(); + let setup = format!("var d = app.activeDocument, r = d.rasterItems[0], p = d.rasterItems[1].trace(); {artwork}"); + let mut expected = Session::new(); + expected.docs = s.docs.clone(); + expected.active = s.active; + log(&mut expected, &base, &setup); + let before = vectorcraft_format::save(&expected.active().unwrap().doc, false); + let selection = expected.active().unwrap().selection.clone(); + let steps = undo_steps(&expected); + let out = log( + &mut s, + &base, + &format!( + "{setup} var items = app.activeDocument.pageItems;\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + var o = p.tracing.tracingOptions, m = '';\ + try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);" + ), + ); + assert_eq!(out, [json!("Cannot retrace a tracing containing added artwork")], "{artwork} {action}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(s.active().unwrap().selection, selection); + assert_eq!(undo_steps(&s), steps); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn copied_traces_remap_child_records_without_accepting_added_artwork() { + let base = folder("retrace-copied-artwork"); + for (added, retraced) in [(false, false), (true, false), (false, true), (true, true)] { + let (mut s, _) = session(&base, false); + let retrace = if retraced { "o.threshold = 100;" } else { "" }; + let artwork = if added { "d.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" }; + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.rasterItems[0].trace(), copy = p.duplicate(), o = copy.tracing.tracingOptions;\ + {retrace} {artwork}\ + var m = ''; try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(copy.isTracing); vc.log(o.threshold);" + ), + ); + let message = if added { "Cannot retrace a tracing containing added artwork" } else { "" }; + assert_eq!(out[..2], [json!(message), json!(true)], "added: {added}, retraced: {retraced}"); + if !added { + assert_eq!(out[2], json!(90)); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn engine_trace_can_be_retraced_by_a_script() { + let base = folder("retrace-engine-artwork"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap(); + let group = NodeId(made["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.pageItems[0], o = p.tracing.tracingOptions;\ + o.threshold = 90; vc.log(o.threshold); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(90), json!(true)]); + let groups = traces(&s); + assert_eq!(groups.len(), 1); + assert_ne!(groups[0], group); + assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90)); + assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0])); + assert_eq!(undo_steps(&s), steps + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn retrace_limit_counts_retraces_of_an_undone_group() { + let base = folder("retrace-limit-undo"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions, count = 0, m = '';\ + try { for (; count < 10001; count++) { o.threshold = 90; app.undo(); } } catch (e) { m = e.message; }\ + vc.log(count); vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!(10000), json!("a run traces a tracing again at most 10000 times"), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn trace_and_option_changes_log_command_warnings() { + let base = folder("trace-warnings"); + let (mut s, _) = session(&base, false); + let png = base.join("main/wide.png"); + std::fs::write(&png, vectorcraft_trace::Raster::from_fn(1501, 2, |_, _| [0, 0, 0, 255]).encode_png()).unwrap(); + let placed = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap(); + let image = placed["ids"][0].as_u64().unwrap(); + let made = s.execute("imageTrace.make", &json!({"id": image})).unwrap(); + let warnings = made["warnings"].as_array().unwrap().clone(); + assert!(!warnings.is_empty()); + s.execute("imageTrace.release", &json!({"id": made["id"]})).unwrap(); + let report = run(&mut s, &base, "var p = app.activeDocument.rasterItems[0].trace(); p.tracing.tracingOptions.threshold = 90;").unwrap(); + let lines = report["console"]["lines"].as_array().unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(lines, &expected.iter().chain(&expected).cloned().collect::>()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn option_changes_log_why_no_paths_were_traced() { + let base = folder("trace-no-paths-warning"); + let (mut s, image) = session(&base, false); + let made = s.execute("imageTrace.make", &json!({"id": image.0, "params": {"keepColors": ["#ff00ff"]}})).unwrap(); + assert_eq!(made["paths"], json!(0)); + let warnings = made["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nothing was traced"))); + let report = run(&mut s, &base, "app.activeDocument.pageItems[0].tracing.tracingOptions.threshold = 90;").unwrap(); + let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect(); + assert_eq!(report["console"]["lines"], json!(expected)); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn tracing_parent_keeps_plugin_identity_after_retracing() { let base = folder("parent-identity"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index bee1b78188..39647ff587 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -46,6 +46,25 @@ fn data_folder(s: &mut Session, base: &Path) -> PathBuf { PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) } +#[cfg(unix)] +#[test] +fn save_as_uses_the_supplied_alias_extension() { + let base = folder("save-alias-format"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let target = dir.join("output.vectorcraft"); + let alias = dir.join("output.svg"); + std::fs::write(&target, "before").unwrap(); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias))); + let svg = std::fs::read_to_string(&target).unwrap(); + assert!(svg.contains(" String { serde_json::to_string(&p.to_string_lossy()).unwrap() }