Merge pull request #10332 from dotCooCoo/fix/script-page-item-edits

Scripts: locked artboards stop path edits, and move and zOrder respect clipping paths
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-01 06:19:21 -08:00
commit 4e6cc52aea
5 files changed
+180 -32

No files matched your search

+28 -13
View File
@@ -2675,8 +2675,9 @@ struct Destination {
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
/// `layer.move` puts copies, and a move there leaves the object where it is.
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a
/// clipping path cannot go below it.
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
@@ -2709,6 +2710,15 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
(parent, Some(target))
}
};
// The clipping path stays at the bottom of its clip group or clipping layer. Moving the
// clipping path below itself leaves it where it is.
if how == Placement::Below
&& (target != item.id || copy)
&& d.node(parent).is_some_and(crate::doc::Node::clips)
&& d.position(target).is_some_and(|(_, i, _)| i == 0)
{
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
}
if !editable(d, parent) {
return Err(HostError::Error("the layer or group is hidden or locked".into()));
}
@@ -2763,7 +2773,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer {
if matches!(arg(a, 1), Data::Undefined) {
return Err(HostError::Type("move needs a relative object".into()));
}
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
if to.beside != Some(item.id) {
place(h, item.doc, item.id, &to)?;
}
@@ -2804,7 +2814,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
None
}
target => Some(destination(h, item, target, arg(a, 2))?),
target => Some(destination(h, item, target, arg(a, 2), true)?),
};
let id = atomically(h, |h| {
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
@@ -2836,17 +2846,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
}
refuse_protected_edit(h, item)?;
selection_ids(h, item.doc, arg(a, 0))?;
let (before, after) = with_doc(h, item.doc, |_, st| {
let at = st.doc.position(item.id);
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
(at.map(|(_, i, _)| i), count)
// The Arrange commands keep a clipping path at the bottom of its parent and the art below the
// parent's ruler guides, so the item's place is counted among the art above the clipping path.
let (before, floor, art) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let at = d.position(item.id);
let parent = at.and_then(|(p, ..)| p);
let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips));
let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c));
(at.map(|(_, i, _)| i), floor, art)
});
let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) };
let top = i + 1 >= after;
let unchanged = match id {
"object.arrange.bringToFront" | "object.arrange.bringForward" => top,
_ => i == 0,
};
let unchanged = i < floor
|| match id {
"object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art,
_ => i <= floor,
};
if !unchanged {
edit_item(h, item, id, &json!({"ids": [item.id.0]}))?;
}
+31 -15
View File
@@ -15,7 +15,9 @@
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
//! groups and compound paths included.
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
//! or locked layer or group, throws `Cannot edit` with nothing changed.
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
//! artboard.
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
@@ -106,6 +108,18 @@ fn cannot_edit(id: NodeId) -> HostError {
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
}
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
if !editable(&st.doc, id) {
return Err(cannot_edit(id));
}
if super::on_locked_artboard(h, st, id) {
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
}
Ok(())
}
/// The path `d` names, which must still be in its document.
fn path_of(h: &super::Host, d: &Data) -> std::result::Result<Item, HostError> {
let item = item_of(h, d)?;
@@ -234,7 +248,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
/// that is, is written at once, so that its points read as the grid snaps them.
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
forget_waiting_starts(h);
@@ -246,15 +260,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
flush(h)?;
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
let r = f(&mut subs);
let (same, ok, aligned) = read_path(h, item, |st, _, pd| {
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
let d = &st.doc;
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
(pd.subpaths == subs, editable(d, item.id), aligned)
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
})?;
if !same {
if !ok {
return Err(cannot_edit(item.id));
}
refused?;
*h.dom.pending.borrow_mut() = Some((item, subs));
if aligned {
flush(h)?;
@@ -337,15 +349,12 @@ fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
}
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
/// must be one the user could edit.
/// must be one the user could edit ([`refuse_path_edit`]).
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
/// back afterwards, so the edit changes only the path.
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id));
if !ok {
return Err(cannot_edit(item.id));
}
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
if let Some(o) = params.as_object_mut() {
o.entry("ids").or_insert_with(|| json!([item.id.0]));
}
@@ -436,18 +445,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
}
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
/// path, or one in a hidden or locked layer or group, stops it before anything is deleted.
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
/// anything is deleted, as `PageItems.removeAll()` does.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
let (ids, refused) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st)?;
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused))
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();
Ok::<_, HostError>((ids, refused, on_locked))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
}
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<_>>()})))?;
}
+81
View File
@@ -895,6 +895,87 @@ fn a_path_inside_a_compound_path_is_not_reordered() {
assert_eq!(out, vec![json!([1, 2])]);
}
/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The
/// page items are `g`, `b`, `a` and `c`, topmost first.
fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) {
let (mut s, a, b) = doc();
let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0);
s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom");
(s, g, a, b, c)
}
/// The ids of the children of `id`, bottom first.
fn children_of(s: &Session, id: NodeId) -> Vec<NodeId> {
s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect()
}
#[test]
fn nothing_is_placed_below_a_clipping_path() {
let (mut s, g, a, b, c) = clip_group();
let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0);
s.execute("select.none", &json!({})).unwrap();
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
// From outside the group, from above the clipping path inside it, a copy, and a copy of the
// clipping path below itself.
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, mask = p[4], out = [];\
var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\
function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\
function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\
function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\
for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\
vc.log(out);",
);
let messages = out[0].as_array().cloned().unwrap_or_default();
assert_eq!(messages.len(), 4, "{out:?}");
for m in &messages {
assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}");
}
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
// Directly above the clipping path is allowed, and so is moving the clipping path beside itself.
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);");
assert_eq!(children_of(&s, g), [c, d, a, b]);
let steps = undo_steps(&s);
log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);");
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps));
}
#[test]
fn zorder_that_leaves_an_object_in_place_runs_no_command() {
// The topmost art of a layer with a ruler guide above it.
let (mut s, a, b) = doc();
let layer = s.active().unwrap().doc.layers[0].id;
s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap();
let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone();
assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art");
let steps = undo_steps(&s);
let r =
run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap();
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
assert_eq!(layer_order(&s)[..2], [a, b]);
// The lowest object above a clipping path, and the clipping path itself.
let (mut s, g, a, b, c) = clip_group();
let steps = undo_steps(&s);
let r = run(
&mut s,
"var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\
ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\
p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\
for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);",
)
.unwrap();
assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps));
assert_eq!(children_of(&s, g), [c, a, b]);
// A change still runs the command.
log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);");
assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1));
}
#[test]
fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
let (mut s, a, b) = doc();
@@ -1480,6 +1480,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() {
assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide");
}
#[test]
fn path_changes_refuse_paths_on_a_locked_artboard() {
let (mut s, a, _) = doc();
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let (before, steps) = (art(&s), undo_steps(&s));
// Points (waiting and written at once), paint, stroke and a transform.
for change in [
"p.closed = false;",
"p.pathPoints[0].anchor = [1, 2];",
"p.setEntirePath([[0, 0], [10, 10]]);",
"p.filled = false;",
"p.strokeWidth = 7;",
"p.translate(5, 5);",
] {
let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}"));
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}");
}
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
assert!(e.contains("cannot delete objects on a locked artboard"), "{e}");
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps));
// A value the path has changes nothing and does not throw, and the path changes once the
// artboard is unlocked.
log(&mut s, "app.activeDocument.pathItems[0].closed = true;");
s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;");
assert_ne!(art(&s), before);
}
fn is_guide(s: &Session, id: NodeId) -> bool {
matches!(node(s, id).kind, NodeKind::Path { guide: true, .. })
}
+12 -4
View File
@@ -3032,14 +3032,21 @@ through `$`:
copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same
document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a
group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER`
directly below it. An object of another document throws `Cross-document placement is not available`, and when
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 one exception
is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the
document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. 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
locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an
object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`,
`locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard
throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such
an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the value the object already has, which
an object throws `Cannot edit` too. `zOrder()` that would leave the object where it is runs no command: bringing
forward the topmost art of a layer whose ruler guides are above it, sending backward the lowest object above a
clipping path, or any method on the clipping path itself. The one exception is `opacity` or `blendingMode` given the value the object already has, which
changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity or blend mode, that
value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an
object that is hidden or locked itself takes `hidden`, `locked`, `opacity` and `blendingMode` (VectorCraft's own rule). Position,
@@ -3279,8 +3286,9 @@ through `$`:
`resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with
`inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path
that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing
changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard throws
`Cannot edit` with nothing changed, and `pathItems.removeAll()` when any path is on a locked artboard throws
`cannot delete objects on a locked artboard` and deletes nothing. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new
art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops
are not available yet.