Scripts: layer, artboard and scoped collection fixes

- A layer's, group's or compound path's collections and Artboard objects
  read before File > Revert throw their stale errors.
- Scoped PageItems answer index() by number.
- removeAll() refuses to delete a clipping path whose group or layer keeps
  other objects (ruler guides do not count), after the lock checks.
- Layers lists are kept while the document is unchanged, so a loop over
  layers[i] lists them once; getByName on scoped collections is charged
  each time.
- Action steps act on the artboard the script chose with
  setActiveArtboardIndex, or on its index when it was deleted.
- object.newGroup refuses null for parent, index and compound.
This commit is contained in:
dotCooCoo committed 2026-11-29 15:08:19 -08:00
1 parent 52879dd78f
commit b816f072c1
8 files changed
+313 -24

No files matched your search

+4 -3
View File
@@ -110,17 +110,18 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
/// selection stays as it is.
pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.newGroup";
// Only an omitted key takes its default; `null` is refused like any other bad value.
let compound = match p.get("compound") {
None | Some(Value::Null) => false,
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?,
};
let st = s.doc()?;
let parent = match p.get("parent") {
None | Some(Value::Null) => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
None => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?),
};
let index = match p.get("index") {
None | Some(Value::Null) => usize::MAX,
None => usize::MAX,
Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?,
};
let d = &st.doc;
+1 -1
View File
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Group",
[],
None,
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; the selection stays as it is",
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
has_doc,
new_group
),
+12 -1
View File
@@ -253,7 +253,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
// A document whose active artboard the script chose uses that choice, not the one the run
// started with.
let chosen = h.session.borrow().active().and_then(|st| {
let (_, index) = h.dom.chosen_artboards.borrow().iter().find(|(uid, _)| *uid == st.uid).copied()?;
let index = st.active_artboard.and_then(|id| st.doc.artboards.iter().position(|a| a.id == id)).unwrap_or(index);
Some((st.uid, index))
});
let active = match &chosen {
Some(chosen) => std::slice::from_ref(chosen),
None => h.active_artboards.as_slice(),
};
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
+14
View File
@@ -168,6 +168,12 @@ pub(super) enum Coords {
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
#[cfg(test)]
thread_local! {
/// How many nodes the layer lists of `Layers` objects have looked at on this thread.
pub(crate) static LAYER_SCANS: Cell<u64> = const { Cell::new(0) };
}
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
@@ -207,8 +213,13 @@ pub(super) struct State {
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
/// used first, each kept while its document is unchanged.
art: RefCell<Vec<layers::ArtList>>,
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
/// first, each kept while its document is unchanged.
layers: RefCell<Vec<layers::LayerList>>,
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
pub(super) active_artboards: RefCell<Vec<u64>>,
/// Each document's uid and the index last chosen with `setActiveArtboardIndex`, changed or not.
pub(super) chosen_artboards: RefCell<Vec<(u64, usize)>>,
/// Each open document's uid and the index of its active artboard when the run started.
pub(super) boards_at_start: Vec<(u64, usize)>,
text: text::TextState,
@@ -2090,6 +2101,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
}
fn items_index(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
return layers::scoped_index(h, a);
}
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
+92 -15
View File
@@ -126,9 +126,8 @@ fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it.
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
let [high, low] = id_parts(id);
[float(h.run), float(uid), high, low, float(reverts)]
[float(h.run), float(uid), high, low, float(reverts_of(h, uid))]
}
/// Reads the layer `this` names with `f`.
@@ -488,9 +487,44 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
None => Some(&d.layers),
Some(p) => d.children(Some(p)),
};
#[cfg(test)]
super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64)));
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
}
/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top
/// level) and the layers it listed then.
pub(super) type LayerList = (u64, Arc<Document>, Option<NodeId>, Rc<Vec<NodeId>>);
/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while
/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list
/// is charged by the objects it looks at.
fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
{
let mut lists = h.dom.layers.borrow_mut();
let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent);
if let Some(at) = at {
let list = lists.remove(at);
let ids = list.3.clone();
lists.push(list);
return Ok(ids);
}
}
let looked_at = match parent {
None => st.doc.layers.len(),
Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len),
};
h.charge_call(looked_at as u64)?;
let ids = Rc::new(layer_list(&st.doc, parent));
let mut lists = h.dom.layers.borrow_mut();
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
if lists.len() >= ART_LISTS {
lists.remove(0);
}
lists.push((st.uid, st.doc.clone(), parent, ids.clone()));
Ok(ids)
}
fn layers_of(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
Ok(host_ref("Layers", &layer_handle(h, doc.uid, id)))
@@ -498,7 +532,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer {
fn layers_length(h: &Host, a: &[Data]) -> Answer {
let (doc, parent) = layers_scope(h, arg(a, 0))?;
Ok(num(float(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).len()) as u64)))
Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64)))
}
fn layers_parent(h: &Host, a: &[Data]) -> Answer {
@@ -527,14 +561,14 @@ fn layers_at(h: &Host, a: &[Data]) -> Answer {
}
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
}
fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
let (doc, parent) = layers_scope(h, arg(a, 0))?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = layer_list(&st.doc, parent);
let ids = layers_listed(h, st, parent)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -577,7 +611,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
if parent.is_none() {
return Err(HostError::Error("a document needs at least one layer".into()));
}
let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent));
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
@@ -592,11 +626,13 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
match handle.as_slice() {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
[run, uid, high, low] => {
[run, uid, high, low, reverts] => {
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
// A collection read before File › Revert is stale like its container.
let holds = with_doc(h, doc, |_, st| {
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
whole(*reverts) == Some(st.reverts)
&& st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
});
if !holds {
return Err(HostError::Error(STALE_ITEM.into()));
@@ -654,12 +690,17 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
/// names the container.
pub(super) fn is_scoped(a: &[Data]) -> bool {
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 4)
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
}
/// How many times File › Revert has reloaded the document with uid `uid`.
fn reverts_of(h: &Host, uid: u64) -> u64 {
h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts)
}
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
match container {
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1]]),
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]),
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
}
}
@@ -693,6 +734,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = art_list(h, st, kind, c)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
})
@@ -715,7 +757,7 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
/// `pageItems.removeAll()` is stopped.
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
let all = art_list(h, st, kind, c)?;
let d = &st.doc;
let listed: std::collections::HashSet<NodeId> = all.iter().copied().collect();
@@ -725,7 +767,22 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = d.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))
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let masks: Vec<u64> = ids
.iter()
.filter(|i| {
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
let kids = p.children().map_or(&[][..], Vec::as_slice);
p.clips()
&& kids.first().is_some_and(|f| f.id == **i)
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
})
})
.map(|i| i.0)
.take(20)
.collect();
Ok::<_, HostError>((ids, refused, on_locked, masks))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -735,6 +792,12 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !masks.is_empty() {
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!(
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {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<_>>(), "keepEmpty": true})))?;
}
@@ -759,6 +822,10 @@ pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer {
art_by_name(h, a, Kind::Any)
}
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
art_index(h, a, Kind::Any)
}
pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer {
art_remove_all(h, a, Kind::Any)
}
@@ -1001,15 +1068,17 @@ fn board_index(st: &DocState, id: u32) -> Option<usize> {
fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> {
let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) };
let [run, uid, id] = handle.as_slice() else { return Err(type_error("Artboard")) };
let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
let index = with_doc(h, doc, |_, st| board_index(st, id)).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
// An artboard read before File › Revert is stale, as the page items read with it are.
let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts)))
.ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
Ok((Board { doc }, index))
}
fn board_ref(h: &Host, uid: u64, id: u32) -> Data {
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id)])
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))])
}
fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> {
@@ -1319,6 +1388,14 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
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);
}
{
let mut chosen = h.dom.chosen_artboards.borrow_mut();
if let Some((_, index)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
*index = i;
} else {
chosen.push((doc.uid, i));
}
}
if i != now {
let mut moved = h.dom.active_artboards.borrow_mut();
if !moved.contains(&doc.uid) {
+45
View File
@@ -262,6 +262,51 @@ fn steps_act_on_the_artboard_active_as_they_run() {
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
}
/// After the script makes another artboard active with `setActiveArtboardIndex`, a step that acts
/// on the active artboard acts on that one.
#[test]
fn steps_act_on_the_artboard_the_script_made_active() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 0);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", &actions);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now[0], was[0], "the artboard active as the run started is unchanged");
assert_ne!(now[1], was[1], "the artboard the script made active is fitted");
// Choosing the artboard that is already active, after an insert moved it, also counts.
make_active(&mut s, 0);
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
log_with(
&mut s,
"var b = app.activeDocument.artboards; b.insert([300, 300, 400, 200], 0); b.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');",
&actions,
);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_ne!(now[1], was[0], "the artboard chosen again is fitted");
}
#[test]
fn steps_use_the_chosen_index_when_the_chosen_artboard_is_deleted() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 2);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
log_with(&mut s, "var b = app.activeDocument.artboards; b.setActiveArtboardIndex(2); b.remove(2); app.doScript('Fit', 'Set');", &actions);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now.len(), 2);
assert_eq!(now[0], was[0], "the first artboard is unchanged");
assert_ne!(now[1], was[1], "the last remaining artboard is fitted");
}
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
#[test]
+131
View File
@@ -1790,6 +1790,25 @@ fn wrappers_go_stale_after_revert() {
}
}
/// A layer's or group's collection and an artboard read before File › Revert are stale after it,
/// while the document's own collections follow the loaded document.
#[test]
fn scoped_collections_and_artboards_go_stale_after_revert() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-scoped");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let held = "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.layers[0].groupItems, ab = d.artboards[0], all = d.groupItems;\
d.pageItems[0].name = 'changed'; vc.run('file.revert');";
for (read, stale) in
[("p.length", "Stale page item"), ("g.length", "Stale page item"), ("ab.name", "Stale artboard"), ("ab.name = 'x'", "Stale artboard")]
{
let source = format!("{held} try {{ {read}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}");
assert_eq!(log(&mut s, &source), vec![json!(stale)], "{read}");
}
assert_eq!(log(&mut s, &format!("{held} vc.log(all.length); vc.log(d.artboards[0].name);")), vec![json!(0), json!("Artboard 1")]);
}
#[test]
fn remove_all_refuses_locked_art_before_deleting_anything() {
let (mut s, a, b) = doc();
@@ -2597,6 +2616,59 @@ fn a_compound_paths_path_items_list_the_topmost_path_first() {
assert_eq!(log(&mut s, source), [json!(30), json!(50)]);
}
/// `index(i)` on a layer's `pageItems` and a compound path's `pathItems` gives the object `[i]`
/// gives, and `Not found` past the end.
#[test]
fn scoped_collections_index_by_number() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, L = d.layers[0].pageItems, P = d.compoundPathItems[0].pathItems;\
vc.log(L.index(0).typename); vc.log(P.index(1).width === P[1].width);",
);
assert_eq!(out, vec![json!("CompoundPathItem"), json!(true)]);
let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.index(5);");
assert!(e.contains("Not found"), "{e}");
}
/// Ruler guides left in a clipped layer do not count as other objects: `removeAll()` deletes the
/// layer's clipping compound path.
#[test]
fn scoped_remove_all_deletes_a_clipping_path_beside_ruler_guides() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
let layer = s.active().unwrap().doc.parent_of(cid).unwrap();
s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
run(&mut s, "app.activeDocument.layers[0].compoundPathItems.removeAll();").unwrap();
assert!(s.active().unwrap().doc.node(cid).is_none());
}
/// `removeAll()` refuses to delete the compound path that clips a group while the group keeps
/// other art, and deletes nothing.
#[test]
fn scoped_remove_all_refuses_a_clipping_compound_path() {
let (mut s, a, b) = doc();
let e = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("select.set", &json!({"ids": [cid.0, e.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let before = format!("{:?}", s.active().unwrap().doc.layers);
let steps = undo_steps(&s);
let err = failure(&mut s, "app.activeDocument.groupItems[0].compoundPathItems.removeAll();");
assert!(err.contains("clipping"), "{err}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
}
/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound
/// path's paint and pixel alignment, as Release Compound Path gives them.
#[test]
@@ -2643,6 +2715,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() {
assert!(!d.node(a).unwrap().extras().pixel_aligned);
}
/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid
/// with the compound path's other paths.
#[test]
fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() {
let (mut s, a, _) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let to = s.active().unwrap().doc.parent_of(a).unwrap();
let r = rect(&mut s, 200.3, 100.3, 20.4, 20.4);
s.execute("object.setPixelAligned", &json!({"ids": [r.0], "on": false})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert!(!s.active().unwrap().doc.node(r).unwrap().extras().pixel_aligned);
let before = s.active().unwrap().doc.bounds_of(&[r], false).unwrap();
assert!(before.x0.fract().abs() > 0.01, "{before:?}");
s.execute("node.move", &json!({"id": r.0, "parent": to.0, "index": 0})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(to).unwrap().extras().pixel_aligned);
let after = d.bounds_of(&[r], false).unwrap();
assert!([after.x0, after.y0, after.x1, after.y1].iter().all(|v| (v * 2.0).fract().abs() < 1e-9), "not snapped: {after:?}");
}
#[test]
fn a_compound_paths_path_items_are_path_items() {
let (mut s, a, b) = doc();
@@ -2692,6 +2787,37 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() {
assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}");
}
/// A loop over `layers.length` and `layers[i]` lists the layers once while the document is
/// unchanged, so it looks at each layer a bounded number of times.
#[test]
fn a_loop_over_layers_lists_them_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for _ in 0..39 {
s.execute("layer.new", &json!({})).unwrap();
}
let n = s.active().unwrap().doc.layers.len() as u64;
crate::script::dom::LAYER_SCANS.with(|c| c.set(0));
let out = log(&mut s, "var L = app.activeDocument.layers, n = 0; for (var i = 0; i < L.length; i++) { L[i]; n++; } vc.log(n);");
assert_eq!(out, vec![json!(n)]);
let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get);
assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers");
}
/// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the
/// document's `pageItems`, also when the list was already built.
#[test]
fn scoped_name_searches_are_charged_each_time() {
let (mut s, ..) = doc();
let calls = |s: &mut Session, list: &str, k: usize| {
let source = format!("var p = {list}; p.length; for (var i = 0; i < {k}; i++) {{ try {{ p.getByName('none'); }} catch (e) {{}} }}");
run(s, &source).unwrap()["hostCalls"].as_u64().unwrap()
};
let doc_cost = calls(&mut s, "app.activeDocument.pageItems", 6) - calls(&mut s, "app.activeDocument.pageItems", 1);
let layer_cost = calls(&mut s, "app.activeDocument.layers[0].pageItems", 6) - calls(&mut s, "app.activeDocument.layers[0].pageItems", 1);
assert_eq!(layer_cost, doc_cost);
}
#[test]
fn group_items_remove_all_refuses_locked_groups() {
let (mut s, a, b) = doc();
@@ -2718,6 +2844,11 @@ fn new_group_command_checks_its_parent() {
assert!(s.execute("object.newGroup", &json!({"parent": 999_999})).unwrap_err().to_string().contains("no layer or group"));
assert!(s.execute("object.newGroup", &json!({"parent": "x"})).unwrap_err().to_string().contains("parent must be"));
assert!(s.execute("object.newGroup", &json!({"index": -1})).unwrap_err().to_string().contains("index must be"));
let groups = s.active().unwrap().doc.layers.len();
assert!(s.execute("object.newGroup", &json!({"parent": null})).unwrap_err().to_string().contains("parent must be"));
assert!(s.execute("object.newGroup", &json!({"index": null})).unwrap_err().to_string().contains("index must be"));
assert!(s.execute("object.newGroup", &json!({"compound": null})).unwrap_err().to_string().contains("compound must be"));
assert_eq!(s.active().unwrap().doc.layers.len(), groups);
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
assert!(s.execute("object.newGroup", &json!({"parent": layer.0})).unwrap_err().to_string().contains("hidden or locked"));
}
+14 -4
View File
@@ -3070,7 +3070,12 @@ through `$`:
tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws
`Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that
`Stale page item`. Layer objects also become stale after their document is reverted, and so do the `pageItems`,
`groupItems` and `compoundPathItems` of a layer or group, the `pathItems` of a compound path (`Stale page item`)
and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document.
`removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's
`groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group
or layer that keeps other objects. `remove()` on an object that
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`
@@ -3162,6 +3167,8 @@ through `$`:
default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group,
index 0 puts it directly above the clipping path), as one undo step named Group, and
gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path.
An omitted key takes its default (`parent`: the current layer; `index`: on top; `compound`: false).
Explicit `null` is refused for `parent`, `index` and `compound`.
The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path
gives up its own paint (a clip group's or clipping layer's clipping path is refused until its mask is released), and an empty compound path takes the paint the first path that goes in was drawn with. A
path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel
@@ -3408,9 +3415,12 @@ through `$`:
app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own
steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and
Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to
Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run
started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one
past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
Selected Art) and does not name one acts on the active document's active artboard. Once the script has called
`setActiveArtboardIndex` on that document, it is the artboard the script chose while that artboard exists. If it
has been deleted, the step uses the artboard at the index last chosen by the script, or the last artboard past
the end. If the script has not chosen an artboard on that document, the step uses the index of its active artboard
as the run started: after the script deletes artboards, the artboard now at that index, or the last one past the
end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that
names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's
own rules: the action and its set are matched by their exact names, and a name that matches no action or more than