From 9ffec7e72d57b8aec80d46b9e6e7efbf686b581d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:07:11 -0800 Subject: [PATCH 01/19] Scripts: perspective grid members and getPresetSettings for scripts A document in the script object model can now show and hide its perspective grid, read and set the active plane, and reset the grid to a built-in or saved preset, as the Document page lists them (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). The values come from the PerspectiveGridType and PerspectiveGridPlaneType enumerations on the scripting constants page. app.getPresetSettings returns a new DocumentPreset with the settings that a document made from the named startup preset starts with, and addDocument accepts it back without changes. - showPerspectiveGrid, hidePerspectiveGrid and setActivePlane run perspective.grid.show and perspective.plane.set. They add no undo step, and a failed run restores the grid. A run that only changes the grid's view state no longer adds an undo step. A run in which a command records its own undo step still adds one. - selectPerspectivePreset throws, and leaves the grid unchanged, when the preset name is not listed, when the preset's grid is not of gridType, when gridType is InvalidPerspectiveGridType, and when the name is longer than 4,096 bytes. A one-point grid accepts only the left and floor planes. - The workspace methods, loadColorSettings, showPresets and the perspective grid preset file methods throw an error that says they are not available yet. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/distortcmds.rs | 4 +- .../engine/src/cmd/distortcmds/perspective.rs | 29 ++ crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/script/dom.rs | 7 + crates/engine/src/script/dom/perspective.rs | 252 ++++++++++++++++ crates/engine/src/script/mod.rs | 6 +- crates/engine/src/tests.rs | 1 + .../src/tests/script_dom_perspective.rs | 282 ++++++++++++++++++ docs/mcp.md | 26 ++ docs/target-app-parity.md | 1 + 10 files changed, 607 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/script/dom/perspective.rs create mode 100644 crates/engine/src/tests/script_dom_perspective.rs diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index dc36e24380..516547d1a6 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -26,7 +26,9 @@ pub use perspective::perspective_click; use perspective::{ attach, edit_text, grid_set, grid_show, persp_draw, persp_move, persp_nudge, persp_transform, plane_match, plane_move, plane_set, release, }; -pub(crate) use perspective::{finish_edit_text, grid_kept, grid_of, perspective_rewrite, silent, store_grid, transform_again}; +pub(crate) use perspective::{ + finish_edit_text, grid_kept, grid_of, only_grid_view_changed, perspective_rewrite, silent, store_grid, transform_again, +}; pub fn specs() -> Vec { vec![ diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 90d58541a6..89b2327e59 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -24,6 +24,35 @@ pub(crate) fn grid_kept(d: &Document, g: &PerspectiveGrid) -> bool { serde_json::to_value(&g).is_ok_and(|v| d.unknown.get(persp::DOC_KEY) == Some(&v)) } +/// Whether `now` differs from `before` only in the view state of its perspective grid (whether it +/// shows, the active plane, the point Automatic Plane Positioning holds and the view options), the +/// changes [`silent`] makes without an undo step. +pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool { + let (a, b) = (now.unknown.get(persp::DOC_KEY), before.unknown.get(persp::DOC_KEY)); + if a == b { + return false; + } + let (mut g, mut was) = (PerspectiveGrid::current(now), PerspectiveGrid::current(before)); + g.visible = was.visible; + g.plane = was.plane; + g.inferred = was.inferred; + g.locked = was.locked; + g.lock_station = was.lock_station; + g.snap = was.snap; + g.rulers = was.rulers; + g.attached.clear(); + was.attached.clear(); + if serde_json::to_value(&g).ok() != serde_json::to_value(&was).ok() { + return false; + } + let mut rest = now.clone(); + match b { + Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()), + None => rest.unknown.remove(persp::DOC_KEY), + }; + rest == *before +} + /// Change view state of the grid without an undo step. pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result { let st = s.doc_mut()?; diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..b0de09d251 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -801,7 +801,7 @@ pub fn find(s: &Session, name: &str) -> Option { impl Session { /// New Document's starting settings: Letter in Preferences ▸ Units ▸ General. - fn default_settings(&self) -> DocSettings { + pub(crate) fn default_settings(&self) -> DocSettings { DocSettings { units: self.default_units(), ..DocSettings::default() } } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fadaeb133d..e0a09054fc 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -39,6 +39,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session}; pub(super) mod layers; +mod perspective; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -1718,6 +1719,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + for (name, members) in perspective::enums() { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -1728,6 +1733,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(perspective::application_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1769,6 +1775,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ]); document.extend(["pathItems", "textFrames", "swatches", "symbols", "views", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m))); document.extend(layers::document_members(l)); + document.extend(perspective::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs new file mode 100644 index 0000000000..3a0bd6bf40 --- /dev/null +++ b/crates/engine/src/script/dom/perspective.rs @@ -0,0 +1,252 @@ +//! The perspective grid of a document and the New Document settings of a startup preset in the +//! script object model, as the help pages +//! and list them, with the values of +//! . +//! +//! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with +//! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them +//! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows +//! the grid and makes one undo step when the grid's geometry changes. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has +//! that name (in any case), and when the preset's grid is not of `gridType`; nothing changes then. +//! - A one-point grid takes only the left and the floor plane as its active plane, as the archived +//! scripting guide says +//! (). +//! `INVALIDGRIDPLANETYPE` makes no plane active. +//! - `showPerspectiveGrid` and `setActivePlane` give `true`, also when nothing changed; +//! `hidePerspectiveGrid` gives `false` when the grid was already hidden. +//! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new +//! `DocumentPreset` with the settings a new document from that preset starts with, which +//! `addDocument` takes back unchanged (settings it cannot take, such as other units or more than +//! 100 artboards, are left out); changing it changes nothing else. +//! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset +//! files are not available yet. + +use serde_json::json; +use vectorcraft_js::{Data, HostError, HostMember}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; + +use super::{Answer, MAX_TEXT_BYTES, arg, later, method, named, num, on_doc, startup_preset, text, this_doc, with_doc}; +use crate::script::{Host, Link}; + +type Result = std::result::Result; + +/// The `PerspectiveGridType` values, with the grid kind (`perspective.grid.set`'s `kind`) of each. +const GRID_TYPES: &[(&str, Option)] = &[ + ("OnePointPerspectiveGridType", Some(1)), + ("TwoPointPerspectiveGridType", Some(2)), + ("ThreePointPerspectiveGridType", Some(3)), + ("InvalidPerspectiveGridType", None), +]; + +/// The `PerspectiveGridPlaneType` values, with the plane of each. +const PLANE_TYPES: &[(&str, Plane)] = &[ + ("GRIDLEFTPLANETYPE", Plane::Left), + ("GRIDRIGHTPLANETYPE", Plane::Right), + ("GRIDFLOORPLANETYPE", Plane::Ground), + ("INVALIDGRIDPLANETYPE", Plane::None), +]; + +/// The enumerations this module adds, as `dom::install` defines them. +pub(super) fn enums() -> Vec<(&'static str, Vec<&'static str>)> { + vec![ + ("PerspectiveGridType", GRID_TYPES.iter().map(|(n, _)| *n).collect()), + ("PerspectiveGridPlaneType", PLANE_TYPES.iter().map(|(n, _)| *n).collect()), + ] +} + +/// The kind a `PerspectiveGridType` value names (`None`: `InvalidPerspectiveGridType`). +fn grid_type(d: &Data) -> Result> { + let found = match d { + Data::String(s) => s.strip_prefix("PerspectiveGridType.").and_then(|m| GRID_TYPES.iter().find(|(n, _)| *n == m)), + _ => None, + }; + found.map(|(_, k)| *k).ok_or_else(|| HostError::Type("gridType must be a PerspectiveGridType value".into())) +} + +/// The plane a `PerspectiveGridPlaneType` value names. +fn plane_type(d: &Data) -> Result { + let found = match d { + Data::String(s) => s.strip_prefix("PerspectiveGridPlaneType.").and_then(|m| PLANE_TYPES.iter().find(|(n, _)| *n == m)), + _ => None, + }; + found.map(|(_, p)| *p).ok_or_else(|| HostError::Type("gridPlane must be a PerspectiveGridPlaneType value".into())) +} + +/// The document `this` names and its perspective grid. +fn grid(h: &Host, a: &[Data]) -> Result<(super::Doc, PerspectiveGrid)> { + let doc = this_doc(h, a)?; + Ok((doc, with_doc(h, doc, |_, st| PerspectiveGrid::effective(&st.doc)))) +} + +/// `showPerspectiveGrid()`: shows the document's grid (its default one when none was defined). +fn show_grid(h: &Host, a: &[Data]) -> Answer { + let (doc, g) = grid(h, a)?; + if !g.visible { + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": true})))?; + } + Ok(Data::Bool(true)) +} + +/// `hidePerspectiveGrid()`: hides the document's grid. → whether a grid was hidden. +fn hide_grid(h: &Host, a: &[Data]) -> Answer { + let (doc, g) = grid(h, a)?; + if !g.visible { + return Ok(Data::Bool(false)); + } + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.show", &json!({"visible": false})))?; + Ok(Data::Bool(true)) +} + +/// `getPerspectiveActivePlane()`: the grid's active plane, shown or hidden. +fn active_plane(h: &Host, a: &[Data]) -> Answer { + let (_, g) = grid(h, a)?; + let name = PLANE_TYPES.iter().find(|(_, p)| *p == g.plane).map_or("INVALIDGRIDPLANETYPE", |(n, _)| *n); + Ok(text(format!("PerspectiveGridPlaneType.{name}"))) +} + +/// `setActivePlane(gridPlane)`: makes `gridPlane` the grid's active plane. +fn set_active_plane(h: &Host, a: &[Data]) -> Answer { + let plane = plane_type(arg(a, 1))?; + let (doc, g) = grid(h, a)?; + if g.kind == 1 && plane == Plane::Right { + return Err(HostError::Range("a one-point grid has no right plane to make active".into())); + } + if g.plane != plane { + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.plane.set", &json!({"plane": plane.id()})))?; + } + Ok(Data::Bool(true)) +} + +/// `selectPerspectivePreset(gridType, presetName)`: resets the grid to the preset `presetName`, +/// which must be a grid of `gridType`. +fn select_preset(h: &Host, a: &[Data]) -> Answer { + let kind = grid_type(arg(a, 1))?.ok_or_else(|| HostError::Range("InvalidPerspectiveGridType has no presets".into()))?; + let Data::String(name) = arg(a, 2) else { return Err(HostError::Type("presetName must be a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the preset's name is too long".into())); + } + let doc = this_doc(h, a)?; + let preset = h.session.borrow().perspective_preset(name); + let preset = preset.ok_or_else(|| HostError::Error(format!("no perspective grid preset called {name}")))?; + if preset.kind != kind { + return Err(HostError::Error(format!("the preset {} is not a grid of that type", preset.name))); + } + on_doc(h, doc.uid, false, |h| super::command(h, "perspective.grid.preset", &json!({"name": preset.name})))?; + Ok(Data::Bool(true)) +} + +/// The `RulerUnits` value of `u`, for the units `documents.addDocument` takes (`None`: other units, +/// which a preset given back to `addDocument` keeps by leaving `units` out). +fn units(u: crate::doc::Unit) -> Option<&'static str> { + use crate::doc::Unit; + Some(match u { + Unit::Points => "RulerUnits.Points", + Unit::Picas => "RulerUnits.Picas", + Unit::Inches => "RulerUnits.Inches", + Unit::Millimeters => "RulerUnits.Millimeters", + Unit::Centimeters => "RulerUnits.Centimeters", + Unit::Pixels => "RulerUnits.Pixels", + _ => return None, + }) +} + +/// `artboardRowsOrCols` as `addDocument` reads it: the rows of a grid filled by column and the +/// columns of the other layouts. `None`: a grid by column whose artboards no row count places the +/// same. +fn rows_or_cols(d: &crate::cmd::newdoc::DocSettings) -> Option { + use crate::cmd::newdoc::ArtboardLayout; + let n = d.artboards.max(1) as usize; + if d.layout != ArtboardLayout::GridByColumn { + return Some(d.grid_columns().max(1)); + } + if d.rows > 0 { + return Some((d.rows as usize).min(n)); + } + let rows = n.div_ceil(d.grid_columns().max(1)); + let by_rows = crate::cmd::newdoc::DocSettings { rows: u32::try_from(rows).ok()?, ..d.clone() }; + (by_rows.boards() == d.boards()).then_some(rows) +} + +/// `app.getPresetSettings(preset)`: a new `DocumentPreset` with the settings a document from the +/// startup preset `preset` starts with. +fn preset_settings(h: &Host, a: &[Data]) -> Answer { + use crate::cmd::newdoc::{ArtboardLayout, PreviewMode}; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("getPresetSettings needs a startup preset's name".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the startup preset's name is too long".into())); + } + let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // The settings `documents.addDocument` starts from: the first preset of the profile's category + // (found by name, as `file.new` finds it), else New Document's starting settings. + let d = { + let s = h.session.borrow(); + let first = profile.and_then(|n| crate::cmd::newdoc::category(&s, n)?.into_iter().next()); + first.map_or_else(|| s.default_settings(), |f| crate::cmd::newdoc::find(&s, &f.name).unwrap_or(f)) + }; + let cmyk = mode.map_or(d.color_mode == crate::doc::ColorMode::Cmyk, |m| m == "cmyk"); + let layout = match (d.layout, d.right_to_left) { + (ArtboardLayout::GridByRow, false) => "GridByRow", + (ArtboardLayout::GridByColumn, false) => "GridByCol", + (ArtboardLayout::Row, false) => "Row", + (ArtboardLayout::Column, _) => "Column", + (ArtboardLayout::GridByRow, true) => "RLGridByRow", + (ArtboardLayout::GridByColumn, true) => "RLGridByCol", + (ArtboardLayout::Row, true) => "RLRow", + }; + let preview = match d.preview_mode { + PreviewMode::Default => "DefaultPreview", + PreviewMode::Pixel => "PixelPreview", + PreviewMode::Overprint => "OverprintPreview", + }; + let item = |k: &str, v: Data| (k.to_string(), v); + let mut out = vec![ + item("typename", text("DocumentPreset")), + item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))), + item("artboardSpacing", num(d.spacing)), + item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })), + item("height", num(d.height)), + item("previewMode", text(format!("DocumentPreviewMode.{preview}"))), + item("width", num(d.width)), + ]; + // The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them + // back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row + // count lays out the same), so `addDocument` with the same preset keeps the preset's own. + if f64::from(d.artboards.max(1)) <= super::MAX_ARTBOARDS { + out.push(item("numArtboards", num(f64::from(d.artboards.max(1))))); + if let Some(n) = rows_or_cols(&d) { + out.push(item("artboardRowsOrCols", num(super::float(n as u64)))); + } + } + if let Some(u) = units(d.units) { + out.push(item("units", text(u))); + } + let resolutions = [(72.0, "ScreenResolution"), (150.0, "MediumResolution"), (300.0, "HighResolution")]; + if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) { + out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}")))); + } + Ok(Data::Object(out)) +} + +/// The members this module adds to `Document`'s. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![ + ("showPerspectiveGrid", method(l, show_grid)), + ("hidePerspectiveGrid", method(l, hide_grid)), + ("getPerspectiveActivePlane", method(l, active_plane)), + ("setActivePlane", method(l, set_active_plane)), + ("selectPerspectivePreset", method(l, select_preset)), + ]); + m.extend(["exportPerspectiveGridPreset", "importPerspectiveGridPreset"].into_iter().map(|n| later(l, "Document", n))); + m +} + +/// The members this module adds to `Application`'s. +pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![("getPresetSettings", method(l, preset_settings))]); + let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"]; + m.extend(missing.into_iter().map(|n| later(l, "Application", n))); + m +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 34779c7b5e..6292be8727 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2249,7 +2249,11 @@ impl Session { changed_names.push(st.title()); continue; }; - let changed = !st.same_content(&b.doc); + // The perspective grid's view state changes without an undo step, as it does outside a + // run, when no command in the run recorded an undo step of its own on the working copy. + let (now, was) = (&st.history.undo, &b.history.undo); + let recorded = now.len() != was.len() || !now.last().zip(was.last()).map_or(now.is_empty(), |(x, y)| Arc::ptr_eq(&x.doc, &y.doc)); + let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc)); st.history = std::mem::take(&mut b.history); st.recovery.clone_from(&b.recovery); if changed { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..4736063a3a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_perspective; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs new file mode 100644 index 0000000000..c9398ffd4c --- /dev/null +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -0,0 +1,282 @@ +//! The script object model's perspective grid members and `app.getPresetSettings`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn grid(s: &mut Session) -> Value { + s.execute("perspective.grid.get", &json!({})).unwrap()["grid"].clone() +} + +#[test] +fn show_and_hide_change_the_view_without_an_undo_step() { + let mut s = doc(); + let before = undo_steps(&s); + let out = + log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.showPerspectiveGrid()); vc.log(d.showPerspectiveGrid());"); + assert_eq!(out, vec![json!(false), json!(true), json!(true)]); + assert_eq!(grid(&mut s)["visible"], true); + assert_eq!(undo_steps(&s), before); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.hidePerspectiveGrid()); vc.log(d.hidePerspectiveGrid());"); + assert_eq!(out, vec![json!(true), json!(false)]); + assert_eq!(grid(&mut s)["visible"], false); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() { + let mut s = doc(); + let before = undo_steps(&s); + run(&mut s, "vc.run('perspective.grid.show', {visible: true}); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap(); + assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground"))); + assert_eq!(undo_steps(&s), before); + run(&mut s, "app.activeDocument.hidePerspectiveGrid(); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});").unwrap(); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(grid(&mut s)["visible"], true); +} + +#[test] +fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() { + let mut s = doc(); + let before = undo_steps(&s); + s.execute("perspective.grid.set", &json!({"locked": true})).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let mut s = doc(); + let source = "vc.run('perspective.grid.set', {locked: true}); app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE);"; + run(&mut s, source).unwrap(); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!((grid(&mut s)["locked"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground"))); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!grid(&mut s).get("locked").and_then(Value::as_bool).unwrap_or(false)); +} + +#[test] +fn the_active_plane_round_trips_and_a_failed_run_puts_it_back() { + let mut s = doc(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.getPerspectiveActivePlane());\ + vc.log(d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE)); vc.log(d.getPerspectiveActivePlane());\ + d.setActivePlane(PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE); vc.log(d.getPerspectiveActivePlane());", + ); + let expected = ["PerspectiveGridPlaneType.GRIDLEFTPLANETYPE", "PerspectiveGridPlaneType.GRIDFLOORPLANETYPE"]; + assert_eq!(out[..3], [json!(expected[0]), json!(true), json!(expected[1])]); + assert_eq!(out[3], json!("PerspectiveGridPlaneType.INVALIDGRIDPLANETYPE")); + assert_eq!(grid(&mut s)["plane"], "none"); + failure(&mut s, "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE); d.showPerspectiveGrid(); throw 1;"); + assert_eq!(grid(&mut s)["plane"], "none"); + assert_eq!(grid(&mut s)["visible"], false); +} + +#[test] +fn a_bad_plane_or_a_right_plane_on_a_one_point_grid_throws() { + let mut s = doc(); + for bad in ["'left'", "0", "PerspectiveGridType.OnePointPerspectiveGridType", "undefined"] { + let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({bad});")); + assert!(e.contains("PerspectiveGridPlaneType"), "{bad}: {e}"); + } + s.execute("perspective.grid.preset", &json!({"kind": 1})).unwrap(); + let e = failure(&mut s, "app.activeDocument.setActivePlane(PerspectiveGridPlaneType.GRIDRIGHTPLANETYPE);"); + assert!(e.contains("one-point grid"), "{e}"); + assert_eq!(grid(&mut s)["plane"], "left"); + let out = log( + &mut s, + "var d = app.activeDocument; d.setActivePlane(PerspectiveGridPlaneType.GRIDFLOORPLANETYPE); vc.log(d.getPerspectiveActivePlane());", + ); + assert_eq!(out, vec![json!("PerspectiveGridPlaneType.GRIDFLOORPLANETYPE")]); +} + +#[test] +fn select_perspective_preset_checks_the_type_and_the_name() { + let mut s = doc(); + let one = s.execute("perspective.presets.list", &json!({})).unwrap()["presets"] + .as_array() + .unwrap() + .iter() + .find(|p| p["kind"] == 1) + .map(|p| p["name"].as_str().unwrap().to_string()) + .unwrap(); + let before = undo_steps(&s); + for (call, message) in [ + (format!("PerspectiveGridType.TwoPointPerspectiveGridType, '{one}'"), "not a grid of that type"), + (format!("PerspectiveGridType.InvalidPerspectiveGridType, '{one}'"), "has no presets"), + ("PerspectiveGridType.OnePointPerspectiveGridType, 'No Such Preset'".to_string(), "no perspective grid preset called"), + (format!("'one', '{one}'"), "PerspectiveGridType value"), + ("PerspectiveGridType.OnePointPerspectiveGridType, 7".to_string(), "presetName must be a string"), + (format!("PerspectiveGridType.OnePointPerspectiveGridType, '{}'", "x".repeat(5000)), "too long"), + ] { + let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({call});")); + assert!(e.contains(message), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(grid(&mut s)["kind"], 2); + let out = log( + &mut s, + &format!("vc.log(app.activeDocument.selectPerspectivePreset(PerspectiveGridType.OnePointPerspectiveGridType, '{}'));", one.to_uppercase()), + ); + assert_eq!(out, vec![json!(true)]); + let g = grid(&mut s); + assert_eq!((g["kind"].clone(), g["visible"].clone()), (json!(1), json!(true))); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn hostile_names_and_numbers_throw_with_nothing_changed() { + let mut s = doc(); + s.execute("perspective.presets.save", &json!({"name": "Mine"})).unwrap(); + let before = (undo_steps(&s), grid(&mut s)); + for name in ["../Mine", "..\\\\Mine", "/Mine", "C:\\\\Mine", "Mine/..", "Mi\\u0000ne", "~/Mine"] { + for call in [ + format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, '{name}');"), + format!("app.getPresetSettings('{name}');"), + ] { + let e = failure(&mut s, &call); + assert!(e.contains("no perspective grid preset called") || e.contains("no startup preset called"), "{call}: {e}"); + } + } + // The script host refuses a number that is not finite before the member runs. + for value in ["NaN", "Infinity", "-1e308", "1e308", "2"] { + let refused = |e: &str, message: &str| e.contains(message) || e.contains("is not a finite number"); + let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset({value}, 'Mine');")); + assert!(refused(&e, "PerspectiveGridType value"), "{value}: {e}"); + let e = failure(&mut s, &format!("app.activeDocument.setActivePlane({value});")); + assert!(refused(&e, "PerspectiveGridPlaneType value"), "{value}: {e}"); + let e = failure(&mut s, &format!("app.activeDocument.selectPerspectivePreset(PerspectiveGridType.TwoPointPerspectiveGridType, {value});")); + assert!(refused(&e, "presetName must be a string"), "{value}: {e}"); + } + assert_eq!((undo_steps(&s), grid(&mut s)), before); +} + +#[test] +fn a_closed_document_throws_on_every_grid_member() { + let mut s = doc(); + run(&mut s, "#targetengine keep\nvar held = app.activeDocument;").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.showPerspectiveGrid();"); + assert!(e.contains("Stale document"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; vc.run('file.close', {}); d.hidePerspectiveGrid();"); + assert!(e.contains("Stale document"), "{e}"); + let e = failure(&mut s, "Document.prototype.getPerspectiveActivePlane.call({});"); + assert!(e.contains("not a Document"), "{e}"); +} + +#[test] +fn get_preset_settings_gives_a_copy_add_document_takes() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Basic CMYK'); vc.log(p.typename); vc.log(p.colorMode); vc.log(p.width); vc.log(p.height);\ + vc.log(p.numArtboards); p.width = 100; vc.log(app.getPresetSettings('Basic CMYK').width);\ + var d = app.documents.addDocument('Basic CMYK', p); vc.log(d.width); vc.log(d.documentColorSpace);\ + vc.log(app.getPresetSettings(DocumentPresetType.BasicRGB).colorMode);", + ); + let expected = [json!("DocumentPreset"), json!("DocumentColorSpace.CMYK"), json!(612), json!(792), json!(1), json!(612)]; + assert_eq!(out[..6], expected); + assert_eq!(out[6..], [json!(100), json!("DocumentColorSpace.CMYK"), json!("DocumentColorSpace.RGB")]); + for (call, message) in [("'No Such Preset'", "no startup preset called"), ("3", "startup preset's name"), ("undefined", "startup preset's name")] + { + let e = failure(&mut s, &format!("app.getPresetSettings({call});")); + assert!(e.contains(message), "{call}: {e}"); + } + let e = failure(&mut s, &format!("app.getPresetSettings('{}');", "x".repeat(5000))); + assert!(e.contains("too long"), "{e}"); +} + +#[test] +fn get_preset_settings_of_a_profile_gives_what_add_document_starts_from() { + let mut s = Session::new(); + for preset in ["Video", "Web", "Mobile", "Print", "DocumentPresetType.Video"] { + let out = log( + &mut s, + &format!( + "var p = app.getPresetSettings('{preset}'); var d = app.documents.addDocument('{preset}');\ + vc.log([p.width, p.height, p.units, p.colorMode]); vc.log([d.width, d.height, d.rulerUnits, d.documentColorSpace]);" + ), + ); + assert_eq!(out[0], out[1], "{preset}"); + } + let out = log(&mut s, "var p = app.getPresetSettings('Video'); vc.log([p.width, p.height]);"); + assert_ne!(out[0], json!([612, 792])); +} + +#[test] +fn get_preset_settings_given_back_to_add_document_makes_the_same_document() { + let mut s = Session::new(); + s.execute("prefs.set", &json!({"key": "unitsGeneral", "value": "feet"})).unwrap(); + let layout = json!({"layout": "gridByColumn", "rows": 3, "spacing": 30}); + s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": 5, "artboardLayout": layout})).unwrap(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Print'); vc.log(p.artboardRowsOrCols); vc.log(p.units === undefined);\ + function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\ + var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\ + vc.log(boards(a)); vc.log(boards(b)); vc.log(a.rulerUnits === b.rulerUnits);", + ); + assert_eq!(out[..2], [json!(3), json!(true)]); + assert_eq!(out[2], out[3]); + assert_eq!(out[2].as_array().map(Vec::len), Some(5)); + assert_eq!(out[4], json!(true)); + // Settings a DocumentPreset cannot hold are left out, and addDocument keeps the preset's own. + for (artboards, layout, has_count, has_rows) in [ + (6, json!({"layout": "gridByColumn", "columns": 4}), true, true), + (5, json!({"layout": "gridByColumn", "columns": 4, "spacing": 7.3}), true, true), + (6, json!({"layout": "gridByColumn", "columns": 3}), true, true), + (150, json!({"layout": "gridByRow", "columns": 12}), false, false), + (7, json!({"layout": "gridByRow", "columns": 3, "rightToLeft": true}), true, true), + ] { + s.execute("file.newPresets.save", &json!({"name": "Letter", "artboards": artboards, "artboardLayout": layout})).unwrap(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Print'); vc.log(p.numArtboards !== undefined); vc.log(p.artboardRowsOrCols !== undefined);\ + function boards(d) { var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); return r; }\ + vc.log(boards(app.documents.addDocument('Print'))); vc.log(boards(app.documents.addDocument('Print', p)));", + ); + assert_eq!(out[..2], [json!(has_count), json!(has_rows)], "{artboards} {layout}"); + assert_eq!(out[2].as_array().map(Vec::len), Some(artboards), "{layout}"); + assert_eq!(out[2], out[3], "{artboards} {layout}"); + } +} + +#[test] +fn members_not_built_yet_say_so() { + let mut s = doc(); + for (owner, member) in [ + ("app", "saveWorkspace"), + ("app", "switchWorkspace"), + ("app", "deleteWorkspace"), + ("app", "resetWorkspace"), + ("app", "loadColorSettings"), + ("app", "showPresets"), + ("app.activeDocument", "exportPerspectiveGridPreset"), + ("app.activeDocument", "importPerspectiveGridPreset"), + ] { + let e = failure(&mut s, &format!("{owner}.{member}('x');")); + assert!(e.contains(&format!("{member} is not available yet")), "{member}: {e}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 2b6b988f91..583af55a11 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2728,6 +2728,32 @@ 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. +- A document also has `showPerspectiveGrid()`, `hidePerspectiveGrid()`, `getPerspectiveActivePlane()`, + `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` + (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` + run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and + a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved + preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo + step when the grid changes. The enumerations `PerspectiveGridType` (`OnePointPerspectiveGridType`, + `TwoPointPerspectiveGridType`, `ThreePointPerspectiveGridType`, `InvalidPerspectiveGridType`) and + `PerspectiveGridPlaneType` (`GRIDLEFTPLANETYPE`, `GRIDRIGHTPLANETYPE`, `GRIDFLOORPLANETYPE`, + `INVALIDGRIDPLANETYPE`) come from https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/. A + one-point grid takes only the left and the floor plane as its active plane, as the archived scripting guide + describes + (https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf). + `getPresetSettings` takes the names `addDocument` takes and gives a new `DocumentPreset` with the settings a + document from that preset starts with, which `addDocument` takes back unchanged. It leaves out `units` when the + preset's units are not one of the six `RulerUnits` values a new document takes, and `numArtboards` and + `artboardRowsOrCols` when the preset has more than 100 artboards, so `addDocument` with the same preset keeps the + preset's own. + VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` give `true`, and `hidePerspectiveGrid` gives + `false` when the grid was already hidden. `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not + listed, a preset whose grid is not of `gridType`, `InvalidPerspectiveGridType` and a name of more than 4,096 bytes + throw an error with nothing changed. Changing the `DocumentPreset` `getPresetSettings` gives changes nothing else. + `app.saveWorkspace`, `switchWorkspace`, `deleteWorkspace`, `resetWorkspace`, `loadColorSettings` and + `showPresets`, and `Document.exportPerspectiveGridPreset` and `importPerspectiveGridPreset`, 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6edddf19b3..2d098d4977 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,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`). 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 perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.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 8b31227089aca76ef50904eb309aac4e22194c26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:20:04 -0800 Subject: [PATCH 02/19] Scripts: docs give the grid members' return values and every omitted preset setting docs/mcp.md and the perspective module doc now say that the Document page describes the return values of showPerspectiveGrid, setActivePlane and hidePerspectiveGrid; only the true result when nothing changed is VectorCraft's own rule. They also list every setting getPresetSettings leaves out: rasterResolution for a PPI other than 72, 150 or 300, and artboardRowsOrCols for a grid by column that no row count lays out the same. --- crates/engine/src/script/dom/perspective.rs | 14 +++++++++----- docs/mcp.md | 13 ++++++++----- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 3a0bd6bf40..0df2dc3cfa 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -6,7 +6,10 @@ //! `showPerspectiveGrid`, `hidePerspectiveGrid` and `setActivePlane` change view state with //! `perspective.grid.show` and `perspective.plane.set`: no undo step, and a failed run puts them //! back with the document. `selectPerspectivePreset` runs `perspective.grid.preset`, which shows -//! the grid and makes one undo step when the grid's geometry changes. +//! the grid and makes one undo step when the grid's geometry changes. As the Document page +//! describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and +//! `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already +//! hidden. //! //! VectorCraft's own rules, which the help pages do not state: //! - `selectPerspectivePreset(gridType, presetName)` throws when no built-in or saved preset has @@ -15,12 +18,13 @@ //! scripting guide says //! (). //! `INVALIDGRIDPLANETYPE` makes no plane active. -//! - `showPerspectiveGrid` and `setActivePlane` give `true`, also when nothing changed; -//! `hidePerspectiveGrid` gives `false` when the grid was already hidden. +//! - `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. //! - `getPresetSettings(preset)` takes the names `documents.addDocument` takes, and gives a new //! `DocumentPreset` with the settings a new document from that preset starts with, which -//! `addDocument` takes back unchanged (settings it cannot take, such as other units or more than -//! 100 artboards, are left out); changing it changes nothing else. +//! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than +//! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout +//! of more than 100 artboards, and the layout of a grid by column that no row count lays out the +//! same. Changing the result changes nothing else. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. diff --git a/docs/mcp.md b/docs/mcp.md index 583af55a11..7cdca29574 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2744,11 +2744,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf). `getPresetSettings` takes the names `addDocument` takes and gives a new `DocumentPreset` with the settings a document from that preset starts with, which `addDocument` takes back unchanged. It leaves out `units` when the - preset's units are not one of the six `RulerUnits` values a new document takes, and `numArtboards` and - `artboardRowsOrCols` when the preset has more than 100 artboards, so `addDocument` with the same preset keeps the - preset's own. - VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` give `true`, and `hidePerspectiveGrid` gives - `false` when the grid was already hidden. `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not + preset's units are not one of the six `RulerUnits` values a new document takes, `rasterResolution` when the + preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 + artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so + `addDocument` with the same preset keeps the preset's own. As the Document page describes, + `showPerspectiveGrid` and `setActivePlane` give `true` on success, and `hidePerspectiveGrid` gives `true` when it + hides a grid and `false` when the grid was already hidden. + VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. + `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not listed, a preset whose grid is not of `gridType`, `InvalidPerspectiveGridType` and a name of more than 4,096 bytes throw an error with nothing changed. Changing the `DocumentPreset` `getPresetSettings` gives changes nothing else. `app.saveWorkspace`, `switchWorkspace`, `deleteWorkspace`, `resetWorkspace`, `loadColorSettings` and From 7ac929f2e4a8cc174d6541be03affba1c701c314 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:40:23 -0800 Subject: [PATCH 03/19] Scripts: a grid view run after an edit adds no undo step, host names listed A run that only showed the perspective grid or set its active plane added a Run Script undo step when the document already had an undo step, because the check compared the working copy's history with the document's own. The working copy starts with no undo steps, so the check now asks whether it holds any. The host name inventory lists the perspective grid enumerations and the new Application and Document members, including the setter rows of the members that are not available yet. --- crates/engine/src/script/mod.rs | 5 +++-- .../src/tests/script_dom_perspective.rs | 13 ++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 21 ++++++++++++------- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 6292be8727..c2c70ae0f8 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2251,8 +2251,9 @@ impl Session { }; // The perspective grid's view state changes without an undo step, as it does outside a // run, when no command in the run recorded an undo step of its own on the working copy. - let (now, was) = (&st.history.undo, &b.history.undo); - let recorded = now.len() != was.len() || !now.last().zip(was.last()).map_or(now.is_empty(), |(x, y)| Arc::ptr_eq(&x.doc, &y.doc)); + // The working copy starts with no undo steps (`World::working`), so any step it holds now + // was recorded in the run. + let recorded = !st.history.undo.is_empty(); let changed = !st.same_content(&b.doc) && (recorded || !cmd::distortcmds::only_grid_view_changed(&st.doc, &b.doc)); st.history = std::mem::take(&mut b.history); st.recovery.clone_from(&b.recovery); diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index c9398ffd4c..eebea33e7e 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -61,6 +61,19 @@ fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() { assert_eq!(grid(&mut s)["visible"], true); } +#[test] +fn a_grid_view_run_after_an_edit_adds_no_undo_step() { + let mut s = doc(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let before = undo_steps(&s); + let drawn = s.active().unwrap().doc.node_count(); + run(&mut s, "app.activeDocument.showPerspectiveGrid(); vc.run('perspective.plane.set', {plane: 'ground'});").unwrap(); + assert_eq!((grid(&mut s)["visible"].clone(), grid(&mut s)["plane"].clone()), (json!(true), json!("ground"))); + assert_eq!(undo_steps(&s), before); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.node_count(), drawn - 1); +} + #[test] fn a_grid_edit_that_changes_only_view_fields_keeps_its_undo_step_in_a_run() { let mut s = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 881cb64d04..95a8607329 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -42,7 +42,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// documents; `Document.saveAs`, `close` and the perspective grid preset files, and the workspace +/// methods, `loadColorSettings` and `showPresets` of `Application`, throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -75,14 +76,16 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application Artboard Artboards CompoundPathItem CompoundPathItems CoordinateSystem Document \ DocumentArtboardLayout DocumentColorSpace DocumentPresetType DocumentPreviewMode DocumentRasterResolution \ - DocumentTransparencyGrid Documents ElementPlacement GroupItem GroupItems Layer Layers PageItem PageItems RulerUnits \ - ZOrderMethod", + DocumentTransparencyGrid Documents ElementPlacement GroupItem GroupItems Layer Layers PageItem PageItems \ + PerspectiveGridPlaneType PerspectiveGridType RulerUnits ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= deleteWorkspace \ + deleteWorkspace= documents getIsFileOpen getPresetSettings loadColorSettings loadColorSettings= resetWorkspace \ + resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= switchWorkspace switchWorkspace= \ + typename", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -90,8 +93,10 @@ const INSIDE: &[(&str, &str)] = &[ ( "Document.prototype.", "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 \ + documentColorSpace exportPerspectiveGridPreset exportPerspectiveGridPreset= getPerspectiveActivePlane groupItems \ + height hidePerspectiveGrid importPerspectiveGridPreset importPerspectiveGridPreset= layers name pageItems parent \ + pathItems pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selectPerspectivePreset selection \ + selection= setActivePlane showPerspectiveGrid swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -153,6 +158,8 @@ const INSIDE: &[(&str, &str)] = &[ TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("PerspectiveGridPlaneType.", "GRIDFLOORPLANETYPE GRIDLEFTPLANETYPE GRIDRIGHTPLANETYPE INVALIDGRIDPLANETYPE"), + ("PerspectiveGridType.", "InvalidPerspectiveGridType OnePointPerspectiveGridType ThreePointPerspectiveGridType TwoPointPerspectiveGridType"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; From 6af735865376fce14669cfc38aa12fdda616733a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:24:17 -0800 Subject: [PATCH 04/19] Scripts: getPresetSettings gives a DocumentPreset that addDocument takes app.getPresetSettings returned a plain object with a typename of DocumentPreset, which addDocument refuses since it takes only an object of the DocumentPreset class. It now makes a DocumentPreset of the run with the preset's settings, through the same storage new DocumentPreset() uses, so addDocument takes it back and the result counts toward the run's limit of 10,000 DocumentPreset objects. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 27 ++++++++++++++------- crates/engine/src/script/dom/perspective.rs | 6 ++--- docs/mcp.md | 2 ++ 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5ec1172a54..ca687f6ba3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -948,19 +948,28 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { /// left out. The settings stay with the run, which hands the script an object of the /// `DocumentPreset` class. fn new_preset(h: &Host) -> Answer { + let item = |k: &str, v: Data| (k.to_string(), v); + add_preset( + h, + vec![ + item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), + item("artboardRowsOrCols", num(1.0)), + item("artboardSpacing", num(20.0)), + item("height", num(792.0)), + item("numArtboards", num(1.0)), + item("width", num(612.0)), + ], + ) +} + +/// A new `DocumentPreset` of the run with the settings `fields`, which `new DocumentPreset()` and +/// `app.getPresetSettings` both make. +fn add_preset(h: &Host, fields: Vec<(String, Data)>) -> Answer { let mut presets = h.dom.presets.borrow_mut(); if presets.len() >= MAX_PRESETS { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } - let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ - item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), - item("artboardRowsOrCols", num(1.0)), - item("artboardSpacing", num(20.0)), - item("height", num(792.0)), - item("numArtboards", num(1.0)), - item("width", num(612.0)), - ]); + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 0df2dc3cfa..6a697234d4 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -24,7 +24,8 @@ //! `addDocument` takes back unchanged. Settings it cannot take are left out: units other than //! the six `RulerUnits` values, a PPI other than 72, 150 or 300, the artboard count and layout //! of more than 100 artboards, and the layout of a grid by column that no row count lays out the -//! same. Changing the result changes nothing else. +//! same. Changing the result changes nothing else. Each result counts toward the run's limit +//! of `DocumentPreset` objects, as `new DocumentPreset()` does. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. @@ -207,7 +208,6 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { }; let item = |k: &str, v: Data| (k.to_string(), v); let mut out = vec![ - item("typename", text("DocumentPreset")), item("artboardLayout", text(format!("DocumentArtboardLayout.{layout}"))), item("artboardSpacing", num(d.spacing)), item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })), @@ -231,7 +231,7 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { if let Some((_, r)) = resolutions.iter().find(|(ppi, _)| (d.raster_effects_ppi - ppi).abs() < 1e-9) { out.push(item("rasterResolution", text(format!("DocumentRasterResolution.{r}")))); } - Ok(Data::Object(out)) + super::add_preset(h, out) } /// The members this module adds to `Document`'s. diff --git a/docs/mcp.md b/docs/mcp.md index 917c5d1837..b879148df5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2765,6 +2765,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `INVALIDGRIDPLANETYPE` makes no plane active. A preset name that is not listed, a preset whose grid is not of `gridType`, `InvalidPerspectiveGridType` and a name of more than 4,096 bytes throw an error with nothing changed. Changing the `DocumentPreset` `getPresetSettings` gives changes nothing else. + A run makes at most 10,000 `DocumentPreset` objects, those of `new DocumentPreset()` and `getPresetSettings` + together; one more throws a `RangeError`. `app.saveWorkspace`, `switchWorkspace`, `deleteWorkspace`, `resetWorkspace`, `loadColorSettings` and `showPresets`, and `Document.exportPerspectiveGridPreset` and `importPerspectiveGridPreset`, throw an error that says they are not available yet. From b41cd40be92b5551e30d91ecdc64cfcf2aba7ae3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 10:20:23 -0800 Subject: [PATCH 05/19] Scripts: app.startupPresetsList lists the startup presets addDocument takes app.startupPresetsList gives a new array of the startup preset names each read: the New Document profiles in the order the New Document dialog lists them, then Basic CMYK and Basic RGB. documents.addDocument and app.getPresetSettings take every name in it. --- crates/engine/src/script/dom/perspective.rs | 16 ++++++++++++-- .../src/tests/script_dom_perspective.rs | 22 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 3 ++- docs/mcp.md | 10 ++++++--- docs/target-app-parity.md | 2 +- 5 files changed, 46 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 6a697234d4..8521fff8f1 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -26,6 +26,10 @@ //! of more than 100 artboards, and the layout of a grid by column that no row count lays out the //! same. Changing the result changes nothing else. Each result counts toward the run's limit //! of `DocumentPreset` objects, as `new DocumentPreset()` does. +//! - `startupPresetsList` is an array of the startup preset names, each of which +//! `documents.addDocument` and `getPresetSettings` take: the New Document profiles in the order +//! the New Document dialog lists them, then `Basic CMYK` and `Basic RGB`. Each read gives a new +//! array, so changing it changes nothing else. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. @@ -33,7 +37,7 @@ use serde_json::json; use vectorcraft_js::{Data, HostError, HostMember}; use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; -use super::{Answer, MAX_TEXT_BYTES, arg, later, method, named, num, on_doc, startup_preset, text, this_doc, with_doc}; +use super::{Answer, MAX_TEXT_BYTES, arg, get, later, method, named, num, on_doc, startup_preset, text, this_doc, with_doc}; use crate::script::{Host, Link}; type Result = std::result::Result; @@ -234,6 +238,14 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { super::add_preset(h, out) } +/// The startup presets besides the New Document profiles, which give a document of one color mode. +const BASIC_PRESETS: [&str; 2] = ["Basic CMYK", "Basic RGB"]; + +/// `app.startupPresetsList`: the names of the startup presets, as a new array. +fn startup_presets(_: &Host, _: &[Data]) -> Answer { + Ok(Data::Array(crate::cmd::newdoc::profile_names().chain(BASIC_PRESETS).map(text).collect())) +} + /// The members this module adds to `Document`'s. pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { let mut m = named(vec![ @@ -249,7 +261,7 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { /// The members this module adds to `Application`'s. pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { - let mut m = named(vec![("getPresetSettings", method(l, preset_settings))]); + let mut m = named(vec![("getPresetSettings", method(l, preset_settings)), ("startupPresetsList", get(l, startup_presets))]); let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"]; m.extend(missing.into_iter().map(|n| later(l, "Application", n))); m diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index eebea33e7e..f8196d6663 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -276,6 +276,28 @@ fn get_preset_settings_given_back_to_add_document_makes_the_same_document() { } } +#[test] +fn startup_presets_list_names_presets_add_document_takes() { + let mut s = Session::new(); + let out = log( + &mut s, + "var l = app.startupPresetsList; vc.log(l); l.push('Mine'); l[0] = 'x'; vc.log(app.startupPresetsList.length === l.length - 1);\ + vc.log(app.startupPresetsList[0] !== 'x');\ + for (var i = 0; i < l.length - 1; i++) { var n = app.startupPresetsList[i]; var p = app.getPresetSettings(n);\ + var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", + ); + let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + for name in ["Print", "Web", "Basic CMYK", "Basic RGB"] { + assert!(names.contains(&name), "{name}: {names:?}"); + } + assert_eq!(out[1..3], [json!(true), json!(true)]); + assert_eq!(out.len(), 3 + names.len()); + for (name, made) in names.iter().zip(&out[3..]) { + assert_eq!(made, &json!([name, true]), "{name}"); + } + assert_eq!(s.documents().len(), names.len()); +} + #[test] fn members_not_built_yet_say_so() { let mut s = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b76b8fb37a..7ac23d41ae 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -84,7 +84,8 @@ const INSIDE: &[(&str, &str)] = &[ "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= deleteWorkspace \ deleteWorkspace= documents getIsFileOpen getPresetSettings loadColorSettings loadColorSettings= resetWorkspace \ - resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= switchWorkspace switchWorkspace= \ + resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= startupPresetsList switchWorkspace \ + switchWorkspace= \ typename", ), ("DocumentPreset.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index b879148df5..39a91da05b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2741,8 +2741,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `GroupItems.createFromFile` throw an error that says they are not available yet. - A document also has `showPerspectiveGrid()`, `hidePerspectiveGrid()`, `getPerspectiveActivePlane()`, `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` - (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` - (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` and + `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo @@ -2758,7 +2758,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot preset's units are not one of the six `RulerUnits` values a new document takes, `rasterResolution` when the preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so - `addDocument` with the same preset keeps the preset's own. As the Document page describes, + `addDocument` with the same preset keeps the preset's own. `startupPresetsList` is a read-only array of the + startup preset names, each of which `addDocument` and `getPresetSettings` take: the New Document profiles in the + order the New Document dialog lists them (`Mobile`, `Web`, `Print`, `Film & Video`, `Art & Illustration`, + `Branding`, `Social`), then `Basic CMYK` and `Basic RGB`. This order is VectorCraft's own. Each read gives a new + array, so changing it changes nothing else. As the Document page describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already hidden. VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2d098d4977..0e25ded443 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,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`). 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 perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. + - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.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 2f931e0444bbf7274aa76ee8922da09e6adc3f69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:21:13 -0800 Subject: [PATCH 06/19] Tests: startupPresetsList keeps the New Document dialog's order The test now compares app.startupPresetsList with the New Document profiles in the dialog's order followed by Basic CMYK and Basic RGB, the order docs/mcp.md gives, instead of checking that four names are present. --- crates/engine/src/tests/script_dom_perspective.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index f8196d6663..e0b8d4c4c9 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -287,9 +287,9 @@ fn startup_presets_list_names_presets_add_document_takes() { var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", ); let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - for name in ["Print", "Web", "Basic CMYK", "Basic RGB"] { - assert!(names.contains(&name), "{name}: {names:?}"); - } + // The New Document profiles in the dialog's order, then the Basic presets. + let listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect(); + assert_eq!(names, listed); assert_eq!(out[1..3], [json!(true), json!(true)]); assert_eq!(out.len(), 3 + names.len()); for (name, made) in names.iter().zip(&out[3..]) { From d7ba04760d1f9b134fdbb0908ae6c7102d36e2ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:22:32 -0800 Subject: [PATCH 07/19] Scripts: app.startupPresetsList lists Print first Scripts read app.startupPresetsList[0] as the print preset. The list now starts with Print, then Web, Mobile, Film & Video, Art & Illustration, Branding and Social, then Basic CMYK and Basic RGB. The order is VectorCraft's own. The test now checks that Print comes first and that the list holds each New Document profile and both Basic presets once, instead of comparing with the profiles' order in the New Document dialog. docs/mcp.md states the new order and that a script which changes the array a read gave does not change the list a later read gives. --- crates/engine/src/script/dom/perspective.rs | 13 +++++++------ crates/engine/src/tests/script_dom_perspective.rs | 11 ++++++++--- docs/mcp.md | 12 ++++++------ docs/target-app-parity.md | 2 +- 4 files changed, 22 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index 8521fff8f1..33d2c821b4 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -27,9 +27,9 @@ //! same. Changing the result changes nothing else. Each result counts toward the run's limit //! of `DocumentPreset` objects, as `new DocumentPreset()` does. //! - `startupPresetsList` is an array of the startup preset names, each of which -//! `documents.addDocument` and `getPresetSettings` take: the New Document profiles in the order -//! the New Document dialog lists them, then `Basic CMYK` and `Basic RGB`. Each read gives a new -//! array, so changing it changes nothing else. +//! `documents.addDocument` and `getPresetSettings` take: `Print` first, then the other New +//! Document profiles, then `Basic CMYK` and `Basic RGB`. Each read gives a new +//! array; a script that changes that array does not change the list a later read gives. //! - The workspace methods, `loadColorSettings`, `showPresets` and the perspective grid preset //! files are not available yet. @@ -238,12 +238,13 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { super::add_preset(h, out) } -/// The startup presets besides the New Document profiles, which give a document of one color mode. -const BASIC_PRESETS: [&str; 2] = ["Basic CMYK", "Basic RGB"]; +/// The startup presets in the order `app.startupPresetsList` gives them: `Print` first, then the +/// other New Document profiles, then the presets that give a document of one color mode. +const STARTUP_PRESETS: [&str; 9] = ["Print", "Web", "Mobile", "Film & Video", "Art & Illustration", "Branding", "Social", "Basic CMYK", "Basic RGB"]; /// `app.startupPresetsList`: the names of the startup presets, as a new array. fn startup_presets(_: &Host, _: &[Data]) -> Answer { - Ok(Data::Array(crate::cmd::newdoc::profile_names().chain(BASIC_PRESETS).map(text).collect())) + Ok(Data::Array(STARTUP_PRESETS.into_iter().map(text).collect())) } /// The members this module adds to `Document`'s. diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index e0b8d4c4c9..8d533349bf 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -287,9 +287,14 @@ fn startup_presets_list_names_presets_add_document_takes() { var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", ); let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - // The New Document profiles in the dialog's order, then the Basic presets. - let listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect(); - assert_eq!(names, listed); + // Scripts take `startupPresetsList[0]` as the print preset. + assert_eq!(names.first(), Some(&"Print")); + // Every New Document profile and both Basic presets, each once. + let mut sorted = names.clone(); + sorted.sort_unstable(); + let mut listed: Vec<&str> = crate::cmd::newdoc::profile_names().chain(["Basic CMYK", "Basic RGB"]).collect(); + listed.sort_unstable(); + assert_eq!(sorted, listed); assert_eq!(out[1..3], [json!(true), json!(true)]); assert_eq!(out.len(), 3 + names.len()); for (name, made) in names.iter().zip(&out[3..]) { diff --git a/docs/mcp.md b/docs/mcp.md index 39a91da05b..18e1839727 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2742,8 +2742,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot - A document also has `showPerspectiveGrid()`, `hidePerspectiveGrid()`, `getPerspectiveActivePlane()`, `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` and - `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` and `hidePerspectiveGrid` - run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and + `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` + and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo step when the grid changes. The enumerations `PerspectiveGridType` (`OnePointPerspectiveGridType`, @@ -2759,10 +2759,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so `addDocument` with the same preset keeps the preset's own. `startupPresetsList` is a read-only array of the - startup preset names, each of which `addDocument` and `getPresetSettings` take: the New Document profiles in the - order the New Document dialog lists them (`Mobile`, `Web`, `Print`, `Film & Video`, `Art & Illustration`, - `Branding`, `Social`), then `Basic CMYK` and `Basic RGB`. This order is VectorCraft's own. Each read gives a new - array, so changing it changes nothing else. As the Document page describes, + startup preset names, each of which `addDocument` and `getPresetSettings` take: `Print`, `Web`, `Mobile`, + `Film & Video`, `Art & Illustration`, `Branding`, `Social`, `Basic CMYK` and `Basic RGB`, in that order, so + `app.startupPresetsList[0]` is `Print`. This order is VectorCraft's own. Each read gives a new array; a script + that changes that array does not change the list a later read gives. As the Document page describes, `showPerspectiveGrid` and `setActivePlane` give `true` on success, and `hidePerspectiveGrid` gives `true` when it hides a grid and `false` when the grid was already hidden. VectorCraft's own rules: `showPerspectiveGrid` and `setActivePlane` also give `true` when nothing changed. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0e25ded443..afd314657f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,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`). 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 perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names, and `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`, and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`. + - Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names; `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`; and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.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 74bea71d0fc17e2477a6104865727822c00feed1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:34:33 -0800 Subject: [PATCH 08/19] Docs: rewrap the perspective grid paragraph in docs/mcp.md The startupPresetsList test comment now says that Print first is VectorCraft's own order. The Application.prototype member list in the scriptcheck table keeps switchWorkspace= and typename on one line. --- crates/engine/src/tests/script_dom_perspective.rs | 2 +- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 3 +-- docs/mcp.md | 9 +++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index 8d533349bf..c0c1bdbc80 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -287,7 +287,7 @@ fn startup_presets_list_names_presets_add_document_takes() { var d = app.documents.addDocument(n); vc.log([n, d.width === p.width && d.documentColorSpace === p.colorMode]); }", ); let names: Vec<&str> = out[0].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); - // Scripts take `startupPresetsList[0]` as the print preset. + // VectorCraft's own order puts Print first. assert_eq!(names.first(), Some(&"Print")); // Every New Document profile and both Basic presets, each once. let mut sorted = names.clone(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 7ac23d41ae..e528c675e1 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -85,8 +85,7 @@ const INSIDE: &[(&str, &str)] = &[ "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= deleteWorkspace \ deleteWorkspace= documents getIsFileOpen getPresetSettings loadColorSettings loadColorSettings= resetWorkspace \ resetWorkspace= saveWorkspace saveWorkspace= selection showPresets showPresets= startupPresetsList switchWorkspace \ - switchWorkspace= \ - typename", + switchWorkspace= typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 18e1839727..7509ba8832 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2743,10 +2743,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setActivePlane(gridPlane)` and `selectPerspectivePreset(gridType, presetName)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/), and `app` has `getPresetSettings(preset)` and `startupPresetsList` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `showPerspectiveGrid` - and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of them adds an undo step, and - a failed run puts the grid back. `selectPerspectivePreset` runs `perspective.grid.preset` with a built-in or saved - preset of `perspective.presets.list` (its name in any case), which shows the grid and is part of the run's undo - step when the grid changes. The enumerations `PerspectiveGridType` (`OnePointPerspectiveGridType`, + and `hidePerspectiveGrid` run `perspective.grid.show`, and `setActivePlane` runs `perspective.plane.set`; none of + them adds an undo step, and a failed run puts the grid back. `selectPerspectivePreset` runs + `perspective.grid.preset` with a built-in or saved preset of `perspective.presets.list` (its name in any case), + which shows the grid and is part of the run's undo step when the grid changes. The enumerations + `PerspectiveGridType` (`OnePointPerspectiveGridType`, `TwoPointPerspectiveGridType`, `ThreePointPerspectiveGridType`, `InvalidPerspectiveGridType`) and `PerspectiveGridPlaneType` (`GRIDLEFTPLANETYPE`, `GRIDRIGHTPLANETYPE`, `GRIDFLOORPLANETYPE`, `INVALIDGRIDPLANETYPE`) come from https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/. A From 333f49139de6b60425c8cd71eab8febe2087a4bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:51:20 -0800 Subject: [PATCH 09/19] 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.rs | 2 +- crates/engine/src/script/dom/layers.rs | 21 +++++++++----- crates/engine/src/tests/script_dom.rs | 40 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ca687f6ba3..6b43d6b887 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1581,7 +1581,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// The error of `remove()` and `removeAll()` for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index bd0046a4b4..2d6993f860 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -37,9 +37,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, ON_LOCKED_ARTBOARD, 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, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -654,11 +654,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(); @@ -666,12 +667,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 c44ecb4887..6ff113bef5 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 71f6414cf0a704474a9571d11c9398300a94c586 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:12:51 -0800 Subject: [PATCH 10/19] 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 6b43d6b887..ff97c2fa7b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -95,9 +95,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 2d6993f860..973270c07a 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 6ff113bef5..f2203a8ea5 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1290,6 +1290,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 68de13f3454d8ac6cda8cf664b9cec5a36e79bd9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 15:23:44 -0800 Subject: [PATCH 11/19] Scripts: the report and the Artboard tool follow the active artboard a run moves - script.run's report lists a document whose active artboard has another index at the end of the run because artboards were inserted, removed or reordered before it. - After a run, the Artboard tool takes the active artboard as its only selected one, as choosing it in the Artboards panel does. - layers.add, groupItems.add and artboards.add read the new object's id from the command's own result, so ids above 2^53 stay exact. --- crates/engine/src/script/dom.rs | 7 ++++ crates/engine/src/script/dom/layers.rs | 44 +++++++++++++++----------- 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, 95 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ff97c2fa7b..896f454931 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -100,10 +100,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 973270c07a..1251972f64 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; @@ -38,8 +40,8 @@ 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, 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, + 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))) @@ -783,7 +782,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()))?; @@ -1201,7 +1200,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()))?; @@ -1265,9 +1264,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 28d36f030d..3b2614fd9e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2108,7 +2108,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()), run_docs: RefCell::new( self.docs .iter() @@ -2349,7 +2349,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 f2203a8ea5..99fd7ae784 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1133,6 +1133,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(); @@ -1442,6 +1458,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 8cfc7e4c4b..d0454658ef 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -38,7 +38,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()); @@ -50,6 +52,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 877875077d..9e30323364 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -156,6 +156,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_canceled_pick_does_not_take_a_dropped_script() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index c3f5a33db2..22a0eda208 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2765,7 +2765,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 b249beb9176fa70ab2e487f162d02df2fbdc3fb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:01:37 -0800 Subject: [PATCH 12/19] New Document: picking the selected Grid by Column keeps a preset's rows Picking the layout that is already selected in More Settings removed the rows of a preset made with file.new's rows and kept only the columns they showed, so Create put a different number of artboards in each column. With five artboards and rows 4, the first column got three artboards instead of four. A different layout or a new column count still replaces the rows. --- crates/ui-egui/src/dialogs/new_document.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 0852e55bec..09253c1a91 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -480,8 +480,12 @@ fn shown_columns(s: &DocSettings) -> u32 { s.columns.max(1).min(s.artboards.max(1)) } -/// Picks the artboard layout `l`. A preset's rows give way to the column count they showed. +/// Picks the artboard layout `l`. A preset's rows give way to the column count they showed; +/// picking the layout that is already selected keeps them. fn pick_layout(s: &mut DocSettings, l: ArtboardLayout) { + if l == s.layout { + return; + } if by_rows(s) { s.columns = shown_columns(s); } @@ -812,7 +816,7 @@ mod tests { /// showed. Under a grid by row the dialog shows the stored columns, and they stay. #[test] fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { - for to in ArtboardLayout::ALL { + for to in ArtboardLayout::ALL.into_iter().filter(|l| *l != ArtboardLayout::GridByColumn) { for rows in [json!(4), json!(4.0), json!(3.6)] { let mut s = settings(json!({"artboards": 9, "artboardLayout": {"layout": "gridByColumn", "columns": 2, "rows": rows}})); assert_eq!(shown_columns(&s), 3, "9 artboards in rows {rows}"); @@ -827,6 +831,18 @@ mod tests { assert_eq!(shown_columns(&s), 2); } + /// Picking the grid by column that is already selected keeps a preset's rows, so Create puts + /// as many artboards in each column as before. + #[test] + fn picking_the_selected_layout_keeps_a_presets_rows() { + let mut s = settings(json!({"artboards": 5, "artboardLayout": {"layout": "gridByColumn", "columns": 2, "rows": 4, "spacing": 10}})); + let before = s.to_json()["artboardLayout"].clone(); + assert_eq!(before["rows"], json!(4)); + pick_layout(&mut s, ArtboardLayout::GridByColumn); + assert_eq!(s.to_json()["artboardLayout"], before); + assert_eq!(shown_columns(&s), 2); + } + /// Columns shows what a preset's rows give the current number of artboards; the dialog's /// fields list the rows with those columns. #[test] From 3b1058b7e532f5085735b23d6f7df3eb553a4077 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:36:21 -0800 Subject: [PATCH 13/19] Scripts: fix review findings in preset settings, removeAll, artboard insert and grid view getPresetSettings leaves out previewMode for a Pixel Preview preset, which addDocument does not take. removeAll releases the clip of a group or layer whose clipping mask it deletes. Inserting an artboard keeps the active artboard by id, and the run report gives its new index, also in a document the run opened. Scoped name lookups charge for the entries they scan. Showing or hiding the perspective grid of an older document adds no undo step for the attachment migration alone. --- .../engine/src/cmd/distortcmds/perspective.rs | 6 +- crates/engine/src/script/dom.rs | 11 ++- crates/engine/src/script/dom/layers.rs | 36 +++++++- crates/engine/src/script/dom/perspective.rs | 10 ++- crates/engine/src/script/mod.rs | 3 +- crates/engine/src/tests/script_dom.rs | 83 +++++++++++++++++++ .../src/tests/script_dom_perspective.rs | 39 +++++++++ docs/mcp.md | 3 +- 8 files changed, 178 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index a1928a19d6..7c2b633af3 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -46,11 +46,13 @@ pub(crate) fn only_grid_view_changed(now: &Document, before: &Document) -> bool return false; } let mut rest = now.clone(); - match b { + let mut normalized_before = before.clone(); + PerspectiveGrid::current(before).store(&mut normalized_before); + match normalized_before.unknown.get(persp::DOC_KEY) { Some(v) => rest.unknown.insert(persp::DOC_KEY.to_string(), v.clone()), None => rest.unknown.remove(persp::DOC_KEY), }; - rest == *before + rest == normalized_before } /// Change view state of the grid without an undo step. diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9f60bd6cc5..bd0ef91f4b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -178,8 +178,9 @@ 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)>, + /// Each open document's uid and the index of its active artboard when the run started, and for + /// a document the run opened, the index before the run first added an artboard to it. + pub(super) boards_at_start: RefCell>, text: text::TextState, presets: RefCell>>, preset_bytes: Cell, @@ -190,7 +191,11 @@ pub(super) struct State { impl State { /// The state of a run whose heap is `heap_bytes` and that starts with the documents `docs` open. pub(super) fn new(heap_bytes: usize, docs: &[DocState]) -> Self { - Self { preset_limit: heap_bytes as u64, boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() } + Self { + preset_limit: heap_bytes as u64, + boards_at_start: RefCell::new(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. diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 1e43abfbd7..3f16b07e2f 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -690,7 +690,9 @@ 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)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let at = ids.iter().position(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + h.charge_call(at.map_or(ids.len(), |i| i + 1) as u64)?; + let id = at.map(|i| &ids[i]); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -724,6 +726,18 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { 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 container whose clipping mask is deleted is no longer clipped, so its next child does not become the mask. + let masked: Vec = with_doc(h, doc, |_, st| { + let d = &st.doc; + Ok::<_, HostError>( + ids.iter() + .filter_map(|id| { + let p = d.parent_of(*id)?; + d.node(p).filter(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|f| f.id == *id)).map(|_| p) + }) + .collect(), + ) + })?; 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}"))); @@ -733,7 +747,12 @@ 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| { + for p in &masked { + command(h, "layer.clippingMask.toggle", &json!({"id": p.0}))?; + } + command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + })?; } Ok(Data::Undefined) } @@ -1249,8 +1268,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"))); } + // A document the run opened is compared from the index it had before its first new artboard. + let active = with_doc(h, doc, |_, st| Ok::<_, HostError>(active_artboard(st)))?; + { + let mut start = h.dom.boards_at_start.borrow_mut(); + if !start.iter().any(|(uid, _)| *uid == doc.uid) { + start.push((doc.uid, active)); + } + } let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { + { + 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(active_artboard(st)).map(|ab| ab.id); + } 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()) diff --git a/crates/engine/src/script/dom/perspective.rs b/crates/engine/src/script/dom/perspective.rs index c3b0d2658b..18ebb1d10e 100644 --- a/crates/engine/src/script/dom/perspective.rs +++ b/crates/engine/src/script/dom/perspective.rs @@ -208,9 +208,9 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { (ArtboardLayout::Row, true) => "RLRow", }; let preview = match d.preview_mode { - PreviewMode::Default => "DefaultPreview", - PreviewMode::Pixel => "PixelPreview", - PreviewMode::Overprint => "OverprintPreview", + PreviewMode::Default => Some("DefaultPreview"), + PreviewMode::Pixel => None, + PreviewMode::Overprint => Some("OverprintPreview"), }; let item = |k: &str, v: Data| (k.to_string(), v); let mut out = vec![ @@ -218,9 +218,11 @@ fn preset_settings(h: &Host, a: &[Data]) -> Answer { item("artboardSpacing", num(d.spacing)), item("colorMode", text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })), item("height", num(d.height)), - item("previewMode", text(format!("DocumentPreviewMode.{preview}"))), item("width", num(d.width)), ]; + if let Some(preview) = preview { + out.push(item("previewMode", text(format!("DocumentPreviewMode.{preview}")))); + } // The artboard count and `artboardRowsOrCols` are left out when `addDocument` cannot take them // back exactly (more than `MAX_ARTBOARDS`, or a grid by column set by its columns that no row // count lays out the same), so `addDocument` with the same preset keeps the preset's own. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index c012b317c2..cb4538f8b1 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2606,7 +2606,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()) { + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start.borrow(), 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 1a52f80111..0f6371d0f0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2382,6 +2382,29 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); } +#[test] +fn scoped_name_lookups_charge_for_every_scan_of_a_cached_list() { + for grouped in [false, true] { + let (mut s, a, b) = doc(); + if grouped { + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + let scope = if grouped { "app.activeDocument.groupItems[0]" } else { "app.activeDocument.layers[0]" }; + run(&mut s, &format!("{scope}.pageItems[0].name = 'target';")).unwrap(); + let mut costs = Vec::new(); + for key in ["0", "'target'"] { + let mut calls = Vec::new(); + for lookups in [1, 2] { + let r = run(&mut s, &format!("var p = {scope}.pageItems; p.length; for (var i = 0; i < {lookups}; i++) p.index({key});")).unwrap(); + calls.push(r["hostCalls"].as_u64().unwrap()); + } + costs.push(calls[1] - calls[0]); + } + assert!(costs[1] > costs[0], "{costs:?}"); + } +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); @@ -2397,6 +2420,30 @@ fn group_items_remove_all_refuses_locked_groups() { assert!(d.node(NodeId(g)).is_none() && d.node(a).is_none() && d.node(b).is_some()); } +#[test] +fn scoped_remove_all_clears_clipping_and_undo_restores_the_mask() { + for grouped in [false, true] { + let (mut s, a, b) = doc(); + let container = if grouped { + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + } else { + s.active().unwrap().doc.layer_containing(a).unwrap() + }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(container).unwrap().set_clips(true); + let scope = if grouped { "app.activeDocument.groupItems[0]" } else { "app.activeDocument.layers[0]" }; + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + run(&mut s, &format!("var c = {scope}; c.pageItems.removeAll(); c.groupItems.add();")).unwrap(); + let n = s.active().unwrap().doc.node(container).unwrap(); + assert!(!n.clips()); + assert_eq!(n.children().unwrap().len(), 1); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before); + } +} + #[test] fn new_group_command_checks_its_parent() { let (mut s, a, _) = doc(); @@ -2510,6 +2557,42 @@ fn the_report_gives_the_active_artboard_the_run_leaves() { assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); } +#[test] +fn inserting_before_the_default_active_artboard_preserves_its_id_and_origin() { + { + let (mut s, _, _) = doc(); + let original = s.active().unwrap().doc.artboards[0].id; + assert!(s.active().unwrap().active_artboard.is_none()); + let r = run( + &mut s, + "var A = app.activeDocument.artboards; app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + var before = A[0].artboardRect; A.insert([800, 0, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex()); vc.log(before); vc.log(A[1].artboardRect);", + ) + .unwrap(); + assert_eq!(s.active().unwrap().active_artboard, Some(original)); + assert_eq!(r["log"][0], 1); + assert_eq!(r["log"][1], r["log"][2]); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + } +} + +#[test] +fn the_report_gives_the_active_artboard_shift_in_a_document_created_during_the_run() { + let mut s = Session::new(); + let r = run( + &mut s, + "var d = app.documents.add(DocumentColorSpace.RGB, 100, 100);\ + var original = d.artboards[0]; d.artboards.insert([200, 0, 300, -100], 0);\ + vc.log(d.artboards.getActiveArtboardIndex()); vc.log(d.artboards[1].name === original.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!([1, true])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + let st = s.active().unwrap(); + assert_eq!(st.active_artboard, Some(st.doc.artboards[1].id)); +} + #[test] fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_perspective.rs b/crates/engine/src/tests/script_dom_perspective.rs index c0c1bdbc80..b53f66d4cd 100644 --- a/crates/engine/src/tests/script_dom_perspective.rs +++ b/crates/engine/src/tests/script_dom_perspective.rs @@ -48,6 +48,31 @@ fn show_and_hide_change_the_view_without_an_undo_step() { assert_eq!(undo_steps(&s), before); } +#[test] +fn grid_view_migrates_legacy_attachments_without_an_undo_step() { + use vectorcraft_tools::distort::perspective::{self as persp, PerspectiveGrid, Plane}; + + for (call, edit) in [("showPerspectiveGrid", false), ("hidePerspectiveGrid", false), ("showPerspectiveGrid", true), ("hidePerspectiveGrid", true)] + { + let mut s = doc(); + let made = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + let id = NodeId(made["id"].as_u64().unwrap()); + let st = s.doc_mut().unwrap(); + let d = std::sync::Arc::make_mut(&mut st.doc); + let mut g = PerspectiveGrid::current(d); + g.visible = call == "hidePerspectiveGrid"; + g.attached.insert(id.0.to_string(), Plane::Right); + d.unknown.insert(persp::DOC_KEY.into(), serde_json::to_value(&g).unwrap()); + let before = undo_steps(&s); + let draw = if edit { "vc.run('shape.rectangle', {x: 50, y: 50, width: 10, height: 10});" } else { "" }; + run(&mut s, &format!("app.activeDocument.{call}(); {draw}")).unwrap(); + assert_eq!(undo_steps(&s), before + usize::from(edit)); + let d = &s.active().unwrap().doc; + assert_eq!(PerspectiveGrid::current(d).attachment_of(d, id), Some((Plane::Right, 0.0))); + assert!(d.node(id).unwrap().extras().perspective.is_some()); + } +} + #[test] fn grid_view_commands_in_a_run_add_no_undo_step_but_an_edit_still_does() { let mut s = doc(); @@ -276,6 +301,20 @@ fn get_preset_settings_given_back_to_add_document_makes_the_same_document() { } } +#[test] +fn pixel_preview_preset_settings_can_be_given_back_to_add_document() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "previewMode": "pixel"})).unwrap(); + let out = log( + &mut s, + "var p = app.getPresetSettings('Print'); vc.log(p.previewMode === undefined);\ + var a = app.documents.addDocument('Print'); var b = app.documents.addDocument('Print', p);\ + vc.log([a.width, a.height, a.documentColorSpace]); vc.log([b.width, b.height, b.documentColorSpace]);", + ); + assert_eq!(out[0], json!(true)); + assert_eq!(out[1], out[2]); +} + #[test] fn startup_presets_list_names_presets_add_document_takes() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index dd31cd0e06..f707d0b75f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3167,7 +3167,8 @@ through `$`: document from that preset starts with, which `addDocument` takes back unchanged. It leaves out `units` when the preset's units are not one of the six `RulerUnits` values a new document takes, `rasterResolution` when the preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100 - artboards, and `artboardRowsOrCols` alone for a grid by column that no row count lays out the same, so + artboards, `previewMode` when the preset uses Pixel Preview, and `artboardRowsOrCols` alone for a grid by + column that no row count lays out the same, so `addDocument` with the same preset keeps the preset's own. `startupPresetsList` is a read-only array of the startup preset names, each of which `addDocument` and `getPresetSettings` take: `Print`, `Web`, `Mobile`, `Film & Video`, `Art & Illustration`, `Branding`, `Social`, `Basic CMYK` and `Basic RGB`, in that order, so From eae7c8318f37e4823dbad0354eb1d2677b811f06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:43:51 -0800 Subject: [PATCH 14/19] Scripts: layer loops list once, clipped and Artboards.insert follow the help pages - A Layers object keeps its list of layers while the document is unchanged, so a loop over layers.length and layers[i] lists them once. - GroupItem.clipped refuses a change to a group in a hidden or locked layer or on a locked artboard, before the mask changes. - Artboards.insert returns undefined, as the Artboards help page describes; add still returns the new artboard. - docs/mcp.md: Row and Column do not use artboardRowsOrCols for placement. --- crates/engine/src/script/dom.rs | 9 +++++ crates/engine/src/script/dom/layers.rs | 52 ++++++++++++++++++++++---- crates/engine/src/tests/script_dom.rs | 44 +++++++++++++++++++++- docs/mcp.md | 7 ++-- 4 files changed, 100 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 64fc714b74..8d12f16a4f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -171,6 +171,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 @@ -211,6 +217,9 @@ 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 open document's uid and the index of its active artboard when the run started, and for diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3f16b07e2f..7eddf8bb1c 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -473,9 +473,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", &held_handle(h, doc.uid, id))) @@ -483,7 +518,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 { @@ -522,14 +557,14 @@ fn layers_at_position(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)))) + 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())) @@ -572,7 +607,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))?; let max = crate::cmd::layer::MAX_ROWS; if ids.len() > max { return Err(HostError::Range(format!("cannot delete more than {max} layers at once"))); @@ -916,6 +951,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))); } @@ -1305,12 +1341,14 @@ 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`. It returns nothing, as the +/// Artboards page describes (). 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 { @@ -1474,7 +1512,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("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("Artboard", &[("artboardRect", "Array"), ("index", "number")])), + ("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")])), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0c1f935e24..ca1091bcbf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1866,6 +1866,45 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { assert!(s.active().unwrap().doc.node(b).is_none()); } +/// `clipped` on a shown, unlocked group on a locked artboard throws and changes nothing; the same +/// value as the group has stays a no-op. +#[test] +fn clipped_refuses_a_group_on_a_locked_artboard() { + 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()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + run(&mut s, "app.activeDocument.groupItems[0].clipped = false;").unwrap(); + let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); + assert!(e.contains("locked artboard"), "{e}"); + assert!(!s.active().unwrap().doc.node(gid).unwrap().clips()); + assert_eq!(undo_steps(&s), steps); +} + +/// 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"); +} + /// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. #[test] fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { @@ -2607,10 +2646,11 @@ 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); vc.log(A.insert([0, -100, 100, -200], 0) === undefined); 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")]); + // `insert` returns nothing, as the Artboards page describes; `add` returns the new artboard. + assert_eq!(out, [json!("Artboard 3"), json!(true), json!("Artboard 4"), json!("Artboard 5")]); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 12456d9d2b..4542c9ffc3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2964,7 +2964,8 @@ through `$`: (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of - columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` + columns for `GridByRow` and `RLGridByRow`; `Row` and `RLRow` put every artboard in one row and `Column` puts + them in one column, without using it for placement), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` @@ -3119,9 +3120,9 @@ through `$`: (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/) + `clipped` runs `layer.clippingMask.toggle`; a change to a group on a locked artboard throws. `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 + `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, and returns `undefined`), `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 From cf81f627992b03f4a08cff301e1fdd859cbbd8b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:12:51 -0800 Subject: [PATCH 15/19] Scripts: compound pathItems are PathItems, clipped checks its clipping path, doScript follows inserted artboards - A compound path's `pathItems` is a `PathItems` object scoped to the compound path: it reads its paths, `parent` is the compound path, and the methods that make a path throw. `removeAll()` keeps the compound path, empty, as `remove()` of its last path does. `PathItems` gains `toString()`. - `GroupItem.clipped` throws when the path that would become the clipping path, or the clipping path it would release, is hidden or locked, before `layer.clippingMask.toggle` changes it. - After `artboards.add` or `insert` gives the active artboard another index, `app.doScript` steps act on that artboard at its new index. The Artboard tool's selection kept from the run's start is held by artboard id, so a Fit to Artwork Bounds or paste step acts on the same artboards after one is inserted or removed. - `Layer.opacity` runs no command only for the exact value its getter reports, as a page item's does. - `Layer.zOrderPosition` reads the kept list of layers and each layer's place in it, so a loop over the layers lists them once. - Tests: the Revert test compares the artboard's name with the saved one, and the `clipped` test reads `clipped` inside the script after the error. --- crates/engine/src/script/actions.rs | 26 ++-- crates/engine/src/script/dom.rs | 3 + crates/engine/src/script/dom/layers.rs | 120 ++++++++++++++--- crates/engine/src/script/dom/paths.rs | 33 +++++ crates/engine/src/script/mod.rs | 12 +- crates/engine/src/tests/script_actions.rs | 43 ++++++ crates/engine/src/tests/script_dom.rs | 124 +++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 5 +- docs/mcp.md | 13 +- 9 files changed, 337 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 28c98af3fc..f16cb3ada2 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -254,20 +254,30 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. // A document whose active artboard the run set with `setActiveArtboardIndex` plays on that - // artboard, and the Artboard tool's selection as the run started no longer holds for it. - let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !h.dom.active_artboards.borrow().contains(uid)); - let active: Vec<(u64, usize)> = { + // artboard, and the Artboard tool's selection as the run started no longer holds for it. One + // where `artboards.add` or `artboards.insert` moved the active artboard to another index plays + // on that artboard at its new index. The Artboard tool's selection is the artboards it held, + // at the indices they have now. + let (active, picks): (Vec<(u64, usize)>, Option<(u64, Vec)>) = { let moved = h.dom.active_artboards.borrow(); + let shifted = h.dom.boards_shifted.borrow(); let session = h.session.borrow(); - h.active_artboards + let doc = |uid: u64| session.documents().iter().find(|d| d.uid == uid); + let active = h + .active_artboards .iter() - .map(|&(uid, i)| match session.documents().iter().find(|d| d.uid == uid) { - Some(st) if moved.contains(&uid) => (uid, super::dom::active_artboard(st)), + .map(|&(uid, i)| match doc(uid) { + Some(st) if moved.contains(&uid) || shifted.contains(&uid) => (uid, super::dom::active_artboard(st)), _ => (uid, i), }) - .collect() + .collect(); + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !moved.contains(uid)).map(|(uid, ids)| { + let at = doc(*uid).map(|st| ids.iter().filter_map(|id| st.doc.artboards.iter().position(|ab| ab.id == *id)).collect()); + (*uid, at.unwrap_or_default()) + }); + (active, picks) }; - let start = Start { active: &active, picks, batch: s.artboard }; + let start = Start { active: &active, picks: 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 1b79fa783d..402e7c5a3f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -224,6 +224,9 @@ pub(super) struct State { layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, + /// The uids of the documents where `artboards.add` or `artboards.insert` gave the active + /// artboard another index. + pub(super) boards_shifted: RefCell>, /// Each open document's uid and the index of its active artboard when the run started, and for /// a document the run opened, the index before the run first added an artboard to it. pub(super) boards_at_start: RefCell>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index e27f59fd65..04debab36a 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -32,6 +32,8 @@ //! active artboard has another index at the end of the run, because artboards were inserted, //! removed or reordered before it. +use std::cell::OnceCell; +use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; @@ -65,6 +67,8 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, + /// Paths (`PathItem`): the `pathItems` of a compound path. + Path, } impl Kind { @@ -73,6 +77,7 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", + Kind::Path => "PathItems", } } @@ -81,6 +86,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"), } } } @@ -227,7 +233,8 @@ 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})) + // Only the exact number the getter reports counts as the same opacity, as for a page item. + set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4 == v, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { @@ -273,13 +280,19 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list of the layers beside it and each one's place in it are kept as +/// [`layers_listed`] keeps the list, so a loop over the layers reads them once. 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 (list, places) = layers_kept(h, st, st.doc.parent_of(id))?; + let places = places.get_or_init(|| { + #[cfg(test)] + super::LAYER_SCANS.with(|c| c.set(c.get() + list.len() as u64)); + list.iter().enumerate().map(|(i, l)| (*l, i)).collect() + }); + Ok::<_, HostError>(places.get(&id).map(|i| list.len() - i)) + })?; at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) } @@ -479,21 +492,28 @@ fn layer_list(d: &Document, parent: Option) -> Vec { } /// 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>); +/// level), the layers it listed then and, once a layer's place was asked for, each layer's index in +/// that list. +pub(super) type LayerList = (u64, Arc, Option, Rc>, 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>> { + layers_kept(h, st, parent).map(|(ids, _)| ids) +} + +/// The list [`layers_listed`] gives, with the index of each layer in it, which is built the first +/// time it is asked for. +fn layers_kept(h: &Host, st: &DocState, parent: Option) -> Result<(Rc>, Rc>>)> { { 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); + 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(); + let kept = (list.3.clone(), list.4.clone()); lists.push(list); - return Ok(ids); + return Ok(kept); } } let looked_at = match parent { @@ -507,8 +527,9 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result= ART_LISTS { lists.remove(0); } - lists.push((st.uid, st.doc.clone(), parent, ids.clone())); - Ok(ids) + let places = Rc::new(OnceCell::new()); + lists.push((st.uid, st.doc.clone(), parent, ids.clone(), places.clone())); + Ok((ids, places)) } fn layers_of(h: &Host, a: &[Data]) -> Answer { @@ -781,12 +802,17 @@ 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}"))); } + // A compound path whose members are cleared stays, empty, as it does after `remove()` of its last + // path. + let in_compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); if !ids.is_empty() { on_doc(h, doc.uid, true, |h| { for p in &masked { command(h, "layer.clippingMask.toggle", &json!({"id": p.0}))?; } - command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + let ids: Vec = ids.iter().map(|i| i.0).collect(); + let params = if in_compound { json!({"ids": ids, "keepEmpty": true}) } else { json!({"ids": ids}) }; + command(h, "edit.clear", ¶ms) })?; } Ok(Data::Undefined) @@ -852,10 +878,42 @@ 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())) +} + +/// The `PathItems` of a compound path: a `PathItems` object whose handle names the compound path. +/// `PathItems`' members hand over to the functions below when their handle names one +/// ([`is_scoped_paths`]). +fn compound_path_items(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(collection(h, Kind::Path, Some(item.id), item.doc.uid)) +} + +pub(super) fn is_scoped_paths(a: &[Data]) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PathItems" && handle.len() == 5) +} + +pub(super) fn paths_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Path) +} +pub(super) fn paths_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Path) +} +pub(super) fn paths_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Path) +} +pub(super) fn paths_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Path) +} +pub(super) fn paths_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Path) +} +pub(super) fn paths_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Path) +} +pub(super) fn paths_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Path) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -943,11 +1001,19 @@ fn group_clipped(h: &Host, a: &[Data]) -> Answer { } /// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the -/// clipping mask. The group keeps its id either way. +/// clipping mask. The group keeps its id either way. The path that becomes or stops being the +/// clipping path (the topmost object, or the bottom one while the group clips) must be shown and +/// unlocked, as the group must. 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))); + let (now, ok, mask) = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id); + let now = n.is_some_and(crate::doc::Node::clips); + let children = n.and_then(|n| n.children()).map_or(&[][..], Vec::as_slice); + let mask = if now { children.first() } else { children.iter().rev().find(|c| !c.is_ruler_guide()) }; + (now, editable(&st.doc, item.id), mask.map(|m| (m.id, editable(&st.doc, m.id)))) + }); if now == on { return Ok(Data::Undefined); } @@ -955,6 +1021,12 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } + if let Some((mask, mask_ok)) = mask { + super::refuse_protected_edit(h, Item { doc: item.doc, id: mask })?; + if !mask_ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: its clipping path {} is hidden or locked", item.id.0, mask.0))); + } + } on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; Ok(Data::Undefined) } @@ -977,7 +1049,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), collection_of("PathItems"))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_path_items), collection_of("PathItems"))]), _ => Vec::new(), } } @@ -1333,6 +1405,14 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + // The active artboard keeps its id; an artboard inserted before it gives it the next index, which + // the steps `app.doScript` plays then act on. + if with_doc(h, doc, |_, st| active_artboard(st)) != active { + let mut shifted = h.dom.boards_shifted.borrow_mut(); + if !shifted.contains(&doc.uid) { + shifted.push(doc.uid); + } + } Ok(board_ref(h, doc.uid, id)) } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 03ec3812a6..8f6929e35c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -395,27 +395,50 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } +/// The document of a document's `PathItems`. The `PathItems` of a compound path are read through +/// [`super::layers`], and they make no paths: each method that would make one throws. fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + if super::layers::is_scoped_paths(a) { + return Err(HostError::Error("a compound path's pathItems cannot make paths".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_paths(a) { + return super::layers::paths_typename(h, a); + } items_doc(h, a)?; Ok(Data::String("PathItems".into())) } +/// `toString()`: `[PathItems]`, a document's or a compound path's. +fn items_to_string(h: &super::Host, a: &[Data]) -> Answer { + items_typename(h, a)?; + Ok(Data::String("[PathItems]".into())) +} + fn items_length(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_length(h, a); + } let doc = items_doc(h, a)?; Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_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_paths(a) { + return super::layers::paths_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) }; @@ -423,6 +446,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_paths(a) { + return super::layers::paths_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| { @@ -434,6 +460,9 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(_) => match items_at(h, a)? { @@ -448,6 +477,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; @@ -1903,6 +1935,7 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", get(l, items_typename), typed("string")), + ("toString", method(l, items_to_string), 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/script/mod.rs b/crates/engine/src/script/mod.rs index 361a7e0e00..bbd00ecebe 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -827,9 +827,10 @@ struct Host { /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, /// The artboards the Artboard tool had selected in the active document as the run starts (two or - /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the - /// steps `app.doScript` plays read them here. - artboard_picks: Option<(u64, Vec)>, + /// more), by artboard id, with that document's uid. The run gives the tool fresh state, which + /// drops them, so the steps `app.doScript` plays read them here, at the indices those artboards + /// have when each step runs. + artboard_picks: Option<(u64, Vec)>, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -2235,7 +2236,10 @@ impl Session { } // The Artboard tool's selection, which the fresh tool state below drops. let picks = cmd::artboard_tool_picks(self); - let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); + let artboard_picks = self + .active() + .filter(|_| !picks.is_empty()) + .map(|d| (d.uid, picks.iter().filter_map(|i| d.doc.artboards.get(*i).map(|ab| ab.id)).collect())); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 396abbab4c..32dfb781b8 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -413,3 +413,46 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { s.execute("artboard.delete", &json!({"index": 2})).unwrap(); assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); } + +/// After the script inserts an artboard before the active one, a step that names no artboard acts +/// on the artboard that was active, at its new index, not on the artboard now at the old index. +#[test] +fn steps_follow_the_active_artboard_past_an_inserted_one() { + 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 boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 1); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with(&mut s, "app.activeDocument.artboards.insert([2000, 300, 2100, 200], 0); app.doScript('Fit', 'Set');", &actions); + let after = boards(&s); + assert_eq!(after.len(), 4); + assert_eq!(after[1], was[0], "the artboard now at the old index is left as it was"); + assert_ne!(after[2], was[1], "the artboard that was active fits the selection"); + assert_eq!(after[3], was[2]); +} + +/// The Artboard tool's selection as the run started stays on the same artboards after the script +/// inserts one before them: a Fit to Artwork Bounds step fits those artboards at their new indices. +#[test] +fn the_artboard_tools_selection_follows_its_artboards_past_an_inserted_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + log_with(&mut s, "app.activeDocument.artboards.insert([2000, 300, 2100, 200], 0); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards[1..], [art[0], was[1], art[2]], "the selected artboards fit their art"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 40b9b31513..5c9488874b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1936,11 +1936,12 @@ fn wrappers_go_stale_after_revert() { assert_eq!(log(&mut s, &source), vec![json!(stale), json!(2)], "{operation}"); } // An artboard read before the revert is stale too, although the loaded document has a board with its id. - let source = "var b = app.activeDocument.artboards[0]; b.name = 'changed'; vc.run('file.revert');\ - try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(app.activeDocument.artboards[0].name);"; + let source = "var b = app.activeDocument.artboards[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\ + try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(app.activeDocument.artboards[0].name); vc.log(saved);"; let out = log(&mut s, source); assert_eq!(out[0], json!("Stale artboard"), "{out:?}"); - assert_ne!(out[1], json!("wrong"), "{out:?}"); + assert_ne!(out[2], json!("changed"), "{out:?}"); + assert_eq!(out[1], out[2], "the revert gives the artboard the saved name: {out:?}"); } #[test] @@ -2011,12 +2012,54 @@ fn clipped_refuses_a_group_on_a_locked_artboard() { .unwrap(); let steps = undo_steps(&s); run(&mut s, "app.activeDocument.groupItems[0].clipped = false;").unwrap(); - let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); - assert!(e.contains("locked artboard"), "{e}"); + // The script reads `clipped` after the error, before the run's rollback could put a change back. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(g.clipped);", + ); + assert!(out[0].as_str().unwrap().contains("locked artboard"), "{out:?}"); + assert_eq!(out[1], json!(false), "{out:?}"); assert!(!s.active().unwrap().doc.node(gid).unwrap().clips()); assert_eq!(undo_steps(&s), steps); } +/// `clipped` on a shown, unlocked group throws and changes nothing when the path that would become +/// the clipping path, or the clipping path it would release, is locked. +#[test] +fn clipped_refuses_a_locked_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 top = s.active().unwrap().doc.node(gid).unwrap().children().unwrap().last().unwrap().id; + let set = |s: &mut Session, on: bool| { + let source = format!( + "var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {on}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);" + ); + log(s, &source) + }; + s.execute("object.setProps", &json!({"ids": [top.0], "locked": true})).unwrap(); + let paint = format!("{:?}", s.active().unwrap().doc.node(top).unwrap()); + let steps = undo_steps(&s); + let out = set(&mut s, true); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "{out:?}"); + assert_eq!(out[1], json!(false), "{out:?}"); + let now = s.active().unwrap().doc.node(gid).unwrap(); + assert!(!now.clips()); + assert_eq!(now.children().unwrap().last().unwrap().id, top, "the locked path stays on top"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(top).unwrap()), paint, "the locked path keeps its paint"); + assert_eq!(undo_steps(&s), steps); + // Releasing a clipping mask whose clipping path is locked is refused too. + s.execute("object.setProps", &json!({"ids": [top.0], "locked": false})).unwrap(); + assert_eq!(set(&mut s, true), [json!("ran"), json!(true)]); + let mask = s.active().unwrap().doc.node(gid).unwrap().children().unwrap()[0].id; + s.execute("object.setProps", &json!({"ids": [mask.0], "locked": true})).unwrap(); + let out = set(&mut s, false); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "{out:?}"); + assert_eq!(out[1], json!(true), "{out:?}"); +} + /// 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] @@ -2034,6 +2077,41 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// A loop that reads each layer's `zOrderPosition` lists the layers and their places once while the +/// document is unchanged. +#[test] +fn a_loop_over_layers_z_order_positions_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, z = []; for (var i = 0; i < L.length; i++) z.push(L[i].zOrderPosition); vc.log(z[0]); vc.log(z[z.length - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 3 * n, "{scans} nodes looked at for {n} layers"); +} + +/// Assigning a layer an opacity its getter would read back as another number runs the command, +/// though it is within 0.0001 of the opacity the layer has; the number the getter reports is a no-op. +#[test] +fn a_layers_opacity_is_set_unless_the_getter_already_reports_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.layers[0].opacity = 0;"); + let steps = undo_steps(&s); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = l.opacity; vc.log(l.opacity);"); + assert_eq!(out, [json!(0)]); + assert_eq!(undo_steps(&s), steps, "the opacity the getter reports runs no command"); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 0.00009; vc.log(l.opacity);"); + assert_eq!(out, [json!(0.0001)]); +} + /// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. #[test] fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { @@ -2633,6 +2711,42 @@ fn a_compound_paths_path_items_are_path_items() { assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); } +/// A compound path's `pathItems` is a `PathItems` object that lists the compound path's own paths: +/// it reads them, its `parent` is the compound path, and each method that would make a path throws +/// and makes none. +#[test] +fn a_compound_paths_path_items_list_its_paths_and_make_none() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 20.0, 10.0, 10.0); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "inner"})).unwrap(); + 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, c = d.compoundPathItems[0], p = c.pathItems, n = d.pathItems.length;\ + vc.log(p.parent === c); vc.log(p.getByName('inner').name);\ + try { p.rectangle(10, 10, 5, 5); vc.log('made'); } catch (e) { vc.log(e.message); }\ + try { p.add(); vc.log('made'); } catch (e) { vc.log(e.message); }\ + vc.log(p.length); vc.log(d.pathItems.length === n);", + ); + let refused = json!("a compound path's pathItems cannot make paths"); + assert_eq!(out, [json!(true), json!("inner"), refused.clone(), refused, json!(2), json!(true)]); +} + +/// `compound.pathItems.removeAll()` deletes the compound path's paths and keeps the compound path, +/// empty, as `remove()` of its last path does. +#[test] +fn removing_all_of_a_compound_paths_paths_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let out = + log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length); vc.log(c.typename);"); + assert_eq!(out, [json!(0), json!("CompoundPathItem")]); + assert!(s.active().unwrap().doc.node(NodeId(c)).is_some()); + assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); +} + #[test] fn a_layers_and_a_compound_paths_items_answer_index_and_to_string() { 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 f806a607d1..d0fa17f497 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -183,7 +183,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 391081ce60..f4795cc55f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3158,7 +3158,9 @@ through `$`: `compoundPathItems` and a layer's or group's `pageItems` list art topmost first, as the document's `pageItems` does. 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 + are a `PathItems` object that lists its paths: `length`, `[i]`, `index(key)`, `getByName(name)`, `parent` (the + compound path), `toString()` and `removeAll()`, which keeps the compound path, empty. Its methods that make a path + throw an error. `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. @@ -3166,7 +3168,8 @@ through `$`: 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. A hidden or locked object that would become the clipping + path, or a hidden or locked clipping path that `false` would release, throws. `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 @@ -3626,8 +3629,10 @@ 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, 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 - Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + past the end. After `artboards.add` or `insert` gives the active artboard another index, such a step acts on that + artboard at its new index. 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 artboards, at the indices they have when the step runs, 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 one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have From a57173accc63373a4b384872a70a9c49a17c4c4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:54:23 -0800 Subject: [PATCH 16/19] ROADMAP: M13 lists the layers, artboards, perspective grid and startup presets scripts have The M13 row lists layers, groups, compound paths and artboards, the perspective grid, `app.getPresetSettings` and `app.startupPresetsList` among what scripts have, and no longer lists layers and artboards as remaining. --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index f669559fd2..3f616c0110 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -209,7 +209,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, 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 | +| 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, its stories and threaded frames, its layers, groups, compound paths and artboards, and its perspective grid, read the startup presets with `app.getPresetSettings` and `app.startupPresetsList`, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (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); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 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 e4e77b422c3b6f910fe1312d52ba7d45fad9478a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:19:24 -0800 Subject: [PATCH 17/19] Scripts: name the artboard and layer-position types clippy flags as complex Clippy's type_complexity lint stopped the gate on the tuple types in doScript's artboard step and the kept layer list. The types get names (ActiveBoards, BoardPicks, LayerPositions); nothing else changes. --- crates/engine/src/script/actions.rs | 7 ++++++- crates/engine/src/script/dom/layers.rs | 7 +++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index f16cb3ada2..490bb3863c 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -27,6 +27,11 @@ use vectorcraft_js::{Data, HostError, HostMember}; use super::{Host, Link, command, current, refused_to_scripts}; +/// Each open document's uid with the artboard index a run plays on. +type ActiveBoards = Vec<(u64, usize)>; +/// A document's uid with the indices of the artboards the Artboard tool holds. +type BoardPicks = Option<(u64, Vec)>; + /// The most actions a run's request may carry. pub const MAX_ACTIONS: usize = 4096; /// The most steps one action may have, after a `command.batch` step gives its own steps. @@ -258,7 +263,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // where `artboards.add` or `artboards.insert` moved the active artboard to another index plays // on that artboard at its new index. The Artboard tool's selection is the artboards it held, // at the indices they have now. - let (active, picks): (Vec<(u64, usize)>, Option<(u64, Vec)>) = { + let (active, picks): (ActiveBoards, BoardPicks) = { let moved = h.dom.active_artboards.borrow(); let shifted = h.dom.boards_shifted.borrow(); let session = h.session.borrow(); diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 04debab36a..b69fb2a6e3 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -494,7 +494,10 @@ fn layer_list(d: &Document, parent: Option) -> Vec { /// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top /// level), the layers it listed then and, once a layer's place was asked for, each layer's index in /// that list. -pub(super) type LayerList = (u64, Arc, Option, Rc>, Rc>>); +pub(super) type LayerList = (u64, Arc, Option, Rc>, LayerPositions); + +/// Each layer's index in a kept list, built the first time it is asked for. +pub(super) type LayerPositions = 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 @@ -505,7 +508,7 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result) -> Result<(Rc>, Rc>>)> { +fn layers_kept(h: &Host, st: &DocState, parent: Option) -> Result<(Rc>, LayerPositions)> { { 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); From c4ba200e9a2fe8fc15245ec99f695c8a9277b4fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:13:56 -0800 Subject: [PATCH 18/19] Scripts: played steps follow the active artboard after the script adds or removes one A script that removed or inserted an artboard before the active one left the steps app.doScript plays on the index the run started with, so an Align to Artboard step acted on a different artboard than getActiveArtboardIndex() and the run's report gave. Adding, inserting or removing an artboard through artboards or Artboard.remove() now makes playback use the active artboard by id, as setActiveArtboardIndex does, which also follows an undo inside the run. - The locked-artboard removeAll test reads the collections' lengths inside the run after catching the refusal, so a delete before the refusal fails it. - layer.setProps and docs/mcp.md give dimImages: true as 50%. - docs/mcp.md says artboards.insert reorders only when the new artboard is not already at the index, and describes the playback rule. - The Document.views progress line no longer says Type is missing. --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/script/actions.rs | 4 +-- crates/engine/src/script/dom.rs | 3 +- crates/engine/src/script/dom/layers.rs | 26 ++++++++++------ crates/engine/src/tests/script_actions.rs | 36 +++++++++++++++++++++++ crates/engine/src/tests/script_dom.rs | 12 +++++++- docs/mcp.md | 18 +++++++----- docs/target-app-parity.md | 4 +-- 8 files changed, 81 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 469ff2721e..77b1ad4755 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|true (50)|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step, and none when every row already has every option given", has_doc, set_props ), diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 8728bd76fb..d1e4088eee 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -253,8 +253,8 @@ 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. - // A document whose active artboard the script chose uses that choice, not the one the run - // started with. + // A document whose active artboard the script chose, or whose artboards the script added or + // removed, uses its active artboard by id, not the index the run started with. let chosen = h.session.borrow().active().and_then(|st| { h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; Some((st.uid, super::dom::active_artboard(st))) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2a82bfe3cb..e8559e3cd9 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -238,7 +238,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 revert generation when `setActiveArtboardIndex` last chose it. + /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose its active + /// artboard, or the script last added or removed one of its artboards. 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)>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..433cd9c805 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1289,6 +1289,7 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { 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})))?; + follow_active_board(h, b.doc.uid); Ok(Data::Undefined) } @@ -1401,6 +1402,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + follow_active_board(h, doc.uid); Ok(board_ref(h, doc.uid, id)) } @@ -1423,9 +1425,23 @@ fn boards_remove(h: &Host, a: &[Data]) -> Answer { 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})))?; + follow_active_board(h, doc.uid); Ok(Data::Undefined) } +/// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays +/// act on the document's active artboard by id, at the index the run's report gives it, as after +/// `setActiveArtboardIndex`, until the document is reverted. +fn follow_active_board(h: &Host, uid: u64) { + let reverts = reverts_of(h, uid); + let mut chosen = h.dom.chosen_artboards.borrow_mut(); + if let Some((_, generation)) = chosen.iter_mut().find(|(u, _)| *u == uid) { + *generation = reverts; + } else { + chosen.push((uid, reverts)); + } +} + 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))) @@ -1444,15 +1460,7 @@ 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(); - 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, reverts)); - } - } + follow_active_board(h, doc.uid); // 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) { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index ea399d2fd2..eb9af77a70 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -338,6 +338,42 @@ fn steps_discard_the_chosen_artboard_after_revert() { assert_ne!(now[2], was[2], "playback uses the run's original index after revert"); } +/// An artboard the script removes or inserts moves the active artboard's index; its played steps act +/// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does, +/// also after an undo puts the artboards back. +#[test] +fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() { + let setup = |active: Option| { + 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(); + if let Some(i) = active { + make_active(&mut s, i); + } + (s, id) + }; + let actions = set(&[("Align", vec![json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}})])]); + let cases = [ + (Some(1), "A.remove(0);"), + (Some(1), "A[0].remove();"), + (Some(1), "A.insert([2000, 500, 2100, 400], 0);"), + (Some(1), "A.insert([2000, 500, 2100, 400], 2);"), + (Some(1), "A.remove(0); app.undo();"), + (None, "A.insert([2000, 500, 2100, 400], 0);"), + ]; + for (active, edit) in cases { + let (mut s, id) = setup(active); + let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');"); + let out = log_with(&mut s, &source, &actions); + let index = out[0].as_u64().unwrap() as usize; + let board = s.active().unwrap().doc.artboards[index].rect; + let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + assert_eq!(left, board.x0, "{active:?} {edit}"); + } +} + /// 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 73e44c2af7..77d6a72d68 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2334,6 +2334,11 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { lock(&mut s, true); let before = format!("{:?}", s.active().unwrap().doc.layers); let steps = undo_steps(&s); + // The lengths are read inside the run, after the refusal is caught, so a delete that ran before + // the refusal shows here even though a failed run would put the tree back. + let lengths = "vc.log([d.pageItems.length, d.layers[0].pageItems.length, d.groupItems.length, d.groupItems.length && d.groupItems[0].pageItems.length, \ + d.compoundPathItems.length]);"; + let counts = log(&mut s, &format!("var d = app.activeDocument; {lengths}")); for scope in [ "app.activeDocument.layers[0].pageItems", "app.activeDocument.layers[0].groupItems", @@ -2342,8 +2347,13 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", ] { - let err = failure(&mut s, &format!("{scope}.removeAll();")); + let out = log( + &mut s, + &format!("var d = app.activeDocument; try {{ {scope}.removeAll(); vc.log('ok'); }} catch (e) {{ vc.log(e.message); }} {lengths}"), + ); + let err = out[0].as_str().unwrap_or_default(); assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + assert_eq!(out[1..], counts[..], "{scope}: nothing is deleted before the refusal"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); assert_eq!(undo_steps(&s), steps, "{scope}"); } diff --git a/docs/mcp.md b/docs/mcp.md index c3a96d73f9..f63a7a1049 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3284,7 +3284,8 @@ through `$`: `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` and returns - the new artboard), `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, returns nothing; + the new artboard), `insert(artboardRect, index)` (runs `artboard.new`, and `artboard.reorder` only when the new artboard is not + already at `index`, so an index equal to the length appends it; 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`, @@ -3914,12 +3915,13 @@ through `$`: 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. 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, 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 + `setActiveArtboardIndex` on that document, or added, inserted or removed one of its artboards through `artboards` + or `Artboard.remove()`, it is the artboard `getActiveArtboardIndex()` gives: the artboard the script chose while + that artboard exists, otherwise the same fallback as script coordinates and the view use (the saved active artboard + if it still exists, otherwise index 0). An undo inside the run that puts artboards back moves it with them. File > + Revert discards the script's stored choice. Otherwise the step uses the index of the document's active artboard as + the run started: after steps or commands such as `artboard.delete` delete 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 @@ -8277,7 +8279,7 @@ and `layerRows`, the rows highlighted in the panel. `layer.selectAll {id}` and then `layer.setCurrent {id}`. - **Eye and lock**: `layer.setProps {ids?, visible?, locked?, name?}` for any rows, plus Layer Options for layers: `template` (also locks the layer and dims its images to 50% unless given), `printable`, `preview` (off: the layer - draws and is clicked in outline, Ctrl/Cmd-click its eye), `dimImages` (0–100, or false) and `color` (an index 0–26, + draws and is clicked in outline, Ctrl/Cmd-click its eye), `dimImages` (0–100, true for 50, or false) and `color` (an index 0–26, `#rrggbb` or a preset name; a hex color with an alpha part, `#rrggbbaa` or `#rgba`, is an error, and so it is in `layer.new` and `layer.newSublayer`). Several rows change in one undo step (a drag down the eye or lock column). When every row already has every option given, the call records no undo step. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 69a695c269..bfa548cb7f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,11 +1132,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.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`. + `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`. `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.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.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: `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 the script adds, inserts or removes an artboard, playback acts on the active artboard at the index `getActiveArtboardIndex()` gives. 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 570a7bfe6f067a410eb730d600cc41945d8fa667 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 01:42:03 -0800 Subject: [PATCH 19/19] Scripts: the active artboard stays active when the script adds or removes one before it Adding, inserting or removing an artboard from a script now keeps the artboard that was active before the change by its id, as setActiveArtboardIndex does, also when the script never chose one. Before, with no artboard chosen, an artboard inserted at index 0 became the active one, so later app.doScript steps acted on it. A stored id of a removed artboard no longer stops the fallback from being kept, and a document the run made is reported when its active artboard moves. The script run summary in docs/target-app-parity.md now says that showing or hiding a perspective grid and its active plane add no undo step. --- crates/engine/src/script/dom/layers.rs | 38 +++++++++++++++++++++++ crates/engine/src/tests/script_actions.rs | 5 ++- crates/engine/src/tests/script_dom.rs | 32 +++++++++++++++++++ docs/mcp.md | 6 ++-- docs/target-app-parity.md | 4 +-- 5 files changed, 80 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 341505da5f..0d6c200c27 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -1365,7 +1365,9 @@ fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { fn board_remove(h: &Host, a: &[Data]) -> Answer { let (b, i) = this_board(h, a)?; + let active = active_board_id(h, b.doc); on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + keep_active_board(h, b.doc.uid, active); follow_active_board(h, b.doc.uid); Ok(Data::Undefined) } @@ -1467,6 +1469,7 @@ 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 active = active_board_id(h, doc); let id = super::atomically(h, |h| { on_doc(h, doc.uid, true, |h| { let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; @@ -1483,6 +1486,7 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + keep_active_board(h, doc.uid, active); follow_active_board(h, doc.uid); Ok(board_ref(h, doc.uid, id)) } @@ -1505,11 +1509,45 @@ 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")?; + let active = active_board_id(h, doc); on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + keep_active_board(h, doc.uid, active); follow_active_board(h, doc.uid); Ok(Data::Undefined) } +/// The id and index of the artboard that is active in `doc` now, chosen or only the fallback. +fn active_board_id(h: &Host, doc: Doc) -> Option<(u32, usize)> { + with_doc(h, doc, |_, st| { + let i = active_artboard(st); + st.doc.artboards.get(i).map(|ab| (ab.id, i)) + }) +} + +/// Keeps artboard `id` active in document `uid` by its id when it is still there, as +/// `setActiveArtboardIndex` does, so an artboard added or removed before it moves its index +/// instead of making another artboard the active one. +/// A stored id of an artboard that is gone is replaced as well. In a document made during the run, +/// the index the artboard had before the change is recorded for the run's report, as the first +/// `setActiveArtboardIndex` records it. +fn keep_active_board(h: &Host, uid: u64, active: Option<(u32, usize)>) { + let Some((id, index)) = active else { return }; + { + let mut s = h.session.borrow_mut(); + let Some(st) = s.document_mut(uid) else { return }; + if !st.doc.artboards.iter().any(|ab| ab.id == id) { + return; + } + st.active_artboard = Some(id); + } + if !h.dom.boards_at_start.iter().any(|(u, _)| *u == uid) { + let mut made = h.dom.boards_chosen_in_new.borrow_mut(); + if !made.iter().any(|(u, _)| *u == uid) { + made.push((uid, index)); + } + } +} + /// After the script adds or removes an artboard in document `uid`, the steps `app.doScript` plays /// act on the document's active artboard by id, at the index the run's report gives it, as after /// `setActiveArtboardIndex`, until the document is reverted. diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index f7d78b4392..cf2010e7a1 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -340,7 +340,8 @@ fn steps_discard_the_chosen_artboard_after_revert() { /// An artboard the script removes or inserts moves the active artboard's index; its played steps act /// on the active artboard at the index `getActiveArtboardIndex()` gives, as the run's report does, -/// also after an undo puts the artboards back. +/// also after an undo puts the artboards back. The artboard that was active stays active, also when +/// none was chosen before the run. #[test] fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_before_it() { let setup = |active: Option| { @@ -365,12 +366,14 @@ fn steps_follow_the_active_artboard_after_the_script_removes_or_inserts_one_befo ]; for (active, edit) in cases { let (mut s, id) = setup(active); + let was = s.active().unwrap().doc.artboards[active.unwrap_or(0)].rect; let source = format!("var A = app.activeDocument.artboards; {edit} vc.log(A.getActiveArtboardIndex()); app.doScript('Align', 'Set');"); let out = log_with(&mut s, &source, &actions); let index = out[0].as_u64().unwrap() as usize; let board = s.active().unwrap().doc.artboards[index].rect; let left = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; assert_eq!(left, board.x0, "{active:?} {edit}"); + assert_eq!(board, was, "the artboard active before the edit stays active: {active:?} {edit}"); } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 020a49028c..7c7b07a101 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4577,6 +4577,38 @@ fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() { assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}"); } +/// Without a chosen artboard, an artboard inserted before the default active one moves it to the +/// next index, in an open document and in one the run makes, and the report gives that index. +#[test] +fn inserting_before_the_default_active_artboard_keeps_it() { + let (mut s, _, _) = doc(); + let first = s.active().unwrap().doc.artboards[0].id; + 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!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); + let r = run(&mut s, "var d = app.documents.add(); var A = d.artboards; 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}"); +} + +/// After the chosen artboard is removed, the artboard active in its place stays active when one is +/// inserted before it. +#[test] +fn inserting_before_the_fallback_after_the_chosen_artboard_is_removed_keeps_it() { + let (mut s, _, _) = doc(); + let r = run( + &mut s, + "var A = app.activeDocument.artboards; A.add([800, 300, 900, 100]); A.setActiveArtboardIndex(1); A.remove(1);\ + var was = A[A.getActiveArtboardIndex()].name; A.insert([1000, 300, 1100, 100], 0);\ + vc.log(A[A.getActiveArtboardIndex()].name == was);", + ) + .unwrap(); + assert_eq!(r["log"], json!([true]), "{r}"); +} + /// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard. #[test] fn artboards_insert_returns_nothing() { diff --git a/docs/mcp.md b/docs/mcp.md index c1f823f1a4..d5aa0d0835 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3362,8 +3362,10 @@ through `$`: change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because artboards were inserted, removed or reordered before it, and a document the run opened in which an artboard was - chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active - one. An index outside the list throws a + chosen, or whose active artboard ends at another index after artboards were added, inserted or removed before it. + The chosen artboard stays active when another is inserted before it, even if it was already the active + one. When the script adds, inserts or removes an artboard without having chosen one, the artboard active before + the change stays active. 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. `GroupItems.createFromFile` on a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bfd542a01c..0cca5398e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1114,7 +1114,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Variables: a type object holds one text variable. `variable.bind` and Make Text Dynamic refuse a second one and name the text variable the object has; a visibility variable can still share the object, and a document saved with two text variables on one object opens with both. - 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: 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; showing or hiding a perspective grid and choosing its active plane change only the view and add no undo step. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.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 the script adds, inserts or removes an artboard, playback acts on the active artboard at the index `getActiveArtboardIndex()` gives. After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document or adds, inserts or removes one of its artboards, untargeted paste and Fit to Artwork Bounds use the active artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `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 the script adds, inserts or removes an artboard, the artboard active before the change stays active, also when the script never chose one, and playback acts on it at the index `getActiveArtboardIndex()` gives. After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document or adds, inserts or removes one of its artboards, untargeted paste and Fit to Artwork Bounds use the active artboard instead of the Artboard tool's selection at the start of the run; 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. A line's menu copies that line or the selected range. `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`.