From 62ce314f752fddd5de5994e09bfafddb36fa2928 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:03:22 -0800 Subject: [PATCH 01/17] New Document: test that the column count the rows show leaves a preset unchanged --- crates/ui-egui/src/dialogs/new_document.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 1bcfb52473..1f42df5ae1 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -885,7 +885,7 @@ mod tests { let rows = DocSettings { artboards: 9, layout: ArtboardLayout::GridByColumn, columns: 2, rows: 4, ..DocSettings::default() }; let mut s = rows.clone(); set_columns(&mut s, 3); - assert_eq!((s.columns, s.rows), (3, 4), "3 is what the rows show"); + assert_eq!(s, rows, "3 is what the rows show"); set_columns(&mut s, 2); assert_eq!((s.layout, s.columns, s.rows), (ArtboardLayout::GridByColumn, 2, 0)); assert_eq!(s.grid_columns(), 2); From d84b1cb5650e80cfeef1b05c4ec36117652608fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:10:57 -0800 Subject: [PATCH 02/17] Scripts: a clipping path stays out of compound paths, and near opacities are set node.move refuses to put a clip group's or clipping layer's clipping path into a compound path, so the next object up does not become the clipping path. The art the group clips still moves in. An item's or a layer's opacity assignment is skipped or replaced by the stored value only when it equals the value the getter reports. A value such as 0.00009 on an item at 0% is now set instead of being dropped. --- crates/engine/src/cmd/layer.rs | 7 ++++- crates/engine/src/script/dom.rs | 16 +++++++---- crates/engine/src/script/dom/layers.rs | 6 ++-- crates/engine/src/tests/script_dom.rs | 40 ++++++++++++++++++++++++++ docs/mcp.md | 2 +- 5 files changed, 61 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 322246f8aa..4ac560fdba 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -924,6 +924,11 @@ fn move_node(s: &mut Session, p: &Value) -> Result { if !matches!(n.kind, NodeKind::Path { guide: false, .. }) { return Err(bad(C, "a compound path holds only paths")); } + // A clip group's or clipping layer's clipping path stays where it is: without it, the + // next object up would become the clipping path. + if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) { + return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first")); + } if !d.is_editable(c.id) { return Err(bad(C, "the compound path is hidden or locked")); } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1aeb8d333a..154e9e1cf3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1521,8 +1521,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } +/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four +/// decimals. +fn reported_opacity(opacity: f32) -> f64 { + (f64::from(opacity) * 100.0 * 1e4).round() / 1e4 +} + fn item_opacity(h: &Host, a: &[Data]) -> Answer { - read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) + read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) } fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { @@ -1530,12 +1536,12 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - // A value the getter reports for the item's opacity sends the opacity it has, and + // The value the getter reports for the item's opacity sends the opacity it has, and // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still - // replaces the one the graph keeps for its series or kind. + // replaces the one the graph keeps for its series or kind. Any other value is sent as given. let item = this_item(h, a)?; - let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| n.opacity)); + let v = now.filter(|now| reported_opacity(*now) == v).map_or(v, |now| f64::from(now) * 100.0); set_props(h, a, |_| false, json!({"opacity": v})) } diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..eff3079574 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -42,7 +42,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_ use super::{ Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, later, - method, named, num, number, on_doc, on_doc_layer, page_items, placement_of, property, text, typename, whole, with_doc, + method, named, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -222,7 +222,7 @@ fn layer_set_dim(h: &Host, a: &[Data]) -> Answer { } fn layer_opacity(h: &Host, a: &[Data]) -> Answer { - read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) + read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) } fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { @@ -230,7 +230,7 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e8522ed334..25d3d3f0cf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -257,6 +257,23 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps); } +/// An item's or a layer's opacity that differs from the reported one, however little, is set as +/// given. +#[test] +fn an_opacity_near_the_reported_one_is_still_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 0})).unwrap(); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0]; i.opacity = 0.00009; vc.log(i.opacity);\ + var l = app.activeDocument.layers[0]; l.opacity = 0; l.opacity = 0.00009; vc.log(l.opacity);", + ); + assert_eq!(out, vec![json!(0.0001), json!(0.0001)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).unwrap().opacity > 0.0); + assert!(d.node(d.layer_containing(a).unwrap()).unwrap().opacity > 0.0); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -1695,6 +1712,29 @@ fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() { assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); } +/// `node.move` refuses a clip group's clipping path for a compound path and leaves the group +/// clipped as it was; the art the group clips still goes in. +#[test] +fn node_move_refuses_a_clipping_path_for_a_compound_path() { + 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 cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); + let (before, steps) = (format!("{:?}", d.layers), undo_steps(&s)); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("clipping path"), "{err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(cid)); + assert!(d.node(g).unwrap().clips()); + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); +} + /// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint. #[test] fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() { diff --git a/docs/mcp.md b/docs/mcp.md index 49c913442e..b1733075ba 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2829,7 +2829,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. 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, and an empty compound path takes the paint the first path that goes in was drawn with. A + 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 alignment. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and From f5090591bc05bd272612bcde7f4e6ac93cf9f60f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:11:44 -0800 Subject: [PATCH 03/17] Scripts: setActiveArtboardIndex keeps the artboard when one is inserted before it An assignment that chooses the artboard already active by default now records it, so a later insert moves it to the next index. hasSelectedArtwork = true counts only the art it would add toward the 10,000-object limit. --- crates/engine/src/script/dom/layers.rs | 30 +++++++++++++---------- crates/engine/src/tests/script_dom.rs | 33 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 75938cc6df..3da57533fb 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -297,29 +297,30 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "hasSelectedArtwork")?; let (doc, id) = this_layer(h, a)?; - let (ids, total) = with_doc(h, doc, |_, st| { + let (ids, over) = with_doc(h, doc, |_, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); let selected = &st.selection.objects; if !on { - return (selected.iter().copied().filter(inside).collect::>(), 0); + return (selected.iter().copied().filter(inside).collect::>(), false); } let locks = st.doc.locked_artboards(); let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default(); let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); for o in art { - if selected.len() + ids.len() > MAX_LISTED { - break; + if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + continue; } - if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { - have.insert(o); - ids.push(o); + // Only art that would be added counts toward the limit. + if selected.len() + ids.len() >= MAX_LISTED { + return (ids, true); } + have.insert(o); + ids.push(o); } - let total = selected.len() + ids.len(); - (ids, total) + (ids, false) }); - if total > MAX_LISTED { + if over { return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); } if ids.is_empty() { @@ -1291,16 +1292,19 @@ fn boards_active(h: &Host, a: &[Data]) -> Answer { } /// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the -/// document changes, and no command runs. +/// document changes, and no command runs. The artboard is kept by its id even when it is already +/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later +/// in the run moves it to the next index instead of taking its place. 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 { + { 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); + } + if i != now { 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 e2d6a25442..6e02f9dca9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2109,6 +2109,24 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +/// Choosing the artboard that is active only by default keeps that artboard: one inserted before it +/// moves it to the next index, and the report gives that index. +#[test] +fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() { + let (mut s, _, _) = doc(); + assert_eq!(s.active().unwrap().active_artboard, None); + let first = s.active().unwrap().doc.artboards[0].id; + let r = run( + &mut s, + "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); @@ -2193,6 +2211,21 @@ fn has_selected_artwork_keeps_the_rest_of_the_selection() { assert_eq!(sel.guides.len(), 1); } +/// The selection limit counts only the art an assignment would add: a layer with nothing to add +/// changes nothing beside a selection already at the limit, and one with art to add throws. +#[test] +fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() { + let (mut s, a, _) = doc(); + run(&mut s, "app.activeDocument.layers.add();").unwrap(); + // A selection of 10,001 entries, as the limit counts them. + s.active_mut().unwrap().selection.objects = vec![a; 10_001]; + run(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_001); + s.active_mut().unwrap().selection.objects = vec![a; 10_000]; + let e = failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;"); + assert!(e.contains("at most 10000"), "{e}"); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); From 19e1e5126831c929264f6f36bd850d56ed51878c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:07:37 -0800 Subject: [PATCH 04/17] Scripts: a host constructor called with new must give an object A host class constructor that returned a number, string or other primitive made new return it. new now throws a TypeError for a primitive result. --- crates/js/src/host_tests.rs | 9 +++++++++ crates/js/src/interp.rs | 3 +++ 2 files changed, 12 insertions(+) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..3f4bf1bf13 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -715,6 +715,15 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn a_host_class_constructor_called_with_new_cannot_give_a_primitive() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Number(7.0))); + with_thing(&mut r, Some(make)); + r.start("var r; try { r = new Thing(); } catch (e) { r = e instanceof TypeError; } r").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); +} + #[test] fn objects_of_a_host_class_report_its_available_members_as_their_own() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 9edea621c5..d938ac9eb2 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2952,6 +2952,9 @@ impl Interp { let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); self.constructing = was; let v = v?; + if !matches!(v, Value::Object(_)) { + return Err(self.type_error("a constructor gave a value that is not an object")); + } if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) && matches!(self.object(*o)?.class, Class::Ordinary) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? From 3650f71cdcacc585f0f59f02c1913ca5ab994f1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:37:40 -0800 Subject: [PATCH 05/17] Scripts: removeAll on a compound path's paths keeps the compound path pathItems.removeAll() on a compound path deleted the compound path with its last path, which made its handle stale. It now stays, empty, as remove() on its last path leaves it. --- crates/engine/src/script/dom/layers.rs | 2 +- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3da57533fb..e5f371046e 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -726,7 +726,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> 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::>()})))?; + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 6e02f9dca9..0742b3ff28 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1329,6 +1329,24 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// `removeAll()` on a compound path's `pathItems` deletes its paths and keeps the compound path, +/// empty, as `remove()` on its last path does. +#[test] +fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() { + 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 compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length, app.activeDocument.compoundPathItems.length]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 0, 1])]); + assert!(s.active().unwrap().doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1); +} + #[test] fn move_and_duplicate_refuse_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); From b54c9f063f9103f14e211d60def24bb1fe1b7e26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:10:27 -0800 Subject: [PATCH 06/17] Scripts: placedItems and rasterItems list the topmost image first, as pageItems does pageItems on main lists the topmost object first, and the image lists are built from it, so their order now follows it. The raster metadata test places its images in the order that keeps its assertions, and the plugins test that main added gives ScriptGate the held field this branch adds. --- crates/engine/src/script/dom/images.rs | 3 ++- crates/engine/src/tests/plugins.rs | 1 + crates/engine/src/tests/script_dom_images.rs | 3 ++- docs/mcp.md | 3 ++- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 0e7be90dfe..4528151057 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -135,7 +135,8 @@ pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, Ho Ok(Some([run, uid, high, low])) } -/// The ids of a document's linked (`placed`) or embedded images in paint order. +/// The ids of a document's linked (`placed`) or embedded images, topmost first, in the order of +/// `pageItems`. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; if let Some(l) = &*h.dom.images.lists.borrow() diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 1ae16ec6a8..c6da92ac55 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 594582e9f9..f1f58a3c96 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -319,8 +319,9 @@ fn raster_metadata_uses_encoded_header_not_rgb_fallback() { std::fs::write(&g, gray_png(6, 4)).unwrap(); std::fs::write(&c, super::links::png(3, 2, [10, 20, 30])).unwrap(); let mut s = session(); - place(&mut s, &g, false); + // `rasterItems` lists the topmost image first, so the gray image placed last is `r[0]`. place(&mut s, &c, false); + place(&mut s, &g, false); let out = log( &mut s, &base, diff --git a/docs/mcp.md b/docs/mcp.md index 85c29806de..fbba0226f2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2933,7 +2933,8 @@ other files through `$`: keeps the preset's value. A bad value throws an error before anything is written. - `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones, - in paint order, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()` + topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and + `removeAll()`. `placedItems.add()` gives a `PlacedItem` with no file; assigning a `File` to its `file` runs `file.place` with `link: true`, and every other member of it throws `PlacedItem.file is required` until then. A `PlacedItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/) has `file`, `relink(file)` (`links.relink`), `embed()` From 51778505363acbe79a38e0f4fd5497e17acbe329 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:17:08 -0800 Subject: [PATCH 07/17] Scripts: placed and raster items take contentVariable Every page item kind that holds content now binds a variable through contentVariable on main, and the placed and raster item classes this branch adds defined it as not available yet. They now take the same member, so a linked image binds an image variable and an embedded one refuses it, as script_variables' an_embedded_image_cannot_take_an_image_variable checks. --- crates/engine/src/script/dom/images.rs | 6 ++++-- docs/mcp.md | 3 +-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 4528151057..06e1774536 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -660,7 +660,8 @@ pub(super) fn classes(l: &Link) -> Vec { ("matrix", property(l, placed_matrix, placed_set_matrix)), ("boundingBox", get(l, placed_box)), ]); - placed.extend(["contentVariable", "trace"].into_iter().map(|m| later(l, "PlacedItem", m))); + placed.extend(super::variables::item_members(l, "PlacedItem")); + placed.push(later(l, "PlacedItem", "trace")); let mut raster = named(vec![ ("bitsPerChannel", get(l, raster_bits)), ("channels", get(l, raster_channels)), @@ -673,7 +674,8 @@ pub(super) fn classes(l: &Link) -> Vec { ("transparent", get(l, raster_transparent)), ("boundingBox", get(l, raster_box)), ]); - raster.extend(["colorants", "colorize", "contentVariable", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); + raster.extend(super::variables::item_members(l, "RasterItem")); + raster.extend(["colorants", "colorize", "overprint", "trace"].into_iter().map(|m| later(l, "RasterItem", m))); vec![ class("PlacedItems", None, placed_list, Some(super::function(l, placed_at))), class("RasterItems", None, raster_list, Some(super::function(l, raster_at))), diff --git a/docs/mcp.md b/docs/mcp.md index 2b40fb55e5..b43a7c7841 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2960,8 +2960,7 @@ other files through `$`: item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` result without a file throws `PlacedItem.file is required` whatever the value, and assigning `file` to one checks the file and places the image. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a - file is dropped at the end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not - available yet. + file is dropped at the end of the run. `trace`, `colorants`, `colorize` and `overprint` are not available yet. - A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and `exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables` (https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets` From 1e2b68b71cc3a27e7381f1efddac32f8e1fb261a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:46:29 -0800 Subject: [PATCH 08/17] Docs: name the Document members scripts do not expose yet --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 725e8f957e..4845543b29 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1130,7 +1130,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). - `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, `Document.artboards`, `Document.groupItems`, `Document.swatches`, `Document.symbols` and `Document.close` are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. From b816f072c16788d16440649c04c2dcfbbb9fb8cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:08:19 -0800 Subject: [PATCH 09/17] 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. --- crates/engine/src/cmd/object/arrange.rs | 7 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/script/actions.rs | 13 ++- crates/engine/src/script/dom.rs | 14 +++ crates/engine/src/script/dom/layers.rs | 107 +++++++++++++++--- crates/engine/src/tests/script_actions.rs | 45 ++++++++ crates/engine/src/tests/script_dom.rs | 131 ++++++++++++++++++++++ docs/mcp.md | 18 ++- 8 files changed, 313 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 36b3cef6fe..955520427c 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -110,17 +110,18 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { /// selection stays as it is. pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { 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; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index b0b59b59ab..a01820f9fe 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 2abb290cf7..88b531cd30 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -253,7 +253,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { 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, ¶ms); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d54d10541a..0c35c7ec20 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -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 = 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>, + /// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used + /// first, each kept while its document is unchanged. + layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, + /// Each document's uid and the index last chosen with `setActiveArtboardIndex`, changed or not. + pub(super) chosen_artboards: RefCell>, /// 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) => { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index e621e636b7..3cb0686be9 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -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) -> Vec { 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, Option, Rc>); + +/// 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) -> Result>> { + { + 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::>()})))?; } @@ -592,11 +626,13 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { 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) -> 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, 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 = all.iter().copied().collect(); @@ -725,7 +767,22 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); let locks = d.locked_artboards(); let on_locked: Vec = 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 = ids.iter().copied().collect(); + let masks: Vec = 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::>().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::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().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::>(), "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 { 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) { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 1432b8671b..507c866ee4 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -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] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 8dc4228530..215217d011 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -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")); } diff --git a/docs/mcp.md b/docs/mcp.md index 1b971736d7..67de11e0b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 From 0507cfade0ec02cd12c5dcd5b1d8d00d86e3908b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:58:27 -0800 Subject: [PATCH 10/17] Scripts: clipping, artboard fallback and collection fixes - A scoped removeAll() or Edit > Clear that leaves a clipping group or layer without art releases its mask in the same undo step, also when the mask was a compound path's last member. - GroupItem.clipped refuses changes to a hidden or locked group, layer or artboard. - After the script deletes the artboard it chose, action steps use the same active artboard as getActiveArtboardIndex() and the view. File > Revert discards the script's choice. - A compound path's pathItems is a PathItems object; its creation methods throw an error. PathItems and PageItems methods refuse the other class's scoped collections. - Scoped collections convert to strings. - Layer.color returns an RGBColor, so it can be assigned to paint. - Each zOrderPosition read counts its scan toward the script's budget. --- crates/engine/src/cmd/edit.rs | 18 +- crates/engine/src/cmd/path.rs | 2 + crates/engine/src/script/actions.rs | 5 +- crates/engine/src/script/dom.rs | 22 +- crates/engine/src/script/dom/colors.rs | 2 +- crates/engine/src/script/dom/layers.rs | 67 +++--- crates/engine/src/script/dom/paths.rs | 22 ++ crates/engine/src/tests/script_actions.rs | 37 ++- crates/engine/src/tests/script_dom.rs | 212 +++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 5 +- docs/mcp.md | 22 +- docs/target-app-parity.md | 4 +- 12 files changed, 362 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 4fc1b83c29..c7988b1731 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); a clipping group or layer left without art releases its mask in the same undo step; without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1255,6 +1255,20 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } +pub(super) fn clipped_ancestors(d: &Document, ids: impl IntoIterator) -> BTreeSet { + ids.into_iter().flat_map(|id| d.ancestry(id).unwrap_or_default()).filter(|id| d.node(*id).is_some_and(Node::clips)).collect() +} + +pub(super) fn release_empty_clips(d: &mut Document, ids: BTreeSet) { + for id in ids { + if let Some(n) = d.node_mut(id) + && n.children().is_some_and(|c| c.iter().all(|n| n.is_ruler_guide())) + { + n.set_clips(false); + } + } +} + fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; @@ -1291,6 +1305,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { + let clipped = clipped_ancestors(d, ids.iter().copied()); let parents: Vec<_> = if keep_empty { Vec::new() } else { @@ -1306,6 +1321,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { let gone = sel.guides.clone(); d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } + release_empty_clips(d, clipped); if is_explicit { sel.remove_all(ids.iter().copied()); sel.prune(d); diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index a6f85d0c46..190c8b5810 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1921,6 +1921,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); + let clipped = super::edit::clipped_ancestors(d, whole_ids.iter().chain(sel.keys()).chain(segments.keys()).copied()); // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. let compounds: BTreeSet = if keep_empty { BTreeSet::new() @@ -2002,6 +2003,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo d.remove(p)?; } } + super::edit::release_empty_clips(d, clipped); selection.set(survivors); for (id, next) in following { if !next.is_empty() { diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 88b531cd30..8728bd76fb 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -256,9 +256,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // 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)) + h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; + Some((st.uid, super::dom::active_artboard(st))) }); let active = match &chosen { Some(chosen) => std::slice::from_ref(chosen), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0c35c7ec20..dbb8c9aff3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -218,8 +218,8 @@ pub(super) struct State { layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, - /// Each document's uid and the index last chosen with `setActiveArtboardIndex`, changed or not. - pub(super) chosen_artboards: RefCell>, + /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it. + pub(super) chosen_artboards: RefCell>, /// 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, @@ -2012,7 +2012,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_length(h, a); } let doc = items_doc(h, a)?; @@ -2021,7 +2021,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer { } fn items_typename(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_typename(h, a); } items_doc(h, a)?; @@ -2029,12 +2029,16 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer { } fn items_to_string(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + layers::scoped_typename(h, a)?; + return Ok(text("[PageItems]")); + } items_doc(h, a)?; Ok(text("[PageItems]")) } fn items_parent(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_parent(h, a); } let doc = items_doc(h, a)?; @@ -2056,7 +2060,7 @@ fn position(n: f64) -> Option { /// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is /// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_at(h, a); } let doc = items_doc(h, a)?; @@ -2082,7 +2086,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Data { } fn items_by_name(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_by_name(h, a); } let doc = items_doc(h, a)?; @@ -2101,7 +2105,7 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_index(h, a); } match arg(a, 1) { @@ -2121,7 +2125,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { /// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, /// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a) { + if layers::is_scoped(a, "PageItems") { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index b9f0bb3a30..4de02e881b 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[ ("PatternColor", &[]), ]; -fn color_object(class: &str, values: &[(&str, f64)]) -> Data { +pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data { let mut items = vec![("typename".to_string(), text(class))]; items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v)))); Data::Object(items) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3cb0686be9..cf06be541a 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -20,7 +20,7 @@ //! - `locked` true means the layer is locked. //! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or //! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it. -//! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255. +//! - A layer's `color` is an `RGBColor` object with values from 0 to 255. //! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it //! gives it its paint, as Make Compound Path takes the paint of a path it joins. //! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a @@ -66,6 +66,8 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, + /// Paths (`PathItem`). + Path, } impl Kind { @@ -74,6 +76,7 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", + Kind::Path => "PathItems", } } @@ -82,6 +85,7 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Path => typename(n) == Some("PathItem"), } } } @@ -247,8 +251,7 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { fn layer_color(h: &Host, a: &[Data]) -> Answer { read_layer(h, a, |_, n| { let [r, g, b] = layer_flags(n).3.rgb(); - let item = |k: &str, v: u8| (k.to_string(), num(f64::from(v))); - Ok(Data::Object(vec![item("red", r), item("green", g), item("blue", b)])) + Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))])) }) } @@ -290,9 +293,13 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let list = layer_list(&st.doc, st.doc.parent_of(id)); - list.iter().position(|l| *l == id).map(|i| list.len() - i) - }); + let parent = st.doc.parent_of(id); + let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len)); + h.charge_call(count as u64)?; + let list = layer_list(&st.doc, parent); + h.charge_call(list.len() as u64)?; + Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) + })?; at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) } @@ -687,10 +694,13 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R Ok(ids) } -/// 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() == 5) +/// Whether a `PageItems` or `PathItems` object's handle names its container. +pub(super) fn is_scoped(a: &[Data], class: &str) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5) +} + +fn scoped_kind(a: &[Data]) -> Kind { + if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any } } /// How many times File › Revert has reloaded the document with uid `uid`. @@ -804,30 +814,29 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { Ok(Data::Undefined) } -/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their -/// handle names one ([`is_scoped`]). +/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]). pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { - art_length(h, a, Kind::Any) + art_length(h, a, scoped_kind(a)) } pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { - art_parent(h, a, Kind::Any) + art_parent(h, a, scoped_kind(a)) } pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { - art_at(h, a, Kind::Any) + art_at(h, a, scoped_kind(a)) } pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { - art_by_name(h, a, Kind::Any) + art_by_name(h, a, scoped_kind(a)) } pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { - art_index(h, a, Kind::Any) + art_index(h, a, scoped_kind(a)) } pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { - art_remove_all(h, a, Kind::Any) + art_remove_all(h, a, scoped_kind(a)) } fn groups_length(h: &Host, a: &[Data]) -> Answer { @@ -868,14 +877,12 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - // A compound path's `pathItems` are its `PageItems`: it holds only paths. - let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); - Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { - art_typename(h, a, Kind::Any) + art_typename(h, a, scoped_kind(a)) } fn groups_typename(h: &Host, a: &[Data]) -> Answer { art_typename(h, a, Kind::Group) @@ -938,6 +945,10 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Any) } +fn held_paths(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Path) +} + fn held_groups(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Group) } @@ -977,6 +988,7 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if now == on { return Ok(Data::Undefined); } + super::refuse_protected_edit(h, item)?; if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } @@ -1002,7 +1014,7 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items), listed("PathItems"))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), _ => Vec::new(), } } @@ -1390,10 +1402,11 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { } { let mut chosen = h.dom.chosen_artboards.borrow_mut(); - if let Some((_, index)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { - *index = i; + let reverts = reverts_of(h, doc.uid); + if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { + *generation = reverts; } else { - chosen.push((doc.uid, i)); + chosen.push((doc.uid, reverts)); } } if i != now { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4f6bb203e..4de44ee6c2 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -385,26 +385,41 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { } fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + if super::layers::is_scoped(a, "PathItems") { + return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into())); + } doc_of(h, arg(a, 0), "PathItems") } /// `typename` of the paths of a document that is still open. fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(Data::String("PathItems".into())) } fn items_length(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_length(h, a); + } let doc = items_doc(h, a)?; Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_at(h, a); + } let doc = items_doc(h, a)?; 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) }; @@ -412,6 +427,9 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_by_name(h, a); + } let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { @@ -436,6 +454,9 @@ 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. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); @@ -1885,6 +1906,7 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", get(l, items_typename), typed("string")), + ("toString", super::class_text("PathItems"), returns("string", &[])), ("length", get(l, items_length), typed("number")), ("parent", get(l, items_parent), typed("Document")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 507c866ee4..ea399d2fd2 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -300,11 +300,42 @@ fn steps_use_the_chosen_index_when_the_chosen_artboard_is_deleted() { 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 report = run_with( + &mut s, + "var b = app.activeDocument.artboards; b.setActiveArtboardIndex(2); b.remove(2);\ + vc.log(b.getActiveArtboardIndex()); app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + vc.log(app.activeDocument.selection[0].position); app.doScript('Fit', 'Set');", + &actions, + ) + .unwrap(); + assert_eq!(report["log"], json!([0, [10, 10]])); + assert_eq!(report["activeArtboards"], json!([{"document": 0, "artboard": 0}])); 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"); + assert_ne!(now[0], was[0], "the fallback artboard is fitted"); + assert_eq!(now[1], was[1], "the other artboard is unchanged"); +} + +#[test] +fn steps_discard_the_chosen_artboard_after_revert() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-actions-revert-artboard"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).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, + "app.activeDocument.artboards.setActiveArtboardIndex(0); app.activeDocument.pageItems[0].name = 'changed'; vc.run('file.revert');\ + app.activeDocument.selection = app.activeDocument.pageItems[0]; app.doScript('Fit', 'Set');", + &actions, + ); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now[..2], was[..2]); + assert_ne!(now[2], was[2], "playback uses the run's original index after revert"); } /// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 215217d011..0945618b88 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2633,6 +2633,71 @@ fn scoped_collections_index_by_number() { assert!(e.contains("Not found"), "{e}"); } +#[test] +fn scoped_collection_methods_reject_the_other_collection_class() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (class, receiver) in + [("PathItems", "app.activeDocument.layers[0].pageItems"), ("PageItems", "app.activeDocument.compoundPathItems[0].pathItems")] + { + for call in ["removeAll.call(r)", "getByName.call(r, '')", "index.call(r, 0)"] { + let source = format!("var r = {receiver}; {class}.prototype.{call};"); + let error = failure(&mut s, &source); + assert!(error.contains(&format!("not a {class}")), "{source}: {error}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + for property in ["typename", "length", "parent"] { + let source = format!("Object.getOwnPropertyDescriptor({class}.prototype, '{property}').get.call({receiver});"); + let error = failure(&mut s, &source); + assert!(error.contains(&format!("not a {class}")), "{source}: {error}"); + } + } + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn clear_releases_a_group_after_removing_its_last_compound_mask_member() { + for mode in ["whole", "anchors", "mixed"] { + 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 compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + if mode == "anchors" { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]})).unwrap(); + } else if mode == "mixed" { + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + } + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + s.execute("edit.clear", &json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(compound).is_none(), "{mode}"); + assert!(d.node(other).is_some(), "{mode}"); + assert!(d.node(group).unwrap().children().unwrap().is_empty(), "{mode}"); + assert!(!d.node(group).unwrap().clips(), "{mode}"); + assert_eq!(undo_steps(&s), steps + 1, "{mode}"); + let after = d.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before, "{mode}"); + assert_eq!(s.active().unwrap().selection, selection, "{mode}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, after, "{mode}"); + } +} + /// Ruler guides left in a clipped layer do not count as other objects: `removeAll()` deletes the /// layer's clipping compound path. #[test] @@ -2646,6 +2711,93 @@ fn scoped_remove_all_deletes_a_clipping_path_beside_ruler_guides() { 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()); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); + let added = rect(&mut s, 200.0, 20.0, 30.0, 40.0); + assert_eq!(s.active().unwrap().doc.parent_of(added), Some(layer)); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(cid).is_some()); + assert!(s.active().unwrap().doc.node(layer).unwrap().clips()); + s.execute("edit.redo", &json!({})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); +} + +#[test] +fn scoped_remove_all_releases_an_empty_clipping_group_in_one_step() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let steps = undo_steps(&s); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);"); + assert_eq!(out, [json!(false), json!(0)]); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.pageItems.length);"); + assert_eq!(out, [json!(true), json!(2)]); +} + +#[test] +fn clipped_setter_refuses_locked_artboards_layers_and_groups() { + for target in ["artboard", "layer", "group"] { + for clipped in [false, true] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + if clipped { + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + } + let layer = s.active().unwrap().doc.layer_containing(NodeId(g)).unwrap(); + s.edit("Lock", |d, _| { + match target { + "artboard" => d.artboards[0].locked = true, + "layer" => d.node_mut(layer).unwrap().locked = true, + _ => d.node_mut(NodeId(g)).unwrap().locked = true, + } + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let src = format!( + "var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {}; vc.log('changed'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);", + !clipped + ); + let out = log(&mut s, &src); + assert!(out[0].as_str().unwrap().contains("locked"), "{target}: {out:?}"); + assert_eq!(out[1], json!(clipped)); + assert_eq!(undo_steps(&s), steps); + } + } +} + +#[test] +fn scoped_collections_convert_to_strings() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0], g = l.groupItems.add(), c = g.compoundPathItems.add();\ + var lists = [l.pageItems, g.pageItems, l.layers, l.groupItems, g.groupItems, l.compoundPathItems, g.compoundPathItems, c.pathItems];\ + for (var i = 0; i < lists.length; i++) { vc.log(String(lists[i])); vc.log(lists[i].toString()); }", + ); + let expected: Vec<_> = ["PageItems", "PageItems", "Layers", "GroupItems", "GroupItems", "CompoundPathItems", "CompoundPathItems", "PathItems"] + .into_iter() + .flat_map(|name| [json!(format!("[{name}]")), json!(format!("[{name}]"))]) + .collect(); + assert_eq!(out, expected); +} + +#[test] +fn layer_color_can_be_assigned_to_path_paint() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; l.color = {red: 10, green: 20, blue: 30};\ + var c = l.color; vc.log(c.typename); var p = l.pageItems[0]; p.fillColor = c;\ + vc.log([p.fillColor.red, p.fillColor.green, p.fillColor.blue]);", + ); + assert_eq!(out, [json!("RGBColor"), json!([10, 20, 30])]); } /// `removeAll()` refuses to delete the compound path that clips a group while the group keeps @@ -2735,7 +2887,11 @@ fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() { let d = &s.active().unwrap().doc; assert!(d.node(to).unwrap().extras().pixel_aligned); let after = d.bounds_of(&[r], false).unwrap(); + assert_ne!(after, before); + assert!(!d.node(r).unwrap().extras().pixel_aligned); assert!([after.x0, after.y0, after.x1, after.y1].iter().all(|v| (v * 2.0).fract().abs() < 1e-9), "not snapped: {after:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.bounds_of(&[r], false).unwrap(), before); } #[test] @@ -2746,9 +2902,24 @@ fn a_compound_paths_path_items_are_path_items() { let out = log( &mut s, "var d = app.activeDocument, p = d.compoundPathItems[0].pathItems; vc.log(p.typename); vc.log(p.length);\ - vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename);", + vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename); vc.log(p instanceof PathItems);\ + vc.log(p instanceof PageItems); vc.log(p.parent === d.compoundPathItems[0]);\ + p[0].name = 'member'; vc.log(p.getByName('member') === p[0]); vc.log(p.index(0) === p[0]);", ); - assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); + assert_eq!( + out, + [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)] + ); + for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] { + let source = format!( + "var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);" + ); + let out = log(&mut s, &source); + assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}"); + assert_eq!(out[1], json!(2)); + } + run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap(); + assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); } #[test] @@ -2818,6 +2989,43 @@ fn scoped_name_searches_are_charged_each_time() { assert_eq!(layer_cost, doc_cost); } +#[test] +fn layer_z_order_scans_are_charged_each_time() { + let (mut s, ..) = doc(); + let repeated = "var l = app.activeDocument.layers[0]; for (var i = 0; i < 512; i++) l.zOrderPosition;"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let small = run(&mut s, repeated); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + small.unwrap(); + for _ in 0..100 { + s.execute("layer.new", &json!({})).unwrap(); + } + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let once = run(&mut s, "var l = app.activeDocument.layers[0]; l.zOrderPosition;"); + let large = run(&mut s, repeated); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + once.unwrap(); + let error = large.unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +#[test] +fn has_selected_artwork_keeps_selected_objects_in_other_layers() { + let (mut s, a, b) = doc(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, other.0]})).unwrap(); + for (operation, a_selected, b_selected) in + [("vc.log(l.hasSelectedArtwork)", true, false), ("l.hasSelectedArtwork = false", false, false), ("l.hasSelectedArtwork = true", true, true)] + { + let source = format!("var l = app.activeDocument.layers.getByName('Layer 1'); {operation};"); + run(&mut s, &source).unwrap(); + assert!(s.active().unwrap().selection.objects.contains(&other), "{operation}"); + let selected = &s.active().unwrap().selection.objects; + assert_eq!((selected.contains(&a), selected.contains(&b)), (a_selected, b_selected), "{operation}"); + } +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f1515c5e64..766969a0f9 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -171,7 +171,10 @@ const INSIDE: &[(&str, &str)] = &[ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", diff --git a/docs/mcp.md b/docs/mcp.md index 67de11e0b9..e9a28ed6bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3132,21 +3132,27 @@ through `$`: `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound - path's `pathItems` have the typename `PathItems`. A layer's or artboard's `name` takes a number or a boolean as - `String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + path's `pathItems` are `PathItems` objects with `length`, `[i]`, `index`, `getByName`, `removeAll` and string conversion. + Their path creation methods throw an error; a script can move existing paths into the compound path. + Scoped collections support `toString()` and `String()`. A layer's or artboard's `name` takes a number or a boolean as + `String()` writes it. `locked` true means the layer is locked. `color` is an `RGBColor` object with `typename` and `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers - beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past + beside it from 1 at the bottom, leaving out art; each scan counts toward the script's operation budget. + `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past the next layer beside it and any art between them. `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false` deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer with nothing to add or deselect runs no command. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping - path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the + path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is + hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer + without art releases its mask in the same undo step. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()` makes an empty compound path in the same place (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` or `duplicate` puts into a compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. The - compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. An empty + compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. A path moved + into an already pixel-aligned compound path is snapped to the pixel grid. An empty compound path takes the paint the first path that goes in was drawn with: the path's own, or the paint of the compound path it leaves. Other objects are refused. A path that `move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths. @@ -3417,8 +3423,9 @@ through `$`: 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. 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 + has been deleted, playback uses the same fallback as `getActiveArtboardIndex()`, script coordinates and the view: + the saved active artboard if it still exists, otherwise index 0. File > Revert discards the script's stored choice. + If the script has not chosen an artboard on that document since its last revert, 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 @@ -4488,6 +4495,7 @@ Without `ids`, direct-selected anchors or selected ruler guides retain their usu With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected. +A clipping group or layer left without art releases its mask in the same undo step. Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as `path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected (the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index df94565ef0..2d9a75efb6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1127,12 +1127,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Scoped collections support string conversion; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. From ec4a813fa3c7426ebbcbbebadc0f03b2abb6410e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:32:07 -0800 Subject: [PATCH 11/17] Scripts: stale placed items are refused as relative objects; exact image matrix checks - move() and duplicate() resolve a page-item relative object, an add() result included, through item_of, so a PlacedItem object made stale by embed() throws "Stale page item" instead of acting as a target. - Assigning matrix compares each requested coefficient exactly with the value the getter reports. A coefficient left as reported keeps the image's own value, so a change of 5e-10 still moves the image and an untouched axis does not shift. A move alone is applied as an offset. A matrix that a nearly singular image cannot reach within 1e-6 pt at its corners, or that would leave it with no area, throws an error with nothing changed, and a change that rounds away runs no command. - The RasterItem.embedded test calls the getter itself on 1 and on a live raster item. - docs/mcp.md states when assigning matrix runs no command and when it is refused. --- crates/engine/src/script/dom.rs | 10 +++- crates/engine/src/script/dom/images.rs | 47 ++++++++++++++-- crates/engine/src/tests/script_dom_images.rs | 56 +++++++++++++++++++- docs/mcp.md | 5 +- 4 files changed, 109 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1946bab86a..fd0c9746ec 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2635,6 +2635,7 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec()); + let is_pending = pending.is_some(); let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer")); let Some(handle) = handle.filter(|parts| parts.len() == 5) else { if handle_of(target, "Document").is_some() { @@ -2642,7 +2643,14 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let (doc, target) = if is_pending || handle_of(target, "PageItem").is_some() { + // A page item, an `add()` result included, must still be of its class: an embedded + // `PlacedItem`'s old object is stale. + let it = item_of(h, target)?; + (it.doc, it.id) + } else { + node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))? + }; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 2373f47302..8ac02076c8 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -27,8 +27,10 @@ //! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only //! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file. //! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of -//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a -//! matrix with no area or one that puts a corner of the image outside the canvas is refused. +//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`, +//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a +//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly +//! is refused. //! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system. use std::cell::RefCell; @@ -525,13 +527,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { return Err(HostError::Range("the matrix puts the image outside the canvas".into())); } let old = im.xf; - if old.as_coeffs().iter().zip(target.as_coeffs()).all(|(o, t)| (o - t).abs() <= 1e-9) { + // Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small + // change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the + // conversion to document space rounds away leaves the image's matrix as it is and runs nothing. + // A coefficient the script left as the getter reports keeps the image's own value, so the + // conversion back does not shift an untouched axis. + let olds = old.as_coeffs(); + let [a0, b0, c0, d0, e0, f0] = olds; + let reported = match h.dom.coords.get() { + Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0], + Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top], + }; + let mut wanted = target.as_coeffs(); + for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) { + if r == v { + *w = o; + } + } + if wanted == olds { return Ok(None); } if !area_of(old) { return Err(HostError::Error("the image has no area to transform".into())); } - Ok(Some((target * old.inverse()).as_coeffs())) + let target = Affine::new(wanted); + let [ta, tb, tc, td, te, tf] = wanted; + if [ta, tb, tc, td] == [a0, b0, c0, d0] { + // A move alone: the offset difference, without the error an inverse adds. + return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0])); + } + // A nearly singular image loses precision through the inverse; refuse a change that would + // not land where the script asked rather than move the image somewhere else. + let delta = target * old.inverse(); + let landed = delta * old; + if landed.as_coeffs() == olds { + return Ok(None); + } + let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| { + let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y)); + (p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6 + }); + if !close || !area_of(landed) { + return Err(HostError::Range("the matrix cannot be applied exactly to this image".into())); + } + Ok(Some(delta.as_coeffs())) })?; if let Some(d) = delta { edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?; diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index f1f58a3c96..7affe83582 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -368,6 +368,55 @@ fn image_matrix_assignment_transforms_the_image() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_tiny_matrix_change_still_transforms_the_image() { + let base = folder("matrix-tiny"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, false); + let before = undo_steps(&s); + let tx = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Image(im) => im.xf.as_coeffs()[4], + _ => panic!("not an image"), + }; + let old = tx(&s); + log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueTX = m.mValueTX + 5e-10; r.matrix = m;"); + assert_eq!(undo_steps(&s), before + 1); + assert!(tx(&s) != old, "the image did not move"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_stale_placed_item_is_not_a_relative_object() { + let base = folder("stale-relative"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + place(&mut s, &a, true); + place(&mut s, &a, true); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems[0], q = d.placedItems[1], r = d.placedItems[2], m = [];\ + r.move(q, ElementPlacement.PLACEBEFORE); m.push('live');\ + var n = d.placedItems.add(); n.file = new File('{}'); r.move(n, ElementPlacement.PLACEAFTER); m.push('added');\ + p.embed();\ + try {{ r.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\ + try {{ r.duplicate(p, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\ + n.embed();\ + try {{ r.move(n, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\ + try {{ r.duplicate(n, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\ + vc.log(m);", + js_path(&a) + ), + ); + assert_eq!(out, vec![json!(["live", "added", "Stale page item", "Stale page item", "Stale page item", "Stale page item"])]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn image_matrix_refuses_bad_values_without_changing_the_image() { let base = folder("matrix-bad"); @@ -489,16 +538,19 @@ fn stale_and_foreign_placed_items_are_refused() { std::fs::write(&a, gray_png(4, 4)).unwrap(); let mut s = session(); let id = place(&mut s, &a, true); + place(&mut s, &a, false); let out = log( &mut s, &base, "var p = app.activeDocument.placedItems[0], m = []; p.remove();\ try { p.relink(null); } catch (e) { m.push(e.message); }\ - try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\ + var g = Object.getOwnPropertyDescriptor(RasterItem.prototype, 'embedded').get;\ + try { g.call(1); } catch (e) { m.push(e.name); }\ + m.push(g.call(app.activeDocument.rasterItems[0]));\ try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\ vc.log(m);", ); - assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]); + assert_eq!(out, vec![json!(["Stale page item", "TypeError", true, "this is not a PlacedItem"])]); assert!(s.active().unwrap().doc.node(id).is_none()); let _ = std::fs::remove_dir_all(base); } diff --git a/docs/mcp.md b/docs/mcp.md index 16c03f4502..1aaa922659 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3215,8 +3215,9 @@ through `$`: `null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY` that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning - `matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of - the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point + `matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value + that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a + nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` From 6a9ab599c49f364cad7b9f8a7d754969da4e6551 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:14:32 -0800 Subject: [PATCH 12/17] Scripts: image lists propagate a page item rebuild error The merge of main brought in fe89d3f8, which makes page_items return a Result so that a rebuilt list counts against the run. The image collection still used the list as a plain Vec, so the engine did not compile (E0308, E0599 in images.rs). It now propagates the error with ?, as the other collections do. --- crates/engine/src/script/dom/images.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index 8ac02076c8..525345ffc6 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -166,7 +166,7 @@ fn images(h: &Host, st: &DocState, placed: bool) -> Result>, Host { return Ok(pick(l)); } - let all = page_items(h, st); + let all = page_items(h, st)?; h.charge_call(all.len() as u64)?; let (mut linked, mut embedded) = (Vec::new(), Vec::new()); for id in all.iter() { From ba45b5d5c26d9d139bb3c32378487d8601c53591 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 12:40:23 -0800 Subject: [PATCH 13/17] New Document: Columns shows the laid-out count when none is stored With no stored column or row count, More Settings showed 1 in Columns while file.new lays a grid out as one row of all the artboards. Entering 1 then matched the shown value and was dropped, so the stored 0 stayed. Columns now shows the count file.new uses for the layout, so entering 1 is stored and a step that leaves the count unchanged changes nothing. --- crates/ui-egui/src/dialogs/new_document.rs | 26 ++++++++++++++++++++-- docs/mcp.md | 3 ++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 4a8bcf6248..0b11d73c5d 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -590,10 +590,17 @@ fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUni /// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns /// those rows give the current number of artboards, as `file.new` lays them out; otherwise the -/// stored count. At most one for each artboard. +/// stored count, where a stored 0 shows the columns `file.new` lays out for the layout. At most +/// one for each artboard. fn shown_columns(s: &DocSettings) -> u32 { let n = s.artboards.max(1); - if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) } + if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { + u32::try_from(s.grid_columns()).unwrap_or(n) + } else if s.columns == 0 { + u32::try_from(s.grid_columns()).unwrap_or(n).clamp(1, n) + } else { + s.columns.min(n) + } } /// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column @@ -1281,6 +1288,21 @@ mod tests { assert_eq!(s.grid_columns(), 2); } + /// A stored column count of 0 shows the one row of all the artboards that `file.new` lays out, so + /// entering 1 is stored and the same count as the row changes nothing. + #[test] + fn a_column_count_without_rows_is_stored() { + let mut s = DocSettings { artboards: 4, layout: ArtboardLayout::GridByRow, columns: 0, rows: 0, ..DocSettings::default() }; + assert_eq!(shown_columns(&s), u32::try_from(s.grid_columns()).unwrap_or(0)); + set_columns(&mut s, 4); + assert_eq!((s.columns, s.rows), (0, 0), "4 is what the row shows"); + set_columns(&mut s, 1); + assert_eq!((s.columns, s.rows), (1, 0)); + assert_eq!(s.grid_columns(), 1); + let column = DocSettings { artboards: 4, layout: ArtboardLayout::Column, columns: 0, rows: 0, ..DocSettings::default() }; + assert_eq!(shown_columns(&column), 1, "the Column layout is one column"); + } + /// The preset keeps the artboard layout, spacing and columns More Settings set (#4893); an empty /// name is refused. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index a39a89360e..abaa351219 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10652,7 +10652,8 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns -the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), +the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes; +with neither `columns` nor `rows` set, Columns shows the columns `file.new` lays out: one row of all the artboards in a grid), `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). From 44c5c4ccd9d77f665107c1f7479bcc856ff9e853 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 14:18:46 -0800 Subject: [PATCH 14/17] Scripts: insert returns nothing, stale collections fail toString, charges and reports fixed - `artboards.insert` returns nothing, as the scripting reference says; `add` still returns the new artboard. - `toString` of `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` checks the collection as `typename` does, so a collection whose container is gone throws instead of stringifying. - The collections' `index` is described as returning their element class, with an `itemKey` of any type. `PageItems.parent` and `PathItems.parent` are described as any type, since scoped collections return a layer or group. - `hasSelectedArtwork` charges the selection and every node of the layer it looks at to the script budget, also when it runs no command. - A document made during the run whose active artboard the run chose is reported when an artboard inserted before it moves it. - Tests: a test-only counter of built art lists bounds the group loop test, and the rejected-parameter checks of `object.newGroup` compare the whole layer tree. --- crates/engine/src/script/dom.rs | 7 +- crates/engine/src/script/dom/layers.rs | 88 +++++++++++++++----- crates/engine/src/script/dom/paths.rs | 2 +- crates/engine/src/script/mod.rs | 3 +- crates/engine/src/tests/script_dom.rs | 108 ++++++++++++++++++++++++- docs/mcp.md | 12 ++- docs/target-app-parity.md | 2 +- 7 files changed, 192 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 738726fb9c..972607dd5d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -176,6 +176,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; thread_local! { /// How many nodes the layer lists of `Layers` objects have looked at on this thread. pub(crate) static LAYER_SCANS: Cell = const { Cell::new(0) }; + /// How many lists of art the art collections have built on this thread. + pub(crate) static ART_SCANS: Cell = const { Cell::new(0) }; } /// What the object model keeps for one run: its coordinate system, the lists of page items and the @@ -227,6 +229,9 @@ pub(super) struct State { pub(super) chosen_artboards: RefCell>, /// Each open document's uid and the index of its active artboard when the run started. pub(super) boards_at_start: Vec<(u64, usize)>, + /// Each document made during the run whose active artboard `setActiveArtboardIndex` chose, + /// with the index it chose the first time. + pub(super) boards_chosen_in_new: RefCell>, /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, text: text::TextState, @@ -3183,7 +3188,7 @@ fn classes(link: &Link) -> Vec { named(vec![ ("typename", get(l, items_typename), typed("string")), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 2f7efc5e8e..4328c1bad2 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_ use super::{ Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, - arg, boolean, class_text, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, - item_ref, later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, - reported_opacity, returns, text, typed, typename, whole, with_doc, + arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, + later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity, + returns, text, typed, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -308,6 +308,24 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) } +/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every +/// child visited, including skipped children. +fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec) -> u64 { + let mut count = 0; + for child in n.children().into_iter().flatten() { + count += 1; + if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() { + continue; + } + if child.is_layer() { + count += collect_editable_art(child, out); + } else { + out.push(child.id); + } + } + count +} + /// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its /// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays, /// and no command runs when there is nothing to deselect or add. @@ -317,11 +335,16 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let (ids, over) = with_doc(h, doc, |_, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); let selected = &st.selection.objects; + h.charge_call(selected.len() as u64)?; if !on { - return (selected.iter().copied().filter(inside).collect::>(), false); + return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::>(), false)); } let locks = st.doc.locked_artboards(); - let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default(); + let mut art = Vec::new(); + let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art)); + // The walk is charged by every node it looks at, hidden and locked ones included, whether + // or not anything is added. + h.charge_call(count)?; let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); for o in art { @@ -330,13 +353,13 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { } // Only art that would be added counts toward the limit. if selected.len() + ids.len() >= MAX_LISTED { - return (ids, true); + return Ok((ids, true)); } have.insert(o); ids.push(o); } - (ids, false) - }); + Ok((ids, false)) + })?; if over { return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); } @@ -672,6 +695,8 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R return Ok(ids); } } + #[cfg(test)] + super::ART_SCANS.with(|c| c.set(c.get() + 1)); let ids: Vec = match container { None => { let all = page_items(h, st)?; @@ -1286,6 +1311,24 @@ fn boards_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("Artboards")) } +/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`. +fn layers_to_string(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("[Layers]")) +} +fn groups_to_string(h: &Host, a: &[Data]) -> Answer { + art_scope(h, arg(a, 0), Kind::Group.class())?; + Ok(text("[GroupItems]")) +} +fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { + art_scope(h, arg(a, 0), Kind::Compound.class())?; + Ok(text("[CompoundPathItems]")) +} +fn boards_to_string(h: &Host, a: &[Data]) -> Answer { + boards_doc(h, a)?; + Ok(text("[Artboards]")) +} + /// An artboard index argument: a whole number below `len` (`len + 1` with `insert`). fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { let n = number(d, what)?; @@ -1366,12 +1409,13 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer { add_board(h, a, None) } -/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing. fn boards_insert(h: &Host, a: &[Data]) -> Answer { if matches!(arg(a, 2), Data::Undefined) { return Err(HostError::Type("insert needs an index".into())); } - add_board(h, a, Some(arg(a, 2))) + add_board(h, a, Some(arg(a, 2)))?; + Ok(Data::Undefined) } fn boards_remove(h: &Host, a: &[Data]) -> Answer { @@ -1409,6 +1453,14 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { chosen.push((doc.uid, reverts)); } } + // A document made during the run has no index from the start of the run, so the first choice + // records one; an artboard inserted before it later still puts it in the report. + if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) { + let mut made = h.dom.boards_chosen_in_new.borrow_mut(); + if !made.iter().any(|(uid, _)| *uid == doc.uid) { + made.push((doc.uid, i)); + } + } if i != now { let mut moved = h.dom.active_artboards.borrow_mut(); if !moved.contains(&doc.uid) { @@ -1480,11 +1532,11 @@ pub(super) fn classes(l: &Link) -> Vec { ("typename", get(l, layers_typename), typed("string")), ("length", get(l, layers_length), typed("number")), ("parent", get(l, layers_parent), typed("*")), - ("index", method(l, layers_index), returns("number", &[("itemKey", "Layer")])), + ("index", method(l, layers_index), returns("Layer", &[("itemKey", "*")])), ("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])), ("add", method(l, layers_add), returns("Layer", &[])), ("removeAll", method(l, layers_remove_all), returns("undefined", &[])), - ("toString", class_text("Layers"), returns("string", &[])), + ("toString", method(l, layers_to_string), returns("string", &[])), ]), Some(super::function(l, layers_at)), ), @@ -1496,11 +1548,11 @@ pub(super) fn classes(l: &Link) -> Vec { ("typename", get(l, groups_typename), typed("string")), ("length", get(l, groups_length), typed("number")), ("parent", get(l, groups_parent), typed("*")), - ("index", method(l, groups_index), returns("number", &[("itemKey", "GroupItem")])), + ("index", method(l, groups_index), returns("GroupItem", &[("itemKey", "*")])), ("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])), ("add", method(l, groups_add), returns("GroupItem", &[])), ("removeAll", method(l, groups_remove_all), returns("undefined", &[])), - ("toString", class_text("GroupItems"), returns("string", &[])), + ("toString", method(l, groups_to_string), returns("string", &[])), ]); m.push(later(l, "GroupItems", "createFromFile")); m @@ -1514,11 +1566,11 @@ pub(super) fn classes(l: &Link) -> Vec { ("typename", get(l, compounds_typename), typed("string")), ("length", get(l, compounds_length), typed("number")), ("parent", get(l, compounds_parent), typed("*")), - ("index", method(l, compounds_index), returns("number", &[("itemKey", "CompoundPathItem")])), + ("index", method(l, compounds_index), returns("CompoundPathItem", &[("itemKey", "*")])), ("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])), ("add", method(l, compounds_add), returns("CompoundPathItem", &[])), ("removeAll", method(l, compounds_remove_all), returns("undefined", &[])), - ("toString", class_text("CompoundPathItems"), returns("string", &[])), + ("toString", method(l, compounds_to_string), returns("string", &[])), ]), Some(super::function(l, compounds_at)), ), @@ -1547,14 +1599,14 @@ pub(super) fn classes(l: &Link) -> Vec { ("typename", get(l, boards_typename), typed("string")), ("length", get(l, boards_length), typed("number")), ("parent", get(l, boards_parent), typed("Document")), - ("index", method(l, boards_index), returns("number", &[("itemKey", "Artboard")])), + ("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])), ("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])), ("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])), ("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])), ("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])), ("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])), ("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])), - ("toString", class_text("Artboards"), returns("string", &[])), + ("toString", method(l, boards_to_string), returns("string", &[])), ]), Some(super::function(l, boards_at)), ), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index f6c3ff11de..7ef59cd3c5 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1926,7 +1926,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("typename", get(l, items_typename), typed("string")), ("toString", super::class_text("PathItems"), returns("string", &[])), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 066d1f054c..2b3141b62e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2641,7 +2641,8 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); - if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) { + let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect(); + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) { report["activeArtboards"] = boards; } let rejections = rejections_report(host, &job.realm); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ebf85d52b7..1d7d7ec858 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3152,7 +3152,12 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\ for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ vc.log(n);"; - let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap()); + crate::script::dom::ART_SCANS.with(|c| c.set(0)); + let a = run(&mut s, nested).unwrap(); + // The groups' list and each group's list are built once: 1 + 5 lists. + let scans = crate::script::dom::ART_SCANS.with(std::cell::Cell::get); + assert!(scans <= 6, "{scans} lists built for 5 groups"); + let b = run(&mut s, in_order).unwrap(); assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); } @@ -3251,11 +3256,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(); + let before = format!("{:?}", s.active().unwrap().doc.layers); 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); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); 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")); } @@ -3287,7 +3292,7 @@ fn new_artboards_get_a_name_no_other_artboard_has() { let out = log( &mut s, "var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\ - vc.log(A.add([500, 300, 700, 100]).name); vc.log(A.insert([0, -100, 100, -200], 0).name);\ + vc.log(A.add([500, 300, 700, 100]).name); A.insert([0, -100, 100, -200], 0); vc.log(A[0].name);\ vc.log(A.add([800, 300, 900, 100]).name);", ); assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); @@ -3400,6 +3405,101 @@ fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() { assert_eq!(s.active().unwrap().active_artboard, Some(first)); } +/// In a document the run makes, choosing artboard 0 and then inserting one before it still puts +/// the document in the report. +#[test] +fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() { + let (mut s, _, _) = doc(); + let r = run( + &mut s, + "var d = app.documents.add(); var A = d.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + let list = r["activeArtboards"].as_array().cloned().unwrap_or_default(); + assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}"); +} + +/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard. +#[test] +fn artboards_insert_returns_nothing() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([0, -100, 100, -200], 0)); vc.log(A.add([500, 300, 700, 100]).typename);", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard")]); +} + +/// The collections' `index` is described as giving an element, and `toString` of a collection +/// whose container is gone fails as `typename` does. +#[test] +fn collection_index_reflection_and_stale_to_string() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log([d.layers.reflect.find('index').dataType, d.groupItems.reflect.find('index').dataType,\ + d.compoundPathItems.reflect.find('index').dataType, d.artboards.reflect.find('index').dataType]);", + ); + assert_eq!(out, [json!(["Layer", "GroupItem", "CompoundPathItem", "Artboard"])]); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let live = log(&mut s, "vc.log(app.activeDocument.groupItems[0].groupItems.toString()); vc.log(app.activeDocument.layers[0].layers.toString());"); + assert_eq!(live, [json!("[GroupItems]"), json!("[Layers]")]); + let source = "var g = app.activeDocument.groupItems[0]; var c = g.groupItems; g.remove(); c.toString();"; + let error = failure(&mut s, source); + assert!(error.contains("Stale page item"), "{error}"); + let source = "var l = app.activeDocument.layers.add(); var c = l.layers; l.remove(); c.toString();"; + let error = failure(&mut s, source); + assert!(error.contains("Stale layer"), "{error}"); +} + +/// Setting `hasSelectedArtwork = true` on a layer whose art is all selected runs no command but +/// is still charged for the art it looks at. +#[test] +fn has_selected_artwork_charges_the_walk_when_nothing_is_added() { + // `locked`: the art is locked, so nothing is selectable; otherwise it is all selected. + let repeated = |n: usize, locked: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + if locked { + s.execute("object.setProps", &json!({"ids": ids, "locked": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + } + let steps = undo_steps(&s); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = true;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(undo_steps(&s), steps); + r + }; + for locked in [false, true] { + repeated(1, locked).unwrap(); + let error = repeated(200, locked).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{locked}: {error}"); + } + // `false` on an empty layer is charged for the selection held in another layer, which stays. + let deselect = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = false;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(s.active().unwrap().selection.objects.len(), n); + r + }; + deselect(1).unwrap(); + let error = deselect(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + #[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 404ba0f220..4528ce4d6f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3148,8 +3148,9 @@ through `$`: (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, `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`), `remove(index)` (runs + has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new` and returns + the new artboard), `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, returns nothing; + read `artboards[index]` afterward), `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 @@ -3161,7 +3162,9 @@ through `$`: depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` are `PathItems` objects with `length`, `[i]`, `index`, `getByName`, `removeAll` and string conversion. Their path creation methods throw an error; a script can move existing paths into the compound path. - Scoped collections support `toString()` and `String()`. A layer's or artboard's `name` takes a number or a boolean as + Scoped collections support `toString()` and `String()`. For `Layers`, `GroupItems`, `CompoundPathItems` and + `Artboards`, the conversion throws the same error as `typename` once the container is deleted or the document is + closed. A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. `locked` true means the layer is locked. `color` is an `RGBColor` object with `typename` and `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art; each scan counts toward the script's operation budget. @@ -3169,7 +3172,8 @@ through `$`: the next layer beside it and any art between them. `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false` deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer - with nothing to add or deselect runs no command. + with nothing to add or deselect runs no command. Each assignment counts the current selection toward the script's + operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 863f4a5986..3fed44ee11 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Scoped collections support string conversion; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. From 1576aac89ff4e568573906cd9ecddbf720909793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:56:24 -0800 Subject: [PATCH 15/17] Scripts: compound path pathItems.index(n) reads the members `PathItems.index()` with a number went straight to `items_doc`, which refuses every compound-path-scoped `PathItems` so that creating paths there stays unavailable. Its siblings (`[n]`, `getByName`, `length`, `removeAll`) already dispatch scoped collections to the layer handlers first, but `index` did not, so `compoundPathItems[0].pathItems.index(0)` threw "creating paths in a compound path is not available yet". Route a scoped `index` to `scoped_index` like the other lookups; the guard now only stops real creation. --- crates/engine/src/script/dom/paths.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ae2fcda50a..4ac860ebee 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -477,6 +477,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { From 499055bbbdbeced54007b481b9b60c8af93f35ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:16:38 -0800 Subject: [PATCH 16/17] Tools: show Edit Toolbar alone in the one-column rail The one-column Tools rail stacked Search above Edit Toolbar in its footer. The extra row made the default rail taller than a 1000 pt window holds, so the rail scrolled and Edit Toolbar was out of view. A one-column rail now shows Edit Toolbar alone. Search Commands stays in the title bar, Help > Search Commands... and its shortcut. The two-column rail keeps Search beside Edit Toolbar. Tests: one_column_rail_shows_edit_toolbar_in_a_1000_point_window; the #8758 layout test checks the one-column footer, and the search query test runs on the two-column rail. --- crates/ui-egui/src/toolbar.rs | 26 +++++++-------- crates/ui-egui/src/toolbar/tests.rs | 50 +++++++++++++++++++++++------ docs/gaps.md | 2 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 4 +-- 6 files changed, 59 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 34a7829ba9..217c08bf42 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -21,7 +21,7 @@ use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowC use craft::ui::display::Divider; use craft::ui::docking::{DockGrid, GroupAt}; use craft::ui::form::Field; -use craft::ui::layout_components::{Row, Stack}; +use craft::ui::layout_components::Row; use craft::ui::pickers::{Anchor9, ReferencePointLook, Select}; use craft::ui::rails::{LastUsed, RailDensity, RailFooter, RailTool, SlotId, ToolRail, ToolSlot}; use craft::ui::runtime::commands::{self, CommandRef}; @@ -893,17 +893,21 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) { } pub(crate) mod card; -/// Search and Edit Toolbar share a row in a wide rail; a narrow rail keeps Edit Toolbar last. +/// Search and Edit Toolbar share a row in a wide rail. A one-column rail shows Edit Toolbar alone, so the default +/// rail still fits a 1000 pt window; Search Commands stays in the title bar, the Help menu and on its shortcut. fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter) -> Option { let enabled = !crate::panel_docking::modal_window_up(app); + let wide = footer.columns > 1; let mut edit = None; let buttons = |ui: &mut Ui, _: &mut BodyCx<'_>| { - IconButton::command(IconId::new("search"), "help.commandPalette") - .label(tl!("Search commands")) - .tooltip(tl!("Search commands, tools, panels and effects")) - .selected(app.ui.palette_open) - .enabled(enabled) - .show(ui); + if wide { + IconButton::command(IconId::new("search"), "help.commandPalette") + .label(tl!("Search commands")) + .tooltip(tl!("Search commands, tools, panels and effects")) + .selected(app.ui.palette_open) + .enabled(enabled) + .show(ui); + } edit = Some( IconButton::new(IconId::new("more")) .label(tl!("Edit Toolbar")) @@ -913,11 +917,7 @@ fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter .response, ); }; - if footer.columns > 1 { - Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); - } else { - Stack::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); - } + Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); edit } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 91becce66b..bd52339ac2 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -703,19 +703,22 @@ fn review_8758_layout(double: bool) { let nodes = settled(&mut app, &ctx, 0.0, 1400.0); review_8758_edit_control(&mut app, &ctx, &nodes); let nodes = settled(&mut app, &ctx, 3.0, 1400.0); - let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap(); let panel = review_8758_panel(&app, &ctx); + if !double { + assert!(panel.contains_rect(edit) && edit.bottom() <= 1400.0, "Edit Toolbar fits the actual Tools panel"); + assert!( + !nodes + .iter() + .any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| panel.contains_rect(r))), + "a one-column rail shows Edit Toolbar alone" + ); + return; + } + let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); assert!(panel.contains_rect(search) && panel.contains_rect(edit), "both controls fit the actual Tools panel"); assert!(search.bottom() <= 1400.0 && edit.bottom() <= 1400.0, "both controls fit the window"); - if double { - assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row"); - } else { - assert!( - search.bottom() <= edit.top() && (search.center().x - edit.center().x).abs() < 0.01, - "one column keeps both controls in a fitted stack" - ); - } + assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row"); let chord = crate::menus::shortcut_of(&app, "help.commandPalette").expect("the native Search command has its current shortcut"); let expected = craft::ui::contract::tooltip::with_chord("Search commands, tools, panels and effects", &chord, crate::keymap::platform()); let tips = review_8758_hovered_texts(&mut app, &ctx, 4.0, search.center()); @@ -744,10 +747,39 @@ fn review_8758_toolbar_search_fits_beside_edit_and_opens_the_existing_palette() } } +/// The default one-column rail in a window 1000 points tall: its footer ends with Edit Toolbar inside the rail's +/// visible area, so the button shows without scrolling the rail. +#[test] +fn one_column_rail_shows_edit_toolbar_in_a_1000_point_window() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(300, 300); + let ctx = reader(); + let nodes = settled(&mut app, &ctx, 0.0, 1000.0); + let panel = review_8758_panel(&app, &ctx); + let rail = nodes + .iter() + .find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools") && bounds(n).is_some_and(|r| panel.contains_rect(r))) + .and_then(bounds) + .expect("the Tools rail is drawn"); + let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap(); + let screen_mode = named_rect(&nodes, "Change Screen Mode (F)"); + assert!(rail.contains_rect(edit), "Edit Toolbar shows inside the rail without scrolling: {edit:?} in {rail:?}"); + assert!(screen_mode.bottom() <= edit.top(), "Edit Toolbar stays the last control of the footer"); + assert!( + !nodes.iter().any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| rail.intersects(r))), + "one column leaves Search Commands to the title bar, the Help menu and its shortcut" + ); + // Edit Toolbar still opens the Tools customization drawer. + click(&mut app, &ctx, 1.0, edit.center(), 1000.0); + assert!(app.ui.tools_drawer, "the footer's Edit Toolbar opens the customization drawer"); +} + #[test] fn review_8758_toolbar_search_accepts_a_tool_query_and_is_disabled_over_a_dialog() { crate::i18n::set_current(crate::i18n::Lang::EN); let mut app = app_with(300, 300); + // The two-column rail, whose footer has Search. + app.run("window.toolbarColumns", json!({"double": true})).unwrap(); let ctx = reader(); let nodes = settled(&mut app, &ctx, 0.0, 1400.0); let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); diff --git a/docs/gaps.md b/docs/gaps.md index f17b874b92..b7a50c6cdf 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -27,7 +27,7 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offe OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. - **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. diff --git a/docs/roadmap.md b/docs/roadmap.md index f2e6058229..16a01a5ac1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -33,7 +33,7 @@ ## Feature submission evidence Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..41f90515cf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -77,7 +77,7 @@ Script appearance and geometry setters reject objects on locked artboards. Assig **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f2bd6e1ff3..611ae42c25 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -29,7 +29,7 @@ **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. @@ -497,7 +497,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | unknown | | Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | unknown | | Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | unknown | -| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and stacked in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown | +| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and Edit Toolbar alone in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown | | Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | unknown | | Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | unknown | | Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | unknown | From 32f4dfd62a307d75596ce8f3e10764686870da2a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:29:36 -0800 Subject: [PATCH 17/17] Docs: title-bar Search shows only while the app bar is wide enough In a narrow window the title bar drops Search, so the one-column Tools note now names Help > Search Commands... and its shortcut first. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 41f90515cf..92fad7cdcb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -77,7 +77,7 @@ Script appearance and geometry setters reject objects on locked artboards. Assig **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. -**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in Help › Search Commands… and its shortcut, and in the title bar while the app bar is wide enough to show it. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.