From a1b8b013832dc70f5afd547bc8fe3666443b8512 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:26:30 -0800 Subject: [PATCH] Scripts: refuse moves that make a tracing, and a release that drops added art - move, remove() and zOrder throw "Only Image Trace can make a tracing", with nothing changed, when they would leave an image at the bottom of an ordinary group named Image Trace: a path moved out of the group or to its top, Send to Back or Send Backward on the image, and Bring to Front or Bring Forward on the object below it. - releaseTracing() throws "Cannot release a tracing containing added artwork", with nothing changed, when the tracing holds an object its trace did not make. imageTrace.release keeps only the source image, so the added object would be deleted. - The TracingOptions members with no setting and TracingObject.areaCount are left out of hasOwnProperty and reflect. Reading them still throws. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 37 +++++++- crates/engine/src/script/dom/tracing.rs | 38 +++++--- crates/engine/src/tests/script_dom_tracing.rs | 92 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- docs/mcp.md | 6 +- 5 files changed, 157 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cf073482ba..998e528e26 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2696,6 +2696,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // An image left first in an ordinary group named as a tracing would make that group one. + if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; Ok(Data::Undefined) @@ -2831,6 +2835,20 @@ fn named_as_tracing(d: &Document, id: NodeId) -> bool { }) } +/// Whether taking the object `id` out of `parent` and, with `at`, putting it back at that index of +/// what is left would make `parent`, an ordinary group named as a tracing, one: an image first in it. +fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> bool { + if !named_as_tracing(d, parent) { + return false; + } + let image = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Image(_)); + let rest = d.children(Some(parent)).map(|c| c.iter().filter(|n| n.id != id).collect::>()).unwrap_or_default(); + match at { + Some(0) => d.node(id).is_some_and(|n| image(n)), + _ => rest.first().is_some_and(|n| image(n)), + } +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { @@ -2862,8 +2880,10 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul (_, None) => count, }; let at = if clips { at.max(1) } else { at }; - // An image put first in an ordinary group named as a tracing would make that group one. - if at == 0 && d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) && named_as_tracing(d, to.parent) { + // An image left or put first in an ordinary group named as a tracing would make that group + // one, in the group it leaves as in the group it goes into. + let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent); + if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) { return Err(HostError::Error(NOT_A_TRACING.into())); } Ok::<_, HostError>(at) @@ -2985,6 +3005,19 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if unchanged { return Ok(Data::Undefined); } + // Where the Arrange command puts the item among its parent's art, worked out as + // `object.arrange` works it out for one object. An image put first, or another object moved + // from above an image that becomes first, in an ordinary group named as a tracing would make + // that group one. + let to = match id { + "object.arrange.bringToFront" => art - 1, + "object.arrange.bringForward" => i + 1, + "object.arrange.sendBackward" => i - 1, + _ => floor, + }; + if parent.is_some_and(|p| with_doc(h, item.doc, |_, st| makes_tracing(&st.doc, p, item.id, Some(to)))) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } match parent { Some(p) if in_trace && id == "object.arrange.sendToBack" => { edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?; diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index 9e058ebc95..a5b4ee561c 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -25,7 +25,8 @@ //! `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 +//! its trace did not make, whether this run, an earlier run or a command added it, and +//! `releaseTracing()` throws [`ADDED_ARTWORK_RELEASE`] in the same case. 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 @@ -56,6 +57,8 @@ use crate::{NodeId, NodeKind}; 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 releasing a tracing that holds an object its trace did not make. +pub const ADDED_ARTWORK_RELEASE: &str = "Cannot release 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)`. @@ -318,12 +321,8 @@ 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.retraces.get() >= MAX_RETRACES { - return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); - } +/// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make. +fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { read_group(h, item, |_, group| { remember_source(h, item.doc.uid, group); // The objects the trace made, as the tracing records them; a tracing saved without that @@ -344,10 +343,19 @@ fn retrace(h: &Host, item: Item, mut params: Map) -> Result<(), H }; }); if added { - return Err(HostError::Error(ADDED_ARTWORK.into())); + return Err(HostError::Error(refusal.into())); } Ok(()) - })?; + }) +} + +/// 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.retraces.get() >= MAX_RETRACES { + return Err(HostError::Range(format!("a run traces a tracing again at most {MAX_RETRACES} times"))); + } + refuse_added(h, item, ADDED_ARTWORK)?; params.insert("id".into(), json!(item.id.0)); // One savepoint covers the trace and the selection's restore, so a failed restore undoes the trace. let new = super::atomically(h, |h| replace(h, item, "imageTrace.make", &Value::Object(params), "id"))?; @@ -582,9 +590,12 @@ fn tracing_expand(h: &Host, a: &[Data]) -> Answer { Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) } -/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. +/// `releaseTracing()`: `imageTrace.release` → the source image, back in the tracing's place. A +/// tracing that holds an object its trace did not make throws [`ADDED_ARTWORK_RELEASE`], since the +/// release keeps only the source image. fn tracing_release(h: &Host, a: &[Data]) -> Answer { let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; + refuse_added(h, item, ADDED_ARTWORK_RELEASE)?; let id = replace(h, item, "imageTrace.release", &json!({"ids": [item.id.0]}), "ids")?; Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, id))) } @@ -836,7 +847,8 @@ fn options_store(h: &Host, a: &[Data]) -> Answer { } /// A member of `TracingOptions` with no VectorCraft setting: reading and assigning it both throw, -/// after the check that the tracing `this` names is still there. +/// after the check that the tracing `this` names is still there, and `reflect` and +/// `hasOwnProperty` leave it out. fn missing(link: &Link, name: &'static str) -> Described { let message = not_implemented("TracingOptions", name); let l = link.clone(); @@ -846,7 +858,7 @@ fn missing(link: &Link, name: &'static str) -> Described { tracing_of(&h, arg(&a, 0), "TracingOptions")?; Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) + (name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() }) } /// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`. @@ -868,7 +880,7 @@ pub(super) fn classes(l: &Link) -> Vec { let tracing = named(vec![ ("typename", typename_of("TracingObject"), typed("string")), ("anchorCount", get(l, tracing_anchors), typed("number")), - ("areaCount", get(l, tracing_areas), typed("number")), + ("areaCount", HostMember::Unavailable(super::function(l, tracing_areas)), MemberInfo { unavailable: true, ..MemberInfo::default() }), ("imageResolution", get(l, tracing_resolution), typed("number")), ("parent", get(l, tracing_parent), typed("PluginItem")), ("pathCount", get(l, tracing_paths), typed("number")), diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 940f653184..ee3bb6a1b8 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1150,6 +1150,98 @@ fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// `move`, `remove()` and `zOrder` refuse to leave an image at the bottom of an ordinary group named +/// as a tracing, before the document changes, and allow the same moves when another object stays +/// at the bottom. +#[test] +fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { + let base = folder("leave-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], r = d.rasterItems[0], p = d.pathItems[0], m = [];\ + function t(f) { try { f(); m.push('done'); } catch (e) { m.push(e.message); } }\ + t(function () { p.move(g, ElementPlacement.PLACEBEFORE); });\ + t(function () { p.move(g, ElementPlacement.PLACEATBEGINNING); });\ + t(function () { p.remove(); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGTOFRONT); });\ + t(function () { p.zOrder(ZOrderMethod.BRINGFORWARD); });\ + t(function () { r.zOrder(ZOrderMethod.SENDTOBACK); });\ + t(function () { r.zOrder(ZOrderMethod.SENDBACKWARD); });\ + vc.log(m); vc.log(g.typename);", + ); + assert_eq!(out, [json!(vec!["Only Image Trace can make a tracing"; 7]), json!("GroupItem")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], p = d.pathItems[0];\ + d.pathItems.rectangle(40, 40, 5, 5).move(g, ElementPlacement.PLACEATEND);\ + p.move(g, ElementPlacement.PLACEBEFORE); vc.log(g.typename);", + ); + assert_eq!(out, [json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let d = &s.active().unwrap().doc; + let g = top(&s).into_iter().find(|i| d.node(*i).is_some_and(|n| n.name.as_deref() == Some(crate::cmd::TRACE_NAME))).unwrap(); + assert_eq!(d.children(Some(g)).unwrap().len(), 2, "the rectangle left the group"); + let _ = std::fs::remove_dir_all(base); +} + +/// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object +/// its trace did not make, before the document changes. +#[test] +fn release_refuses_added_artwork_before_changing_the_document() { + let base = folder("release-added-artwork"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, p = d.rasterItems[0].trace(); d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var items = app.activeDocument.pageItems, p, m = '';\ + for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\ + try { p.tracing.releaseTracing(); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!("Cannot release a tracing containing added artwork")]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert_eq!(traces(&s).len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// The `TracingOptions` and `TracingObject` members that are not implemented are left out of +/// `hasOwnProperty` and `reflect`, and still throw when read. +#[test] +fn unimplemented_tracing_members_are_not_reported() { + let base = folder("unimplemented-members"); + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = '';\ + vc.log([o.hasOwnProperty('pathFitting'), t.hasOwnProperty('areaCount'), t.hasOwnProperty('pathCount')]);\ + vc.log([o.reflect.find('pathFitting') === null, t.reflect.find('areaCount') === null, t.reflect.find('pathCount') === null]);\ + try { t.areaCount; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, [json!([false, false, true]), json!([true, true, false]), json!("TracingObject.areaCount is not implemented")]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 469968e618..2bf79b10c0 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -161,7 +161,7 @@ const INSIDE: &[(&str, &str)] = &[ ("TracingObject.", "prototype"), ( "TracingObject.prototype.", - "anchorCount areaCount constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ + "anchorCount areaCount areaCount= constructor expandTracing imageResolution parent pathCount releaseTracing sourceArt \ tracingOptions typename usedColorCount", ), ("TracingOptions.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index ce3af183f8..bc05206aa8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3047,7 +3047,8 @@ through `$`: unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before - the document changes, as renaming such a group does. An object of + the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with + nothing changed, when they would leave an image at the bottom of such a group. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or @@ -3268,7 +3269,8 @@ through `$`: `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. 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 + did not make, whether this run, an earlier run or a command added it, and `releaseTracing()` throws + `Cannot release a tracing containing added artwork` in the same case. `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