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.
This commit is contained in:
dotCooCoo committed 2026-12-02 01:26:30 -08:00
1 parent a7129f3eed
commit a1b8b01383
5 files changed
+157 -18

No files matched your search

+35 -2
View File
@@ -2696,6 +2696,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
if on_locked { if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); 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`. // 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}))?; edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
Ok(Data::Undefined) 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<usize>) -> 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::<Vec<_>>()).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. /// 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> { fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> {
let index = with_doc(h, doc, |_, st| { 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, (_, None) => count,
}; };
let at = if clips { at.max(1) } else { at }; 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. // An image left or put first in an ordinary group named as a tracing would make that group
if at == 0 && d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) && named_as_tracing(d, to.parent) { // 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())); return Err(HostError::Error(NOT_A_TRACING.into()));
} }
Ok::<_, HostError>(at) Ok::<_, HostError>(at)
@@ -2985,6 +3005,19 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
if unchanged { if unchanged {
return Ok(Data::Undefined); 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 { match parent {
Some(p) if in_trace && id == "object.arrange.sendToBack" => { 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}))?; edit_item(h, item, "node.move", &json!({"id": item.id.0, "parent": p.0, "index": floor}))?;
+25 -13
View File
@@ -25,7 +25,8 @@
//! `TracingOptions` follow it. A tracing that another command traced again, expanded or //! `TracingOptions` follow it. A tracing that another command traced again, expanded or
//! released, or whose source image was deleted, is stale. //! released, or whose source image was deleted, is stale.
//! - Tracing again throws [`ADDED_ARTWORK`], with nothing changed, when the tracing holds an object //! - 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 //! 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. //! 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 //! - `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"; 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. /// 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"; 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. /// The error of options that trace with neither fills nor strokes.
pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes"; pub const NEEDS_FILLS_OR_STROKES: &str = "TracingOptions requires fills or strokes";
/// The error of `expandTracing(true)`. /// 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 /// Throws `refusal` when the Image Trace object of `item` holds an object its trace did not make.
/// script objects follow the new one. fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> {
fn retrace(h: &Host, item: Item, mut params: Map<String, Value>) -> 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")));
}
read_group(h, item, |_, group| { read_group(h, item, |_, group| {
remember_source(h, item.doc.uid, group); remember_source(h, item.doc.uid, group);
// The objects the trace made, as the tracing records them; a tracing saved without that // 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<String, Value>) -> Result<(), H
}; };
}); });
if added { if added {
return Err(HostError::Error(ADDED_ARTWORK.into())); return Err(HostError::Error(refusal.into()));
} }
Ok(()) 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<String, Value>) -> 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)); 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. // 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"))?; 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))) 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 { fn tracing_release(h: &Host, a: &[Data]) -> Answer {
let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; 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")?; 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))) 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, /// 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 { fn missing(link: &Link, name: &'static str) -> Described {
let message = not_implemented("TracingOptions", name); let message = not_implemented("TracingOptions", name);
let l = link.clone(); let l = link.clone();
@@ -846,7 +858,7 @@ fn missing(link: &Link, name: &'static str) -> Described {
tracing_of(&h, arg(&a, 0), "TracingOptions")?; tracing_of(&h, arg(&a, 0), "TracingOptions")?;
Err(HostError::Error(message.clone())) 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`. /// Adds `trace()` to the `PlacedItem` and `RasterItem` classes in `classes`.
@@ -868,7 +880,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let tracing = named(vec![ let tracing = named(vec![
("typename", typename_of("TracingObject"), typed("string")), ("typename", typename_of("TracingObject"), typed("string")),
("anchorCount", get(l, tracing_anchors), typed("number")), ("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")), ("imageResolution", get(l, tracing_resolution), typed("number")),
("parent", get(l, tracing_parent), typed("PluginItem")), ("parent", get(l, tracing_parent), typed("PluginItem")),
("pathCount", get(l, tracing_paths), typed("number")), ("pathCount", get(l, tracing_paths), typed("number")),
@@ -1150,6 +1150,98 @@ fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() {
let _ = std::fs::remove_dir_all(base); 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] #[test]
fn retrace_keeps_the_tracing_opacity_and_blend_mode() { fn retrace_keeps_the_tracing_opacity_and_blend_mode() {
let base = folder("retrace-appearance"); let base = folder("retrace-appearance");
@@ -161,7 +161,7 @@ const INSIDE: &[(&str, &str)] = &[
("TracingObject.", "prototype"), ("TracingObject.", "prototype"),
( (
"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 typename usedColorCount",
), ),
("TracingOptions.", "prototype"), ("TracingOptions.", "prototype"),
+4 -2
View File
@@ -3047,7 +3047,8 @@ through `$`:
unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave 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 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 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 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 `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 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` `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 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 `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 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 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 number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest