From 5ad69e554aaeca5991c395a5e89389b2a9edcb5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:15:38 -0800 Subject: [PATCH] Scripts: fix stale index, clip mask moves, removeAll masks and active artboard - A stale layer or group collection throws its stale error from index(n) for any number, a negative one included, instead of Not found. - Moving a clipping path directly below the object above it is a no-op instead of throwing "an object cannot go below a clipping mask". - A clip group's removeAll() that deletes every object in it also releases the mask in the same undo step, so a later groupItems.add() is not made the clipping path. groupItems.removeAll() that leaves the clipping path keeps the mask. - setActiveArtboardIndex stores the chosen artboard on every call, so an artboard inserted before the default active one leaves it active, and a document the run opened is listed in the report. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 12 ++--- crates/engine/src/script/dom/layers.rs | 43 +++++++++++++++-- crates/engine/src/tests/script_dom.rs | 67 ++++++++++++++++++++++++++ docs/mcp.md | 14 ++++-- 4 files changed, 120 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d3dcb9c7a4..5a2ed9aadd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2239,10 +2239,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), // A number is a position only; a scoped list answers its own positions. - Data::Number(n) if layers::is_scoped(a) => match position(*n).map(|_| layers::scoped_at(h, a)).transpose()? { - None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), - Some(d) => Ok(d), - }, + Data::Number(_) if layers::is_scoped(a) => layers::scoped_index(h, a), Data::Number(n) => { let doc = items_doc(h, a)?; match position(*n).map(|i| item_at(h, doc, i)).transpose()? { @@ -2808,6 +2805,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + // The clipping path itself, put back where it is, stays the clipping path. + let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0); let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -2822,14 +2821,15 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let at = if how == Placement::Above { i + 1 } else { i }; // A place behind a clipping path is refused; an object put into the clip group // itself goes directly above the clipping path. - if clips && at == 0 { + if clips && at == 0 && !mask_stays { return Err(HostError::Error("an object cannot go below a clipping mask".into())); } at } (_, None) => count, }; - Ok::<_, HostError>(if clips { at.max(1) } else { at }) + let stays = mask_stays && at == 0 && to.how != Placement::Bottom; + Ok::<_, HostError>(if clips && !stays { at.max(1) } else { at }) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 02926e1317..739fe441b3 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -741,8 +741,11 @@ fn art_named(h: &Host, doc: Doc, c: Option, kind: Kind, name: &str) -> A fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { match arg(a, 1) { Data::String(_) => art_by_name(h, a, kind), - // A number is a position only. - Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => Err(HostError::Error(NOT_FOUND.into())), + // A number is a position only. A stale collection throws its stale error first. + Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + art_scope(h, arg(a, 0), kind.class())?; + Err(HostError::Error(NOT_FOUND.into())) + } Data::Number(_) => match art_at(h, a, kind)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -780,7 +783,27 @@ 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::>(), "keepEmpty": c.is_some()}); - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?; + // 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 = 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", ¶ms) + })?; } Ok(Data::Undefined) } @@ -799,6 +822,10 @@ pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { art_at(h, a, Kind::Any) } +pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Any) +} + pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { art_by_name(h, a, Kind::Any) } @@ -1368,11 +1395,17 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st))); let i = board_index_arg(arg(a, 1), len, "index")?; - if i != now { + // The artboard's id is stored on every call, so an artboard inserted before it later does not + // change which artboard is active. + { let mut s = h.session.borrow_mut(); let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); - drop(s); + } + // A document the run opened is reported whenever an artboard is chosen in it, since the report + // has no start index for it to compare with. + let new_doc = !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid); + if i != now || new_doc { let mut moved = h.dom.active_artboards.borrow_mut(); if !moved.contains(&doc.uid) { moved.push(doc.uid); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1dcac9cae..bdced805e9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -872,6 +872,11 @@ fn an_object_cannot_go_behind_a_clipping_path() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); assert!(e.contains("an object cannot go below a clipping mask"), "{e}"); assert_eq!(kids(&s), before); + // The clipping path moved directly below the object above it stays where it is. + let steps = undo_steps(&s); + 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); 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);"); @@ -3193,6 +3198,68 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +/// Choosing the artboard that is already active by default keeps that artboard active when another +/// is inserted before it. +#[test] +fn choosing_the_default_active_artboard_follows_it_past_an_insert() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap(); + let first = s.active().unwrap().doc.artboards[0].id; + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());", + ); + assert_eq!(out, [json!(1)]); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); + // In a document the run opens, the report gives the chosen artboard's index at the end. + let r = run(&mut s, "var d = app.documents.add(); d.artboards.setActiveArtboardIndex(0); d.artboards.insert([800, 300, 900, 100], 0);").unwrap(); + let boards = r["activeArtboards"].as_array().cloned().unwrap_or_default(); + assert!(boards.iter().any(|b| b["document"] == json!(1) && b["artboard"] == json!(1)), "{r}"); +} + +/// A stale container's `pageItems.index(n)` and `groupItems.index(n)` throw the stale error for +/// every number, a negative one included. +#[test] +fn a_stale_containers_list_throws_its_stale_error_for_any_index() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-stale-index"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pageItems", "groupItems"] { + let source = + format!("var d = app.activeDocument, p = d.layers[0].{list}; d.pageItems[0].name = 'changed'; vc.run('file.revert'); p.index(-1);"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{list}: {e}"); + } +} + +/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is +/// not its clipping path; the run's one undo step puts everything back. +#[test] +fn remove_all_on_a_clip_group_releases_its_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &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 steps = undo_steps(&s); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); g.groupItems.add(); vc.log(g.clipped);"); + assert_eq!(out, [json!(false), json!(false)]); + assert!(!s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert!(st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // `groupItems.removeAll()` leaves the clipping path, and the group keeps its mask. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; g.groupItems.add(); g.groupItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);", + ); + assert_eq!(out, [json!(true), json!(2)]); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 5f6503bf48..7850ab1515 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3035,9 +3035,10 @@ through `$`: group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` 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 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 + `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 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 @@ -3099,7 +3100,8 @@ 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. Setting `width` or `height` scales the object along + 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 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, @@ -3183,7 +3185,9 @@ through `$`: `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because - artboards were inserted, removed or reordered before it. An index outside the list throws a + artboards were inserted, removed or reordered before it, and a document the run opened in which an artboard was + chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active + one. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet.