Scripts: release a mask whose clipping path is deleted, charge controlBounds

- remove(), any collection's removeAll() and the document's
  pageItems.removeAll() release the mask of a clip group or clipping
  layer whose clipping path they delete, in the same undo step, so the
  object above it does not become the clipping path. A deletion that
  leaves the clipping path keeps the mask.
- move(group, PLACEATEND) on a clip group's own clipping path leaves it
  where it is; INSIDE and PLACEATBEGINNING still throw node.move's error.
- controlBounds charges each object and anchor it visits against the
  data a run may pass.
- The scoped removeAll() test catches the locked-artboard error inside
  the script and checks that art on an unlocked artboard is still there.
- A test checks that a layer, page item or artboard handle from before
  app.undo() does not name an object added afterwards.

Docs: docs/mcp.md (artboards.insert runs artboard.reorder only when the
index differs from the new artboard's).
This commit is contained in:
dotCooCoo committed 2026-12-01 20:38:12 -08:00
1 parent 7ee38e71d0
commit d22384d6ba
4 files changed
+180 -42

No files matched your search

+48 -11
View File
@@ -2273,13 +2273,16 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
return layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| {
let ids = top_items(&st.doc);
let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
// A clipping layer emptied of its art releases its mask, so art added later is not made its
// clipping path.
let released = masks_cleared_by(&st.doc, &ids);
(ids, refused, on_locked, released)
});
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -2290,7 +2293,7 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
Ok(Data::Undefined)
}
@@ -2552,24 +2555,31 @@ fn item_control(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
// An object with nothing in it reads zeros, as its other bounds do.
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r)));
// Each object and anchor the walk visits is charged, so reading a large group's bounds again
// and again counts against the run.
let mut steps = 0u64;
let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps)));
h.charge_call(steps)?;
Ok(f.bounds(h.dom.coords.get(), r))
}
/// `r` with the anchors and direction handles of the shown paths in `n`. Hidden objects, the
/// objects in them and guides are left out, as the visible bounds leave them out, and a clip group
/// or clipping layer gives only its clipping path's.
fn take_in_handles(n: &crate::doc::Node, mut r: Rect) -> Rect {
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
/// path's.
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
*steps += 1;
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return r;
}
for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) {
*steps += 1;
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
}
let children = n.children().map_or(&[][..], Vec::as_slice);
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
for c in children {
r = take_in_handles(c, r);
r = take_in_handles(c, r, steps);
}
r
}
@@ -2704,11 +2714,37 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id]));
// 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}))?;
let params = json!({"ids": [item.id.0], "keepEmpty": true});
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, &params)));
h.dom.editing.set(kept);
r?;
Ok(Data::Undefined)
}
/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping
/// path releases its mask, so the object above it does not become the clipping path.
pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter()
.filter_map(|i| {
let p = d.parent_of(*i)?;
let n = d.node(p)?;
(n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p)
})
.collect()
}
/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`.
pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result<Data, HostError> {
for g in released {
command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?;
}
command(h, "edit.clear", params)
}
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
@@ -2842,7 +2878,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
}
(_, None) => count,
};
let stays = mask_stays && at == 0 && to.how != Placement::Bottom;
// Any other place for the clipping path is left to `node.move`, which refuses it.
let stays = mask_stays && at == 0;
Ok::<_, HostError>(if clips && !stays { at.max(1) } else { at })
})?;
let now = with_doc(h, doc, |_, st| st.doc.position(id));
+5 -21
View File
@@ -783,27 +783,11 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
if !ids.is_empty() {
// The container stays, empty, as a compound path whose last path `remove()` takes out does.
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
// An emptied clipping group releases its mask, so an object added to it later is not
// made its clipping path.
// Only a deletion that takes every object of the group, its clipping path included, does.
let clipped = c.filter(|c| {
with_doc(h, doc, |_, st| {
st.doc.node(*c).is_some_and(|n| {
matches!(n.kind, NodeKind::Group { .. })
&& n.clips()
&& n.children().is_some_and(|k| {
let gone: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
k.iter().all(|k| gone.contains(&k.id))
})
})
})
});
on_doc(h, doc.uid, true, |h| {
if let Some(g) = clipped {
command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?;
}
command(h, "edit.clear", &params)
})?;
// A deletion that takes a clipping path releases its clip group's or clipping layer's mask,
// so neither the object above it nor one added later is made the clipping path. A deletion
// that leaves the clipping path keeps the mask.
let released = with_doc(h, doc, |_, st| super::masks_cleared_by(&st.doc, &ids));
on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, &params))?;
}
Ok(Data::Undefined)
}
+117 -4
View File
@@ -160,6 +160,25 @@ fn control_bounds_leave_out_hidden_paths() {
assert_eq!(out[1], out[0], "{out:?}");
}
/// Each anchor `controlBounds` visits counts toward the data a run passes, so reading the bounds of
/// a large path again and again ends the run where reading its geometric bounds does not.
#[test]
fn control_bounds_count_the_anchors_they_visit() {
let (mut s, _, _) = doc();
let d: String = (0..2000u32).map(|i| format!(" L{} {}", i % 300, (i * 7) % 200)).collect();
let id = s.execute("path.create", &json!({"d": format!("M0 0{d}")})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
// 100 reads of 2001 anchors are about 200 KB of steps, over a 64 KiB limit.
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let read = |s: &mut Session, what: &str| run(s, &format!("var i = app.activeDocument.selection[0]; for (var n = 0; n < 100; n++) i.{what};"));
let geometric = read(&mut s, "geometricBounds");
let control = read(&mut s, "controlBounds");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
geometric.unwrap();
let e = control.unwrap_err().to_string();
assert!(e.contains("passed more data"), "{e}");
}
/// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping
/// path.
#[test]
@@ -448,6 +467,36 @@ fn app_undo_and_redo_step_through_the_runs_edits() {
assert!(failure(&mut s, "app.redo();").contains("No active document"));
}
/// A layer, page item or artboard read before `app.undo()` took it away is stale, even when an
/// object added afterwards takes its id; one that `app.redo()` brings back, and one that was there
/// before the undone step, still work.
#[test]
fn a_handle_from_before_an_undo_does_not_name_a_later_object() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument, kept = d.layers[0], m;\
var a = d.layers.add(); app.undo(); var b = d.layers.add(); b.name = 'b';\
m = ''; try { a.name = 'x'; } catch (e) { m = e.message; } vc.log([m, b.name]);\
m = ''; try { a.groupItems.length; } catch (e) { m = e.message; } vc.log(m);\
var p = d.groupItems.add(); app.undo(); var q = d.groupItems.add(); q.name = 'q';\
m = ''; try { p.name = 'y'; } catch (e) { m = e.message; } vc.log([m, q.name]);\
var r = d.artboards.add([500, 300, 700, 100]); app.undo(); var t = d.artboards.add([800, 300, 1000, 100]); t.name = 't';\
m = ''; try { r.name = 'z'; } catch (e) { m = e.message; } vc.log([m, t.name]);\
var c = d.layers.add(); app.undo(); app.redo(); c.name = 'c'; kept.name = 'kept'; vc.log([c.name, kept.name]);",
);
assert_eq!(
out,
vec![
json!(["Stale layer", "b"]),
json!("Stale layer"),
json!(["Stale page item", "q"]),
json!(["Stale artboard", "t"]),
json!(["c", "kept"]),
]
);
}
/// An opacity a graph mark already has still replaces the opacity another mark of its series left on
/// the graph, as `object.setProps` does.
#[test]
@@ -877,6 +926,19 @@ fn an_object_cannot_go_behind_a_clipping_path() {
log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art'), ElementPlacement.PLACEAFTER);");
assert_eq!(kids(&s), before);
assert_eq!(undo_steps(&s), steps);
// The clipping path put at the end of its own clip group stays where it is; put on top of the
// group's contents, it is refused.
log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);");
assert_eq!(kids(&s), before);
assert_eq!(undo_steps(&s), steps);
for place in ["INSIDE", "PLACEATBEGINNING"] {
let e = failure(
&mut s,
&format!("var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.{place});"),
);
assert!(e.contains("the clipping path stays at the bottom of its clip group"), "{place}: {e}");
assert_eq!(kids(&s), before, "{place}");
}
let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0);
s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap();
log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);");
@@ -2236,7 +2298,8 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() {
fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setProps", &json!({"id": g, "name": "locked"})).unwrap();
let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
@@ -2249,20 +2312,32 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
.unwrap();
};
lock(&mut s, true);
// A path and a group on a second, unlocked artboard, made last so each lists first in its
// scope, are not deleted either.
s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap();
let u = rect(&mut s, 1300.0, 100.0, 20.0, 20.0);
let v = rect(&mut s, 1100.0, 100.0, 20.0, 20.0);
let w = rect(&mut s, 1150.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [v.0, w.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let before = format!("{:?}", s.active().unwrap().doc.layers);
let steps = undo_steps(&s);
for scope in [
"app.activeDocument.layers[0].pageItems",
"app.activeDocument.layers[0].groupItems",
"app.activeDocument.groupItems",
"app.activeDocument.groupItems[0].pageItems",
"app.activeDocument.groupItems.getByName('locked').pageItems",
"app.activeDocument.layers[0].compoundPathItems",
"app.activeDocument.compoundPathItems",
] {
let err = failure(&mut s, &format!("{scope}.removeAll();"));
assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}");
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}");
assert_eq!(undo_steps(&s), steps, "{scope}");
let doc = &s.active().unwrap().doc;
assert!([u, v, w].iter().all(|i| doc.node(*i).is_some()), "{scope}");
}
lock(&mut s, false);
let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);");
@@ -3264,6 +3339,44 @@ fn remove_all_on_a_clip_group_releases_its_mask() {
assert_eq!(out, [json!(true), json!(2)]);
}
/// Deleting a clip group's clipping path while other art stays in the group releases the mask, so
/// the art above it is not made the clipping path. `remove()` on the clipping path does the same,
/// and so does emptying a clipping layer with the document's `pageItems.removeAll()`.
#[test]
fn deleting_a_clipping_path_releases_its_mask() {
let (mut s, a, b) = doc();
let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("select.add", &json!({"ids": [a.0, b.0]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::<Vec<_>>();
let mask = kids(&s)[0];
assert!(matches!(s.active().unwrap().doc.node(mask).unwrap().kind, NodeKind::Compound { .. }));
s.execute("object.setProps", &json!({"id": mask.0, "name": "mask"})).unwrap();
let clips = |s: &Session| s.active().unwrap().doc.node(g).unwrap().clips();
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.compoundPathItems.removeAll(); vc.log([g.clipped, g.pageItems.length]);");
assert_eq!(out, [json!([false, 2])]);
assert!(!clips(&s));
assert_eq!(kids(&s), [a, b]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(clips(&s));
let out =
log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.getByName('mask').remove(); vc.log([g.clipped, g.pageItems.length]);");
assert_eq!(out, [json!([false, 2])]);
assert!(!clips(&s));
assert_eq!(kids(&s), [a, b]);
// A clipping layer emptied by `pageItems.removeAll()` releases its mask too.
let (mut s, _, _) = doc();
let layer = s.active().unwrap().doc.layers[0].id;
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
assert!(s.active().unwrap().doc.layers[0].clips());
log(&mut s, "app.activeDocument.pageItems.removeAll();");
assert!(!s.active().unwrap().doc.layers[0].clips());
}
#[test]
fn the_report_gives_the_active_artboard_the_run_leaves() {
let (mut s, _, _) = doc();
+10 -6
View File
@@ -3042,9 +3042,11 @@ through `$`:
directly above the relative object and `PLACEAFTER` directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the
object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws
`an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The exceptions
are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself and `mask.move(art,
ElementPlacement.PLACEAFTER)` with the object directly above it, which succeed and leave the document unchanged;
`mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of
are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, `mask.move(art,
ElementPlacement.PLACEAFTER)` with the object directly above it and `mask.move(group, ElementPlacement.PLACEATEND)`
with its own clip group, which succeed and leave the document unchanged;
`mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Any other place for the clipping path, such as
`INSIDE` or `PLACEATBEGINNING` of its own clip group, throws the `node.move` error below and moves nothing. 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
@@ -3106,8 +3108,9 @@ through `$`:
is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()`
when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on
a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard`
and delete nothing. A clip group's `removeAll()` that deletes every object in it, the clipping path included,
also releases the group's clipping mask in the same undo step. Setting `width` or `height` scales the object along
and delete nothing. `remove()`, and any collection's `removeAll()`, that deletes the clipping path of a clip group
or clipping layer also releases that clipping mask in the same undo step, so the object above the clipping path
does not become the new clipping path; a deletion that leaves the clipping path keeps the mask. Setting `width` or `height` scales the object along
the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw
`Not found`; and
`app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item,
@@ -3153,7 +3156,8 @@ through `$`:
`index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`.
`clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/)
has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`),
`insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, and returns `undefined`), `remove(index)` (runs
`insert(artboardRect, index)` (runs `artboard.new`, then `artboard.reorder` when `index` is not the index the new
artboard got, so an index that appends runs no `artboard.reorder`; returns `undefined`), `remove(index)` (runs
`artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard`
(https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`,
`rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its