From 92cc8c77e5e50cb4f0ad37a88eb31c518f5c1eed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:19:32 -0800 Subject: [PATCH 01/49] Scripts: layers, groups, compound paths and artboards for scripts A document now has layers, activeLayer, groupItems, compoundPathItems and artboards, and every page item has its layer. - Layers and sublayers: add, remove, removeAll, getByName, index, name, visibility, lock, print, preview, dim images, opacity, color, stacking, move and zOrder, each through the existing layer and node commands. - Groups: clipped makes or releases the clipping mask, and groupItems.add() makes an empty group through the new narrow command object.newGroup. A document's groupItems and compoundPathItems hold every group or compound path at any depth; a layer's or group's hold only the ones directly in it. - Artboards: add, insert, remove, getByName, rectangles, names, ruler origin, pixel aspect ratio and display options, and the active artboard. A new artboard gets an "Artboard N" name no other artboard has. setActiveArtboardIndex adds no undo step; script.run's report lists the change in activeArtboards and the app shows it. - Bad values throw before any command runs, and a value a layer or artboard already has runs no command. Handles to a deleted layer or artboard throw Stale layer or Stale artboard. Docs: docs/mcp.md, docs/gaps.md, docs/target-app-parity.md. --- crates/engine/src/cmd/object/arrange.rs | 31 + crates/engine/src/cmd/object/commands.rs | 11 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/script/dom.rs | 56 +- crates/engine/src/script/dom/layers.rs | 1339 +++++++++++++++++ crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests/script_dom.rs | 337 ++++- .../tests/it/script_host_vs_scriptcheck.rs | 56 +- crates/ui-egui/src/script_runs.rs | 17 + crates/ui-egui/src/tests/script_run.rs | 12 + docs/gaps.md | 6 +- docs/mcp.md | 53 +- docs/target-app-parity.md | 3 +- 13 files changed, 1883 insertions(+), 42 deletions(-) create mode 100644 crates/engine/src/script/dom/layers.rs diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index a0f292fecf..bd993ec1ec 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -105,6 +105,37 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { Ok(json!({ "id": gid.0 })) } +/// `object.newGroup`: an empty group in a layer or a group (default: the current layer), on top +/// of its contents or at `index` (0 = bottom). The selection stays as it is. +pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.newGroup"; + 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"))?, + 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, + 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; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + let gid = s.edit("Group", |d, _| { + let gid = d.alloc_id(); + let clips = d.node(parent).is_some_and(Node::clips); + let index = if clips { index.max(1) } else { index }; + d.insert(Some(parent), index, Node::group(gid, Vec::new()))?; + Ok(gid) + })?; + Ok(json!({ "id": gid.0 })) +} + /// Put `ids` (top-level objects, in paint order) in a new group where the front-most one was. pub(crate) fn group_nodes(d: &mut Document, ids: &[NodeId]) -> Result { if ids.is_empty() { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0bc08c748e..dab3a0378c 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -1,5 +1,5 @@ use super::align::{align, can_distribute, distribute, distribute_spacing}; -use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all}; +use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, new_group, send_to_current_layer, show_all, ungroup, unlock_all}; use super::bounds::set_bounds; use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release}; use super::pixelgrid::set_pixel_aligned; @@ -137,6 +137,15 @@ pub fn specs() -> Vec { has_selection, group ), + cmd!( + "object.newGroup", + "Group", + [], + None, + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom; default: on top)} → {id}: an empty group in a shown, unlocked layer or group; the selection stays as it is", + has_doc, + new_group + ), cmd!( "object.ungroup", "Ungroup", diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..d7be5411ae 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -334,6 +334,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.mesh.movePoints", "object.mesh.setPointColor", "object.move", + "object.newGroup", "object.nudge", "object.objectsOnPath.attach", "object.objectsOnPath.detach", diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 55073e70ec..7bfecbb264 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +pub(super) mod layers; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -92,6 +94,9 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + /// The documents whose active artboard `setActiveArtboardIndex` changed: each one's uid and + /// the artboard's id. + pub(super) active_artboards: RefCell>, } impl State { @@ -151,7 +156,7 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. +/// the check that a document, layer or page item `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -162,7 +167,10 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "Layer" => { + layers::layer_of(&h, arg(&a, 0))?; + } + c if c == "PageItem" || ITEM_CLASSES.contains(&c) => { item_of(&h, arg(&a, 0))?; } _ => {} @@ -1122,22 +1130,34 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_length(h, a); + } let doc = items_doc(h, a)?; let n = with_doc(h, doc, |_, st| page_items(h, st).len()); Ok(num(float(n as u64))) } fn items_typename(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(text("PageItems")) } fn items_parent(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) } fn items_at(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return 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) }; @@ -1145,6 +1165,9 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { } fn items_by_name(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return 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| { @@ -1169,6 +1192,9 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { /// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or /// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); @@ -1644,19 +1670,6 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -fn layer_name(h: &Host, a: &[Data]) -> Answer { - let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); - with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) -} - -fn layer_typename(h: &Host, a: &[Data]) -> Answer { - layer_name(h, a)?; - Ok(text("Layer")) -} - fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } @@ -1752,11 +1765,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("pageItems", get(l, doc_page_items)), ("selection", property(l, doc_selection, doc_set_selection)), ]); - document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] - .into_iter() - .map(|m| later(l, "Document", m)), - ); + document.extend(["pathItems", "textFrames", "swatches", "symbols", "views", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m))); + document.extend(layers::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1795,12 +1805,12 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("remove", method(l, item_remove)), ("zOrder", method(l, item_z_order)), ]); + page_item.extend(layers::page_item_members(l)); page_item.extend( [ "artworkKnockout", "blendingMode", "isIsolated", - "layer", "pixelAligned", "sliced", "tags", @@ -1820,8 +1830,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), layers::members(c, l), None))); + classes.extend(layers::classes(l)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs new file mode 100644 index 0000000000..a6b165fbef --- /dev/null +++ b/crates/engine/src/script/dom/layers.rs @@ -0,0 +1,1339 @@ +//! Layers, groups, compound paths and artboards in the script object model, as the help pages +//! , +//! , +//! , +//! , +//! , +//! and +//! describe them. +//! +//! A layer is named by its id and an artboard by its artboard id, so a handle keeps naming the same +//! one after others are added, moved or removed, and throws once it is gone. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `layers` lists layers top first, as the Layers panel shows them; `groupItems`, +//! `compoundPathItems` and a layer's or group's `pageItems` list art in paint order, bottom first, +//! as `pageItems` does. The document's `groupItems` and `compoundPathItems` hold every group or +//! compound path at any depth; a layer's or group's hold the ones directly in it. +//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes +//! a sublayer on top of that layer's contents. The new layer becomes the current one. +//! - `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. +//! - `CompoundPathItems.add()` throws: a compound path holds at least one path. +//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a +//! document, the limit `Documents.add` uses. Artboard names are unique: a name another artboard +//! has throws. +//! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global +//! rulers, setting it moves the document's zero point. +//! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report +//! lists it in `activeArtboards` for the app to show. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; + +use super::{ + Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, 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, + page_items, placement_of, property, set_selection, text, typename, whole, with_doc, +}; +use crate::script::{Host, Link}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error for a layer that was deleted, or that came from an earlier run. +pub const STALE_LAYER: &str = "Stale layer"; +/// The error for an artboard that was deleted, or that came from an earlier run. +pub const STALE_ARTBOARD: &str = "Stale artboard"; +/// The longest name a layer takes, in characters, as Layer Options keeps it. +pub const MAX_LAYER_NAME: usize = 512; + +type Result = std::result::Result; + +/// What a collection of art lists. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + /// Every page item. + Any, + /// Groups (`GroupItem`). + Group, + /// Compound paths (`CompoundPathItem`). + Compound, +} + +impl Kind { + fn class(self) -> &'static str { + match self { + Kind::Any => "PageItems", + Kind::Group => "GroupItems", + Kind::Compound => "CompoundPathItems", + } + } + + fn holds(self, n: &crate::doc::Node) -> bool { + match self { + Kind::Any => typename(n).is_some(), + Kind::Group => typename(n) == Some("GroupItem"), + Kind::Compound => typename(n) == Some("CompoundPathItem"), + } + } +} + +fn type_error(what: &str) -> HostError { + HostError::Type(format!("this is not a {what}")) +} + +/// The id a command's result gives under `key`. +fn result_id(d: &Data, key: &str) -> Option { + let Data::Object(o) = d else { return None }; + match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { + Some(Data::Number(n)) => whole(*n), + _ => None, + } +} + +// ---- Layer ---- + +/// The layer `d` names, which must still be a layer of its document. +pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> { + let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(type_error("Layer")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer)); + if !ok { + return Err(HostError::Error(STALE_LAYER.into())); + } + Ok((doc, id)) +} + +fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { + layer_of(h, arg(a, 0)) +} + +fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { + let [high, low] = id_parts(id); + host_ref("Layer", &[float(h.run), float(uid), high, low]) +} + +/// Reads the layer `this` names with `f`. +fn read_layer(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let (doc, id) = this_layer(h, a)?; + with_doc(h, doc, |_, st| match st.doc.node(id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_LAYER.into())), + }) +} + +/// Runs `id` with `params` and the layer's id on its document, unless `unchanged` says the layer +/// already has what they set. +fn set_layer(h: &Host, a: &[Data], command_id: &str, unchanged: impl FnOnce(&crate::doc::Node) -> bool, params: Value) -> Answer { + let (doc, id) = this_layer(h, a)?; + let same = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(unchanged)); + if !same { + let mut p = params; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([id.0])); + } + on_doc(h, doc.uid, true, |h| command(h, command_id, &p))?; + } + Ok(Data::Undefined) +} + +fn layer_flags(n: &crate::doc::Node) -> (bool, bool, Option, crate::doc::LayerColor) { + match &n.kind { + NodeKind::Layer { printable, preview, dim_images, color, .. } => (*printable, *preview, *dim_images, *color), + _ => (true, true, None, crate::doc::LayerColor::Preset(0)), + } +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +fn layer_set_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) }; + if name.trim().is_empty() { + return Err(HostError::Range("a layer's name cannot be empty".into())); + } + if name.chars().count() > MAX_LAYER_NAME { + return Err(HostError::Range(format!("a layer's name has at most {MAX_LAYER_NAME} characters"))); + } + set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), json!({"name": name})) +} + +fn layer_visible(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.visible))) +} + +fn layer_set_visible(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "visible")?; + set_layer(h, a, "layer.setProps", |n| n.visible == v, json!({"visible": v})) +} + +fn layer_locked(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn layer_set_locked(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "locked")?; + set_layer(h, a, "layer.setProps", |n| n.locked == v, json!({"locked": v})) +} + +fn layer_printable(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).0))) +} + +fn layer_set_printable(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "printable")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).0 == v, json!({"printable": v})) +} + +fn layer_preview(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).1))) +} + +fn layer_set_preview(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "preview")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).1 == v, json!({"preview": v})) +} + +fn layer_dim(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).2.is_some()))) +} + +fn layer_set_dim(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "dimPlacedImages")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).2.is_some() == v, json!({"dimImages": v})) +} + +fn layer_opacity(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) +} + +fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + 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})) +} + +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)])) + }) +} + +/// `color = {red, green, blue}`: each a whole number from 0 to 255. +fn layer_set_color(h: &Host, a: &[Data]) -> Answer { + let Data::Object(o) = arg(a, 1) else { return Err(HostError::Type("color must be an object with red, green and blue".into())) }; + let mut rgb = [0u8; 3]; + for (slot, key) in rgb.iter_mut().zip(["red", "green", "blue"]) { + let v = o.iter().find(|(k, _)| k == key).map(|(_, v)| v).unwrap_or(&Data::Undefined); + let n = number(v, &format!("color.{key}"))?; + if n.fract() != 0.0 || !(0.0..=255.0).contains(&n) { + return Err(HostError::Range(format!("color.{key} must be a whole number from 0 to 255"))); + } + *slot = u8::try_from(whole(n).unwrap_or(0)).unwrap_or(0); + } + let hex = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]); + set_layer(h, a, "layer.setProps", |n| layer_flags(n).3.rgb() == rgb, json!({"color": hex})) +} + +fn layer_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(with_doc(h, doc, |_, st| match st.doc.parent_of(id) { + Some(p) => layer_ref(h, st.uid, p), + None => doc_ref(h, st.uid), + })) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + this_layer(h, a)?; + Ok(text("Layer")) +} + +/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is +/// not counted. +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) + }); + at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) +} + +fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + 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)))))) +} + +/// `hasSelectedArtwork = false` deselects the layer's art; `true` adds its visible, unlocked art +/// to the selection. +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 = with_doc(h, doc, |_, st| { + let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); + let mut ids: Vec = st.selection.objects.clone(); + if on { + 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 = ids.iter().copied().collect(); + for o in art { + if ids.len() > MAX_LISTED { + break; + } + if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + have.insert(o); + ids.push(o); + } + } + } else { + ids.retain(|o| !inside(o)); + } + ids + }); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); + } + set_selection(h, doc, ids) +} + +fn layer_is_isolated(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.isolation == Some(id)))) +} + +fn layer_remove(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": [id.0]})))?; + Ok(Data::Undefined) +} + +/// The layers of `parent` (`None`: the top level), without its ruler guides and art. +fn art_count(d: &Document, parent: Option) -> usize { + d.children(parent).map_or(0, |c| crate::doc::Node::guide_run_start(c)) +} + +/// Moves the layer `id` to `index` of `parent` with `node.move`, unless it is there already. +fn put_layer(h: &Host, doc: Doc, id: NodeId, parent: Option, index: usize) -> Result<()> { + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == parent && i == index) { + return Ok(()); + } + let parent = parent.map_or(Value::Null, |p| json!(p.0)); + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": parent, "index": index})))?; + Ok(()) +} + +/// `zOrder(method)`: the layer goes to the top or the bottom of the layers beside it, or one step. +fn layer_z_order(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let method = match arg(a, 1) { + Data::String(s) => s.as_str(), + _ => "", + }; + let (parent, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + let (parent, i, _) = d.position(id).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let count = art_count(d, parent); + let last = count.saturating_sub(1); + // One step passes the next layer beside it, and the art between them. + let layer_at = |j: &usize| d.children(parent).and_then(|c| c.get(*j)).is_some_and(|n| n.is_layer()); + let to = match method { + "ZOrderMethod.BRINGTOFRONT" => last, + "ZOrderMethod.BRINGFORWARD" => (i + 1..count).find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDBACKWARD" => (floor.min(i)..i).rev().find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDTOBACK" => floor.min(i), + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + Ok((parent, to)) + })?; + put_layer(h, doc, id, parent, index)?; + Ok(Data::Undefined) +} + +/// `move(relativeObject, insertionLocation?)`: the layer goes into another layer (on top of its +/// contents, or at the bottom with `PLACEATEND`), to the top level of a document, or directly +/// above or below another layer. +fn layer_move(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let how = placement_of(arg(a, 2))?; + let target = arg(a, 1); + let parent = if let Some(handle) = handle_of(target, "Document") { + let [run, uid] = handle.as_slice() else { return Err(type_error("Document")) }; + let to = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if matches!(how, Placement::Above | Placement::Below) { + return Err(HostError::Error("a layer goes above or below another layer, not a document".into())); + } + None + } else if handle_of(target, "Layer").is_some() { + let (to, t) = layer_of(h, target)?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + Some(t) + } else if matches!(target, Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } else { + return Err(HostError::Type("a layer's relative object must be a layer or a document".into())); + }; + let (into, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + if let Some(t) = parent + && d.ancestry(t).is_some_and(|a| a.contains(&id)) + && !(t == id && matches!(how, Placement::Above | Placement::Below)) + { + return Err(HostError::Error("a layer cannot go into itself".into())); + } + let (into, beside) = match (how, parent) { + (Placement::Above | Placement::Below, Some(t)) => (d.parent_of(t), Some(t)), + (_, p) => (p, None), + }; + if into.is_some_and(|p| !editable(d, p)) { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + let from = d.position(id); + let here = |p: Option| from.is_some_and(|(q, ..)| q == p); + let count = art_count(d, into) - usize::from(here(into)); + let floor = usize::from(into.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips) && count > 0); + let index = match (how, beside) { + (Placement::Above | Placement::Below, Some(b)) => { + if b == id { + return Ok((into, from.map_or(0, |(_, i, _)| i))); + } + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + if let Some((_, j, _)) = from + && here(into) + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (Placement::Bottom, _) => 0, + _ => count, + }; + Ok((into, index.max(floor))) + })?; + put_layer(h, doc, id, into, index)?; + Ok(arg(a, 0).clone()) +} + +// ---- Layers ---- + +/// The document and the layer (`None`: the top level) a `Layers` object lists. +fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) }; + 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] => { + let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low]))?; + Ok((doc, Some(id))) + } + _ => Err(type_error("Layers")), + } +} + +/// The layers of `parent` (`None`: the top level), top first. +fn layer_list(d: &Document, parent: Option) -> Vec { + let list = match parent { + None => Some(&d.layers), + Some(p) => d.children(Some(p)), + }; + list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() +} + +fn layers_of(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let [high, low] = id_parts(id); + Ok(host_ref("Layers", &[float(h.run), float(doc.uid), high, low])) +} + +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))) +} + +fn layers_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(parent.map_or_else(|| doc_ref(h, doc.uid), |p| layer_ref(h, doc.uid, p))) +} + +fn layers_typename(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("Layers")) +} + +fn layers_at(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + 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)))) +} + +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); + 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())) + }) +} + +fn layers_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => layers_by_name(h, a), + Data::Number(_) => match layers_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `layers.add()`: a new layer above every top-level layer, or a sublayer on top of the layer's +/// contents. → the new layer, which is the current one. +fn layers_add(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Some(p) = parent { + let ok = with_doc(h, doc, |_, st| editable(&st.doc, p)); + if !ok { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + } + let r = on_doc(h, doc.uid, true, |h| match parent { + None => command(h, "layer.new", &json!({"top": true})), + Some(p) => command(h, "layer.newSublayer", &json!({"parent": p.0})), + })?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; + Ok(layer_ref(h, doc.uid, NodeId(id))) +} + +/// `layers.removeAll()`: deletes every layer of the collection in one command. A document keeps a +/// layer, so on the top-level layers it throws before anything is deleted. +fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + 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)); + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- GroupItems, CompoundPathItems and a container's PageItems ---- + +/// The document and the layer, group or compound path (`None`: the whole document) an art +/// collection of `class` lists. +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] => { + 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()))?; + let holds = with_doc(h, doc, |_, st| { + 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())); + } + Ok((doc, Some(id))) + } + _ => Err(type_error(class)), + } +} + +/// The objects of `kind` in `container` (directly), or in the whole document at any depth, in +/// paint order. +fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result> { + let ids: Vec = match container { + None => { + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() + } + Some(c) => st.doc.node(c).and_then(|n| n.children()).into_iter().flatten().filter(|n| kind.holds(n)).map(|n| n.id).collect(), + }; + 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() == 4) +} + +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]]), + None => host_ref(kind.class(), &[float(h.run), float(uid)]), + } +} + +fn art_length(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let n = with_doc(h, doc, |_, st| art_list(h, st, kind, c).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) +} + +fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + 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) }; + with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + 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)?; + 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())) + }) +} + +fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { + match arg(a, 1) { + Data::String(_) => art_by_name(h, a, kind), + Data::Number(_) => match art_at(h, a, kind)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every object the collection lists (those inside another listed one go +/// with it) in one command. A hidden or locked one, or one in a hidden or locked layer or group, +/// stops it before anything is deleted. +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) = 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(); + let ids: Vec = + all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); + let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + Ok::<_, HostError>((ids, refused)) + })?; + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {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::>()})))?; + } + Ok(Data::Undefined) +} + +/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their +/// handle names one ([`is_scoped`]). +pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Any) +} + +pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Any) +} + +pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Any) +} + +pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Any) +} + +pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Any) +} + +fn groups_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Group) +} +fn groups_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Group) +} +fn groups_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Group) +} +fn groups_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Group) +} +fn groups_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Group) +} +fn groups_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Group) +} +fn compounds_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Compound) +} +fn compounds_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Compound) +} +fn compounds_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Compound) +} +fn compounds_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Compound) +} +fn compounds_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Compound) +} +fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Compound) +} + +fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { + 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) +} +fn groups_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Group) +} +fn compounds_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Compound) +} + +/// `groupItems.add()`: an empty group on top of the layer's or group's contents (the document's: +/// the current layer's), with `object.newGroup`. → the group. +fn groups_add(h: &Host, a: &[Data]) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), "GroupItems")?; + if let Some(c) = c { + let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + if compound { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } + let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + let r = on_doc(h, doc.uid, true, |h| command(h, "object.newGroup", ¶ms))?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +fn compounds_add(_: &Host, _: &[Data]) -> Answer { + Err(HostError::Error("CompoundPathItems.add cannot make an empty compound path: a compound path holds at least one path".into())) +} + +// ---- The art collections of a document, a layer, a group and a compound path ---- + +/// The collection of `kind` the object `this` holds: a document's (`Document`), a layer's +/// (`Layer`) or a page item's. +fn held(h: &Host, a: &[Data], kind: Kind) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Document").is_some() { + let doc = doc_of(h, this, "Document")?; + return Ok(collection(h, kind, None, doc.uid)); + } + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(collection(h, kind, Some(id), doc.uid)); + } + let item = item_of(h, this)?; + Ok(collection(h, kind, Some(item.id), item.doc.uid)) +} + +fn held_page_items(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Any) +} + +fn held_groups(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Group) +} + +fn held_compounds(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Compound) +} + +// ---- GroupItem and CompoundPathItem ---- + +fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { + let item = item_of(h, arg(a, 0))?; + let ok = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename) == Some(what)); + if !ok { + return Err(type_error(what)); + } + Ok(item) +} + +/// The layer the object is in. +fn item_layer(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + Ok(with_doc(h, item.doc, |_, st| st.doc.layer_containing(item.id).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +fn group_clipped(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "GroupItem")?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(crate::doc::Node::clips)))) +} + +/// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the +/// clipping mask. The group keeps its id either way. +fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "clipped")?; + let item = this_item_of(h, a, "GroupItem")?; + let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id))); + if now == on { + return Ok(Data::Undefined); + } + if !ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); + } + on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; + Ok(Data::Undefined) +} + +/// The members `layers.rs` adds to `PageItem`'s. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("layer", get(l, item_layer))]) +} + +/// The members a page item class adds to `PageItem`'s. +pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { + match class { + "GroupItem" => { + let mut m = named(vec![ + ("clipped", property(l, group_clipped, group_set_clipped)), + ("pageItems", get(l, held_page_items)), + ("groupItems", get(l, held_groups)), + ("compoundPathItems", get(l, held_compounds)), + ]); + m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m + } + "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), + _ => Vec::new(), + } +} + +// ---- Document ---- + +fn doc_layers(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Layers", &[float(h.run), float(doc.uid)])) +} + +fn doc_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +/// `activeLayer = layer`: the layer becomes the current one, where new art goes. +fn doc_set_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + let (to, id) = layer_of(h, arg(a, 1))?; + if to.uid != doc.uid { + return Err(HostError::Error("the layer is in another document".into())); + } + let now = with_doc(h, doc, |_, st| st.current_layer()); + if now != Some(id) { + on_doc(h, doc.uid, true, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; + } + Ok(Data::Undefined) +} + +fn doc_artboards(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Artboards", &[float(h.run), float(doc.uid)])) +} + +/// The members `layers.rs` adds to `Document`'s. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("layers", get(l, doc_layers)), + ("activeLayer", property(l, doc_active_layer, doc_set_active_layer)), + ("groupItems", get(l, held_groups)), + ("compoundPathItems", get(l, held_compounds)), + ("artboards", get(l, doc_artboards)), + ]) +} + +// ---- Artboard and Artboards ---- + +/// The document of an artboard. +#[derive(Clone, Copy)] +struct Board { + doc: Doc, +} + +fn board_index(st: &DocState, id: u32) -> Option { + st.doc.artboards.iter().position(|a| a.id == id) +} + +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 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()))?; + 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)]) +} + +fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> { + board_of(h, arg(a, 0)) +} + +/// Reads the artboard `this` names with `f`. +fn read_board(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Artboard, usize) -> Answer) -> Answer { + let (b, i) = this_board(h, a)?; + with_doc(h, b.doc, |_, st| match st.doc.artboards.get(i) { + Some(ab) => f(st, ab, i), + None => Err(HostError::Error(STALE_ARTBOARD.into())), + }) +} + +/// Runs `artboard.setProps` with `props` for the artboard, unless `unchanged` says it has them. +fn set_board(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Artboard) -> bool, props: Value) -> Answer { + let (b, i) = this_board(h, a)?; + let same = with_doc(h, b.doc, |_, st| st.doc.artboards.get(i).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("index".into(), json!(i)); + } + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.setProps", &p))?; + } + Ok(Data::Undefined) +} + +fn board_rect(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, _| Ok(frame(st)?.bounds(h.dom.coords.get(), ab.rect))) +} + +/// A rectangle `[left, top, right, bottom]` a script gave, in document coordinates, checked: finite, +/// inside the canvas, and from 1 to [`super::MAX_SIZE`] points on each side, the sides the artboard +/// commands keep. +fn rect_arg(h: &Host, st: &DocState, d: &Data, what: &str) -> Result { + let Data::Array(v) = d else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let [l, t, r, b] = v.as_slice() else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let n = |d: &Data| super::coordinate(d, what); + let (l, t, r, b) = (n(l)?, n(t)?, n(r)?, n(b)?); + let f = frame(st)?; + let c = h.dom.coords.get(); + let p = f.to_document(c, [l, t]); + let q = f.to_document(c, [r, b]); + let rect = vectorcraft_geom::Rect::new(p.x.min(q.x), p.y.min(q.y), p.x.max(q.x), p.y.max(q.y)); + if q.x <= p.x || q.y <= p.y { + return Err(HostError::Range(format!("{what} must have its right side right of its left side and its bottom below its top"))); + } + if rect.width() < 1.0 || rect.height() < 1.0 { + return Err(HostError::Range(format!("{what} must be at least 1 point wide and tall"))); + } + if rect.width() > super::MAX_SIZE || rect.height() > super::MAX_SIZE { + return Err(HostError::Range(format!("{what} must be at most 3999856 points wide and tall"))); + } + Ok(rect) +} + +fn board_set_rect(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + let r = with_doc(h, b.doc, |_, st| rect_arg(h, st, arg(a, 1), "artboardRect"))?; + let close = |x: f64, y: f64| (x - y).abs() < 1e-9; + set_board( + h, + a, + |ab| close(ab.rect.x0, r.x0) && close(ab.rect.y0, r.y0) && close(ab.rect.x1, r.x1) && close(ab.rect.y1, r.y1), + json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()}), + ) +} + +fn board_name(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) +} + +/// A new artboard name: not empty, at most [`MAX_TEXT_BYTES`] bytes, and no other artboard's +/// (`except`: the artboard being renamed). → the name, trimmed as `artboard.rename` trims it. +fn board_name_arg(st: &DocState, d: &Data, except: Option) -> Result { + let Data::String(name) = d else { return Err(HostError::Type("name must be a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let name = name.trim(); + if name.is_empty() { + return Err(HostError::Range("an artboard's name cannot be empty".into())); + } + if st.doc.artboards.iter().enumerate().any(|(i, ab)| Some(i) != except && ab.name == name) { + return Err(HostError::Error(format!("another artboard is named {name}"))); + } + Ok(name.to_string()) +} + +fn board_set_name(h: &Host, a: &[Data]) -> Answer { + let (b, i) = this_board(h, a)?; + let name = with_doc(h, b.doc, |_, st| board_name_arg(st, arg(a, 1), Some(i)))?; + set_board(h, a, |ab| ab.name == name, json!({"name": name})) +} + +fn board_parent(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + Ok(doc_ref(h, b.doc.uid)) +} + +fn board_typename(h: &Host, a: &[Data]) -> Answer { + this_board(h, a)?; + Ok(text("Artboard")) +} + +/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner +/// with Y down. +fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, i| { + let o = st.doc.ruler_origin_for(i); + Ok(super::pair([o.x - ab.rect.x0, o.y - ab.rect.y0])) + }) +} + +fn board_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let p = super::point(arg(a, 1), "rulerOrigin")?; + let (b, i) = this_board(h, a)?; + let (to, now) = with_doc(h, b.doc, |_, st| { + let ab = &st.doc.artboards[i]; + (vectorcraft_geom::Point::new(ab.rect.x0 + p[0], ab.rect.y0 + p[1]), st.doc.ruler_origin_for(i)) + }); + if to.distance(now) > 1e-9 { + on_doc(h, b.doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": i})))?; + } + Ok(Data::Undefined) +} + +fn board_par(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(num(ab.video_ruler_pixel_aspect_ratio))) +} + +fn board_set_par(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "rulerPAR")?; + if !crate::doc::VIDEO_PIXEL_ASPECT_RANGE.contains(&v) { + return Err(HostError::Range("rulerPAR must be from 0.1 to 10".into())); + } + set_board(h, a, |ab| (ab.video_ruler_pixel_aspect_ratio - v).abs() < 1e-12, json!({"videoRulerPixelAspectRatio": v})) +} + +fn board_center(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_center_mark))) +} + +fn board_set_center(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCenter")?; + set_board(h, a, |ab| ab.show_center_mark == v, json!({"showCenterMark": v})) +} + +fn board_cross_hairs(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_cross_hairs))) +} + +fn board_set_cross_hairs(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCrossHairs")?; + set_board(h, a, |ab| ab.show_cross_hairs == v, json!({"showCrossHairs": v})) +} + +fn board_safe_areas(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_video_safe_areas))) +} + +fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showSafeAreas")?; + set_board(h, a, |ab| ab.show_video_safe_areas == v, json!({"showVideoSafeAreas": v})) +} + +fn board_remove(h: &Host, a: &[Data]) -> Answer { + let (b, i) = this_board(h, a)?; + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_doc(h: &Host, a: &[Data]) -> Result { + doc_of(h, arg(a, 0), "Artboards") +} + +fn boards_length(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.artboards.len()) as u64))) +} + +fn boards_parent(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn boards_typename(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)?; + whole(n) + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < len) + .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) +} + +fn boards_at(h: &Host, a: &[Data]) -> Answer { + let doc = boards_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) }; + Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) +} + +fn boards_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = boards_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| { + h.charge_call(st.doc.artboards.len() as u64)?; + let ab = st.doc.artboards.iter().find(|ab| ab.name == *name); + ab.map(|ab| board_ref(h, st.uid, ab.id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn boards_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => boards_by_name(h, a), + Data::Number(_) => match boards_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// A new artboard at `rect` with `artboard.new`, moved to `at` (`None`: it stays last) with +/// `artboard.reorder`. → the artboard. +fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { + let doc = boards_doc(h, a)?; + let (r, len, name) = with_doc(h, doc, |_, st| { + let boards = &st.doc.artboards; + h.charge_call(boards.len() as u64)?; + // The first "Artboard N" from one past the count that no artboard has, so names stay unique. + let name = (boards.len() + 1..).map(|n| format!("Artboard {n}")).find(|n| !boards.iter().any(|ab| ab.name == *n)).unwrap_or_default(); + Ok::<_, HostError>((rect_arg(h, st, arg(a, 1), "artboardRect")?, boards.len(), name)) + })?; + let to = at.map(|d| board_index_arg(d, len + 1, "index")).transpose()?; + let max = whole(super::MAX_ARTBOARDS).and_then(|m| usize::try_from(m).ok()).unwrap_or(0); + if len >= max { + return Err(HostError::Range(format!("a document has at most {max} artboards"))); + } + let id = on_doc(h, doc.uid, true, |h| { + let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let index = + result_id(&made, "index").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error("the artboard was not made".into()))?; + if let Some(to) = to + && to != index + { + command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + })?; + Ok(board_ref(h, doc.uid, id)) +} + +/// `artboards.add(artboardRect)`: a new artboard, last in the list. +fn boards_add(h: &Host, a: &[Data]) -> Answer { + add_board(h, a, None) +} + +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. +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))) +} + +fn boards_remove(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let len = with_doc(h, doc, |_, st| st.doc.artboards.len()); + let i = board_index_arg(arg(a, 1), len, "index")?; + on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64))) +} + +/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the +/// document changes, and no command runs. +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); + let id = st.active_artboard; + drop(s); + let mut moved = h.dom.active_artboards.borrow_mut(); + moved.retain(|(u, _)| *u != doc.uid); + if let Some(id) = id { + moved.push((doc.uid, id)); + } + } + Ok(Data::Undefined) +} + +/// The documents whose active artboard the run changed, as `script.run`'s report gives them: +/// `[{document, artboard}]`, each an index, or `None` when there are none. +pub(crate) fn active_artboards(moved: &[(u64, u32)], docs: &[DocState]) -> Option { + let list: Vec = moved + .iter() + .filter_map(|(uid, id)| { + let document = docs.iter().position(|d| d.uid == *uid)?; + let artboard = board_index(&docs[document], *id)?; + Some(json!({"document": document, "artboard": artboard})) + }) + .collect(); + (!list.is_empty()).then_some(Value::Array(list)) +} + +/// The classes of layers, art collections and artboards. +pub(super) fn classes(l: &Link) -> Vec { + let class = super::class; + let mut layer = named(vec![ + ("typename", get(l, layer_typename)), + ("name", property(l, layer_name, layer_set_name)), + ("visible", property(l, layer_visible, layer_set_visible)), + ("locked", property(l, layer_locked, layer_set_locked)), + ("printable", property(l, layer_printable, layer_set_printable)), + ("preview", property(l, layer_preview, layer_set_preview)), + ("dimPlacedImages", property(l, layer_dim, layer_set_dim)), + ("opacity", property(l, layer_opacity, layer_set_opacity)), + ("color", property(l, layer_color, layer_set_color)), + ("parent", get(l, layer_parent)), + ("layers", get(l, layers_of)), + ("pageItems", get(l, held_page_items)), + ("groupItems", get(l, held_groups)), + ("compoundPathItems", get(l, held_compounds)), + ("zOrderPosition", get(l, layer_z_position)), + ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), + ("isIsolated", get(l, layer_is_isolated)), + ("move", method(l, layer_move)), + ("remove", method(l, layer_remove)), + ("zOrder", method(l, layer_z_order)), + ]); + layer.extend( + ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] + .map(|m| later(l, "Layer", m)), + ); + vec![ + class("Layer", None, layer, None), + class( + "Layers", + None, + named(vec![ + ("typename", get(l, layers_typename)), + ("length", get(l, layers_length)), + ("parent", get(l, layers_parent)), + ("index", method(l, layers_index)), + ("getByName", method(l, layers_by_name)), + ("add", method(l, layers_add)), + ("removeAll", method(l, layers_remove_all)), + ]), + Some(super::function(l, layers_at)), + ), + class( + "GroupItems", + None, + { + let mut m = named(vec![ + ("typename", get(l, groups_typename)), + ("length", get(l, groups_length)), + ("parent", get(l, groups_parent)), + ("index", method(l, groups_index)), + ("getByName", method(l, groups_by_name)), + ("add", method(l, groups_add)), + ("removeAll", method(l, groups_remove_all)), + ]); + m.push(later(l, "GroupItems", "createFromFile")); + m + }, + Some(super::function(l, groups_at)), + ), + class( + "CompoundPathItems", + None, + named(vec![ + ("typename", get(l, compounds_typename)), + ("length", get(l, compounds_length)), + ("parent", get(l, compounds_parent)), + ("index", method(l, compounds_index)), + ("getByName", method(l, compounds_by_name)), + ("add", method(l, compounds_add)), + ("removeAll", method(l, compounds_remove_all)), + ]), + Some(super::function(l, compounds_at)), + ), + class( + "Artboard", + None, + named(vec![ + ("typename", get(l, board_typename)), + ("artboardRect", property(l, board_rect, board_set_rect)), + ("name", property(l, board_name, board_set_name)), + ("parent", get(l, board_parent)), + ("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin)), + ("rulerPAR", property(l, board_par, board_set_par)), + ("showCenter", property(l, board_center, board_set_center)), + ("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs)), + ("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas)), + ("remove", method(l, board_remove)), + ]), + None, + ), + class( + "Artboards", + None, + named(vec![ + ("typename", get(l, boards_typename)), + ("length", get(l, boards_length)), + ("parent", get(l, boards_parent)), + ("index", method(l, boards_index)), + ("getByName", method(l, boards_by_name)), + ("add", method(l, boards_add)), + ("insert", method(l, boards_insert)), + ("remove", method(l, boards_remove)), + ("getActiveArtboardIndex", method(l, boards_active)), + ("setActiveArtboardIndex", method(l, boards_set_active)), + ]), + Some(super::function(l, boards_at)), + ), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..34779c7b5e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2290,6 +2290,9 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), self.documents()) { + report["activeArtboards"] = boards; + } close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0324e81339..2b3920f3d0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -654,7 +654,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } - assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.views = 1;").contains("Document.views is not available yet")); // A deleted item or an earlier run's document is stale first. let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); assert!(e.contains("Stale page item"), "{e}"); @@ -911,5 +911,338 @@ fn prototype_changes_cannot_forge_a_page_item() { #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); - assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.views;").contains("Document.views is not available yet")); +} + +fn layer_names(s: &Session) -> Vec { + s.active().unwrap().doc.layers.iter().rev().map(|n| n.name.clone().unwrap_or_default()).collect() +} + +#[test] +fn layers_list_top_first_and_add_makes_the_new_layer_current() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers; vc.log(L.length); vc.log(L.typename); vc.log(L.parent.typename);\ + var n = L.add(); n.name = 'Top'; vc.log(L.length); vc.log(L[0].name); vc.log(d.activeLayer.name);\ + vc.log(L.getByName('Top').zOrderPosition); vc.log(L[1].zOrderPosition); vc.log(n.parent.typename);\ + var sub = L[1].layers.add(); sub.name = 'Sub'; vc.log(L[1].layers.length); vc.log(sub.parent.name);\ + vc.log(L.length); vc.log(L[5] === undefined); vc.log(L[1].pageItems.length); vc.log(L[1].pageItems[0].typename);\ + vc.log(sub.zOrderPosition);", + ); + let expected = [json!(1), json!("Layers"), json!("Document"), json!(2), json!("Top"), json!("Top"), json!(2), json!(1), json!("Document")]; + assert_eq!(out[..9], expected); + // A layer's pageItems hold its art, not its sublayers, and a sublayer's zOrderPosition counts + // only the layers beside it. + assert_eq!(out[9..], [json!(1), json!("Layer 1"), json!(2), json!(true), json!(2), json!("PathItem"), json!(1)]); + assert_eq!(layer_names(&s), ["Top", "Layer 1"]); + // One run is one undo step. + assert_eq!(undo_steps(&s), steps + 1); + let lid = s.active().unwrap().doc.layer_containing(a).unwrap(); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.layers.getByName(5);").contains("give a name")); + assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); +} + +#[test] +fn layer_properties_round_trip_and_reject_bad_values() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0];\ + l.name = 'Art'; l.printable = false; l.preview = false; l.opacity = 40; l.dimPlacedImages = true;\ + l.color = {red: 10, green: 20, blue: 30};\ + vc.log(l.name); vc.log(l.printable); vc.log(l.preview); vc.log(l.opacity); vc.log(l.dimPlacedImages);\ + var c = l.color; vc.log([c.red, c.green, c.blue]); vc.log(l.visible); vc.log(l.locked); vc.log(l.typename);\ + l.visible = false; vc.log(l.visible); l.visible = true; l.locked = true; vc.log(l.locked); l.locked = false;", + ); + let expected = [json!("Art"), json!(false), json!(false), json!(40), json!(true), json!([10, 20, 30]), json!(true), json!(false)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("Layer"), json!(false), json!(true)]); + // Setting the values a layer has adds no undo step. + let steps = undo_steps(&s); + let same = "var l = app.activeDocument.layers[0]; l.name = 'Art'; l.opacity = 40; l.printable = false; l.color = {red: 10, green: 20, blue: 30};"; + run(&mut s, same).unwrap(); + assert_eq!(undo_steps(&s), steps); + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (src, msg) in [ + ("app.activeDocument.layers[0].name = 5;", "name must be a string"), + ("app.activeDocument.layers[0].name = ' ';", "cannot be empty"), + ("app.activeDocument.layers[0].name = new Array(600).join('x');", "at most 512"), + ("app.activeDocument.layers[0].opacity = 200;", "from 0 to 100"), + ("app.activeDocument.layers[0].opacity = NaN;", "finite number"), + ("app.activeDocument.layers[0].visible = 1;", "true or false"), + ("app.activeDocument.layers[0].color = {red: 300, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = {red: 1.5, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = 'red';", "red, green and blue"), + ("app.activeDocument.layers[0].zOrder('up');", "ZOrderMethod"), + ("app.activeDocument.activeLayer = 3;", "not a Layer"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn layer_move_and_z_order_keep_ids() { + let (mut s, _, _) = doc(); + run(&mut s, "var L = app.activeDocument.layers; L.add().name = 'B'; L.add().name = 'C';").unwrap(); + assert_eq!(layer_names(&s), ["C", "B", "Layer 1"]); + let out = log( + &mut s, + "var L = app.activeDocument.layers, c = L[0]; c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(L[2].name); vc.log(c.zOrderPosition);\ + c.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(L[1].name);\ + c.move(L.getByName('B'), ElementPlacement.PLACEBEFORE); vc.log(L[0].name);\ + c.move(L.getByName('B')); vc.log(L.length); vc.log(c.parent.name); vc.log(c.name);\ + c.move(app.activeDocument); vc.log(L.length); vc.log(L[0].name);", + ); + assert_eq!(out, [json!("C"), json!(1), json!("C"), json!("C"), json!(2), json!("B"), json!("C"), json!(3), json!("C")]); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[0]);").contains("into itself")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[1].pageItems);").contains("a layer or a document")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move();").contains("relative object")); +} + +#[test] +fn sublayer_z_order_steps_past_the_next_layer_and_the_art_between() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var P = app.activeDocument.layers[0], x = P.layers.add(); x.name = 'X'; x.zOrder(ZOrderMethod.SENDTOBACK);\ + var y = P.layers.add(); y.name = 'Y'; vc.log([x.zOrderPosition, y.zOrderPosition]);\ + y.zOrder(ZOrderMethod.SENDBACKWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(P.pageItems.length);", + ); + assert_eq!(out, [json!([1, 2]), json!([2, 1, "X"]), json!([1, 2, "Y"]), json!(2)]); + // The last step had no layer to pass, so Y stayed under the art. + let d = &s.active().unwrap().doc; + let p = d.layers.last().unwrap(); + let kids = d.children(Some(p.id)).unwrap(); + assert!(kids[1].is_layer() && !kids[2].is_layer() && !kids[3].is_layer()); +} + +#[test] +fn removed_layers_throw_and_the_last_layer_stays() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.add(); n.layers.add(); n.layers.add(); vc.log(n.layers.length);\ + n.layers.removeAll(); vc.log(n.layers.length); n.remove(); vc.log(L.length);\ + try { n.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..3], [json!(2), json!(0), json!(1)]); + assert!(out[3].as_str().unwrap().contains("Stale layer"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "app.activeDocument.layers[0].remove();").contains("at least one layer")); + assert!(failure(&mut s, "app.activeDocument.layers.removeAll();").contains("at least one layer")); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "Object.getOwnPropertyDescriptor(Layer.prototype, 'name').get.call({});").contains("not a Layer")); +} + +#[test] +fn group_items_list_every_depth_and_clipped_toggles_the_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0]; vc.log(d.groupItems.length); vc.log(g.pageItems.length);\ + var inner = g.groupItems.add(); vc.log(inner.typename); vc.log(inner.pageItems.length);\ + vc.log(d.groupItems.length); vc.log(g.groupItems.length); vc.log(d.layers[0].groupItems.length);\ + vc.log(g.layer.name); vc.log(g.clipped); vc.log(d.compoundPathItems.length);\ + d.layers[0].groupItems.add(); vc.log(d.layers[0].groupItems.length); vc.log(g.pageItems.parent.typename);", + ); + let expected = [json!(1), json!(2), json!("GroupItem"), json!(0), json!(2), json!(1), json!(1), json!("Layer 1"), json!(false), json!(0)]; + assert_eq!(out[..10], expected); + assert_eq!(out[10..], [json!(2), json!("GroupItem")]); + // `clipped` on a group with a path on top makes the topmost path its clipping path. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 0.0, 0.0, 5.0, 5.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + run(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = false;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert_eq!(log(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = true; vc.log(g.clipped);"), [json!(true)]); + let st = s.active().unwrap(); + let g = st.doc.node(gid).unwrap(); + assert!(g.clips()); + assert_eq!(g.children().unwrap()[0].id, b); + assert_eq!(undo_steps(&s), steps + 1); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].clipped = 'yes';").contains("true or false")); + assert!(failure(&mut s, "app.activeDocument.compoundPathItems.add();").contains("empty compound path")); + assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); +} + +#[test] +fn group_items_remove_all_refuses_locked_groups() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems.removeAll();").contains("hidden or locked")); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("object.setProps", &json!({"ids": [g], "locked": false})).unwrap(); + run(&mut s, "app.activeDocument.groupItems.removeAll();").unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(NodeId(g)).is_none() && d.node(a).is_none() && d.node(b).is_some()); +} + +#[test] +fn new_group_command_checks_its_parent() { + let (mut s, a, _) = doc(); + let layer = s.active().unwrap().doc.layer_containing(a).unwrap(); + let g = s.execute("object.newGroup", &json!({"parent": layer.0, "index": 0})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(NodeId(g)).map(|(p, i, _)| (p, i)), Some((Some(layer), 0))); + assert!(s.execute("object.newGroup", &json!({"parent": a.0})).unwrap_err().to_string().contains("not a layer or group")); + 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")); + 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")); +} + +#[test] +fn artboards_add_insert_rename_and_remove() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(A.length); vc.log(A[0].artboardRect); vc.log(A.typename);\ + var b = A.add([500, 300, 700, 100]); b.name = 'Two'; vc.log(A.length); vc.log(A[1].name); vc.log(b.artboardRect);\ + A.insert([0, -100, 100, -200], 1); vc.log(A[1].artboardRect); vc.log(b.name); vc.log(A.getByName('Two').artboardRect[0]);\ + b.artboardRect = [500, 300, 650, 150]; vc.log(b.artboardRect); b.rulerPAR = 2; vc.log(b.rulerPAR);\ + b.showCenter = true; b.showCrossHairs = true; b.showSafeAreas = true; vc.log([b.showCenter, b.showCrossHairs, b.showSafeAreas]);\ + b.rulerOrigin = [10, 20]; vc.log(b.rulerOrigin); vc.log(b.parent.typename);\ + A.remove(0); vc.log(A.length); b.remove(); vc.log(A.length); try { b.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..4], [json!(1), json!([0, 300, 400, 0]), json!("Artboards"), json!(2)]); + assert_eq!(out[4..7], [json!("Two"), json!([500, 300, 700, 100]), json!([0, -100, 100, -200])]); + assert_eq!(out[7..11], [json!("Two"), json!(500), json!([500, 300, 650, 150]), json!(2)]); + assert_eq!(out[11..16], [json!([true, true, true]), json!([10, 20]), json!("Document"), json!(2), json!(1)]); + assert!(out[16].as_str().unwrap().contains("Stale artboard"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn new_artboards_get_a_name_no_other_artboard_has() { + let (mut s, _, _) = doc(); + 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([800, 300, 900, 100]).name);", + ); + assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); +} + +#[test] +fn artboards_reject_bad_arguments_before_any_change() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]).name = 'Two';").unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + for (src, msg) in [ + ("app.activeDocument.artboards.add([0, 0, 10]);", "four numbers"), + ("app.activeDocument.artboards.add('x');", "four numbers"), + ("app.activeDocument.artboards.add([10, 0, 0, 10]);", "right side"), + ("app.activeDocument.artboards.add([0, 0, NaN, -10]);", "finite number"), + ("app.activeDocument.artboards.add([0, 0, 1e300, -10]);", "outside the canvas"), + ("app.activeDocument.artboards.add([0, 0, 0.5, -10]);", "at least 1 point"), + ("app.activeDocument.artboards[0].artboardRect = [0, 0, 10, -0.25];", "at least 1 point"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10], 5);", "index must be"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), + ("app.activeDocument.artboards.remove(2);", "index must be"), + ("app.activeDocument.artboards.remove(-1);", "index must be"), + ("app.activeDocument.artboards[0].name = 'Two';", "another artboard"), + ("app.activeDocument.artboards[0].name = '';", "cannot be empty"), + ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), + ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), + ("app.activeDocument.artboards[0].showCenter = 'on';", "true or false"), + ("app.activeDocument.artboards.setActiveArtboardIndex(9);", "index must be"), + ("app.activeDocument.artboards.getByName('none');", "Not found"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); + run(&mut s, "app.activeDocument.artboards.remove(1);").unwrap(); + assert!(failure(&mut s, "app.activeDocument.artboards[0].remove();").to_lowercase().contains("artboard")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn set_active_artboard_index_is_reported_without_an_undo_step() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap(); + let steps = undo_steps(&s); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(1); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert_eq!(st.active_artboard, Some(st.doc.artboards[1].id)); + // Artboard coordinates follow the active artboard. + let out = log(&mut s, "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(app.activeDocument.artboards[1].artboardRect);"); + assert_eq!(out, [json!([0, 0, 200, 200])]); + let r = run(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1);").unwrap(); + assert!(r.get("activeArtboards").is_none()); +} + +#[test] +fn has_selected_artwork_selects_and_deselects_a_layers_art() { + let (mut s, a, b) = doc(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; vc.log(l.hasSelectedArtwork); l.hasSelectedArtwork = true;\ + vc.log(app.activeDocument.selection.length); vc.log(l.hasSelectedArtwork); vc.log(l.isIsolated);", + ); + assert_eq!(out, [json!(false), json!(2), json!(true), json!(false)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + run(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = false;").unwrap(); + assert!(s.active().unwrap().selection.objects.is_empty()); + assert!(failure(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = 0;").contains("true or false")); +} + +#[test] +fn artboards_stop_at_one_hundred() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; for (var i = 1; i < 100; i++) A.add([i * 10, -400, i * 10 + 5, -405]);").unwrap(); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.artboards.add([0, -500, 10, -510]);").contains("at most 100 artboards")); + assert!(failure(&mut s, "app.activeDocument.artboards.insert([0, -500, 10, -510], 0);").contains("at most 100 artboards")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn every_page_item_has_its_layer_and_members_check_this() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ + vc.log(p.layer.name); vc.log(d.pageItems[0].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", + ); + assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); + for src in [ + "Object.getOwnPropertyDescriptor(Layers.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(GroupItems.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboard.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboards.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Layer.prototype, 'pathItems').get.call({});", + ] { + assert!(failure(&mut s, src).contains("this is not a"), "{src}"); + } + let stale = "var L = app.activeDocument.layers, n = L.add(), c = n.layers, g = n.groupItems; n.remove();"; + for read in ["c.typename", "g.typename", "n.pathItems"] { + assert!(failure(&mut s, &format!("{stale} {read};")).contains("Stale"), "{read}"); + } } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..881cb64d04 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,9 +73,10 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ - DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + "app Application Artboard Artboards CompoundPathItem CompoundPathItems CoordinateSystem Document \ + DocumentArtboardLayout DocumentColorSpace DocumentPresetType DocumentPreviewMode DocumentRasterResolution \ + DocumentTransparencyGrid Documents ElementPlacement GroupItem GroupItems Layer Layers PageItem PageItems RulerUnits \ + ZOrderMethod", ), ("Application.", "prototype"), ( @@ -88,21 +89,54 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ + "activeLayer activeLayer= artboards close close= compoundPathItems constructor convertCoordinate \ + documentColorSpace groupItems height layers name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), - ("Layer.prototype.", "constructor name typename"), + ( + "Layer.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ + dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ + locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ + textFrames= typename visible visible= zOrder zOrderPosition", + ), + ("Layers.", "prototype"), + ("Layers.prototype.", "add constructor getByName index length parent removeAll typename"), + ("GroupItem.", "prototype"), + ( + "GroupItem.prototype.", + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + ), + ("GroupItems.", "prototype"), + ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll typename"), + ("CompoundPathItem.", "prototype"), + ("CompoundPathItem.prototype.", "constructor pathItems"), + ("CompoundPathItems.", "prototype"), + ("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Artboard.", "prototype"), + ( + "Artboard.prototype.", + "artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \ + showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= typename", + ), + ("Artboards.", "prototype"), + ( + "Artboards.prototype.", + "add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \ + typename", + ), ("PageItems.", "prototype"), ("PageItems.prototype.", "constructor getByName index length parent removeAll typename"), ("PageItem.", "prototype"), ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ - left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \ + left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", @@ -124,9 +158,9 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; +/// and the page item types that have no members of their own. +const BARE_CLASSES: &str = "BlendItem DocumentPreset EnvelopeItem GraphItem IntertwineItem MeshItem PathItem PlacedDocumentItem \ + PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..e8ae5d8a94 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -33,6 +33,7 @@ pub fn poll(app: &mut VectorcraftApp) { app.ui.dialog = None; } script_run::settle_close(app); + let boards = result.as_ref().ok().and_then(|r| r["activeArtboards"].as_array().cloned()).unwrap_or_default(); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. Ok(_) => { @@ -43,6 +44,22 @@ pub fn poll(app: &mut VectorcraftApp) { Err(e) => failed(app, e.to_string()), } app.sync_views(); + show_artboards(app, &boards); +} + +/// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view +/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). +fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { + for b in boards { + let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok()); + let (Some(doc), Some(board)) = (index("document"), index("artboard")) else { continue }; + let count = app.session.documents().get(doc).map_or(0, |d| d.doc.artboards.len()); + if let Some(view) = app.views.get_mut(doc) + && board < count + { + view.artboard = board; + } + } } /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..d74b9e1699 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -114,6 +114,18 @@ fn stop_puts_the_document_back_and_says_so() { assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); } +#[test] +fn set_active_artboard_index_shows_the_artboard_in_the_view() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.views[0].artboard = 0; + let source = "app.activeDocument.artboards.setActiveArtboardIndex(1);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, 1); +} + #[test] fn a_script_error_goes_to_the_status_bar() { let mut app = app(); diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..142683f55a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,9 +807,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the - other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (views, paths, type and the other + classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new + documents, each document's selection, its page items, layers, groups, compound paths and artboards. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..7c4c190230 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2672,10 +2672,61 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.views`, `PageItem.blendingMode`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- A document also has `layers`, `activeLayer`, `groupItems`, `compoundPathItems` and `artboards`. + `layers` (https://ai-scripting.docsforadobe.dev/jsobjref/Layers/) and a layer's own `layers` have `length`, `[i]`, + `index(key)`, `getByName(name)`, `add()` and `removeAll()`. On the document, `add()` runs `layer.new` and makes a + layer above every top-level layer; on a layer it runs `layer.newSublayer` and makes a sublayer on top of that + layer's contents. The new layer becomes the current one. `removeAll()` runs `layer.delete`; on the document's + layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs + `layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`, + `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, + `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run + `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into + another layer, to the top level of the document, or directly above or below another layer. Every page item has + `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has + `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` + (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 + `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 + properties run `artboard.setProps`, and `rulerOrigin` runs `document.setRulerOrigin`. One document always keeps + one artboard. + VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. `groupItems`, + `compoundPathItems` and a layer's or group's `pageItems` list art in paint order from the bottom. The document's + `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold + only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` + are its `pageItems`. `locked` true means the layer is locked. `color` is an object `{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 + the next layer beside it and any art between them. + `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection, and `false` deselects it. + `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 + layer's or group's contents, or of the current layer's for the document's collection. + `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop + at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is + `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below + its top and each side from 1 to 3,999,856 points. Artboard names are trimmed, cannot be empty and are unique: a name + another artboard has throws. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one + past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. + `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the + change in `activeArtboards` (`[{document, artboard}]`, both indexes). An index outside the list throws a + `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws + `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and + `GroupItems.createFromFile` throw an error that says they are not available yet. +- `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: + the current layer), on top of its contents or at `index` (0 is the bottom), as one undo step named Group, and + gives `{id}`. The selection stays as it is. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..29a93c640b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/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`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). Paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, 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/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.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 `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 6b2a84304ba9bcc163406631f53dbbe9d2bd3a85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:35:09 -0800 Subject: [PATCH 02/49] Scripts: hasSelectedArtwork keeps the rest of the selection, artboards stay on the canvas - hasSelectedArtwork = false deselects only the layer's art with select.toggle, and true adds its art with select.add, so selected ruler guides and art on other layers stay selected. A layer with nothing to deselect or add runs no command. - A compound path's pathItems report the typename PathItems. - An artboard rectangle with an edge more than 4,000,000 points from the document origin throws before artboard.setProps or artboard.new runs. - script.run's activeArtboards gives each document's active artboard as the run leaves it, also when the chosen artboard was deleted later in the run. - A layer's or group's pageItems, groupItems and compoundPathItems, and the document's groupItems and compoundPathItems, keep their last list while the document is unchanged, so indexed reads in a loop do not rebuild it each time. A new list is charged by the objects it looks at. - object.newGroup's help says index 0 goes directly above the clipping path in a clipping layer or group. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/layers.rs | 106 +++++++++++++++-------- crates/engine/src/tests/script_dom.rs | 76 ++++++++++++++++ docs/mcp.md | 15 ++-- docs/target-app-parity.md | 2 +- 6 files changed, 162 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index dab3a0378c..8d17cc0a72 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; default: on top)} → {id}: an empty group 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)} → {id}: an empty group in a shown, unlocked layer or group; the selection stays as it is", has_doc, new_group ), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7bfecbb264..fadaeb133d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -94,9 +94,11 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, - /// The documents whose active artboard `setActiveArtboardIndex` changed: each one's uid and - /// the artboard's id. - pub(super) active_artboards: RefCell>, + /// The last list of art one of [`layers`]' collections gave, kept while its document is + /// unchanged. + art: RefCell>, + /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. + pub(super) active_artboards: RefCell>, } impl State { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index a6b165fbef..91c7bc4a03 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -30,13 +30,16 @@ //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report //! lists it in `activeArtboards` for the app to show. +use std::rc::Rc; +use std::sync::Arc; + use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, 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, - page_items, placement_of, property, set_selection, text, typename, whole, with_doc, + page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -272,36 +275,43 @@ 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)))))) } -/// `hasSelectedArtwork = false` deselects the layer's art; `true` adds its visible, unlocked art -/// to the selection. +/// `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. 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 = with_doc(h, doc, |_, st| { + let (ids, total) = with_doc(h, doc, |_, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); - let mut ids: Vec = st.selection.objects.clone(); - if on { - 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 = ids.iter().copied().collect(); - for o in art { - if ids.len() > MAX_LISTED { - break; - } - if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { - have.insert(o); - ids.push(o); - } - } - } else { - ids.retain(|o| !inside(o)); + let selected = &st.selection.objects; + if !on { + return (selected.iter().copied().filter(inside).collect::>(), 0); } - ids + 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) { + have.insert(o); + ids.push(o); + } + } + let total = selected.len() + ids.len(); + (ids, total) }); - if ids.len() > MAX_LISTED { + if total > MAX_LISTED { return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); } - set_selection(h, doc, ids) + if ids.is_empty() { + return Ok(Data::Undefined); + } + let command_id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) } fn layer_is_isolated(h: &Host, a: &[Data]) -> Answer { @@ -558,17 +568,36 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { } } +/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection, +/// and the ids it listed then. +pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); + /// The objects of `kind` in `container` (directly), or in the whole document at any depth, in -/// paint order. -fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result> { +/// paint order. The last list is kept while the document is unchanged, and each new one is charged +/// by the objects it looks at. +fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { + if let Some((uid, doc, k, c, ids)) = &*h.dom.art.borrow() + && *uid == st.uid + && Arc::ptr_eq(doc, &st.doc) + && *k == kind as u8 + && *c == container + { + return Ok(ids.clone()); + } let ids: Vec = match container { None => { let all = page_items(h, st); h.charge_call(all.len() as u64)?; all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() } - Some(c) => st.doc.node(c).and_then(|n| n.children()).into_iter().flatten().filter(|n| kind.holds(n)).map(|n| n.id).collect(), + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + children.iter().filter(|n| kind.holds(n)).map(|n| n.id).collect() + } }; + let ids = Rc::new(ids); + *h.dom.art.borrow_mut() = Some((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); Ok(ids) } @@ -709,8 +738,10 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - art_scope(h, arg(a, 0), kind.class())?; - Ok(text(kind.class())) + 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() })) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -956,6 +987,9 @@ fn rect_arg(h: &Host, st: &DocState, d: &Data, what: &str) -> Result super::MAX_SIZE || rect.height() > super::MAX_SIZE { return Err(HostError::Range(format!("{what} must be at most 3999856 points wide and tall"))); } + if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| v.abs() > crate::MAX_COORD) { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } Ok(rect) } @@ -1199,26 +1233,24 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { 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); - let id = st.active_artboard; drop(s); let mut moved = h.dom.active_artboards.borrow_mut(); - moved.retain(|(u, _)| *u != doc.uid); - if let Some(id) = id { - moved.push((doc.uid, id)); + if !moved.contains(&doc.uid) { + moved.push(doc.uid); } } Ok(Data::Undefined) } /// The documents whose active artboard the run changed, as `script.run`'s report gives them: -/// `[{document, artboard}]`, each an index, or `None` when there are none. -pub(crate) fn active_artboards(moved: &[(u64, u32)], docs: &[DocState]) -> Option { +/// `[{document, artboard}]`, each an index, with the active artboard each document has at the end +/// of the run, or `None` when there are none. +pub(crate) fn active_artboards(moved: &[u64], docs: &[DocState]) -> Option { let list: Vec = moved .iter() - .filter_map(|(uid, id)| { + .filter_map(|uid| { let document = docs.iter().position(|d| d.uid == *uid)?; - let artboard = board_index(&docs[document], *id)?; - Some(json!({"document": document, "artboard": artboard})) + Some(json!({"document": document, "artboard": active_artboard(&docs[document])})) }) .collect(); (!list.is_empty()).then_some(Value::Array(list)) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 2b3920f3d0..f9e42377db 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1077,6 +1077,31 @@ fn group_items_list_every_depth_and_clipped_toggles_the_mask() { assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); } +#[test] +fn a_compound_paths_path_items_are_path_items() { + 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, 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);", + ); + assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); +} + +#[test] +fn art_collections_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.groupItems; vc.log(p.length); vc.log(g.length);\ + d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[2].typename); vc.log(g.length);\ + p[0].remove(); vc.log(p.length); vc.log(p[0].typename);", + ); + assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); @@ -1193,6 +1218,35 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +#[test] +fn the_report_gives_the_active_artboard_the_run_leaves() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.add([800, 300, 900, 100]);").unwrap(); + // The chosen artboard is deleted later in the run: the report gives the one active at the end. + let r = + run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(2); A.remove(2); vc.log(A.getActiveArtboardIndex());").unwrap(); + let active = r["log"][0].clone(); + assert!(active.as_u64().is_some_and(|i| i < 2), "{r}"); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); +} + +#[test] +fn an_artboard_rectangle_stays_inside_the_canvas() { + let (mut s, _, _) = doc(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + // Each number is within the coordinate range, but the right edge is past the canvas. + for src in [ + "app.activeDocument.artboards[0].artboardRect = [3999950, 0, 4000100, -100];", + "app.activeDocument.artboards.add([-4000100, 0, -3999950, -100]);", + "app.activeDocument.artboards.insert([0, 4000600, 100, 4000500], 0);", + ] { + assert!(failure(&mut s, src).contains("outside the canvas"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn has_selected_artwork_selects_and_deselects_a_layers_art() { let (mut s, a, b) = doc(); @@ -1210,6 +1264,28 @@ fn has_selected_artwork_selects_and_deselects_a_layers_art() { assert!(failure(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = 0;").contains("true or false")); } +#[test] +fn has_selected_artwork_keeps_the_rest_of_the_selection() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // An empty layer has nothing to deselect or add: the selected guide stays. + let steps = undo_steps(&s); + run(&mut s, "var l = app.activeDocument.layers.add(); l.hasSelectedArtwork = false; l.hasSelectedArtwork = true;").unwrap(); + assert_eq!(s.active().unwrap().selection.guides.len(), 1); + assert_eq!(undo_steps(&s), steps + 1); + // Deselecting a layer's art leaves the guide selected, and so does adding it. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = false;").unwrap(); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.len(), sel.guides.len()), (0, 1)); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + let sel = &s.active().unwrap().selection; + assert!(sel.objects.contains(&a) && sel.objects.contains(&b)); + assert_eq!(sel.guides.len(), 1); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 7c4c190230..2b6b988f91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2705,27 +2705,32 @@ app through the global object `vc`, and writes to the Script Console and runs ot `compoundPathItems` and a layer's or group's `pageItems` list art in paint order from the bottom. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` - are its `pageItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + list its paths, with the typename `PathItems`. `locked` true means the layer is locked. `color` is an object `{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 the next layer beside it and any art between them. - `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection, and `false` deselects it. + `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 layer's or group's contents, or of the current layer's for the document's collection. `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below - its top and each side from 1 to 3,999,856 points. Artboard names are trimmed, cannot be empty and are unique: a name + its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. + Artboard names are trimmed, cannot be empty and are unique: a name another artboard has throws. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the - change in `activeArtboards` (`[{document, artboard}]`, both indexes). An index outside the list throws a + change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the + run leaves it). An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. - `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: - the current layer), on top of its contents or at `index` (0 is the bottom), as one undo step named Group, and + 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}`. The selection stays as it is. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 29a93c640b..6edddf19b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/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`). Paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, 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/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.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`. From 185517dac14d179ab9ec007a2a8b15e5ac33188e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:49:49 -0800 Subject: [PATCH 03/49] Scripts: artboards.insert puts the document back when the reorder fails artboards.add and artboards.insert run artboard.new and artboard.reorder inside one savepoint, as duplicate does for its copy and move. When either command or the selection restore after them fails, the new artboard is removed and the undo history is as it was. --- crates/engine/src/script/dom/layers.rs | 29 ++++++++++++++------------ 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 91c7bc4a03..bd0046a4b4 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1166,7 +1166,7 @@ fn boards_index(h: &Host, a: &[Data]) -> Answer { } /// A new artboard at `rect` with `artboard.new`, moved to `at` (`None`: it stays last) with -/// `artboard.reorder`. → the artboard. +/// `artboard.reorder`; when either fails, the document is as it was. → the artboard. fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { let doc = boards_doc(h, a)?; let (r, len, name) = with_doc(h, doc, |_, st| { @@ -1181,18 +1181,21 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { if len >= max { return Err(HostError::Range(format!("a document has at most {max} artboards"))); } - let id = on_doc(h, doc.uid, true, |h| { - let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; - let index = - result_id(&made, "index").and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error("the artboard was not made".into()))?; - if let Some(to) = to - && to != index - { - command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; - } - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + let id = super::atomically(h, |h| { + on_doc(h, doc.uid, true, |h| { + let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let index = result_id(&made, "index") + .and_then(|i| usize::try_from(i).ok()) + .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; + if let Some(to) = to + && to != index + { + command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + }) })?; Ok(board_ref(h, doc.uid, id)) } From ce0da4122fa1be126d6a2059a8a4139cb4929100 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:12:51 -0800 Subject: [PATCH 04/49] Scripts: a loop over groups and their page items lists each collection once The object model kept only the last list of art it built, so a loop that read doc.groupItems[i] and then that group's pageItems rebuilt the document-wide list of groups on every step. It now keeps the last four lists, each while its document is unchanged, and drops a document's older lists when it builds one for a newer version of that document. --- crates/engine/src/script/dom.rs | 6 +++--- crates/engine/src/script/dom/layers.rs | 29 ++++++++++++++++++-------- crates/engine/src/tests/script_dom.rs | 24 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8123566196..a3d49ddd26 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -94,9 +94,9 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, - /// The last list of art one of [`layers`]' collections gave, kept while its document is - /// unchanged. - art: RefCell>, + /// 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 uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, presets: RefCell>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index bd0046a4b4..b6c82ab1f1 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -572,17 +572,23 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { /// and the ids it listed then. pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); +/// How many lists of art [`super::State`] keeps at once. +pub(super) const ART_LISTS: usize = 4; + /// The objects of `kind` in `container` (directly), or in the whole document at any depth, in -/// paint order. The last list is kept while the document is unchanged, and each new one is charged -/// by the objects it looks at. +/// paint order. The last [`ART_LISTS`] lists are kept while their documents are unchanged, so a +/// loop over groups that reads each group's `pageItems` builds each list once. Each new list is +/// charged by the objects it looks at. fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { - if let Some((uid, doc, k, c, ids)) = &*h.dom.art.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - && *k == kind as u8 - && *c == container { - return Ok(ids.clone()); + let mut lists = h.dom.art.borrow_mut(); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.4.clone(); + lists.push(list); + return Ok(ids); + } } let ids: Vec = match container { None => { @@ -597,7 +603,12 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R } }; let ids = Rc::new(ids); - *h.dom.art.borrow_mut() = Some((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + let mut lists = h.dom.art.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(), kind as u8, container, ids.clone())); Ok(ids) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c44ecb4887..7597da4da3 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1250,6 +1250,30 @@ fn art_collections_follow_edits_between_reads() { assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); } +#[test] +fn a_loop_over_groups_and_their_items_lists_each_collection_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..5 { + let x = f64::from(i) * 20.0; + let (a, b) = (rect(&mut s, x, 0.0, 10.0, 10.0), rect(&mut s, x, 20.0, 10.0, 10.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + // Both scripts make the same calls. The first reads the groups and each group's items in + // turn; the second reads every group before any group's items, so it builds each list once. + let nested = "var gs = app.activeDocument.groupItems, n = 0;\ + for (var i = 0; i < gs.length; i++) { var p = gs[i].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let in_order = "var gs = app.activeDocument.groupItems, all = [], n = 0;\ + 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()); + assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); + assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); From fba91c32e6c780f50860be6994c81c21f163f0f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:24:16 -0800 Subject: [PATCH 05/49] Scripts: new layers and groups keep large ids, and runs keep the active artboard in step - layers.add, groupItems.add and artboards.add read the new object's id or index from the command's own result. Read from the script's copy, an id past 2^53 lost precision, and the new layer or group came back stale or null. - script.run's activeArtboards also lists a document whose active artboard has another index at the end of the run, because artboards were inserted, removed or reordered before it, so the view shows the same artboard. - After a run, the Artboard tool takes the view's active artboard again. The end of a run starts the tool afresh, which made artboard 0 the tool's active artboard whatever the view or the script had chosen. --- crates/engine/src/script/dom.rs | 7 ++++ crates/engine/src/script/dom/layers.rs | 46 +++++++++++++++----------- crates/engine/src/script/mod.rs | 4 +-- crates/engine/src/tests/script_dom.rs | 32 ++++++++++++++++++ crates/ui-egui/src/script_runs.rs | 9 ++++- crates/ui-egui/src/tests/script_run.rs | 18 ++++++++++ docs/mcp.md | 3 +- 7 files changed, 96 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a3d49ddd26..4c89cc5a4c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -99,10 +99,17 @@ pub(super) struct State { art: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_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)>, presets: RefCell>>, } impl State { + /// The state of a run that starts with the documents `docs` open. + pub(super) fn new(docs: &[DocState]) -> Self { + Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() } + } + /// Whether a call's own savepoint is open: its commands take none of their own. pub(super) fn saving(&self) -> bool { self.saving.get() diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index b6c82ab1f1..108fe7f2e8 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -28,7 +28,9 @@ //! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global //! rulers, setting it moves the document's zero point. //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report -//! lists it in `activeArtboards` for the app to show. +//! lists it in `activeArtboards` for the app to show. The report also lists a document whose +//! active artboard has another index at the end of the run, because artboards were inserted, +//! removed or reordered before it. use std::rc::Rc; use std::sync::Arc; @@ -37,9 +39,9 @@ use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ - Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, arg, boolean, command, 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, - page_items, placement_of, property, text, typename, whole, with_doc, + Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, 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, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -86,13 +88,10 @@ fn type_error(what: &str) -> HostError { HostError::Type(format!("this is not a {what}")) } -/// The id a command's result gives under `key`. -fn result_id(d: &Data, key: &str) -> Option { - let Data::Object(o) = d else { return None }; - match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { - Some(Data::Number(n)) => whole(*n), - _ => None, - } +/// The whole number under `key` in a command's own result (not the script's copy, whose numbers +/// are exact only up to 2^53), such as the id of the object it made. +fn result_id(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_u64) } // ---- Layer ---- @@ -523,9 +522,9 @@ fn layers_add(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the layer is hidden or locked".into())); } } - let r = on_doc(h, doc.uid, true, |h| match parent { - None => command(h, "layer.new", &json!({"top": true})), - Some(p) => command(h, "layer.newSublayer", &json!({"parent": p.0})), + let (_, r) = on_doc(h, doc.uid, true, |h| match parent { + None => command_value(h, "layer.new", &json!({"top": true})), + Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), })?; let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; Ok(layer_ref(h, doc.uid, NodeId(id))) @@ -776,7 +775,7 @@ fn groups_add(h: &Host, a: &[Data]) -> Answer { } } let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); - let r = on_doc(h, doc.uid, true, |h| command(h, "object.newGroup", ¶ms))?; + let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; @@ -1194,7 +1193,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { } let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { - let made = command(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; let index = result_id(&made, "index") .and_then(|i| usize::try_from(i).ok()) .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; @@ -1258,9 +1257,18 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { /// The documents whose active artboard the run changed, as `script.run`'s report gives them: /// `[{document, artboard}]`, each an index, with the active artboard each document has at the end -/// of the run, or `None` when there are none. -pub(crate) fn active_artboards(moved: &[u64], docs: &[DocState]) -> Option { - let list: Vec = moved +/// of the run, or `None` when there are none. They are the documents in `moved`, then those whose +/// active artboard's index differs from the one in `start` (an artboard added, inserted, removed or +/// reordered before it). +pub(crate) fn active_artboards(moved: &[u64], start: &[(u64, usize)], docs: &[DocState]) -> Option { + let mut uids = moved.to_vec(); + for (uid, at) in start { + let shifted = docs.iter().find(|d| d.uid == *uid).is_some_and(|st| active_artboard(st) != *at); + if shifted && !uids.contains(uid) { + uids.push(*uid); + } + } + let list: Vec = uids .iter() .filter_map(|uid| { let document = docs.iter().position(|d| d.uid == *uid)?; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 34779c7b5e..725e566f12 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2064,7 +2064,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::default(), + dom: dom::State::new(self.documents()), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2290,7 +2290,7 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); - if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), self.documents()) { + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) { report["activeArtboards"] = boards; } close_run(self, host, &mut report, console::Ending::Finished); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7597da4da3..f0862963b4 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1093,6 +1093,22 @@ fn layers_list_top_first_and_add_makes_the_new_layer_current() { assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); } +#[test] +fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The new ids, 2^53 + 1 and 2^53 + 3, are not exact as numbers. + for (id, source) in + [(1, "var l = app.activeDocument.layers.add(); l.name = 'made';"), (3, "var g = app.activeDocument.groupItems.add(); g.name = 'made';")] + { + let big = (1u64 << 53) + id; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + run(&mut s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("made"), "{source}"); + } +} + #[test] fn layer_properties_round_trip_and_reject_bad_values() { let (mut s, _, _) = doc(); @@ -1402,6 +1418,22 @@ fn the_report_gives_the_active_artboard_the_run_leaves() { assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); } +#[test] +fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.setActiveArtboardIndex(1);").unwrap(); + // An artboard inserted or removed before the active one moves it to another index. + let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([2])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 2}])); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.remove(0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + // One added after it leaves its index as it was. + let r = run(&mut s, "app.activeDocument.artboards.add([1000, 300, 1100, 100]);").unwrap(); + assert!(r.get("activeArtboards").is_none(), "{r}"); +} + #[test] fn an_artboard_rectangle_stays_inside_the_canvas() { let (mut s, _, _) = doc(); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index e8ae5d8a94..62e90ad97f 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -48,7 +48,9 @@ pub fn poll(app: &mut VectorcraftApp) { } /// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view -/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). +/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). The end of a run +/// starts the tool afresh, so the Artboard tool then takes the active document's active artboard as +/// its only selected one, as choosing it in the Artboards panel does. fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { for b in boards { let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok()); @@ -60,6 +62,11 @@ fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { view.artboard = board; } } + if app.session.tool_id() == "artboard" + && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0) + { + crate::panels::artboards::select(app, crate::panels::artboards::selected(app, n)); + } } /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index d74b9e1699..f0cf5fa877 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -126,6 +126,24 @@ fn set_active_artboard_index_shows_the_artboard_in_the_view() { assert_eq!(app.views[0].artboard, 1); } +#[test] +fn the_artboard_tool_follows_the_artboard_a_script_makes_active() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.select_tool("artboard"); + crate::panels::artboards::select(&mut app, 2); + // A run starts the tool afresh; it keeps the view's active artboard, then the one the script chose. + for (source, active) in [("vc.log(1);", 2), ("app.activeDocument.artboards.setActiveArtboardIndex(1);", 1)] { + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, active, "{source}"); + assert_eq!(app.session.tool_options()["active"], json!(active), "{source}"); + assert_eq!(app.session.tool_options()["selected"], json!([active]), "{source}"); + } +} + #[test] fn a_script_error_goes_to_the_status_bar() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 7296adf023..a1d9a1a0ee 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2735,7 +2735,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the - run leaves it). An index outside the list throws a + run leaves it). The report also lists a document whose active artboard has another index when the run ends because + artboards were inserted, removed or reordered before it. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. From 9d9c23f6106bcb38959c1e9964e3292694141551 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:51:20 -0800 Subject: [PATCH 06/49] Scripts: a layer's or group's removeAll refuses art on a locked artboard The removeAll() of a layer's or group's pageItems, and of groupItems and compoundPathItems, checked only for hidden or locked objects, so it deleted art on a locked artboard that remove() and the document's pageItems.removeAll() refuse. It now refuses those objects with the same error before anything is deleted, and records no undo step. --- crates/engine/src/script/dom/layers.rs | 21 +++++++++----- crates/engine/src/tests/script_dom.rs | 40 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 108fe7f2e8..1251972f64 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -39,9 +39,9 @@ use serde_json::{Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref, host_ref_parts}; use super::{ - Answer, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, 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, page_items, placement_of, property, text, typename, whole, with_doc, + 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, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -664,11 +664,12 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { } /// `removeAll()`: deletes every object the collection lists (those inside another listed one go -/// with it) in one command. A hidden or locked one, or one in a hidden or locked layer or group, -/// stops it before anything is deleted. +/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or +/// one on a locked artboard stops it before anything is deleted, as the document's +/// `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) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = 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(); @@ -676,12 +677,18 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + 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)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + 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::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f0862963b4..99fd7ae784 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -997,6 +997,46 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// The `removeAll()` of a layer's or group's collections, and of `groupItems` and +/// `compoundPathItems`, refuses art on a locked artboard as the document's `pageItems.removeAll()` +/// does, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for scope in [ + "app.activeDocument.layers[0].pageItems", + "app.activeDocument.layers[0].groupItems", + "app.activeDocument.groupItems", + "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.layers[0].compoundPathItems", + "app.activeDocument.compoundPathItems", + ] { + let err = failure(&mut s, &format!("{scope}.removeAll();")); + assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); + assert_eq!(undo_steps(&s), steps, "{scope}"); + } + lock(&mut s, false); + let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); From de38412a63eec0312cf90c64a0b143de6485cb4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:19:59 -0800 Subject: [PATCH 07/49] Scripts: new layers stay current, lists start at the top, empty compound paths - layers.add() and activeLayer = layer keep the layer the script made current after the call, instead of putting the earlier current layer back with the selection. - A layer's or artboard's name takes a number or a boolean as String() writes it. Two artboards may now have the same name. - A layer's or group's pageItems, groupItems and compoundPathItems, and a compound path's pathItems, list the topmost object first. - compoundPathItems.add() makes an empty compound path (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). object.newGroup takes compound: true for it, and node.move and PageItem.move put paths into it; the first path gives an empty compound path its paint. Other objects are refused. --- crates/engine/src/cmd/layer.rs | 19 +++- crates/engine/src/cmd/object/arrange.rs | 19 +++- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/script/dom.rs | 24 ++++- crates/engine/src/script/dom/layers.rs | 87 +++++++++++------- crates/engine/src/tests/script_dom.rs | 108 ++++++++++++++++++++++- docs/mcp.md | 31 ++++--- docs/target-app-parity.md | 2 +- 8 files changed, 232 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d2258f4e4a..27d5d58336 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; 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 also in a shown, unlocked compound path, and an empty compound path takes the paint of the first path that goes in; 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 ), @@ -919,9 +919,19 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index); let d = &s.doc()?.doc; let n = d.node(id).ok_or(EngineError::NoNode(id))?; - if !accepts(d, parent, n) { + let compound = parent.and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + if let Some(c) = compound { + if !matches!(n.kind, NodeKind::Path { guide: false, .. }) { + return Err(bad(C, "a compound path holds only paths")); + } + if !d.is_editable(c.id) { + return Err(bad(C, "the compound path is hidden or locked")); + } + } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // An empty compound path takes the paint of the first path that goes into it. + let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, n.appearance.clone())); if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -931,6 +941,11 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; + if let Some((c, appearance)) = paint + && let Some(n) = d.node_mut(c) + { + n.appearance = appearance; + } super::intertwine::settle_members(d, &[(id, from)], &left)?; live_paint.finish(d, sel, &[id])?; sel.prune(d); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index bd993ec1ec..bd770334e8 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -105,10 +105,15 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { Ok(json!({ "id": gid.0 })) } -/// `object.newGroup`: an empty group in a layer or a group (default: the current layer), on top -/// of its contents or at `index` (0 = bottom). The selection stays as it is. +/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The +/// selection stays as it is. pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { const C: &str = "object.newGroup"; + let compound = match p.get("compound") { + None | Some(Value::Null) => 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"))?, @@ -126,11 +131,17 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } - let gid = s.edit("Group", |d, _| { + let name = if compound { "Compound Path" } else { "Group" }; + let gid = s.edit(name, |d, _| { let gid = d.alloc_id(); let clips = d.node(parent).is_some_and(Node::clips); let index = if clips { index.max(1) } else { index }; - d.insert(Some(parent), index, Node::group(gid, Vec::new()))?; + let node = if compound { + Node::new(gid, NodeKind::Compound { children: Vec::new(), rule: vectorcraft_geom::FillRule::NonZero }) + } else { + Node::group(gid, Vec::new()) + }; + d.insert(Some(parent), index, node)?; Ok(gid) })?; Ok(json!({ "id": gid.0 })) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 8d17cc0a72..d197d911f3 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)} → {id}: an empty group 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; the selection stays as it is", has_doc, new_group ), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 3a3c625754..c8741952d4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -637,6 +637,18 @@ fn on_doc( uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + on_doc_layer(h, uid, keep_selection, true, f) +} + +/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`, +/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current. +fn on_doc_layer( + h: &Host, + uid: u64, + keep_selection: bool, + keep_layer: bool, + f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer) = { let s = h.session.borrow(); @@ -649,6 +661,12 @@ fn on_doc( command(h, "document.activate", &json!({"index": index}))?; } let r = f(h); + let layer = if keep_layer { + layer + } else { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows())) + }; let mut restored = Ok(()); if keep_selection { let doc = { @@ -1754,7 +1772,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } let (parent, beside) = match how { Placement::Top | Placement::Bottom => { - if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + if matches!(t.kind, NodeKind::Compound { .. }) { + if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); } (target, None) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 1251972f64..15171be00d 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -11,20 +11,21 @@ //! one after others are added, moved or removed, and throws once it is gone. //! //! VectorCraft's own rules, which the help pages do not state: -//! - `layers` lists layers top first, as the Layers panel shows them; `groupItems`, -//! `compoundPathItems` and a layer's or group's `pageItems` list art in paint order, bottom first, -//! as `pageItems` does. The document's `groupItems` and `compoundPathItems` hold every group or -//! compound path at any depth; a layer's or group's hold the ones directly in it. +//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's +//! `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`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. //! - `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. -//! - `CompoundPathItems.add()` throws: a compound path holds at least one path. +//! - `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 -//! document, the limit `Documents.add` uses. Artboard names are unique: a name another artboard -//! has throws. +//! document, the limit `Documents.add` uses. Two artboards may have the same name. +//! - A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. //! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global //! rulers, setting it moves the document's zero point. //! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report @@ -41,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, page_items, placement_of, property, text, typename, whole, with_doc, + method, named, num, number, on_doc, on_doc_layer, page_items, placement_of, property, text, typename, whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -153,15 +154,26 @@ fn layer_name(h: &Host, a: &[Data]) -> Answer { read_layer(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) } +/// A name a script assigns: a string, or a number or boolean as `String()` writes it. +fn name_text(d: &Data) -> Result { + match d { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type("name must be a string".into())), + } +} + fn layer_set_name(h: &Host, a: &[Data]) -> Answer { - let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) }; + let name = name_text(arg(a, 1))?; if name.trim().is_empty() { return Err(HostError::Range("a layer's name cannot be empty".into())); } if name.chars().count() > MAX_LAYER_NAME { return Err(HostError::Range(format!("a layer's name has at most {MAX_LAYER_NAME} characters"))); } - set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), json!({"name": name})) + let params = json!({"name": &name}); + set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), params) } fn layer_visible(h: &Host, a: &[Data]) -> Answer { @@ -522,7 +534,7 @@ fn layers_add(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the layer is hidden or locked".into())); } } - let (_, r) = on_doc(h, doc.uid, true, |h| match parent { + let (_, r) = on_doc_layer(h, doc.uid, true, false, |h| match parent { None => command_value(h, "layer.new", &json!({"top": true})), Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), })?; @@ -574,8 +586,8 @@ pub(super) type ArtList = (u64, Arc, u8, Option, Rc) -> Result>> { @@ -598,7 +610,7 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R Some(c) => { let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); h.charge_call(children.len() as u64)?; - children.iter().filter(|n| kind.holds(n)).map(|n| n.id).collect() + children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() } }; let ids = Rc::new(ids); @@ -771,26 +783,36 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer { art_typename(h, a, Kind::Compound) } -/// `groupItems.add()`: an empty group on top of the layer's or group's contents (the document's: -/// the current layer's), with `object.newGroup`. → the group. -fn groups_add(h: &Host, a: &[Data]) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), "GroupItems")?; +/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. +/// → the new object. +fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; if let Some(c) = c { let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); if compound { return Err(HostError::Error("a compound path holds only paths".into())); } } - let params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + if kind == Kind::Compound + && let Some(o) = params.as_object_mut() + { + o.insert("compound".into(), json!(true)); + } let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; - let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the group was not made".into()))?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the object was not made".into()))?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; Ok(item_ref(h, st, NodeId(id))) } -fn compounds_add(_: &Host, _: &[Data]) -> Answer { - Err(HostError::Error("CompoundPathItems.add cannot make an empty compound path: a compound path holds at least one path".into())) +fn groups_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Group) +} + +fn compounds_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Compound) } // ---- The art collections of a document, a layer, a group and a compound path ---- @@ -905,7 +927,7 @@ fn doc_set_active_layer(h: &Host, a: &[Data]) -> Answer { } let now = with_doc(h, doc, |_, st| st.current_layer()); if now != Some(id) { - on_doc(h, doc.uid, true, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; + on_doc_layer(h, doc.uid, true, false, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; } Ok(Data::Undefined) } @@ -1026,10 +1048,11 @@ fn board_name(h: &Host, a: &[Data]) -> Answer { read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) } -/// A new artboard name: not empty, at most [`MAX_TEXT_BYTES`] bytes, and no other artboard's -/// (`except`: the artboard being renamed). → the name, trimmed as `artboard.rename` trims it. -fn board_name_arg(st: &DocState, d: &Data, except: Option) -> Result { - let Data::String(name) = d else { return Err(HostError::Type("name must be a string".into())) }; +/// A new artboard name: not empty and at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as +/// `String()` writes it. Another artboard may have the same name. → the name, trimmed as +/// `artboard.rename` trims it. +fn board_name_arg(d: &Data) -> Result { + let name = name_text(d)?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } @@ -1037,16 +1060,12 @@ fn board_name_arg(st: &DocState, d: &Data, except: Option) -> Result Answer { - let (b, i) = this_board(h, a)?; - let name = with_doc(h, b.doc, |_, st| board_name_arg(st, arg(a, 1), Some(i)))?; - set_board(h, a, |ab| ab.name == name, json!({"name": name})) + let name = board_name_arg(arg(a, 1))?; + set_board(h, a, |ab| ab.name == name, json!({"name": &name})) } fn board_parent(h: &Host, a: &[Data]) -> Answer { @@ -1189,7 +1208,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { let (r, len, name) = with_doc(h, doc, |_, st| { let boards = &st.doc.artboards; h.charge_call(boards.len() as u64)?; - // The first "Artboard N" from one past the count that no artboard has, so names stay unique. + // The first "Artboard N" from one past the count that no artboard has. let name = (boards.len() + 1..).map(|n| format!("Artboard {n}")).find(|n| !boards.iter().any(|ab| ab.name == *n)).unwrap_or_default(); Ok::<_, HostError>((rect_arg(h, st, arg(a, 1), "artboardRect")?, boards.len(), name)) })?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ccc293c85f..4fe40ddad2 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1391,6 +1391,26 @@ fn layers_list_top_first_and_add_makes_the_new_layer_current() { assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); } +#[test] +fn a_new_or_assigned_layer_stays_the_current_layer() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, base = d.layers[0];\ + var n = d.layers.add(); n.name = 'New'; vc.log(d.activeLayer.name);\ + d.activeLayer = base; vc.log(d.activeLayer.name);\ + d.activeLayer = n; vc.log(d.activeLayer.name);\ + var sub = base.layers.add(); sub.name = 'Sub'; vc.log(d.activeLayer.name);\ + vc.log(d.selection.length); vc.log(d.selection[0].layer.name);", + ); + assert_eq!(out, [json!("New"), json!("Layer 1"), json!("New"), json!("Sub"), json!(1), json!("Layer 1")]); + // The layer the script made current is still current after the run. + let st = s.active().unwrap(); + let current = st.current_layer().and_then(|l| st.doc.node(l)).and_then(|n| n.name.clone()); + assert_eq!(current.as_deref(), Some("Sub")); +} + #[test] fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { let mut s = Session::new(); @@ -1429,7 +1449,8 @@ fn layer_properties_round_trip_and_reject_bad_values() { assert_eq!(undo_steps(&s), steps); let before = format!("{:?}", s.active().unwrap().doc.layers); for (src, msg) in [ - ("app.activeDocument.layers[0].name = 5;", "name must be a string"), + ("app.activeDocument.layers[0].name = null;", "name must be a string"), + ("app.activeDocument.layers[0].name = {};", "name must be a string"), ("app.activeDocument.layers[0].name = ' ';", "cannot be empty"), ("app.activeDocument.layers[0].name = new Array(600).join('x');", "at most 512"), ("app.activeDocument.layers[0].opacity = 200;", "from 0 to 100"), @@ -1535,10 +1556,74 @@ fn group_items_list_every_depth_and_clipped_toggles_the_mask() { assert_eq!(g.children().unwrap()[0].id, b); assert_eq!(undo_steps(&s), steps + 1); assert!(failure(&mut s, "app.activeDocument.groupItems[0].clipped = 'yes';").contains("true or false")); - assert!(failure(&mut s, "app.activeDocument.compoundPathItems.add();").contains("empty compound path")); assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); } +#[test] +fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds, bottom to top, the compound path of `a` and the group of `b` (50 pt wide) + // and `c` (70 pt wide). + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], P = L.pageItems, g = L.groupItems[0];\ + vc.log(P[0].typename); vc.log(P[1].typename); vc.log(g.pageItems[0].width); vc.log(g.pageItems[1].width);\ + var e = L.groupItems.add(); e.name = 'E'; vc.log(L.groupItems[0].name); vc.log(L.pageItems[0].name);\ + vc.log(L.compoundPathItems[0].pathItems[0].width);", + ); + assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); +} + +#[test] +fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(); c.name = 'C'; vc.log(c.typename); vc.log(c.pathItems.length);\ + vc.log(d.compoundPathItems.length); vc.log(c.layer.name);", + ); + assert_eq!(out, [json!("CompoundPathItem"), json!(0), json!(1), json!("Layer 1")]); + assert_eq!(undo_steps(&s), steps + 1); + let cid = { + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap().id + }; + // Paths moved into it become its members, and it takes the paint of the first one. The layer + // lists the new compound path first, then `b`, then `a`. + let source = "var d = app.activeDocument, c = d.compoundPathItems.getByName('C'), L = d.layers[0].pageItems, a = L[2], b = L[1];\ + vc.log(L[0].name); a.move(c, ElementPlacement.PLACEATBEGINNING); b.move(c, ElementPlacement.PLACEATEND);\ + vc.log(c.pathItems.length); vc.log(a.parent.typename); vc.log(b.parent.typename);"; + assert_eq!(log(&mut s, source), [json!("C"), json!(2), json!("CompoundPathItem"), json!("CompoundPathItem")]); + let c = s.active().unwrap().doc.node(cid).unwrap(); + let members: Vec = c.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + assert!(members.contains(&a) && members.contains(&b)); + assert_eq!(c.appearance, red); + // A group goes neither into a compound path nor beside a path inside one. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for src in [ + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C'));", + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C').pathItems[0], ElementPlacement.PLACEBEFORE);", + "app.activeDocument.compoundPathItems.add('x').move(app.activeDocument.compoundPathItems.getByName('C'));", + ] { + assert!(failure(&mut s, src).contains("only paths"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1558,7 +1643,7 @@ fn art_collections_follow_edits_between_reads() { let out = log( &mut s, "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.groupItems; vc.log(p.length); vc.log(g.length);\ - d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[2].typename); vc.log(g.length);\ + d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[0].typename); vc.log(g.length);\ p[0].remove(); vc.log(p.length); vc.log(p[0].typename);", ); assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); @@ -1651,6 +1736,21 @@ fn new_artboards_get_a_name_no_other_artboard_has() { assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); } +#[test] +fn names_take_numbers_and_artboards_may_share_a_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, A = d.artboards, L = d.layers[0]; A.add([500, 300, 700, 100]);\ + L.name = 5; vc.log(L.name); vc.log(typeof L.name); L.name = 1.5; vc.log(L.name); L.name = true; vc.log(L.name);\ + A[0].name = 7; vc.log(A[0].name); A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]);\ + vc.log(A.getByName('Same').artboardRect[0]);", + ); + assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!(["Same", "Same"]), json!(0)]); + let names: Vec = s.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Same", "Same"]); +} + #[test] fn artboards_reject_bad_arguments_before_any_change() { let (mut s, _, _) = doc(); @@ -1669,8 +1769,8 @@ fn artboards_reject_bad_arguments_before_any_change() { ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), ("app.activeDocument.artboards.remove(2);", "index must be"), ("app.activeDocument.artboards.remove(-1);", "index must be"), - ("app.activeDocument.artboards[0].name = 'Two';", "another artboard"), ("app.activeDocument.artboards[0].name = '';", "cannot be empty"), + ("app.activeDocument.artboards[0].name = null;", "must be a string"), ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), ("app.activeDocument.artboards[0].showCenter = 'on';", "true or false"), diff --git a/docs/mcp.md b/docs/mcp.md index 93b4013547..4cec59e36b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2722,11 +2722,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its properties run `artboard.setProps`, and `rulerOrigin` runs `document.setRulerOrigin`. One document always keeps one artboard. - VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. `groupItems`, - `compoundPathItems` and a layer's or group's `pageItems` list art in paint order from the bottom. The document's - `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold - only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` - list its paths, with the typename `PathItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. A layer's or group's + `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 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 the next layer beside it and any art between them. @@ -2735,13 +2736,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 - layer's or group's contents, or of the current layer's for the document's collection. - `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop + 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` puts into a compound path + becomes one of its paths, and an empty compound path takes the paint of the first path that goes in; other objects + are refused. `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. - Artboard names are trimmed, cannot be empty and are unique: a name - another artboard has throws. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one + Artboard names are trimmed and cannot be empty, and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the @@ -2750,10 +2753,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. -- `object.newGroup {parent?, index?}` adds an empty group to a shown, unlocked layer or group (`parent`; 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}`. The selection stays as it is. +- `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; + 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. + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, and an empty + compound path takes the paint of the first path that goes in. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6edddf19b3..023c49c3cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/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`). Paths, type and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.rs`. - - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks and new empty groups, 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/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `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`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.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 `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From ff2ceab181b068de57274c28bbf2d2febd054785 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 19:07:47 -0800 Subject: [PATCH 08/49] Scripts: paths keep the paint they are drawn with as they enter or leave a compound path - A path that node.move, move or duplicate puts into a compound path loses its own paint, live shape and pixel alignment, as Make Compound Path leaves its paths; the compound path becomes pixel-aligned when the path was. An empty compound path takes the paint the first path was drawn with: the path's own, or that of the compound path it leaves. - A path that node.move or 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. Before, it kept the empty paint Make Compound Path left it and drew nothing. - Artboard.name = '' gives the artboard its default name, Artboard N, as artboard.setProps gives a blank name, instead of throwing. - The undo step of object.newGroup is named through `label`, so the translators' list reads Compound Path as well as Group. - Tests: a compound path's pathItems list the topmost path first, and a path duplicated into a compound path keeps no paint, live shape or pixel alignment of its own. Docs: docs/mcp.md (the order rule names the document's lists; move, duplicate and node.move name a compound path as a place). --- crates/engine/src/cmd/layer.rs | 37 ++++- crates/engine/src/cmd/object/arrange.rs | 4 +- crates/engine/src/script/dom.rs | 8 +- crates/engine/src/script/dom/layers.rs | 26 ++-- crates/engine/src/tests/script_dom.rs | 175 +++++++++++++++++++++++- docs/mcp.md | 35 +++-- 6 files changed, 242 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 27d5d58336..5f83152beb 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 in a shown, unlocked compound path, and an empty compound path takes the paint of the first path that goes in; 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 also goes into a shown, unlocked compound path and gives up its own paint, 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 ), @@ -930,8 +930,15 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } - // An empty compound path takes the paint of the first path that goes into it. - let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, n.appearance.clone())); + // An empty compound path takes the paint of the first path that goes into it: the path's own, + // or the paint of the compound path it leaves, which is what painted it. + let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); + let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); + let into = compound.map(|c| c.id); + // A path that leaves a compound path for a layer or a group takes the compound path's paint and + // pixel alignment, as Release Compound Path gives them to its paths. + let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -946,6 +953,30 @@ fn move_node(s: &mut Session, p: &Value) -> Result { { n.appearance = appearance; } + // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as + // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead. + if let Some(c) = into { + let mut aligned = false; + if let Some(m) = d.node_mut(id) { + m.appearance = vectorcraft_doc::Appearance::default().into(); + aligned = std::mem::take(&mut m.extras_mut().pixel_aligned); + if let NodeKind::Path { live, .. } = &mut m.kind { + *live = None; + } + } + if aligned && let Some(cn) = d.node_mut(c) { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } + } + if let Some((appearance, aligned)) = out_of + && let Some(m) = d.node_mut(id) + { + m.appearance = appearance; + if aligned { + m.extras_mut().pixel_aligned = true; + } + } super::intertwine::settle_members(d, &[(id, from)], &left)?; live_paint.finish(d, sel, &[id])?; sel.prune(d); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index bd770334e8..36b3cef6fe 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -131,8 +131,8 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } - let name = if compound { "Compound Path" } else { "Group" }; - let gid = s.edit(name, |d, _| { + let label = if compound { "Compound Path" } else { "Group" }; + let gid = s.edit(label, |d, _| { let gid = d.alloc_id(); let clips = d.node(parent).is_some_and(Node::clips); let index = if clips { index.max(1) } else { index }; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c8741952d4..1aeb8d333a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -14,9 +14,11 @@ //! not the active one makes it active for the command and makes the other one active again after. //! //! VectorCraft's own rules, which the help pages do not state: -//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0. -//! `pageItems` lists every object, with the objects inside groups and compound paths after the -//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! - Collections list documents in tab order and the document's art in paint order (bottom first), +//! counted from 0; the `layers` module gives the order of a layer's, a group's and a compound +//! path's lists. The document's `pageItems` lists every object, with the objects inside groups +//! and compound paths after the group or compound path, and leaves out layers and ruler guides. +//! An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. //! - Script coordinates are points with Y up from the bottom of the first artboard //! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 15171be00d..3fafaf684b 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -13,8 +13,8 @@ //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's //! `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`. +//! 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`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. //! - `locked` true means the layer is locked. @@ -587,9 +587,9 @@ pub(super) type ArtList = (u64, Arc, u8, Option, Rc) -> Result>> { { let mut lists = h.dom.art.borrow_mut(); @@ -1048,23 +1048,21 @@ fn board_name(h: &Host, a: &[Data]) -> Answer { read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) } -/// A new artboard name: not empty and at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as -/// `String()` writes it. Another artboard may have the same name. → the name, trimmed as -/// `artboard.rename` trims it. -fn board_name_arg(d: &Data) -> Result { +/// A new artboard name: at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as `String()` writes +/// it. Another artboard may have the same name. → the name, trimmed as `artboard.setProps` trims +/// it; an empty one gives the artboard its default name, `Artboard N` for the Nth artboard. +fn board_name_arg(d: &Data, index: usize) -> Result { let name = name_text(d)?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } let name = name.trim(); - if name.is_empty() { - return Err(HostError::Range("an artboard's name cannot be empty".into())); - } - Ok(name.to_string()) + Ok(if name.is_empty() { format!("Artboard {}", index + 1) } else { name.to_string() }) } fn board_set_name(h: &Host, a: &[Data]) -> Answer { - let name = board_name_arg(arg(a, 1))?; + let (_, i) = this_board(h, a)?; + let name = board_name_arg(arg(a, 1), i)?; set_board(h, a, |ab| ab.name == name, json!({"name": &name})) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4fe40ddad2..e3d0a46807 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1616,7 +1616,7 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { for src in [ "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C'));", "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C').pathItems[0], ElementPlacement.PLACEBEFORE);", - "app.activeDocument.compoundPathItems.add('x').move(app.activeDocument.compoundPathItems.getByName('C'));", + "app.activeDocument.compoundPathItems.add().move(app.activeDocument.compoundPathItems.getByName('C'));", ] { assert!(failure(&mut s, src).contains("only paths"), "{src}"); } @@ -1624,6 +1624,146 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); } +/// The paint of a compound path's only path is the compound path's: moved into an empty compound +/// path, the path gives it that paint, not its own default one. +#[test] +fn a_path_moved_out_of_a_compound_path_gives_an_empty_one_the_paint_it_was_drawn_with() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, old = d.compoundPathItems[0], c = d.compoundPathItems.add(); c.name = 'C';\ + old.pathItems[0].move(c); vc.log(d.compoundPathItems.getByName('C').pathItems.length);", + ); + assert_eq!(out, [json!(1)]); + let d = &s.active().unwrap().doc; + let c = d.parent_of(a).and_then(|p| d.node(p)).unwrap(); + assert_eq!(c.name.as_deref(), Some("C")); + assert_eq!(c.appearance, red); + assert_ne!(d.node(a).unwrap().appearance, red); +} + +/// `node.move` into a compound path leaves the path without paint or pixel alignment of its own, +/// as Make Compound Path leaves its paths, and the compound path takes the alignment. +#[test] +fn node_move_into_a_compound_path_clears_the_paths_own_paint() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let painted = s.active().unwrap().doc.node(b).unwrap().appearance.clone(); + let member = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(b), Some(cid)); + let n = d.node(b).unwrap(); + assert_ne!(n.appearance, painted); + assert_eq!(n.appearance, member); + assert!(!n.extras().pixel_aligned); + assert!(d.node(cid).unwrap().extras().pixel_aligned); +} + +#[test] +fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() { + let (mut s, a, b) = doc(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(matches!(s.active().unwrap().doc.node(cid).unwrap().kind, NodeKind::Compound { .. })); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("only paths"), "{err}"); + for hide in ["object.lock", "object.hide"] { + s.execute("select.set", &json!({"ids": [cid.0]})).unwrap(); + s.execute(hide, &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("hidden or locked"), "{hide}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +/// `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() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let blue = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(), p = d.layers[0].pageItems[2]; var q = p.duplicate(c);\ + vc.log(c.pathItems.length); vc.log(q.parent.typename); vc.log(p.parent.typename);", + ); + assert_eq!(out, [json!(1), json!("CompoundPathItem"), json!("Layer")]); + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + let c = d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(c.appearance, blue); + assert_eq!(d.node(a).unwrap().appearance, blue); + // The copy keeps no paint, live shape or pixel alignment of its own. + let q = &c.children().unwrap()[0]; + assert_ne!(q.appearance, blue); + assert!(matches!(q.kind, NodeKind::Path { live: None, .. })); + assert!(!q.extras().pixel_aligned); +} + +/// A compound path's `pathItems` list its topmost path first. +#[test] +fn a_compound_paths_path_items_list_the_topmost_path_first() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let source = "var P = app.activeDocument.compoundPathItems[0].pathItems; vc.log(P[0].width); vc.log(P[1].width);"; + // `b` (50 pt wide) on top, then `a` (30 pt wide) on top. + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(50), json!(30)]); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(30), json!(50)]); +} + +/// 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] +fn a_path_moved_out_of_a_compound_path_keeps_the_paint_it_was_drawn_with() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let (cid, red, lid) = { + let d = &s.active().unwrap().doc; + let cid = d.parent_of(a).unwrap(); + (cid, d.node(cid).unwrap().appearance.clone(), d.layer_containing(a).unwrap()) + }; + assert_ne!(s.active().unwrap().doc.node(a).unwrap().appearance, red); + s.execute("node.move", &json!({"id": a.0, "parent": lid.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(lid)); + let n = d.node(a).unwrap(); + assert_eq!(n.appearance, red); + assert!(n.extras().pixel_aligned); + // The path left behind keeps none of its own. + assert_eq!(d.parent_of(b), Some(cid)); + assert_ne!(d.node(b).unwrap().appearance, red); +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1737,16 +1877,38 @@ fn new_artboards_get_a_name_no_other_artboard_has() { } #[test] -fn names_take_numbers_and_artboards_may_share_a_name() { +fn names_take_numbers_and_booleans() { let (mut s, _, _) = doc(); let out = log( &mut s, - "var d = app.activeDocument, A = d.artboards, L = d.layers[0]; A.add([500, 300, 700, 100]);\ + "var d = app.activeDocument, L = d.layers[0];\ L.name = 5; vc.log(L.name); vc.log(typeof L.name); L.name = 1.5; vc.log(L.name); L.name = true; vc.log(L.name);\ - A[0].name = 7; vc.log(A[0].name); A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]);\ - vc.log(A.getByName('Same').artboardRect[0]);", + d.artboards[0].name = 7; vc.log(d.artboards[0].name); vc.log(typeof d.artboards[0].name);", ); - assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!(["Same", "Same"]), json!(0)]); + assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!("string")]); +} + +#[test] +fn an_empty_artboard_name_gives_the_default_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[0].name = 'Front'; A[1].name = 'Back'; A[0].name = ''; A[1].name = ' ';\ + vc.log([A[0].name, A[1].name]);", + ); + assert_eq!(out, [json!(["Artboard 1", "Artboard 2"])]); +} + +#[test] +fn two_artboards_may_share_a_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]); vc.log(A.getByName('Same').artboardRect[0]);", + ); + assert_eq!(out, [json!(["Same", "Same"]), json!(0)]); let names: Vec = s.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); assert_eq!(names, ["Same", "Same"]); } @@ -1769,7 +1931,6 @@ fn artboards_reject_bad_arguments_before_any_change() { ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), ("app.activeDocument.artboards.remove(2);", "index must be"), ("app.activeDocument.artboards.remove(-1);", "index must be"), - ("app.activeDocument.artboards[0].name = '';", "cannot be empty"), ("app.activeDocument.artboards[0].name = null;", "must be a string"), ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), diff --git a/docs/mcp.md b/docs/mcp.md index 4cec59e36b..5bbf805842 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2657,9 +2657,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same - document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a - group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. An object of another document throws `Cross-document placement is not available`, and when + document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's, a + group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` + directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an @@ -2671,8 +2671,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. - VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the - objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates + VectorCraft's own rules: documents are listed in tab order, and the document's page items in paint order from the + bottom, with the objects inside groups and compound paths after their group and without layers and ruler guides + (the layers paragraph below gives the order of a layer's, a group's and a compound path's lists). Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with `CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename` is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` @@ -2738,14 +2739,17 @@ app through the global object `vc`, and writes to the Script Console and runs ot path; `false` releases the mask; the group keeps its id. `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` puts into a compound path - becomes one of its paths, and an empty compound path takes the paint of the first path that goes in; other objects - are refused. `artboards.add` and `insert` stop - at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is + (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. 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. + `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. - Artboard names are trimmed and cannot be empty, and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one - past the artboard count that no other artboard's name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. + Artboard names are trimmed, an empty name gives the artboard its default name (`Artboard N` for the Nth artboard), + and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's + name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because @@ -2757,8 +2761,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. - The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, and an empty - compound path takes the paint of the first path that goes in. + 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 + 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 `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -6463,7 +6469,8 @@ and `layerRows`, the rows highlighted in the panel. bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level - form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. A row that + form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts + a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join, From 331acb4a909b345594b1c64fd85fe9b00c5812b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 14:55:24 -0800 Subject: [PATCH 09/49] Scripts: a path moved between compound paths keeps its pixel alignment A path in a pixel-aligned compound path has no pixel alignment of its own. When node.move or move put it into another compound path, the new compound path did not become pixel-aligned, although it takes the paint the path was drawn with. It now becomes pixel-aligned when the path or the compound path it leaves was. The node.move params text and docs/mcp.md say so. --- crates/engine/src/cmd/layer.rs | 10 ++++++---- crates/engine/src/tests/script_dom.rs | 19 +++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 5f83152beb..9fe8d9e678 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, 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 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 ), @@ -936,6 +936,7 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); let into = compound.map(|c| c.id); + let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned); // A path that leaves a compound path for a layer or a group takes the compound path's paint and // pixel alignment, as Release Compound Path gives them to its paths. let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); @@ -954,12 +955,13 @@ fn move_node(s: &mut Session, p: &Value) -> Result { n.appearance = appearance; } // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as - // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead. + // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when + // the path was, or when the compound path it leaves was. if let Some(c) = into { - let mut aligned = false; + let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { m.appearance = vectorcraft_doc::Appearance::default().into(); - aligned = std::mem::take(&mut m.extras_mut().pixel_aligned); + aligned |= std::mem::take(&mut m.extras_mut().pixel_aligned); if let NodeKind::Path { live, .. } = &mut m.kind { *live = None; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e3d0a46807..e8522ed334 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1764,6 +1764,25 @@ fn a_path_moved_out_of_a_compound_path_keeps_the_paint_it_was_drawn_with() { assert_ne!(d.node(b).unwrap().appearance, red); } +/// A path that leaves a pixel-aligned compound path for another compound path makes that one +/// pixel-aligned, as it gives it the paint it was drawn with. +#[test] +fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { + 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(); + assert!(!s.active().unwrap().doc.node(a).unwrap().extras().pixel_aligned); + let to = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(!s.active().unwrap().doc.node(to).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": a.0, "parent": to.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(to)); + assert!(d.node(to).unwrap().extras().pixel_aligned); + assert!(!d.node(a).unwrap().extras().pixel_aligned); +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 5bbf805842..037d1a5433 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2740,7 +2740,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. An empty + 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 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. From 62ce314f752fddd5de5994e09bfafddb36fa2928 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:03:22 -0800 Subject: [PATCH 10/49] 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 9b8461feb590e6ebb348379083f0f292c1f9bba4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:26:20 -0800 Subject: [PATCH 11/49] Scripts: exportFile writes DXF with ExportOptionsAutoCAD - Document.exportFile with ExportType.AutoCAD takes an ExportOptionsAutoCAD object and writes a DXF file through document.export, adding .dxf unless the name ends with it. ExportType.AUTOCAD is the same value as ExportType.AutoCAD. - The options map to the DXF writer: version (AutoCADRelease13, 14, 15, 18, 21 and 24 as the R13, R14, 2000, 2004, 2007 and 2010 formats), unit, unitScaleRatio (drawing units for one unit, more than 0 and at most 1000), colors, rasterFormat, exportOption, alterPathsForAppearance, convertTextToOutlines, exportSelectedArtOnly and scaleLineweights. - An option the object leaves out takes the default the help page gives. colors, rasterFormat, unit and unitScaleRatio have none there and default to true colors, PNG, millimeters and 1. - AutoCADExportFileFormat.DWG, the help page's default, throws an error that says DWG is not available, and nothing is written. - New enumerations: AutoCADColors, AutoCADCompatibility, AutoCADExportFileFormat, AutoCADExportOption, AutoCADRasterFormat and AutoCADUnit. https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/save_open.rs | 142 +++++++++++++++++++- crates/engine/src/tests/script_save_open.rs | 83 ++++++++++++ docs/mcp.md | 17 ++- docs/target-app-parity.md | 1 + 5 files changed, 238 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..01f4522700 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1808,7 +1808,9 @@ const ENUMS: &[(&str, &[&str])] = &[ /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { - let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name); + items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}")))))); realm.define_host_object(name, items)?; } let l = link; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f54c2f3f0b..e3227da608 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -7,7 +7,8 @@ //! , //! , //! , -//! and +//! , +//! and //! describe. //! //! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's @@ -25,6 +26,12 @@ //! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. //! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, //! and when one of those files may not be written, none of them is. +//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF +//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not +//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page +//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to +//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one +//! `unit`, more than 0 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -63,6 +70,15 @@ pub(in crate::script) struct State { /// The enumerations these members use, as `dom`'s are made. pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]), + ( + "AutoCADCompatibility", + &["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"], + ), + ("AutoCADExportFileFormat", &["DXF", "DWG"]), + ("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]), + ("AutoCADRasterFormat", &["PNG", "JPEG"]), + ("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]), ( "Compatibility", &[ @@ -88,6 +104,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), ]; +/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the +/// same value as `enumeration.member`. +pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")]; + const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; @@ -482,9 +502,118 @@ fn svg_starts() -> Vec<(&'static str, Data)> { ] } +/// The members of the enumeration `name` in [`ENUMS`]. +fn members_of(name: &str) -> &'static [&'static str] { + ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m) +} + +fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsAutoCAD.{name}"); + let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what); + match name { + "alterPathsForAppearance" => { + p.insert("alterPaths".into(), json!(boolean(d, &what)?)); + } + "colors" => { + let colors = match pick("AutoCADColors")? { + "Max8Colors" => json!(8), + "Max16Colors" => json!(16), + "Max256Colors" => json!(256), + _ => json!("true"), + }; + p.insert("colors".into(), colors); + } + "convertTextToOutlines" => { + p.insert("outlineText".into(), json!(boolean(d, &what)?)); + } + "exportFileFormat" => { + if pick("AutoCADExportFileFormat")? == "DWG" { + return Err(HostError::Error( + "AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(), + )); + } + } + "exportOption" => { + let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" }; + p.insert("preserve".into(), json!(preserve)); + } + "exportSelectedArtOnly" => { + p.insert("selectedOnly".into(), json!(boolean(d, &what)?)); + } + "rasterFormat" => { + p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" })); + } + "scaleLineweights" => { + p.insert("scaleLineweights".into(), json!(boolean(d, &what)?)); + } + "unit" => { + let unit = match pick("AutoCADUnit")? { + "Points" => "pt", + "Picas" => "pc", + "Inches" => "in", + "Millimeters" => "mm", + "Centimeters" => "cm", + _ => "px", + }; + p.insert("unit".into(), json!(unit)); + } + "unitScaleRatio" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if !(n > 0.0 && n <= 1000.0) { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000"))); + } + p.insert("scale".into(), json!(n)); + } + "version" => { + let version = match pick("AutoCADCompatibility")? { + "AutoCADRelease13" => "R13", + "AutoCADRelease14" => "R14", + "AutoCADRelease15" => "2000", + "AutoCADRelease18" => "2004", + "AutoCADRelease21" => "2007", + _ => "2010", + }; + p.insert("version".into(), json!(version)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn autocad_starts() -> Vec<(&'static str, Data)> { + vec![ + ("alterPathsForAppearance", Data::Bool(false)), + ("convertTextToOutlines", Data::Bool(false)), + ("exportFileFormat", text("AutoCADExportFileFormat.DWG")), + ("exportOption", text("AutoCADExportOption.MaximizeEditability")), + ("exportSelectedArtOnly", Data::Bool(false)), + ("scaleLineweights", Data::Bool(false)), + ("version", text("AutoCADCompatibility.AutoCADRelease24")), + ] +} + +/// The options object `d` with the options of a new `class` object it leaves out, or holds as +/// `undefined`, added. +fn with_starts(class: &OptionClass, d: &Data) -> Data { + let Data::Object(items) = d else { return d.clone() }; + let mut items = items.clone(); + for (k, v) in (class.starts)() { + match items.iter_mut().find(|(n, _)| n == k) { + Some((_, held)) if matches!(held, Data::Undefined) => *held = v, + Some(_) => {} + None => items.push((k.to_string(), v)), + } + } + Data::Object(items) +} + const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; +const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts }; /// An `ExportType`: the format `document.export` writes, the extensions a file name may already /// end with (the first is added), and its option class (`None`: no options are taken). @@ -495,9 +624,9 @@ struct ExportKind { } fn export_kind(d: &Data) -> std::result::Result { - let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); let raster = |format, extensions| ExportKind { format, extensions, options: None }; - Ok(match member(d, "ExportType", all, "exportType")? { + Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? { + "AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) }, "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, @@ -631,6 +760,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => Map::new(), }, Some(o) => match kind.options { + // An AutoCAD option left out takes its help page's default, not the DXF writer's. + Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?, Some(class) => options_params(class, o)?, None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, @@ -642,7 +773,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - if kind.format != "svg" { + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`. + if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } let format = if svgz { "svgz" } else { kind.format }; @@ -740,7 +872,7 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its /// help page gives for the options mapped here. pub(super) fn classes(link: &Link) -> Vec { - let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]); all.map(|c| { let l = link.clone(); let f: HostFunction = Rc::new(move |_: Vec| { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 126c7c3947..9419b65f76 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -153,6 +153,60 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() { let _ = std::fs::remove_dir_all(base); } +/// The value of the DXF header variable `name` (the group after its name). +fn dxf_header(dxf: &str, name: &str) -> Option { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + lines.iter().position(|l| *l == name).and_then(|i| lines.get(i + 2)).map(|v| v.to_string()) +} + +/// The largest x coordinate (group code 10) in the entities of a DXF. +fn dxf_widest(dxf: &str) -> f64 { + let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); + // The section's name is a value; the group codes start on the line after it. + let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); + lines[start..].chunks(2).filter(|p| p.len() == 2 && p[0] == "10").filter_map(|p| p[1].parse::().ok()).fold(f64::MIN, f64::max) +} + +/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and +/// DWG, the help page's default format, throws without writing a file. +#[test] +fn an_autocad_export_writes_a_dxf_with_its_options() { + let base = folder("autocad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ + try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ + o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ + d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" + ), + ); + assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true])); + assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]); + assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing"); + let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap(); + let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap(); + assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); + assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); + assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); + assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + for name in ["c.dxf", "u.dxf"] { + let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); + assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + } + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -518,6 +572,35 @@ fn bad_arguments_are_refused_with_an_error() { "from 0 to 100", ), (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"), + ( + format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"), + "DWG is not available", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 2000; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "at most 1000", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADCompatibility", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.colors = 256; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "AutoCADColors", + ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScale = 2; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD has no option unitScale", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), diff --git a/docs/mcp.md b/docs/mcp.md index 5dd133dc00..8aeda63840 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2709,7 +2709,18 @@ app through the global object `vc`, and writes to the Script Console and runs ot with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and - `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s + `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written + `ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/) + and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version` + (`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`, + `unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`, + `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. + An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and + `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an + AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, + `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` + hold the members the scripting constants page lists. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, @@ -2722,11 +2733,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot files a command reads or writes besides the one named, such as an SVG's linked files, are read and written only where the script's folders allow. `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the - format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with + format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws - an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help + an error that says it is not available yet, as does `ExportType.FLASH`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 123604eaec..a407294012 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1027,6 +1027,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/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`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents 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/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 52b43e90f08de968117463a91b376b69c18a9ac4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:57:46 -0800 Subject: [PATCH 12/49] Scripts: an AutoCAD export to a DXF before 2004 does not take true color AutoCADRelease13, 14 and 15 write DXF formats that hold no true color. With them, exportFile takes 256 indexed colors when the options leave colors out, and AutoCADColors.TrueColors throws an error instead of writing indexed colors without telling the script. Docs: docs/mcp.md. --- crates/engine/src/script/dom/save_open.rs | 13 +++++++++++++ crates/engine/src/tests/script_save_open.rs | 6 ++++++ docs/mcp.md | 2 ++ 3 files changed, 21 insertions(+) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index e3227da608..6382fabb54 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -766,6 +766,19 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), }, }; + // A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed + // colors, and `AutoCADColors.TrueColors` with it throws. + if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) { + match p.get("colors") { + None => { + p.insert("colors".into(), json!(256)); + } + Some(c) if c.as_str() == Some("true") => { + return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into())); + } + Some(_) => {} + } + } let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9419b65f76..fb304236ec 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -601,6 +601,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "ExportOptionsAutoCAD has no option unitScale", ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease14; o.colors = AutoCADColors.TrueColors; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "TrueColors needs AutoCADRelease18", + ), (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), diff --git a/docs/mcp.md b/docs/mcp.md index 8aeda63840..06a97cf28e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2717,6 +2717,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and + `AutoCADColors.TrueColors` throws an error. `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`, `AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit` From e654a3d5b99c695e2343a4523448496d7f35fed6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 19:42:05 -0800 Subject: [PATCH 13/49] Scripts: an AutoCAD export in picas writes a DXF ExportOptionsAutoCAD.unit = AutoCADUnit.Picas sent a unit name the DXF writer does not read, so exportFile threw instead of writing the file. Each AutoCADUnit member now goes to the writer by its unit's key. The test also checks that an export without artBoardClipping has its origin at the visible art's bounds. --- crates/engine/src/script/dom/save_open.rs | 15 ++++++------ crates/engine/src/tests/script_save_open.rs | 27 ++++++++++++++++++++- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6382fabb54..cfd67ab0bb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -48,6 +48,7 @@ use std::cell::Cell; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ @@ -548,14 +549,14 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: } "unit" => { let unit = match pick("AutoCADUnit")? { - "Points" => "pt", - "Picas" => "pc", - "Inches" => "in", - "Millimeters" => "mm", - "Centimeters" => "cm", - _ => "px", + "Points" => Unit::Points, + "Picas" => Unit::Picas, + "Inches" => Unit::Inches, + "Millimeters" => Unit::Millimeters, + "Centimeters" => Unit::Centimeters, + _ => Unit::Pixels, }; - p.insert("unit".into(), json!(unit)); + p.insert("unit".into(), json!(unit.key())); } "unitScaleRatio" => { let n = match d { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index fb304236ec..76b4d66c75 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -161,10 +161,30 @@ fn dxf_header(dxf: &str, name: &str) -> Option { /// The largest x coordinate (group code 10) in the entities of a DXF. fn dxf_widest(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().fold(f64::MIN, f64::max) +} + +/// The smallest x coordinate (group code 10) in the entities of a DXF. +fn dxf_leftmost(dxf: &str) -> f64 { + dxf_xs(dxf).into_iter().fold(f64::MAX, f64::min) +} + +/// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its +/// elevation point, so hatches are left out. +fn dxf_xs(dxf: &str) -> Vec { let lines: Vec<&str> = dxf.lines().map(str::trim).collect(); // The section's name is a value; the group codes start on the line after it. let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1); - lines[start..].chunks(2).filter(|p| p.len() == 2 && p[0] == "10").filter_map(|p| p[1].parse::().ok()).fold(f64::MIN, f64::max) + let mut entity = ""; + let mut xs = Vec::new(); + for p in lines[start..].chunks(2).filter(|p| p.len() == 2) { + match p[0] { + "0" => entity = p[1], + "10" if entity == "LWPOLYLINE" => xs.extend(p[1].parse::().ok()), + _ => {} + } + } + xs } /// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and @@ -187,6 +207,7 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" ), @@ -203,7 +224,11 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { for name in ["c.dxf", "u.dxf"] { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); + // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. + assert!(dxf_leftmost(&dxf) < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); } + let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); + assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); let _ = std::fs::remove_dir_all(base); } From d84b1cb5650e80cfeef1b05c4ec36117652608fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:10:57 -0800 Subject: [PATCH 14/49] 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 d2ae34dfca3e98304bd4c088535f642e710b6df0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:40:42 -0800 Subject: [PATCH 15/49] Tests: the host name check lists the AutoCAD export names The host adds ExportOptionsAutoCAD, the six AutoCAD enumerations and ExportType.AUTOCAD, and every_name_the_host_adds_has_a_row now finds a row for each. The AutoCAD export test checks that the DXF origin is within 1 mm of the art's left edge on either side of zero. --- crates/engine/src/tests/script_save_open.rs | 2 +- .../engine/tests/it/script_host_vs_scriptcheck.rs | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 81283c528a..5b36ffc5da 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -225,7 +225,7 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); // The rectangle is 10 pt (3.5 mm) from the artboard's left edge. - assert!(dxf_leftmost(&dxf) < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); + assert!(dxf_leftmost(&dxf).abs() < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf)); } let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap(); assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b)); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 5960d189de..7f6afcf448 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -142,6 +142,13 @@ const INSIDE: &[(&str, &str)] = &[ "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ UserInteractionLevel", ), + ("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"), + ("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"), + ("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"), + ("AutoCADExportFileFormat.", "DWG DXF"), + ("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"), + ("AutoCADRasterFormat.", "JPEG PNG"), + ("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ @@ -149,7 +156,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), - ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), @@ -160,8 +167,8 @@ const INSIDE: &[(&str, &str)] = &[ /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG \ + ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. From f5090591bc05bd272612bcde7f4e6ac93cf9f60f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:11:44 -0800 Subject: [PATCH 16/49] 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 17/49] 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 18/49] 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 19/49] 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 11d20c346fcd0fc6bf239857233f079b598c6187 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:40:01 -0800 Subject: [PATCH 20/49] Scripts: refused saves call no writer, white matte, relative paths, checker reassignments - A save of several files whose file access refuses one returns that error without calling the writer for any file, and the check before the write no longer lists the paths as written. - ExportOptionsPNG24 and ExportOptionsJPEG accept matteColor at its default, white (red, green and blue 255); other colors still throw. - Document.path of a file saved under a relative name is the working folder the engine wrote the file in. - The script checker keeps reporting saveAs and exportFile on a variable holding the script's own object when a declaration follows a label, a function body assigns the variable, a member assignment writes a property of that name, code runs from text, or the script includes another file. - docs/mcp.md: saveAs to a .vctemplate file without options writes a template copy and leaves fullName and the saved state as they were. --- crates/engine/src/cmd/fileio/save.rs | 10 ++- crates/engine/src/file_access.rs | 10 ++- crates/engine/src/script/dom/save_open.rs | 23 +++++-- crates/engine/src/tests/script_save_open.rs | 35 +++++++++-- crates/scriptcheck/src/analyze.rs | 29 +++++++-- crates/scriptcheck/src/analyze/declared.rs | 67 +++++++++++++++++++-- crates/scriptcheck/src/tests.rs | 31 +++++++++- docs/mcp.md | 4 +- 8 files changed, 183 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..2234144f54 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. The first refusal is the save's error, and `write` is not called for any of + // the files. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(e) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(crate::EngineError::Other(e)); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 5951df8a64..0dd95b7546 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -461,8 +461,7 @@ pub fn is_path_key(key: &str) -> bool { /// May `path` be written here? Always, without roots in force and outside a script's command /// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write)?; + check_write_unrecorded(path)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -473,6 +472,13 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// [`check_write`] without adding `path` to the files a script run reports as written, for a +/// check made before anything is written. +pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write) +} + /// A file's modification time and length; `None` when there is no file at `path`. type Stamp = Option<(Option, u64)>; diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index a091d229f4..3f56e65b8e 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -141,6 +141,9 @@ enum Default { /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for /// `DownsampleMethod.NODOWNSAMPLE`). Member(&'static str, &'static str), + /// White as an RGB color: an object whose `red`, `green` and `blue` are 255 (its `typename`, when + /// it has one, `RGBColor`). + White, /// The help page gives no default: any value throws. Unset, } @@ -152,6 +155,15 @@ impl Default { (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, (Default::Text(a), Data::String(b)) => a == b, (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + (Default::White, Data::Object(items)) => { + let full = |c: &str| items.iter().any(|(k, v)| k == c && matches!(v, Data::Number(n) if (n - 255.0).abs() < 1e-9)); + let rgb = items.iter().all(|(k, v)| match k.as_str() { + "typename" => matches!(v, Data::String(s) if s == "RGBColor"), + "red" | "green" | "blue" => true, + _ => false, + }); + rgb && ["red", "green", "blue"].into_iter().all(full) + } _ => false, } } @@ -502,7 +514,7 @@ fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::R raster_map("ExportOptionsPNG24", name, d, p) } -const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn png24_starts() -> Vec<(&'static str, Data)> { vec![ @@ -530,7 +542,7 @@ fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } const JPEG_KEPT: &[(&str, Default)] = - &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::White), ("saveAsHTML", Default::Bool(false))]; fn jpeg_starts() -> Vec<(&'static str, Data)> { vec![ @@ -1005,12 +1017,15 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { } /// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a -/// document that has none. +/// document that has none. A file saved under a relative path, which the engine wrote in the +/// process's working folder, is in that folder. fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + let p = std::path::Path::new(p); + let full = if p.is_relative() { std::env::current_dir().ok()?.join(p) } else { p.to_path_buf() }; + let parent = full.parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 5b36ffc5da..86a6e35807 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -110,13 +110,17 @@ fn omitted_options_are_a_new_options_objects_defaults() { d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\ d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\ d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\ + var j3 = new ExportOptionsJPEG(); j3.matteColor = {{red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/j3'), ExportType.JPEG, j3);\n\ + var p3 = new ExportOptionsPNG24(); p3.matteColor = {{typename: 'RGBColor', red: 255, green: 255, blue: 255}};\n\ + d.exportFile(new File(dir + '/p3'), ExportType.PNG24, p3);\n\ d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\ d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\ d.saveAs(new File(dir + '/a1.pdf'));\n\ d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());" ), ); - for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] { + for (one, two) in [("j1.jpg", "j2.jpg"), ("j1.jpg", "j3.jpg"), ("p1.png", "p2.png"), ("p1.png", "p3.png"), ("s1.svg", "s2.svg")] { assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ"); } for name in ["a1.pdf", "a2.pdf"] { @@ -287,7 +291,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// whose last file is refused hands none of them to the writer, the refused one included. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -324,9 +328,10 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { Ok(()) }) }); - assert!(r.is_err(), "{r:?}"); + let e = r.unwrap_err().to_string(); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert!(e.contains(DENIED) && e.contains(&refused), "{e}"); + assert!(written.is_empty(), "no file went to the writer: {written:?}"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -583,6 +588,12 @@ fn bad_arguments_are_refused_with_an_error() { (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.matteColor = {{red: 255, green: 0, blue: 255}}; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "ExportOptionsPNG24.matteColor is not available yet", + ), (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), ( format!( @@ -794,6 +805,22 @@ fn full_name_path_saved_and_close_follow_the_documents_file() { let _ = std::fs::remove_dir_all(base); } +/// A document whose file was saved under a relative name is in the working folder the file was +/// written in. +#[test] +fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { + let base = folder("relative"); + let mut s = session(&base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.active_mut().unwrap().path = Some("drawing.svg".into()); + let out = logged(&mut s, &base, "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName]);"); + let cwd = std::env::current_dir().unwrap(); + assert_eq!(out[0][0], json!(true), "{out}"); + let shown = PathBuf::from(out[0][1].as_str().unwrap()); + assert!(shown == cwd || std::fs::canonicalize(&shown).ok() == std::fs::canonicalize(&cwd).ok(), "{shown:?} is not {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + /// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. #[test] fn a_document_without_unsaved_changes_closes_with_any_save_options() { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 8765501507..a4da181c75 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -56,6 +56,9 @@ pub(crate) struct Known { /// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts /// as a Folder object whatever the path names. pub unsure: bool, + /// The script includes another file ([`Declared::includes`]), whose code may give a file's + /// variables values the scan of that file does not read. + pub others: bool, } impl Known { @@ -70,6 +73,7 @@ impl Known { /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { self.unsure |= other.unsure; + self.others |= other.others; for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { self.bound.entry(name).or_insert(chain); @@ -281,8 +285,8 @@ struct ObjectValue { /// key's whole value, a bit each ([`Analyzer::writers`]). bits: u8, /// It is the value of the first name a `var` statement declares, and the statement is directly - /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or - /// a loop's parentheses: only then does the variable hold `bits` after it. + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do`, a + /// loop's parentheses or a label: only then does the variable hold `bits` after it. whole: bool, /// The bit of the method whose value is being read, and how far that value has been read. value: Option<(u8, Value)>, @@ -647,6 +651,8 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`]. + others: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -727,6 +733,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + others: known.others || declared.includes, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1386,7 +1393,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let body = self.scopes.last().map_or(0, |s| s.depth); let starts = before.is_none() || [";", "{", "}"].iter().any(|p| is(before, p)) - || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); @@ -1432,9 +1439,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// No variable joins when code the scan does not follow at that point may give it another value: + /// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a + /// property of that name, which may be the global object's ([`Declared::rebound`]), code given as + /// text or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.unsure + && !self.others + && !self.declared.rebound.contains(&name) + && !self.declared.body_assigned.contains(name.as_str()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); @@ -1734,7 +1749,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } // A variable that any assignment gave a value that may be a File object leaves as one. let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure }; + let known = Known { + bound: std::mem::take(&mut self.bound), + files: std::mem::take(&mut self.files), + folders, + unsure: self.unsure, + others: self.others, + }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..f00a7240c9 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,8 +1,11 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; -use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; +use super::{ + Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, + unquote, word, +}; /// The names that give variables values the analysis doesn't read: a `with` statement makes an /// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`, @@ -36,6 +39,14 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than + /// in a `var` statement's declarations, unless a body around the assignment declared the name with + /// `var` before it. The function may run at any time after it is defined, + /// also before its body in the text when it is a declaration, so a variable of that name may lose + /// the value an assignment the analysis read gave it. + pub(super) body_assigned: HashSet<&'s str>, + /// The file has an `#include` line: the included file's code may give its variables values. + pub(super) includes: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -82,6 +93,9 @@ struct Declarations<'s, 'a, 'l> { assign: Option, /// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`]. bodies: Vec>, + /// The names the bodies being read declare so far, each with the number of those bodies that + /// declare it. + declared_around: HashMap<&'s str, usize>, /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, @@ -101,6 +115,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { var_depth: None, assign: None, bodies: vec![], + declared_around: HashMap::new(), untracked: None, keys: vec![], out: Declared::default(), @@ -109,7 +124,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { for t in lexer.by_ref() { match breaks.read(&t) { Read::Skip => {} - Read::Directive => d.directive(), + Read::Directive => d.directive(&t), Read::Token(sig) => d.token(sig), } } @@ -164,9 +179,41 @@ impl<'s> Declarations<'s, '_, '_> { if t.word("function") && !member_mark(h0) && !word(h0, "function") { self.function = Some(depth); } + if !self.bodies.is_empty() || self.untracked.is_some() { + self.body_assignment(&t, depth); + } self.h = [Some(t), h0, h1]; } + /// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one + /// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`]. + fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) { + let [h0, h1, _] = self.h; + let name = |s: Option>| s.filter(|s| s.kind == T::Ident).map(|s| s.text); + let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth)); + let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) { + // `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`. + name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares)) + } else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) { + // `++d`. + Some(t.text) + } else if t.word("in") && (is(h1, "(") || word(h1, "var")) { + // `for (d in …)`. + name(h0) + } else { + None + }; + // A name a body around `t` has declared with `var` before it is that body's own. + let own = |name: &str| self.untracked.is_none() && self.declared_around.contains_key(name); + if let Some(name) = assigned.filter(|n| !own(n)) { + if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { + self.out.body_assigned.insert(name); + } else { + self.out.unsure = true; + } + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -261,6 +308,14 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + for name in body.names { + if let Some(n) = self.declared_around.get_mut(name) { + *n = n.saturating_sub(1); + if *n == 0 { + self.declared_around.remove(name); + } + } + } } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; @@ -285,6 +340,7 @@ impl<'s> Declarations<'s, '_, '_> { if let Some(body) = self.bodies.last_mut() { if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) { body.names.insert(t.text); + *self.declared_around.entry(t.text).or_insert(0) += 1; if let Some((_, names)) = self.out.bodies.get_mut(body.index) { names.push(t.text); } @@ -297,7 +353,10 @@ impl<'s> Declarations<'s, '_, '_> { /// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a /// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`), /// so the name may be any. - fn directive(&mut self) { + fn directive(&mut self, t: &Token<'s>) { + if directives::parse(t.text).known == Some("include") { + self.out.includes = true; + } if self.keys.iter().any(|k| k.member) { self.out.unsure = true; } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1524d4d7ae..341ad3b3d0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -615,7 +615,7 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", - "c[k] = w;\n", + "c = app.activeDocument;\n", "delete d.saveAs;\n", "var h = e;\n", "use(g);\n", @@ -633,6 +633,9 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "s.saveAs(f);\n", )); assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); + // A computed key may name any property, a variable's on the global object included. + let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc[k] = w;\nc.saveAs(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name @@ -664,6 +667,32 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A literal's `saveAs` stays the script's own only while no code the check does not follow may give +/// the variable another value: a declaration after a label, which `if` may skip, a function body that +/// assigns the variable (its own method's, or a declaration's that runs before its text), a member +/// assignment of a property of that name, which may be the global object's, code given as text and an +/// included file each leave the write reported. A function that declares its own variable of the name +/// leaves it the script's own. +#[test] +fn a_save_as_other_code_may_replace_writes_a_file() { + let cases: [(&str, &[usize]); 7] = [ + ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), + ( + "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", + &[10], + ), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nswap();\nd.saveAs(f);\nfunction swap() { d = app.activeDocument; }\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), + ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ]; + for (src, lines) in cases { + let r = report(src); + assert_eq!(feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()), lines, "{src}"); + } +} + /// A `saveAs` key's value is a method of the script's own only when the whole value is one function /// expression: a value that goes on after the function's body, and a literal inside another, leave /// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body diff --git a/docs/mcp.md b/docs/mcp.md index 0c6a0bfcbe..902d38a355 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2895,7 +2895,9 @@ other files through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. -- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. A save to a + `.vctemplate` file without options writes a template copy: the document keeps its file, its `fullName` and its + saved state. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). From 306c24c120e8e6f02d748d53007a9e6b94597009 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:05:06 -0800 Subject: [PATCH 21/49] Scripts: absolute paths for relative document files, save warnings in the console - Document.fullName of a file saved or opened under a relative path is the file in the process's working folder, as Document.path already was, and close with SaveOptions.SAVECHANGES saves it there. - saveAs, exportFile, app.open and close with SAVECHANGES write each warning their command gives to the Script Console, starting with the method's name. - The checker tests cover a with statement and an include between a literal and its call. --- crates/engine/src/script/dom/save_open.rs | 55 ++++++++++++++------- crates/engine/src/tests/script_save_open.rs | 35 +++++++++++-- crates/scriptcheck/src/tests.rs | 4 +- docs/mcp.md | 7 ++- 4 files changed, 76 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 3f56e65b8e..1eac9cd9cb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -47,8 +47,8 @@ //! save of one artboard writes only the file at the path, holding that artboard. Without //! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of //! artboard numbers throws. -//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no -//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened +//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. //! `fullName` and `path` of a document whose file the automation read roots do not allow throw //! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. //! - `Document.close` with unsaved changes closes without them with @@ -71,8 +71,8 @@ use vectorcraft_doc::Unit; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ - Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, - property, text, this_doc, whole, + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, command_value, current, doc_ref, get, given, method, named, num, + on_doc, property, text, this_doc, whole, }; /// The most a scale factor of an export takes, in percent. @@ -863,10 +863,20 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } +/// Runs command `id` as [`command`] does, and writes each warning its result gives to the console as +/// `method: warning`, as `addDocument` writes the warnings of `file.new`. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (data, value) = command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(data) +} + /// `path` with the extension of `kind` added, unless its name already ends with one of them. fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; @@ -933,7 +943,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -979,7 +989,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -992,15 +1002,25 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, st.uid)) } -/// The document's file, `None` for a document that has none, or `Script file access denied` with -/// the document's name when the automation read roots do not allow the file to be named +/// A document's file as the engine reads and writes it: a relative path is in the process's working +/// folder. It stays as it is when the working folder is not known. +fn absolute(path: &str) -> String { + let p = std::path::Path::new(path); + match std::env::current_dir() { + Ok(cwd) if p.is_relative() => cwd.join(p).to_string_lossy().into_owned(), + _ => path.to_string(), + } +} + +/// The document's file ([`absolute`]), `None` for a document that has none, or `Script file access +/// denied` with the document's name when the automation read roots do not allow the file to be named /// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. -fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { match st.path.as_deref() { Some(p) if crate::file_access::check_read(p).is_err() => { Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) } - p => Ok(p), + p => Ok(p.map(absolute)), } } @@ -1010,22 +1030,19 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; super::with_doc(h, doc, |_, st| { Ok(match shown_file(st)? { - Some(p) => vectorcraft_js::file_ref(p), + Some(p) => vectorcraft_js::file_ref(&p), None => vectorcraft_js::file_ref(&st.title()), }) }) } /// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a -/// document that has none. A file saved under a relative path, which the engine wrote in the -/// process's working folder, is in that folder. +/// document that has none. fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let p = std::path::Path::new(p); - let full = if p.is_relative() { std::env::current_dir().ok()?.join(p) } else { p.to_path_buf() }; - let parent = full.parent()?.to_string_lossy().into_owned(); + let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; @@ -1077,12 +1094,12 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { - let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + let path = absolute(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?); // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; let p = json!({"path": plain(real), "format": format}); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 86a6e35807..f0ba05bb6e 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -813,11 +813,40 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() { let mut s = session(&base); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); s.active_mut().unwrap().path = Some("drawing.svg".into()); - let out = logged(&mut s, &base, "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName]);"); + let out = logged( + &mut s, + &base, + "var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName, d.fullName.fsName]);", + ); let cwd = std::env::current_dir().unwrap(); assert_eq!(out[0][0], json!(true), "{out}"); - let shown = PathBuf::from(out[0][1].as_str().unwrap()); - assert!(shown == cwd || std::fs::canonicalize(&shown).ok() == std::fs::canonicalize(&cwd).ok(), "{shown:?} is not {cwd:?}"); + let same = |shown: &str, want: &Path| { + let shown = PathBuf::from(shown); + shown == want || std::fs::canonicalize(&shown).ok().zip(std::fs::canonicalize(want).ok()).is_some_and(|(a, b)| a == b) + }; + assert!(same(out[0][1].as_str().unwrap(), &cwd), "{out} is not in {cwd:?}"); + let file = out[0][2].as_str().unwrap(); + assert!(Path::new(file).is_absolute() && Path::new(file).file_name() == Some("drawing.svg".as_ref()), "{file}"); + assert!(same(&Path::new(file).parent().unwrap().to_string_lossy(), &cwd), "{file} is not in {cwd:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The warnings a save gives, such as editing data left out of a PDF of one artboard of several, go +/// to the Script Console. +#[test] +fn a_saves_warnings_go_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + let save = format!( + "Folder.userData; var o = new PDFSaveOptions(); o.preserveEditability = true; o.artboardRange = '1';\n\ + app.activeDocument.saveAs(new File({}), o);", + quoted(&dir.join("one.pdf")) + ); + let r = run(&mut s, &base, &save).unwrap(); + let lines = r["console"]["lines"].as_array().unwrap(); + assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 341ad3b3d0..fa8d8eecbc 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -675,7 +675,7 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// leaves it the script's own. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 7] = [ + let cases: [(&str, &[usize]); 9] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -685,6 +685,8 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]), ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), + ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), ]; for (src, lines) in cases { diff --git a/docs/mcp.md b/docs/mcp.md index 902d38a355..809caffb8a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2897,7 +2897,9 @@ other files through `$`: themselves, such as a path's fill, are not defined yet and read as `undefined`. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. A save to a `.vctemplate` file without options writes a template copy: the document keeps its file, its `fullName` and its - saved state. + saved state. Each warning the command gives, here and for `exportFile`, `app.open` and `close` with + `SaveOptions.SAVECHANGES`, goes to the Script Console as a line that starts with the method's name, such as + `saveAs: `. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). @@ -2964,7 +2966,8 @@ other files through `$`: writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS `artboardRange` is not checked against the document's artboards, but one that is not written as a range of artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's - file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of + file. A file saved or opened under a relative path is in the working folder of the process that wrote or read it, + for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an From 51778505363acbe79a38e0f4fd5497e17acbe329 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:17:08 -0800 Subject: [PATCH 22/49] 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 c58763daf6cfb7d7def224487c6e5af4dd8afb29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:39:33 -0800 Subject: [PATCH 23/49] Save: a refused file of a save without a path is named by its file name A save of several files that the file access refuses before anything is written gave the refused file's full path in its error, also when the client did not give the path and the folder is outside the read roots. The check before the write now names the file as the writer did, so document.save with separateArtboards keeps the folder out of the error. --- crates/engine/src/cmd/fileio/save.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 2234144f54..d3b7fd62b8 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,9 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// The client did not give the path: a file the file access refuses before anything is + /// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]). + hides_paths: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +966,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.hides_paths = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1075,9 +1086,10 @@ impl SaveJob { // the files. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(e) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err()) + && let Some((p, e)) = files.iter().find_map(|(p, _)| crate::file_access::check_write_unrecorded(p).err().map(|e| (p, e))) { - return Err(crate::EngineError::Other(e)); + let e = crate::EngineError::Other(e); + return Err(if self.hides_paths { super::access::naming_in_error(e, p) } else { e }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1239,9 +1251,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refusals() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) From b086db0fbbf171d330f76b3618c112cd411fa129 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:49:55 -0800 Subject: [PATCH 24/49] Script check: a function that sets saveAs or exportFile keeps the write reported A function declared before an object literal could replace the literal's saveAs or exportFile method when it ran later, and the check still treated the method as the script's own and left the write out of filesWritten. When any function body assigns a property of that name, no variable's method of that name counts as the script's own. --- crates/scriptcheck/src/analyze.rs | 7 +++++-- crates/scriptcheck/src/analyze/declared.rs | 8 ++++++++ crates/scriptcheck/src/tests.rs | 18 ++++++++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index a4da181c75..fbcc62ae0a 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1441,8 +1441,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// closes a function body, so a literal given to the body's own variable stays inside the body. /// No variable joins when code the scan does not follow at that point may give it another value: /// a function body that assigns its name ([`Declared::body_assigned`]), a member assignment of a - /// property of that name, which may be the global object's ([`Declared::rebound`]), code given as - /// text or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). + /// property of that name, which may be the global object's ([`Declared::rebound`]), a function + /// body that assigns a `saveAs` or `exportFile` property of any object + /// ([`Declared::body_writer_assigned`]), code given as text or a `with` statement + /// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) @@ -1450,6 +1452,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && !self.others && !self.declared.rebound.contains(&name) && !self.declared.body_assigned.contains(name.as_str()) + && !self.declared.body_writer_assigned && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index f00a7240c9..c03efdd819 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -45,6 +45,11 @@ pub(crate) struct Declared<'s> { /// also before its body in the text when it is a declaration, so a variable of that name may lose /// the value an assignment the analysis read gave it. pub(super) body_assigned: HashSet<&'s str>, + /// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`] + /// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is + /// defined, and the object may be any variable's, so no variable's method of that name stays + /// the script's own. + pub(super) body_writer_assigned: bool, /// The file has an `#include` line: the included file's code may give its variables values. pub(super) includes: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or @@ -245,6 +250,9 @@ impl<'s> Declarations<'s, '_, '_> { None }; if let Some(name) = property { + if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) { + self.out.body_writer_assigned = true; + } if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) { self.out.rebound.insert(name); } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index fa8d8eecbc..1b931a2cca 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -670,12 +670,13 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// A literal's `saveAs` stays the script's own only while no code the check does not follow may give /// the variable another value: a declaration after a label, which `if` may skip, a function body that /// assigns the variable (its own method's, or a declaration's that runs before its text), a member -/// assignment of a property of that name, which may be the global object's, code given as text and an -/// included file each leave the write reported. A function that declares its own variable of the name -/// leaves it the script's own. +/// assignment of a property of that name, which may be the global object's, a function body that +/// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement +/// and an included file each leave the write reported. A function that declares its own variable of the +/// name, or assigns another property of it, leaves it the script's own. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 9] = [ + let cases: [(&str, &[usize]); 12] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -687,6 +688,15 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]), + ( + "var f = new File(p);\nfunction replace() { d.saveAs = app.activeDocument.saveAs; }\nvar d = {saveAs: function () {}};\nreplace();\nd.saveAs(f);\n", + &[5], + ), + ( + "var f = new File(p);\nfunction replace(o) { o['exportFile'] = w; }\nvar d = {exportFile: function () {}};\nreplace(d);\nd.exportFile(f);\n", + &[5], + ), + ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), ]; for (src, lines) in cases { From e46f697d50e43f82b375ea5f3de97ad38fedad8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:10:24 -0800 Subject: [PATCH 25/49] Script check: a nested function that assigns an outer body's variable keeps the write reported A function body's assignment was left out of the names other code may change when any enclosing body had declared the name with var. A nested function such as swap() { d = app.activeDocument; } called before d.saveAs(f) then left d trusted as the script's own literal, and the write went unreported. Only a name the innermost body declared now counts as that body's own; plain, compound, increment and for-in assignments to an outer body's variable all keep the write reported. --- crates/scriptcheck/src/analyze/declared.rs | 21 +++++---------------- crates/scriptcheck/src/tests.rs | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index c03efdd819..85d1f7eb9c 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use super::{ Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark, @@ -98,9 +98,6 @@ struct Declarations<'s, 'a, 'l> { assign: Option, /// The function bodies being read, the innermost last, up to [`crate::Limits::nesting`]. bodies: Vec>, - /// The names the bodies being read declare so far, each with the number of those bodies that - /// declare it. - declared_around: HashMap<&'s str, usize>, /// The bracket depth inside the outermost function body past that limit being read. The names /// declared inside it are not kept. untracked: Option, @@ -120,7 +117,6 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { var_depth: None, assign: None, bodies: vec![], - declared_around: HashMap::new(), untracked: None, keys: vec![], out: Declared::default(), @@ -208,8 +204,10 @@ impl<'s> Declarations<'s, '_, '_> { } else { None }; - // A name a body around `t` has declared with `var` before it is that body's own. - let own = |name: &str| self.untracked.is_none() && self.declared_around.contains_key(name); + // A name the innermost body around `t` has declared with `var` before it is that body's own. A + // name only an outer body declared is that body's variable, which a nested function may assign + // before a call in the outer body runs. + let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name)); if let Some(name) = assigned.filter(|n| !own(n)) { if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) { self.out.body_assigned.insert(name); @@ -316,14 +314,6 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; - for name in body.names { - if let Some(n) = self.declared_around.get_mut(name) { - *n = n.saturating_sub(1); - if *n == 0 { - self.declared_around.remove(name); - } - } - } } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; @@ -348,7 +338,6 @@ impl<'s> Declarations<'s, '_, '_> { if let Some(body) = self.bodies.last_mut() { if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) { body.names.insert(t.text); - *self.declared_around.entry(t.text).or_insert(0) += 1; if let Some((_, names)) = self.out.bodies.get_mut(body.index) { names.push(t.text); } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1b931a2cca..cd97a3b380 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -673,10 +673,11 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { /// assignment of a property of that name, which may be the global object's, a function body that /// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement /// and an included file each leave the write reported. A function that declares its own variable of the -/// name, or assigns another property of it, leaves it the script's own. +/// name, or assigns another property of it, leaves it the script's own. A nested function that assigns +/// a variable its enclosing body declared leaves the write reported too. #[test] fn a_save_as_other_code_may_replace_writes_a_file() { - let cases: [(&str, &[usize]); 12] = [ + let cases: [(&str, &[usize]); 16] = [ ("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]), ( "var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n", @@ -698,6 +699,22 @@ fn a_save_as_other_code_may_replace_writes_a_file() { ), ("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]), ("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d = app.activeDocument; }\n}\nrun();\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d += 1; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d++; }\n}\n", + &[5], + ), + ( + "var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { for (d in o) {} }\n}\n", + &[5], + ), ]; for (src, lines) in cases { let r = report(src); From 1e2b68b71cc3a27e7381f1efddac32f8e1fb261a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:46:29 -0800 Subject: [PATCH 26/49] 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 27/49] 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 cb4c5e5ee9a59616bfac604ecea7f8d9ef8063d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:24:39 -0800 Subject: [PATCH 28/49] Merge main into feat/scripts-export-autocad --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index ff7e13fae7..4d7902f7b9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 0507cfade0ec02cd12c5dcd5b1d8d00d86e3908b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:58:27 -0800 Subject: [PATCH 29/49] 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 73946a86a8479561694834aec1d49ee25b02e96f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:03:05 -0800 Subject: [PATCH 30/49] Docs: exportFile names the image files a DXF writes beside it A DXF of a drawing with placed raster images writes each image it exports beside the drawing as a PNG file, or a JPEG file with rasterFormat JPEG. The exportFile paragraph in docs/mcp.md said it writes one file, with only the SVG companion images as an exception. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 19632196b9..46d40b3dc2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3171,8 +3171,9 @@ through `$`: does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the - visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when the script's folders refuse one of those files, none of them is written; a write that fails once the + visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and a + DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG + file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's folders refuse one of those files, none of them is written; a write that fails once the first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as does `ExportType.FLASH`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and From ec4a813fa3c7426ebbcbbebadc0f03b2abb6410e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:32:07 -0800 Subject: [PATCH 31/49] 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 32/49] 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 33/49] 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 483bf2363dfa63be319cac792e5b9ccf947cff10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:25:11 -0800 Subject: [PATCH 34/49] Scripts: invertMatrix decides overflow from the exact quotient The determinant and the translation numerators are rounded before the division, so a value whose exact quotient is below the overflow midpoint could round to infinity and throw a RangeError, and one at or past it could come out finite. When the rounded quotient overflows or lies within eight steps of Number.MAX_VALUE, the exact quotient is now compared with the midpoint between Number.MAX_VALUE and 2^1024 from exact product parts. An infinite rounded quotient below it is replaced by the number the exact quotient rounds to. --- crates/engine/src/script/dom/matrix.rs | 101 +++++++++++++++++--- crates/engine/src/tests/script_dom_prefs.rs | 25 +++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 4 files changed, 119 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 467a5fc10e..e9fd55e70b 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -125,26 +125,29 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 { // Each product is split into its rounded value and the part that rounding drops, both exact. // The five parts are added one at a time into a list of values that do not overlap, smallest // first, whose sum is exact (Shewchuk's expansion). - let product = |a: f64, b: f64| { - let (a, b) = (Wide::of(a), Wide::of(b)); - let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); - [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] - }; let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w)); let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow); nearest(exact) } +/// `a·b` as its rounded value and the part that rounding drops, both exact. +fn product(a: f64, b: f64) -> [Wide; 2] { + let (a, b) = (Wide::of(a), Wide::of(b)); + let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e)); + [Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)] +} + /// Values that do not overlap, smallest first, held without allocating. Each value added keeps at -/// most one more, so the five parts of a sum and the two of a comparison fit. +/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an +/// inverse's rounding test fit. #[derive(Clone, Copy)] struct Parts { - v: [Wide; 8], + v: [Wide; 16], n: usize, } impl Parts { - const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 }; + const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 }; fn as_slice(&self) -> &[Wide] { &self.v[..self.n] @@ -404,9 +407,85 @@ fn invert(_: &Host, a: &[Data]) -> Answer { // Each value is divided by the determinant before it is brought back into the range of a // number, and the translations are taken whole, so a finite inverse is not lost to an // intermediate value. Adding 0 turns -0 into 0. - let over = |w: Wide| w.div(det).value() + 0.0; - let plain = |v: f64| over(Wide::of(v)); - record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))]) + let exact_det = || difference_parts(a, d, b, c); + let zero = Wide::of(0.0); + let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det); + record([ + plain(d), + plain(0.0 - b), + plain(0.0 - c), + plain(a), + quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det), + quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det), + ]) +} + +/// `a·d − b·c` as four exact parts. +fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { + let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e }; + let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c)); + [p, p_lost, neg(q), neg(q_lost)] +} + +/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts. +/// The result is the rounded quotient, which is within a few steps of the exact one, except where +/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight +/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway +/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it +/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact +/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the +/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0. +fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + let v = num.div(det).value() + 0.0; + // 2^1024 − 9·2^971, eight steps below the largest number. + let near_top = f64::MAX - 8.0 * pow2(971); + if v.is_finite() && v.abs() < near_top { + return v; + } + let (exact_num, exact_det) = (exact_num(), exact_det()); + let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() { + Some(w) if w.m < 0.0 => -1.0, + _ => 1.0, + }; + let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each + // `j·m` is split into its rounded value and the part that rounding drops. + let past = |j: f64| { + let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) }; + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))] + }; + let sum = exact_num + .iter() + .map(|&w| scaled(w, sn, 0)) + .chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024))) + .chain(exact_det.iter().flat_map(|&w| times_j(w))) + .fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + if past(1.0) >= 0 { + return f64::INFINITY; + } + if v.is_finite() { + return v; + } + let even = |x: f64| x.to_bits() & 1 == 0; + let mut top = f64::MAX; + for k in 1..16u8 { + let below = top.next_down(); + match past(f64::from(2 * k + 1)) { + 1 => return top * sn * sd, + 0 => return if even(top) { top } else { below } * sn * sd, + _ => top = below, + } + } + top * sn * sd } fn is_equal(_: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index c56542973e..5cb7acb4b2 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -466,6 +466,31 @@ fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() { assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]); } +#[test] +fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is MAX + 2^970, the overflow midpoint. With b = 2^-53 the + // determinant is 1 + 2^-53, so the exact quotient is MAX - 2^970 + about 2^917, which rounds + // to MAX, while the rounded determinant 1 gives infinity. With b = 0 the quotient is the + // midpoint itself, which rounds to infinity. With a = 1 + 2^-51 and the numerator + // 2^1024 + 3·2^971, the rounded quotient overflows while the exact one is MAX - 2^971 and a + // little more, which rounds to the number below MAX. With b = -2^-54 and ty = -2^969 the rounded + // quotient is MAX, while the exact one is past the overflow midpoint. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var i = app.invertMatrix(mat([1, Math.pow(2, -53), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)]));\ + vc.log(i.mValueTX === Number.MAX_VALUE);\ + try { app.invertMatrix(mat([1, 0, -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }\ + var j = app.invertMatrix(mat([1 + Math.pow(2, -51), Math.pow(2, -53), -1, 1, -Math.pow(2, 1023), -(Math.pow(2, 1023) + 3 * Math.pow(2, 971))]));\ + vc.log(j.mValueTX === Number.MAX_VALUE - Math.pow(2, 971));\ + try { app.invertMatrix(mat([1, -Math.pow(2, -54), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 969)])); vc.log('finite'); }\ + catch (e) { vc.log(e.name); }", + ); + assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index a09de47c27..ae84f1361b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3153,7 +3153,9 @@ through `$`: `scaleY` is `scaleX`; quarter turns are exact; each value `concatenateMatrix` gives is its exact sum of products rounded once; a matrix whose determinant is 0 is singular, and `invertMatrix` of one throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`, - and a result too large for a number throws a `RangeError`. + and a result too large for a number throws a `RangeError`. `invertMatrix` decides overflow from each value's exact + quotient: when its magnitude is below the halfway point between `Number.MAX_VALUE` and 2^1024 the value is a finite + number, and at that point or past it the call throws a `RangeError`. - `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run `edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. With nothing selected `copy` and `cut` do nothing, and with the clipboard empty `paste` does nothing; `paste` with no document open throws diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 407734ce80..fabc5554ee 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1112,7 +1112,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. + - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From 44c5c4ccd9d77f665107c1f7479bcc856ff9e853 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 14:18:46 -0800 Subject: [PATCH 35/49] 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 efdaa06fd260c32545364dac795d2f2e402cd3b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:10:26 -0800 Subject: [PATCH 36/49] Scripts: reflect reports matrix defaults; copy notes keep the recording limit - app.reflect now reports the defaults of the matrix functions' number arguments: 0 for deltaX, deltaY and angle, and 100 for scaleX, in the get and concatenate variants. scaleY has no fixed default, since a left-out vertical scale is the horizontal one; its description says so. - When a script's commands take a recording past its limit and the script also copied, the notes of the Copy's formats no longer replace the limit message in the status bar. The limit is named only once, so the message is kept while it shows. The same applies to a script run that automation takes to its end at once. --- crates/engine/src/script/dom/matrix.rs | 20 ++++++++++++- crates/engine/src/tests/script_dom_prefs.rs | 20 +++++++++++++ .../ui-egui/src/panels/actions/recording.rs | 2 ++ .../src/panels/actions/tests_limits.rs | 29 +++++++++++++++++++ crates/ui-egui/src/sysclip.rs | 11 ++++++- 5 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index e9fd55e70b..0887168db8 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -19,7 +19,7 @@ //! - An argument that is not a finite number, or a matrix with a value that is not one, throws a //! `TypeError`; a result with a value too large for a number throws a `RangeError`. -use vectorcraft_js::{Data, HostError}; +use vectorcraft_js::{Data, HostError, MemberInfo}; use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text}; @@ -54,6 +54,24 @@ pub(super) fn app_members(link: &Link) -> Vec { ("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])), ("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])), ]) + .into_iter() + .map(|(name, member, info)| (name, member, with_defaults(info))) + .collect() +} + +/// `info` with the defaults of its left-out number arguments, which `reflect` reports: 0 for a +/// translation and an angle, 100 for a horizontal scale. A left-out vertical scale is the +/// horizontal one, so it has no fixed default and its description says so. +fn with_defaults(mut info: MemberInfo) -> MemberInfo { + for a in &mut info.arguments { + match a.name.as_str() { + "deltaX" | "deltaY" | "angle" => a.default = Some(num(0.0)), + "scaleX" => a.default = Some(num(100.0)), + "scaleY" => a.description = Some("The vertical scale; when it is left out, the horizontal scale.".into()), + _ => {} + } + } + info } /// The record for `m`, or a `RangeError` when a value is not finite. diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 5cb7acb4b2..624ff8a7f8 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -342,6 +342,26 @@ fn matrix_functions_give_new_records() { assert_eq!(r, vec![json!([c, sn, -sn, c])]); } +#[test] +fn reflect_reports_the_matrix_argument_defaults() { + let mut s = Session::new(); + let out = log( + &mut s, + "function d(f, a) { return String(app.reflect.find(f).arguments[a].defaultValue); }\ + vc.log([d('getScaleMatrix', 'scaleX'), d('concatenateScaleMatrix', 'scaleX'), d('getTranslationMatrix', 'deltaX'),\ + d('concatenateTranslationMatrix', 'deltaY'), d('getRotationMatrix', 'angle'), d('concatenateRotationMatrix', 'angle'),\ + d('getScaleMatrix', 'scaleY'), d('concatenateMatrix', 'matrix')]);\ + vc.log(app.reflect.find('getScaleMatrix').arguments.scaleY.description);", + ); + assert_eq!( + out, + vec![ + json!(["100", "100", "0", "0", "0", "0", "undefined", "undefined"]), + json!("The vertical scale; when it is left out, the horizontal scale."), + ] + ); +} + #[test] fn concatenation_applies_the_first_matrix_first() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/panels/actions/recording.rs b/crates/ui-egui/src/panels/actions/recording.rs index bf0d4440f8..13ce1bf3bf 100644 --- a/crates/ui-egui/src/panels/actions/recording.rs +++ b/crates/ui-egui/src/panels/actions/recording.rs @@ -172,6 +172,8 @@ pub(crate) fn after_journaled_edit(app: &mut VectorcraftApp) -> bool { Ok(()) => false, Err(e) => { app.status(e); + // The limit is named once: the notes of the edit's Copy or Cut do not replace it. + app.clipboard_publishing.keep_status(&app.ui); true } } diff --git a/crates/ui-egui/src/panels/actions/tests_limits.rs b/crates/ui-egui/src/panels/actions/tests_limits.rs index a4b22246fd..5ecd1c718b 100644 --- a/crates/ui-egui/src/panels/actions/tests_limits.rs +++ b/crates/ui-egui/src/panels/actions/tests_limits.rs @@ -295,6 +295,35 @@ fn script_run_checks_recording_step_limit_on_completion() { } } +/// A script that copies type in a family that is not installed, whose Copy's formats therefore +/// have notes, and whose commands take a recording past 10,000 steps: the status bar keeps naming +/// the limit once the formats are written. Without the recording the notes show. +#[test] +fn a_scripts_copy_notes_do_not_replace_the_recording_limit() { + let steps = "the action already has 10,000 steps"; + let copy = "var t = vc.run('text.create', {x: 5, y: 20, text: 'Ab', font: 'Nonexistent Sans Probe'});\ + vc.run('select.set', {ids: [t.id]}); app.copy();"; + for frames in [false, true] { + for recording in [true, false] { + let services = crate::tests::sysclip::fake_clipboard_services(); + let app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services)); + let (mut app, _) = three_moves_in(app); + if recording { + recording_with(&mut app, files::MAX_ACTION_STEPS - 1); + } + app.ui.status.clear(); + run_script(&mut app, copy, frames); + let _ = app.written_clipboard_text(); + let what = format!("frames {frames}, recording {recording}"); + if recording { + assert_eq!(app.ui.status, steps, "{what}: the limit stays in the status bar"); + } else { + assert!(app.ui.status.starts_with("Copied with "), "{what}: {}", app.ui.status); + } + } + } +} + /// A script whose commands give the recording's set a file larger than 8 MiB keeps its edit, /// the status bar names the limit as the run ends, and Stop Playing/Recording keeps the steps /// that fit in a set that Load Actions… reads. One that fills the file exactly names no limit. diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 9371e118fd..8c54822d2f 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -94,6 +94,9 @@ pub(crate) struct Publishing { /// The status bar's message the latest Copy or Cut with notes left, with /// [`crate::state::UiState::status_sets`] then. notes_status: Option<(String, u64)>, + /// A message that no Copy or Cut's notes replace while the status bar shows it (a recording's + /// limit, which is named once), with [`crate::state::UiState::status_sets`] then. + kept: Option<(String, u64)>, } impl Publishing { @@ -118,7 +121,13 @@ impl Publishing { /// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing /// setting the status since? fn shows_status(&self, ui: &crate::state::UiState) -> bool { - ui.status == self.status.0 && ui.status_sets == self.status.1 + let kept = self.kept.as_ref().is_some_and(|(s, sets)| ui.status == *s && ui.status_sets == *sets); + !kept && ui.status == self.status.0 && ui.status_sets == self.status.1 + } + + /// `ui`'s status bar message stays while it shows: no Copy or Cut's notes replace it. + pub(crate) fn keep_status(&mut self, ui: &crate::state::UiState) { + self.kept = Some((ui.status.clone(), ui.status_sets)); } /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing From 61770864ecdf8c48c10c53549398178a8b1ef487 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:49:28 -0800 Subject: [PATCH 37/49] Scripts: an inverse below half the smallest number rounds once app.invertMatrix divided the rounded numerator by the determinant and rounded again, so an x-translation whose exact quotient is just past half the smallest number (numerator 2^-1021 + 2^-1075, determinant 2^54) came back as 0 instead of Number.MIN_VALUE. When the rounded quotient is below 2^-1023, the result is now found from the exact numerator and determinant: the multiple of the smallest number whose halfway points hold the exact quotient, ties to the even one. A quotient exactly at the halfway point still rounds to 0. --- crates/engine/src/script/dom/matrix.rs | 62 ++++++++++++++++++++- crates/engine/src/tests/script_dom_prefs.rs | 22 ++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index 0887168db8..bf5c325295 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -452,12 +452,19 @@ fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] { /// point between the largest number and 2^1024: at it or past it the result is infinite. Below it /// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact /// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the -/// even one. The exact parts are worked out only then. Adding 0 turns -0 into 0. +/// even one. When the rounded quotient is below 2^-1023, where every number is a multiple of the +/// smallest number, the result is the multiple whose halfway points to its neighbors hold the exact +/// quotient, ties to the even one, so a quotient just past half the smallest number is not rounded +/// to 0. The exact parts are worked out only then. Adding 0 turns -0 into 0. fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 { + if num.m == 0.0 { + return 0.0; + } let v = num.div(det).value() + 0.0; // 2^1024 − 9·2^971, eight steps below the largest number. let near_top = f64::MAX - 8.0 * pow2(971); - if v.is_finite() && v.abs() < near_top { + let tiny = f64::MIN_POSITIVE / 2.0; + if v.is_finite() && v.abs() < near_top && v.abs() >= tiny { return v; } let (exact_num, exact_det) = (exact_num(), exact_det()); @@ -466,6 +473,9 @@ fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: _ => 1.0, }; let (sn, sd) = (sign(&exact_num), sign(&exact_det)); + if v.abs() < tiny { + return small_quotient(v, &exact_num, &exact_det, sn, sd); + } // The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each // `j·m` is split into its rounded value and the part that rounding drops. let past = |j: f64| { @@ -506,6 +516,54 @@ fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: top * sn * sd } +/// The exact quotient of `exact_num` by `exact_det`, whose signs are `sn` and `sd`, rounded to a +/// multiple of the smallest number, ties to the even multiple, starting from the rounded quotient +/// `v`, which is below 2^-1023 and within a few steps of it. +fn small_quotient(v: f64, exact_num: &[Wide; 4], exact_det: &[Wide; 4], sn: f64, sd: f64) -> f64 { + let step = f64::from_bits(1); + // The sign of |num| − j·2^-1075·|det|, with each `j·m` split into its rounded value and the + // part that rounding drops. `j` is odd and below 2^53, so it is exact. + let past = |j: f64| { + let times_j = |w: Wide| { + let hi = j * w.m * sd; + let lo = (j * sd).mul_add(w.m, 0.0 - hi); + [Wide::new(0.0 - hi, w.e.saturating_sub(1075)), Wide::new(0.0 - lo, w.e.saturating_sub(1075))] + }; + let sum = exact_num.iter().map(|&w| Wide { m: w.m * sn, e: w.e }).chain(exact_det.iter().flat_map(|&w| times_j(w))).fold(Parts::EMPTY, grow); + match sum.as_slice().last() { + Some(w) if w.m > 0.0 => 1, + Some(w) if w.m < 0.0 => -1, + _ => 0, + } + }; + // `k` steps; dividing by the smallest number is exact. + let mut k = v.abs() / step; + let even = |k: f64| k % 2.0 == 0.0; + for _ in 0..8 { + match past(2.0 * k + 1.0) { + 1 => k += 1.0, + 0 => { + k = if even(k) { k } else { k + 1.0 }; + break; + } + _ => { + if k == 0.0 { + break; + } + match past(2.0 * k - 1.0) { + -1 => k -= 1.0, + 0 => { + k = if even(k) { k } else { k - 1.0 }; + break; + } + _ => break, + } + } + } + } + k * step * sn * sd + 0.0 +} + fn is_equal(_: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(matrix(arg(a, 1), "matrix")? == matrix(arg(a, 2), "secondMatrix")?)) } diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 624ff8a7f8..2f14af0357 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -511,6 +511,28 @@ fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() { assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]); } +#[test] +fn an_inverse_translation_next_to_half_the_smallest_number_rounds_once() { + let mut s = Session::new(); + // The x-translation's numerator is 2^-1021 + 2^-1075 and the determinant 2^54, so the exact + // quotient is 2^-1075 + 2^-1129, just past half the smallest number, which rounds to it. The + // rounded numerator 2^-1021 gives 2^-1075, which rounds to 0. With c = 0 the quotient is 2^-1075 + // itself, which rounds to 0. With both translations negated, the x-translation rounds to minus + // the smallest number. + let out = log( + &mut s, + "function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\ + var t = Math.pow(2, -1021), big = Math.pow(2, 54), small = Math.pow(2, -54);\ + var i = app.invertMatrix(mat([big, 0, small, 1, -t, t]));\ + vc.log([i.mValueTX === Number.MIN_VALUE, i.mValueTY === -t]);\ + var j = app.invertMatrix(mat([big, 0, 0, 1, -t, t]));\ + vc.log([j.mValueTX, 1 / j.mValueTX > 0]);\ + var k = app.invertMatrix(mat([big, 0, small, 1, t, -t]));\ + vc.log([k.mValueTX === -Number.MIN_VALUE, k.mValueTY === t]);", + ); + assert_eq!(out, vec![json!([true, true]), json!([0, true]), json!([true, true])]); +} + #[test] fn inverse_singular_and_equal_matrices() { let mut s = Session::new(); From 4ca2683571a441cf7d3973d30d4ba9ec578a70a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:22:43 -0800 Subject: [PATCH 38/49] Scripts: preference tests check the run result and the quiet level The merge test now requires the run to succeed instead of accepting any result, through the bounded pump helper. The confirm test sets UserInteractionLevel.DONTDISPLAYALERTS without a try/catch, so the run really asks for no dialogs before the confirm. --- crates/engine/src/tests/script_dom_prefs.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/script_dom_prefs.rs b/crates/engine/src/tests/script_dom_prefs.rs index 2f14af0357..bfdcd5a376 100644 --- a/crates/engine/src/tests/script_dom_prefs.rs +++ b/crates/engine/src/tests/script_dom_prefs.rs @@ -151,7 +151,7 @@ fn no_to_the_confirm_or_stop_leaves_the_warning_on() { #[test] fn the_confirm_cannot_be_skipped() { let mut s = Session::new(); - framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}")); + framed(&mut s, &format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; {ASK_OFF}")); assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string())); assert!(s.script_answer(DialogAnswer::Confirm(false))); assert!(pump(&mut s).unwrap().is_ok()); @@ -305,7 +305,7 @@ fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() { assert!(s.script_running()); s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true)); s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3)); - while s.script_pump().is_none() {} + pump(&mut s).unwrap().unwrap(); let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect(); assert_eq!( keys, From 937817609d2347b5bead727b282004dbadca2d69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:33:34 -0800 Subject: [PATCH 39/49] Tests: the PDF 1.3 transparency check reads dictionaries only pdf_1_3_flattens_all_transparency_and_looks_the_same failed now and then because its transparency check searched the whole file for `/BM`. The file ID, written in the trailer and the XMP stream, is base64 that changes with the export time, so some exports had an ID that spells `/BM` and the check reported a blend mode in a flat file. The check now leaves out literal strings and stream data. A stream is found only by the whole `stream` keyword, not a name such as `/stream`, and its data is skipped by the stream dictionary's own `/Length`, read from the outermost dictionary and from its object when it is indirect. A length that does not end at `endstream`, or a stream with no `endstream`, fails the check. Every dictionary key it looked for is still checked. A new test covers an ID and an XMP packet that spell the keys, nested and escaped parentheses, `endstream` inside stream data, nested and indirect lengths, and wrong lengths. The helper comes from #10537. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 215 +++++++++++++++++++- 1 file changed, 213 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 7c0aa4a74b..f3493555c9 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -71,9 +71,157 @@ fn export(s: &mut Session, p: Value) -> (Vec, Vec) { (bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect()) } -/// The transparency `pdf` has, in its dictionaries. +/// Whether `b` ends a PDF token: white space or a delimiter. +fn ends_token(b: u8) -> bool { + b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b) +} + +/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the +/// `startxref` at `startxref` and following `/Prev`. +fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option { + let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::().ok()?; + let mut visited = vec![]; + loop { + if visited.contains(&offset) { + return None; + } + visited.push(offset); + let table = String::from_utf8_lossy(pdf.get(offset..)?); + let mut words = table.split_ascii_whitespace(); + if words.next()? != "xref" { + return None; + } + loop { + let first = words.next()?; + if first == "trailer" { + break; + } + let first = first.parse::().ok()?; + let count = words.next()?.parse::().ok()?; + for index in 0..count { + let at = words.next()?.parse::().ok()?; + let entry_generation = words.next()?.parse::().ok()?; + let status = words.next()?; + if first.checked_add(index)? == number { + return (status == "n" && entry_generation == generation).then_some(at); + } + } + } + let trailer = table.split_once("trailer")?.1.split_once(">>")?.0; + let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()); + words.find(|&w| w == "Prev")?; + offset = words.next()?.parse().ok()?; + } +} + +/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary +/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None` +/// when it is missing or cannot be read. +fn stream_length(text: &[u8], pdf: &[u8]) -> Option { + let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3); + let dict = &text[from..]; + let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; + let mut depth = 1usize; + let mut length = None; + while i < dict.len() && depth > 0 { + let rest = &dict[i..]; + if rest.starts_with(b"<<") { + depth += 1; + i += 2; + } else if rest.starts_with(b">>") { + depth -= 1; + i += 2; + } else if rest[0] == b'<' { + // A hex string. + i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1); + } else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) { + let value = String::from_utf8_lossy(&rest[7..]); + let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect(); + length = match words[..] { + // `n g R` is an indirect length: the integer in object `n g`. + [n, g, "R", ..] => { + let header = format!("{n} {g} obj"); + let read_length = |at: usize| { + let body = String::from_utf8_lossy(&pdf[at + header.len()..]); + match body.split_ascii_whitespace().take(2).collect::>()[..] { + [n, "endobj"] => n.parse::().ok(), + _ => None, + } + }; + if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") { + let at = + xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref"); + let object = pdf.get(at..).expect("stream /Length xref offset is outside the file"); + assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object"); + read_length(at) + } else { + pdf.windows(header.len()) + .enumerate() + // An object header starts a line, and the length object holds one integer. + .filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n'))) + .find_map(|(at, _)| read_length(at)) + } + } + [n, ..] => n.parse::().ok(), + [] => None, + }; + i += 7; + } else { + i += 1; + } + } + length +} + +/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out: +/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time +/// and can spell `/BM`. fn transparency(pdf: &[u8]) -> Vec<&'static str> { - let text = String::from_utf8_lossy(pdf); + let mut text = Vec::with_capacity(pdf.len()); + let mut i = 0; + while i < pdf.len() { + let rest = &pdf[i..]; + // A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name. + let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>'; + if keyword_start && rest.starts_with(b"endstream") { + text.extend_from_slice(b"endstream"); + i += b"endstream".len(); + } else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) { + // Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to + // `endstream`); its bytes are not PDF syntax. + let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 }; + i = match stream_length(&text, pdf) { + Some(n) => { + let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream"); + while matches!(pdf.get(end), Some(b'\r' | b'\n')) { + end += 1; + } + assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream"); + end + } + None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"), + }; + } else if rest[0] == b'(' { + // A literal string: balanced parentheses, with `\` escaping the next byte. + let mut depth = 0usize; + while i < pdf.len() { + match pdf[i] { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + i += 1; + if depth == 0 { + break; + } + } + } else { + text.push(rest[0]); + i += 1; + } + } + let text = String::from_utf8_lossy(&text); let mut found = vec![]; for (what, there) in [ ("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")), @@ -193,3 +341,66 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err() ); } + +/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check +/// reads the file's dictionaries only, not its strings or its XMP packet. +#[test] +fn the_transparency_check_skips_strings_and_metadata() { + let pdf = b"%PDF-1.3\n5 0 obj\n<>\nendobj\n6 0 obj\n<>\nstream\nq/BMx/S/Transparency\nendstream\nendobj\ntrailer\n<>\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + assert_eq!(transparency(b"<>>>>>"), vec!["blend modes", "opacity"]); + // A `(` in image data starts no string, and nested and escaped parentheses end where the + // string does. + let pdf = b"<>\nstream\n(\x00(\nendstream\n<>\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]); + // Stream data is skipped by its length, even when it holds `endstream` itself. + let pdf = b"1 0 obj\n<>\nstream\nendstream (/BM\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let pdf = b"1 0 obj\n<>\nstream\nabc\r\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + let pdf = b"1 0 obj\n<>\nstream\nabcendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // Only the stream dictionary's own `/Length` counts, not one in a nested dictionary. + let pdf = b"1 0 obj\n<>>>\nstream\n/BM \nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + // `stream` inside a name is not the keyword. + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["blend modes"]); + let pdf = b"1 0 obj\n<>\nendobj\n"; + assert_eq!(transparency(pdf), vec!["soft masks"]); + // An indirect length is read from its object, so `endstream` in the data does not end it. + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); + let payload = b"2 0 obj\n13\nendobj\nendstream /BM"; + let mut pdf = b"%PDF-1.3\n".to_vec(); + let stream_at = pdf.len(); + pdf.extend_from_slice(b"1 0 obj\n<>\nstream\n"); + pdf.extend_from_slice(payload); + pdf.extend_from_slice(b"\nendstream\nendobj\n"); + let length_at = pdf.len(); + pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes()); + let catalog_at = pdf.len(); + pdf.extend_from_slice(b"3 0 obj\n<>\nendobj\n"); + let pages_at = pdf.len(); + pdf.extend_from_slice(b"4 0 obj\n<>\nendobj\n"); + let xref_at = pdf.len(); + pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n"); + for at in [stream_at, length_at, catalog_at, pages_at] { + pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes()); + assert_eq!(transparency(&pdf), Vec::<&str>::new()); + // A stream with no length and no `endstream` fails rather than hiding the rest of the file. + let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<>"; + assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err()); + for length in [2, 20, 999, usize::MAX] { + let pdf = format!("1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n<>"); + let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic"); + let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::().map(String::as_str)); + assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); + } +} From a65d251c87f33a46b80d3e979981766a9887136a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 11:52:55 -0800 Subject: [PATCH 40/49] Scripts: DXF scale tests fail on a drawing with no polyline vertices dxf_widest and dxf_leftmost folded from f64::MIN and f64::MAX, so a DXF that kept its header but lost every vertex gave an infinite product and the unitScaleRatio and pica assertions still passed. Both now reduce the coordinates and fail when there are none. docs/mcp.md: a relative save or open path is resolved against the working folder of the process that wrote or read the file. --- crates/engine/src/tests/script_save_open.rs | 4 ++-- docs/mcp.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 7fd60b9f94..b3dd0d2ded 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -423,12 +423,12 @@ fn dxf_header(dxf: &str, name: &str) -> Option { /// The largest x coordinate (group code 10) in the entities of a DXF. fn dxf_widest(dxf: &str) -> f64 { - dxf_xs(dxf).into_iter().fold(f64::MIN, f64::max) + dxf_xs(dxf).into_iter().reduce(f64::max).expect("DXF contains polyline vertices") } /// The smallest x coordinate (group code 10) in the entities of a DXF. fn dxf_leftmost(dxf: &str) -> f64 { - dxf_xs(dxf).into_iter().fold(f64::MAX, f64::min) + dxf_xs(dxf).into_iter().reduce(f64::min).expect("DXF contains polyline vertices") } /// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its diff --git a/docs/mcp.md b/docs/mcp.md index ca6d350642..8a2928c0a8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3301,7 +3301,7 @@ through `$`: writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS `artboardRange` is not checked against the document's artboards, but one that is not written as a range of artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's - file. A file saved or opened under a relative path is in the working folder of the process that wrote or read it, + file. A relative path that a file is saved or opened under is resolved against the working folder of the process that wrote or read it, for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw `Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved From 1576aac89ff4e568573906cd9ecddbf720909793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:56:24 -0800 Subject: [PATCH 41/49] 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 42/49] 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 1c9efecfb65e322518910ca6243841193d65e966 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:20:56 -0800 Subject: [PATCH 43/49] Workspaces: built-in workspaces open their panel again Switching to Essentials Classic, Automation, Layout, Painting, Printing and Proofing, Typography, Web or Touch, or resetting one, brought its panel to the front of its group but no longer opened it from a column collapsed to icons, so the panel stayed hidden. A workspace record keeps the panel open from the icons again: each built-in names its panel, a workspace left or saved keeps the one open then, and switching or Reset opens it. A recorded panel the new layout does not show from icons stays closed. Workspaces saved without the field open none. The Essentials Classic test checks the open panel again, and new tests cover Painting, Automation, switching back as left, Reset, saved workspaces and the preferences' JSON. --- crates/ui-egui/src/workspaces.rs | 77 ++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index 683c087332..5b04aa50f2 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -64,6 +64,10 @@ pub struct WorkspaceRecord { /// Tabs closed together by a panel shortcut. #[serde(skip_serializing_if = "Vec::is_empty")] pub docking_hidden_groups: Vec>, + /// The panel open from a column collapsed to icons (built-in workspaces: the panel the + /// workspace is for; workspaces saved without this field: none). + #[serde(skip_serializing_if = "Option::is_none")] + pub open_panel: Option, /// The tool each flyout group of the main Tools shows (built-in workspaces: the first). pub tools_last_used: LastUsed, /// The toolbars made with New Toolbar in this workspace (built-in workspaces: none). @@ -87,6 +91,7 @@ impl Default for WorkspaceRecord { status_bar: true, help_bar: true, docking_hidden_groups: Vec::new(), + open_panel: None, tools_last_used: LastUsed::default(), toolbars: Vec::new(), } @@ -245,25 +250,30 @@ pub fn builtins() -> Vec { x.rulers = true; x.toolbar_advanced = true; x.task_bar = false; + x.open_panel = Some("color".into()); }), w("Automation", &["layers", "actions"], &|x| { x.control_bar = true; x.toolbar_advanced = true; + x.open_panel = Some("actions".into()); }), w("Layout", &["layers", "align"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("align".into()); }), w("Painting", &["brushes"], &|x| { x.control_bar = true; x.toolbar_advanced = true; + x.open_panel = Some("brushes".into()); }) .double_tools(), w("Printing and Proofing", &["info"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("info".into()); }), w("Tracing", &["layers"], &|x| { x.control_bar = true; @@ -274,16 +284,19 @@ pub fn builtins() -> Vec { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("character".into()); }), w("Web", &["symbols"], &|x| { x.control_bar = true; x.rulers = true; x.toolbar_advanced = true; + x.open_panel = Some("symbols".into()); }), w(TOUCH, &["align"], &|x| { x.control_bar = true; x.toolbar_advanced = true; x.task_bar = true; + x.open_panel = Some("align".into()); }), ] } @@ -387,6 +400,7 @@ pub fn record(ui: &UiState) -> WorkspaceRecord { status_bar: ui.status_bar, help_bar: ui.help_bar, docking_hidden_groups: ui.docking_hidden_groups.clone(), + open_panel: ui.open_panel.clone(), tools_last_used: ui.tools_last_used.clone(), toolbars: ui.custom_toolbars.clone(), } @@ -412,6 +426,7 @@ fn apply_record(ui: &mut UiState, w: &WorkspaceRecord) { ui.status_bar = w.status_bar; ui.help_bar = w.help_bar; ui.docking_hidden_groups = w.docking_hidden_groups.clone(); + ui.open_panel = w.open_panel.clone(); ui.tools_last_used = w.tools_last_used.clone(); ui.custom_toolbars = w.toolbars.clone(); crate::custom_toolbars::sanitize(&mut ui.custom_toolbars); @@ -450,10 +465,19 @@ pub fn switch(app: &mut VectorcraftApp, key: &str) -> Result { let w = ui.workspaces.edited.get(&id).cloned().unwrap_or_else(|| saved_record(&ui.workspaces, &id)); apply_record(ui, &w); crate::panel_docking::reconcile(&mut ui.dock_workspace); + close_stale_flyout(ui); crate::panel_docking::show_panels(app); Ok(name) } +/// Close the open panel when the layout now in use does not show it from a column collapsed to +/// icons (it was moved, expanded or closed). +fn close_stale_flyout(ui: &mut UiState) { + if ui.open_panel.as_ref().is_some_and(|panel| !crate::panel_docking::layout_of(ui).opens_in_flyout(panel)) { + ui.open_panel = None; + } +} + /// Reset the current workspace to the way it was saved, dropping its changes. pub fn reset(app: &mut VectorcraftApp) -> String { let ui = &mut app.ui; @@ -467,6 +491,7 @@ pub fn reset(app: &mut VectorcraftApp) -> String { apply_record(ui, &w); ui.custom_toolbars = toolbars; crate::panel_docking::reconcile(&mut ui.dock_workspace); + close_stale_flyout(ui); crate::panel_docking::show_panels(app); current_name(&app.ui).to_string() } @@ -715,12 +740,64 @@ mod tests { switch(&mut app, "Essentials Classic").unwrap(); assert!(app.ui.control_bar && app.ui.view.rulers && app.ui.toolbar_advanced); assert!(front(&app.ui, "color")); + assert_eq!(app.ui.open_panel.as_deref(), Some("color")); assert_eq!(current_name(&app.ui), "Essentials Classic"); switch(&mut app, "essentials").unwrap(); assert!(!app.ui.control_bar && !app.ui.view.rulers); + assert_eq!(app.ui.open_panel, None); assert_eq!(app.ui.brightness, crate::theme::Brightness::Light); } + /// A built-in workspace shows the panel it is for, from its collapsed column too: the second + /// panel it brings forward (Automation's Actions) as well as the only one (Painting's + /// Brushes). A panel closed there stays closed when the workspace is left and switched back + /// to, and Reset opens it again. + #[test] + fn builtin_workspaces_show_their_panel_after_switch_and_reset() { + let showing = crate::panel_docking::showing; + let mut app = app(); + for (name, panel) in [("Painting", "brushes"), ("Automation", "actions"), ("Essentials Classic", "color")] { + switch(&mut app, name).unwrap(); + assert!(showing(&app.ui, panel), "{name} shows {panel}"); + } + assert!(crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&"color".to_string()), "Classic's Color opens from its icon"); + app.ui.open_panel = None; + switch(&mut app, ESSENTIALS).unwrap(); + assert!(!showing(&app.ui, "color"), "Essentials opens no panel"); + switch(&mut app, "Essentials Classic").unwrap(); + assert!(!showing(&app.ui, "color"), "Classic comes back as it was left"); + reset(&mut app); + assert!(showing(&app.ui, "color"), "Reset Essentials Classic shows Color again"); + } + + /// A saved workspace keeps the panel open from its icons, through the preferences' JSON too; a + /// workspace saved without that field opens none, and one naming a panel its layout does not + /// show from icons opens none either. + #[test] + fn saved_workspaces_restore_the_open_panel() { + let mut app = app(); + switch(&mut app, "Essentials Classic").unwrap(); + save_as(&mut app.ui, "Colors").unwrap(); + switch(&mut app, ESSENTIALS).unwrap(); + assert_eq!(app.ui.open_panel, None); + switch(&mut app, "Colors").unwrap(); + assert_eq!(app.ui.open_panel.as_deref(), Some("color")); + let id = id_of(&app.ui, "Colors"); + let back: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert_eq!(back.workspaces.records[&id].open_panel.as_deref(), Some("color")); + let mut old = serde_json::to_value(&back.workspaces.records[&id]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("openPanel").is_some()); + let old: WorkspaceRecord = serde_json::from_value(old).unwrap(); + assert_eq!(old.open_panel, None); + switch(&mut app, ESSENTIALS).unwrap(); + app.ui.workspaces.edited.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into()); + switch(&mut app, "Colors").unwrap(); + assert_eq!(app.ui.open_panel, None, "switching opens no panel the layout's icons lack"); + app.ui.workspaces.records.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into()); + reset(&mut app); + assert_eq!(app.ui.open_panel, None, "Reset opens no panel the layout's icons lack"); + } + #[test] fn save_apply_round_trip() { let mut app = app(); From 5ce02bb64bd7aae18ea65c6b90f2bb8c82bdd6a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:26:00 -0800 Subject: [PATCH 44/49] Flatten Transparency: write rasterized areas as fast-compressed PNGs Since #7669 the flattener's rasters have been encoded through the shared image codec with its default compression (zlib level 6). EPS export, and any other export that flattens, encodes every rasterized area this way and then decodes it again right away, so a document with many live effects exported about 170 ms slower to EPS. The rasters are now written with PngCompression::Fast, as the SVG filter raster already is (crates/effects/src/svg_filter.rs). The pixels and the EPS output bytes do not change. --- crates/engine/src/cmd/flatten/apply.rs | 14 ++++++++++- crates/engine/src/tests/flatten.rs | 35 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index fe1e183d16..8a884b67ea 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio } } } - let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + // The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it + // again right away. + let raw = craft_image_codecs::Image::from_raw( + img.width, + img.height, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + img.to_straight(), + ) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; + let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() }; + let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts) + .map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?; Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip }) } diff --git a/crates/engine/src/tests/flatten.rs b/crates/engine/src/tests/flatten.rs index 042f741e0e..959c58e9f3 100644 --- a/crates/engine/src/tests/flatten.rs +++ b/crates/engine/src/tests/flatten.rs @@ -350,6 +350,41 @@ fn gradients_rasterize_and_flat_areas_stay_vector() { } } +/// A rasterized area is stored as a PNG written with fast compression: its zlib header (RFC 1950) +/// gives compression level 0, the fastest. +#[test] +fn rasterized_areas_are_png_with_fast_compression() { + let _settings = settings_lock(); + let mut s = session(); + let g = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#000000"); + run( + &mut s, + "paint.setFill", + json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ); + run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40})); + let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "preset": "high"})); + assert_eq!(rasterized, 1); + let mut keys = vec![]; + node(&s, ids[0]).walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + keys.push(im.key.clone()); + } + }); + let [key] = &keys[..] else { panic!("one image: {keys:?}") }; + let png = &s.doc().unwrap().doc.images[key].bytes; + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG"); + let mut at = 8; + let level = loop { + let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) else { panic!("a PNG with image data") }; + if kind == b"IDAT" { + break png[at + 9] >> 6; + } + at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize; + }; + assert_eq!(level, 0, "zlib FLEVEL of the stored PNG"); +} + #[test] fn a_long_rasterized_area_is_placed_whole() { let _settings = settings_lock(); From f5111b293dd78df3e68c26b84b2696aff04eb234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:51:35 -0800 Subject: [PATCH 45/49] Home: the title is drawn at 24 points again The compact type was set to 92% of its nominal sizes (body 13 to 12, labels 12.5 to 11.5, captions 11.5 to 10.5), but the display type that draws the Home title stayed at 26 points on a 32-point line, so the title drew about 8.7% larger than in 0.24.1. The display type is now 24 points on a 29-point line, its nominal 26 on 32 at the same scale. A test checks that the title keeps the nominal title-to-body proportion against the compact body type, and that its line keeps the framework's display line proportion. --- crates/ui-egui/src/theme.rs | 38 ++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 09b5eec0b0..b47ef8e91e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -146,7 +146,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { } /// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners -/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16 +/// where the sets give pills, the Home title is 24-point on a 29-point line (its nominal 26 points on 32 at the 92% +/// the body type below is set at) with a 36-point call to action, 28-point New and Open with 16 /// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections, /// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set /// takes the reference app's metrics: @@ -159,8 +160,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { const SIZES: &[u8] = br#"{ "all": { "radius.button": 4, - "typography.display.size": 26, - "typography.display.line_height": 32, + "typography.display.size": 24, + "typography.display.line_height": 29, "size.page.action": 36, "size.page.button": 28, "size.page.button_side": 16, @@ -236,6 +237,37 @@ mod tests { assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty())); } + /// The Home title (the display type) is set at the same scale as the compact body type, so it keeps the nominal + /// 26-point title over a 13-point body proportion, and its line keeps the framework's display line proportion. + #[test] + fn the_home_title_is_scaled_with_the_body_type() { + use craft::theme::Size; + use craft::ui::runtime::env::{Env, RootEnv}; + use craft::ui::testing::Fixture; + use std::cell::Cell; + use std::rc::Rc; + const NOMINAL_TITLE_OVER_BODY: f32 = 26.0 / 13.0; + let typography = |sizes: Arc| { + let seen = Rc::new(Cell::new(None)); + let seen_in = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let t = Env::of(ui).tokens.tokens().typography; + seen_in.set(Some((t.display, t.body))); + }); + let mut root = RootEnv::new().density(Size::Compact); + root.sizes = sizes; + fixture.root(root); + fixture.frame(vec![]); + seen.get().expect("the fixture drew a frame") + }; + let (display, body) = typography(app_sizes()); + let ratio = display.size / body.size; + assert!((ratio - NOMINAL_TITLE_OVER_BODY).abs() < 0.05, "a {}-point title over a {}-point body", display.size, body.size); + let (framework, _) = typography(Arc::new(AppSizes::default())); + let (line, framework_line) = (display.line_height / display.size, framework.line_height / framework.size); + assert!((line - framework_line).abs() < 0.05, "a {}-point line for a {}-point title", display.line_height, display.size); + } + /// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow /// the framework's spacing scale. #[test] From b7bc86522cbd0a2fc25d417a2b81441367562925 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:52:39 -0800 Subject: [PATCH 46/49] Tools: a strip floated before the canvas is laid out opens beside the rail window.floatTools placed a new strip at the canvas's top left, and fell back to (0,0) when no view had been laid out yet: right after a document opened, or with no document open. The strip then covered the top of the docked Tools rail. Without a laid-out view, the strip now opens beside the docked rail it came from (else the Tools panel's), level with the rail's top and the float space's cascade inset away from it, on the side toward the middle of the window. A dragged tear-off still opens at the pointer. --- crates/ui-egui/src/panel_docking.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/toolbar.rs | 12 +++++++++--- crates/ui-egui/src/toolbar/tests.rs | 24 ++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0fd8936a45..1a47d5a7d2 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -301,6 +301,28 @@ pub(crate) fn column_of<'a>(layout: &'a Layout, panel: &str) -> Option<( Some((edge, column)) } +/// Where the dock last drew the docked column holding `panel`; none until the dock has drawn it, and while `panel` +/// floats or is closed. +pub(crate) fn column_rect(app: &VectorcraftApp, panel: &str) -> Option { + let (Some(_), column) = column_of(layout_of(&app.ui), panel)? else { return None }; + app.dock_rt.columns.iter().find(|(first, _)| column.panels().any(|p| p == first)).map(|(_, rect)| *rect) +} + +/// The top left a new floating window of `panel` takes beside the docked column holding `beside`: level with the +/// column's top, the cascade inset away from it on the side toward the middle of the float space. None until the dock +/// has drawn that column. +pub(crate) fn float_origin_beside(app: &VectorcraftApp, panel: &str, beside: &str) -> Option { + let column = column_rect(app, beside)?; + let space = command_space(app); + let x = if column.center().x <= space.area.center().x { + column.right() + space.inset + } else { + let width = space.size_of(&DragUnit::Panel(panel.to_owned()), None).x; + column.left() - space.inset - width + }; + Some(egui::pos2(x, column.top())) +} + /// Is the dock's outer column of panels (Properties · Layers · Libraries) collapsed to icons? pub(crate) fn dock_collapsed(ui: &UiState) -> bool { dock_columns(layout_of(ui)).first().is_some_and(|c| c.iconic) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 34a7829ba9..49da6d5a44 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -294,11 +294,17 @@ pub(crate) fn is_floating(app: &VectorcraftApp, toolbar: Option<&str>, key: &str strips(app, toolbar).iter().any(|g| g.first() == Some(&key)) } -/// Float the group `first` of `owner` as a strip at `at` (none: the canvas's corner). +/// Float the group `first` of `owner` as a strip at `at`. Without `at` the strip opens at the canvas's corner, or, +/// before a view has been laid out, beside `owner`'s docked rail, else beside the Tools panel's. fn place_strip(app: &mut VectorcraftApp, owner: &Owner, first: &str, at: Option) -> Result<(), String> { - let at = at.unwrap_or_else(|| app.canvas_view().map_or(Pos2::ZERO, |v| v.rect.min)); + let id = strip_id(owner, first); + let at = at + .or_else(|| app.canvas_view().map(|v| v.rect.min)) + .or_else(|| crate::panel_docking::float_origin_beside(app, &id, &owner.panel())) + .or_else(|| crate::panel_docking::float_origin_beside(app, &id, TOOLS)) + .unwrap_or(Pos2::ZERO); // A width of 0 leaves the window's width to the panel's grid. - crate::panel_docking::place_floating(app, &strip_id(owner, first), at, 0.0) + crate::panel_docking::place_floating(app, &id, at, 0.0) } /// Float the toolbar group (of the current layout) holding `tool` as a strip of tool buttons, put diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 91becce66b..2abb2f3cc1 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -483,6 +483,30 @@ fn window_float_tools_floats_and_puts_back_a_group() { assert!(strip_rect(&app, "rectangle").is_none() && !is_floating(&app, None, "pen")); } +/// `window.floatTools` run before a view has been laid out (right after a document opens, or with none open) floats the +/// strip beside the docked Tools rail, not over it, and the strip stays clear of the rail once the frames are drawn. +#[test] +fn a_strip_floated_before_a_view_is_laid_out_opens_beside_the_tools_rail() { + for (case, document) in [("document just opened", true), ("no document", false)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = crate::testing::ui_context(); + settled(&mut app, &ctx, 0.0, 900.0); + if document { + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + } + assert!(app.canvas_view().is_none(), "{case}: no view has been laid out yet"); + let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail is docked")); + app.run("window.floatTools", json!({"tool": "pen"})).unwrap(); + let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip floats")); + assert!(strip.left() >= rail.right(), "{case}: the strip {strip:?} opens right of the rail {rail:?}"); + assert!((strip.top() - rail.top()).abs() <= f32::EPSILON, "{case}: the strip {strip:?} is level with the rail {rail:?}"); + settled(&mut app, &ctx, 1.0, 900.0); + let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail stays docked")); + let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip still floats")); + assert!(!strip.intersects(rail), "{case}: the strip {strip:?} is clear of the rail {rail:?}"); + } +} + /// A floated group is a panel of the workspace's layout: a saved workspace brings it back, the built-in ones have none. #[test] fn workspaces_keep_floating_flyouts_and_reset_puts_them_back() { From f24eff296329cf96f3fe3ae54833a2a84205738d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:11:32 -0800 Subject: [PATCH 47/49] PDF: stream length test helper ignores names ending in obj stream_length took the last "obj" substring in the text as the object header, so a stream dictionary name such as /Tag/obj moved the scan past the outer dictionary and lost its /Length. The keyword now counts only at the start of the text or after PDF white space. --- crates/engine/src/cmd/fileio/tests_pdf13.rs | 25 ++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index f3493555c9..fc386ac09c 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -115,10 +115,16 @@ fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) - } /// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary -/// after the object's `obj` keyword. An indirect length is read from its object in `pdf`. `None` -/// when it is missing or cannot be read. +/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white +/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its +/// object in `pdf`. `None` when it is missing or cannot be read. fn stream_length(text: &[u8], pdf: &[u8]) -> Option { - let from = text.windows(3).rposition(|w| w == b"obj").map_or(0, |at| at + 3); + let from = text + .windows(3) + .enumerate() + .rev() + .find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' '))) + .map_or(0, |(at, _)| at + 3); let dict = &text[from..]; let mut i = dict.windows(2).position(|w| w == b"<<")? + 2; let mut depth = 1usize; @@ -404,3 +410,16 @@ fn the_transparency_check_skips_strings_and_metadata() { assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}"); } } + +/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the +/// stream's `/Length` is still read from the outer dictionary. +#[test] +fn the_stream_length_skips_names_that_end_in_obj() { + let text = b"1 0 obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + // NUL is PDF white space, so it may separate the generation number from `obj`. + let text = b"1 0 obj\n<>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<>\nstream\n"; + assert_eq!(stream_length(text, text), Some(5)); + let pdf = b"1 0 obj\n<>\nstream\nendstream /BM\nendstream\nendobj\n"; + assert_eq!(transparency(pdf), Vec::<&str>::new()); +} From 32f4dfd62a307d75596ce8f3e10764686870da2a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:29:36 -0800 Subject: [PATCH 48/49] 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. From dc94ae977c4f425e5a5da1900d4d0cd1a621993e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:10:05 -0800 Subject: [PATCH 49/49] Docs: matrix records passed in need only the six mValue fields The matrix functions read only mValueA to mValueTY from a record passed in. The typename "Matrix" is on the records they give back. --- crates/engine/src/script/dom/matrix.rs | 7 ++++--- docs/mcp.md | 3 ++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/matrix.rs b/crates/engine/src/script/dom/matrix.rs index aeccf78c95..4de0a9efe4 100644 --- a/crates/engine/src/script/dom/matrix.rs +++ b/crates/engine/src/script/dom/matrix.rs @@ -1,9 +1,10 @@ //! The matrix functions of `app`, as the help pages //! and //! describe them. A matrix is a plain -//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the -//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a -//! new record, those two give a boolean, and none changes the records passed to it. +//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and +//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has +//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives +//! a new record, those two give a boolean, and none changes the records passed to it. //! //! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix //! does (ISO 32000-1, 8.3.4), in script coordinates with Y up. diff --git a/docs/mcp.md b/docs/mcp.md index 3f6d406c90..2a2578895e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3278,7 +3278,8 @@ through `$`: `concatenateTranslationMatrix(matrix, deltaX?, deltaY?)`, `concatenateScaleMatrix(matrix, scaleX?, scaleY?)`, `concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and `isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain - objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each + objects with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY`. A record + passed in needs only those six fields; each record a function gives also has `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`. No function changes the records passed to it. A record maps `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own