Merge pull request #9059 from dotCooCoo/feat/scripts-api-d11-perspective-presets

Scripts: documents show, hide and set their perspective grid, and app gives preset settings
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-05 06:34:26 -08:00
commit 5e108fd768
16 files changed
+929 -61

No files matched your search

+3 -1
View File
@@ -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<CommandSpec> {
vec![
@@ -24,6 +24,37 @@ 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();
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 == normalized_before
}
/// Change view state of the grid without an undo step.
pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> Result<PerspectiveGrid> {
let st = s.doc_mut()?;
+1 -1
View File
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+1 -1
View File
@@ -901,7 +901,7 @@ fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
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() }
}
}
+3 -2
View File
@@ -258,8 +258,9 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
// A document whose active artboard the script chose uses that choice, not the one the run
// started with, nor the Artboard tool's selection from the start of the run.
// 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, nor the
// Artboard tool's selection from the start of the run.
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)))
+26 -10
View File
@@ -106,6 +106,7 @@ mod images;
pub(super) mod layers;
mod matrix;
mod paths;
mod perspective;
pub mod preferences;
mod print;
mod raster_capture;
@@ -274,7 +275,8 @@ pub(super) struct State {
layer_lists: RefCell<Vec<layers::LayerList>>,
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
pub(super) active_artboards: RefCell<Vec<u64>>,
/// Each document's uid and 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<Vec<(u64, u64)>>,
/// Each open document's uid and the index of its active artboard when the run started.
pub(super) boards_at_start: Vec<(u64, usize)>,
@@ -1749,19 +1751,27 @@ fn docs_add_document_no_ui(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);
let fields = 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)),
];
hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?;
presets.push(fields);
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
@@ -3487,6 +3497,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
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 blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
realm.define_host_object("BlendModes", blend_modes)?;
variables::define_enums(realm)?;
@@ -3523,6 +3537,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
application.push(later(l, "Application", "beep"));
application.extend(perspective::application_members(l));
application.extend(preferences::app_members());
application.extend(matrix::app_members(l));
application.extend(clipboard::app_members(l));
@@ -3609,6 +3624,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(layers::document_members(l));
document.extend(perspective::document_members(l));
document.extend(variables::document_members(l));
document.extend(save_open::document_members(l));
document.extend(print::document_members(l));
+55 -9
View File
@@ -1401,7 +1401,10 @@ 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)
}
@@ -1513,6 +1516,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}))?;
@@ -1529,6 +1533,8 @@ 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))
}
@@ -1550,10 +1556,58 @@ 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.
fn follow_active_board(h: &Host, uid: u64) {
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
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)))
@@ -1572,15 +1626,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 = with_doc(h, doc, |_, st| st.reverts);
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) {
+277
View File
@@ -0,0 +1,277 @@
//! The perspective grid of a document and the New Document settings of a startup preset in the
//! script object model, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>
//! and <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> list them, with the values of
//! <https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/>.
//!
//! `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. 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
//! 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
//! (<https://web.archive.org/web/20170622004549/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/AI_ScriptGd.pdf>).
//! `INVALIDGRIDPLANETYPE` makes no plane active.
//! - `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 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. 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: `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.
use serde_json::json;
use vectorcraft_js::{Data, HostError};
use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane};
use super::{
Answer, Described, MAX_TEXT_BYTES, arg, get, later, method, named, num, on_doc, returns, startup_preset, text, this_doc, typed, with_doc,
};
use crate::script::{Host, Link};
type Result<T> = std::result::Result<T, HostError>;
/// The `PerspectiveGridType` values, with the grid kind (`perspective.grid.set`'s `kind`) of each.
const GRID_TYPES: &[(&str, Option<u8>)] = &[
("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<Option<u8>> {
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<Plane> {
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, without the objects attached to it.
fn grid(h: &Host, a: &[Data]) -> Result<(super::Doc, PerspectiveGrid)> {
let doc = this_doc(h, a)?;
Ok((doc, with_doc(h, doc, |_, st| PerspectiveGrid::current(&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<usize> {
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 built-in preset of the profile's
// category, which a saved preset of the same name does not replace, 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.unwrap_or_else(|| s.default_settings())
};
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 => Some("DefaultPreview"),
PreviewMode::Pixel => None,
PreviewMode::Overprint => Some("OverprintPreview"),
};
let item = |k: &str, v: Data| (k.to_string(), v);
let mut out = vec![
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("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.
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}"))));
}
super::add_preset(h, out)
}
/// 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(STARTUP_PRESETS.into_iter().map(text).collect()))
}
/// The members this module adds to `Document`'s.
pub(super) fn document_members(l: &Link) -> Vec<Described> {
let mut m = named(vec![
("showPerspectiveGrid", method(l, show_grid), returns("boolean", &[])),
("hidePerspectiveGrid", method(l, hide_grid), returns("boolean", &[])),
("getPerspectiveActivePlane", method(l, active_plane), returns("PerspectiveGridPlaneType", &[])),
("setActivePlane", method(l, set_active_plane), returns("boolean", &[("gridPlane", "PerspectiveGridPlaneType")])),
("selectPerspectivePreset", method(l, select_preset), returns("boolean", &[("gridType", "PerspectiveGridType"), ("presetName", "string")])),
]);
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<Described> {
let mut m = named(vec![
("getPresetSettings", method(l, preset_settings), returns("DocumentPreset", &[("preset", "string")])),
("startupPresetsList", get(l, startup_presets), typed("Array")),
]);
let missing = ["saveWorkspace", "switchWorkspace", "deleteWorkspace", "resetWorkspace", "loadColorSettings", "showPresets"];
m.extend(missing.into_iter().map(|n| later(l, "Application", n)));
m
}
+6 -1
View File
@@ -2835,7 +2835,12 @@ 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.
// 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);
if changed {
+1
View File
@@ -188,6 +188,7 @@ mod script_dom;
mod script_dom_defaults;
mod script_dom_images;
mod script_dom_paths;
mod script_dom_perspective;
mod script_dom_prefs;
mod script_dom_resources;
mod script_dom_tracing;
+39
View File
@@ -338,6 +338,45 @@ 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. 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<usize>| {
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 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}");
}
}
/// 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]
+44 -3
View File
@@ -2804,6 +2804,11 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
s.execute("select.none", &json!({})).unwrap();
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",
@@ -2815,9 +2820,13 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
"app.activeDocument.groupItems.getByName('locked').pathItems",
"app.activeDocument.compoundPathItems[0].pathItems",
] {
// The error is caught, so the run keeps whatever `removeAll()` did before it threw.
let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);"));
assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}");
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}");
let doc = &s.active().unwrap().doc;
@@ -5190,6 +5199,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() {
@@ -0,0 +1,361 @@
//! 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<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
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_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();
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_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();
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.numArtboards); 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);",
);
// A saved preset with the built-in preset's name changes neither the settings nor the document.
assert_eq!(out[..2], [json!(1), json!(true)]);
assert_eq!(out[2], out[3]);
assert_eq!(out[2].as_array().map(Vec::len), Some(1));
assert_eq!(out[4], json!(true));
for (artboards, layout) in [
(6, json!({"layout": "gridByColumn", "columns": 4})),
(150, json!({"layout": "gridByRow", "columns": 12})),
(7, json!({"layout": "gridByRow", "columns": 3, "rightToLeft": 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);\
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[0], json!(1), "{artboards} {layout}");
assert_eq!(out[1].as_array().map(Vec::len), Some(1), "{layout}");
assert_eq!(out[1], out[2], "{artboards} {layout}");
}
}
#[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);\
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]);",
);
// The saved preset's Pixel Preview does not replace the built-in preset's preview mode.
assert_eq!(out[0], json!("DocumentPreviewMode.DefaultPreview"));
assert_eq!(out[1], out[2]);
assert_eq!(out[1], json!([612, 792, "DocumentColorSpace.CMYK"]));
}
#[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();
// 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();
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..]) {
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();
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}");
}
}
@@ -58,10 +58,11 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
/// Copy does.
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. The perspective
/// grid preset files of `Document`, and the workspace methods, `loadColorSettings` and
/// `showPresets` of `Application`, throw "not available yet". Reading a preference changes nothing,
/// and the matrix functions return new records. `app.copy` and `app.cut` fill VectorCraft's
/// clipboard, which the desktop app offers to other apps after the run as Edit › Copy does.
const INSIDE: &[(&str, &str)] = &[
("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"),
("Window.", "__vcPaletteEvent alert confirm length prompt prototype"),
@@ -103,22 +104,22 @@ const INSIDE: &[(&str, &str)] = &[
CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \
PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \
RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \
View Views ZOrderMethod",
PathPointSelection PathPoints PerspectiveGridPlaneType PerspectiveGridType PlacedItem PlacedItems PluginItem PointType \
PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots \
StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint \
Symbols Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
),
("Application.", "prototype"),
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
printerList redo redraw selection selection= selectTool showColorPicker textFonts toString typename undo unloadAction \
unloadAction= \
userInteractionLevel \
userInteractionLevel=",
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut deleteWorkspace \
deleteWorkspace= documents doScript executeMenuCommand getIdentityMatrix getIsFileOpen getPresetSettings \
getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix isSingularMatrix loadAction \
loadAction= loadColorSettings loadColorSettings= open paste PPDFileList preferences printPresetsList printerList \
redo redraw resetWorkspace resetWorkspace= saveWorkspace saveWorkspace= selection selection= selectTool \
showColorPicker showPresets showPresets= startupPresetsList switchWorkspace switchWorkspace= textFonts toString \
typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
),
("Preferences.", "prototype"),
("Preferences.prototype.", "constructor getBooleanPreference getIntegerPreference getRealPreference getStringPreference typename"),
@@ -140,10 +141,13 @@ const INSIDE: &[(&str, &str)] = &[
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \
gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \
patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \
spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width",
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace \
exportPerspectiveGridPreset exportPerspectiveGridPreset= fullName getPerspectiveActivePlane gradients gradients= \
graphicStyles groupItems height hidePerspectiveGrid importPerspectiveGridPreset importPerspectiveGridPreset= \
layers name pageItems paragraphStyles parent path pathItems patterns patterns= placedItems rasterItems \
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selectPerspectivePreset selection selection= \
setActivePlane showPerspectiveGrid spots stories swatchGroups swatches symbolItems symbols tags textFrames \
toString typename views width",
),
("Views.", "prototype"),
("Views.prototype.", "constructor index length parent toString typename"),
@@ -300,6 +304,8 @@ const INSIDE: &[(&str, &str)] = &[
),
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"),
("PerspectiveGridPlaneType.", "GRIDFLOORPLANETYPE GRIDLEFTPLANETYPE GRIDRIGHTPLANETYPE INVALIDGRIDPLANETYPE"),
("PerspectiveGridType.", "InvalidPerspectiveGridType OnePointPerspectiveGridType ThreePointPerspectiveGridType TwoPointPerspectiveGridType"),
("PointType.", "CORNER SMOOTH"),
("PolarityValues.", "NEGATIVE POSITIVE"),
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
+52 -11
View File
@@ -3432,14 +3432,53 @@ 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. `insert`, `remove` and `setActiveArtboardIndex` throw a `RangeError` for an index outside the list. Reading
an index past the last artboard gives `undefined` from `artboards[i]` and throws `Not found` from
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. `insert`, `remove` and `setActiveArtboardIndex` throw a `RangeError` for an index outside
the list. Reading an index past the last artboard gives `undefined` from `artboards[i]` and throws `Not found` from
`artboards.index(i)`. `layers.index(n)` and `artboards.index(n)` on a collection whose document or layer is stale
throw its stale error for any number, a negative or fractional one included, before `Not found`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws
`Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an
error that says they are not available yet. `GroupItems.createFromFile` on a collection whose document, layer or
group was deleted throws `Stale page item` or `Stale document` first.
- 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 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, `rasterResolution` when the
preset's PPI is not 72, 150 or 300, `numArtboards` and `artboardRowsOrCols` when the preset has more than 100
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
`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.
`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.
- `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`;
default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group,
index 0 puts it directly above the clipping path; in an Image Trace object, index 0 is refused and changes nothing,
@@ -4170,14 +4209,16 @@ through `$`:
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, until the script calls
`setActiveArtboardIndex` on that document; after a revert discards that choice, the selection applies again. A step of a recorded `command.batch` step that
`setActiveArtboardIndex` on that document or adds, inserts or removes one of its artboards; after a revert discards
that choice, the selection applies again. 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
@@ -8858,7 +8899,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.
+4 -3
View File
@@ -1120,7 +1120,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.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. Raster width and height requests outside an effective scale of 0.01 to 64 pixels per point are rejected before the underlying export command writes output; files written by earlier exports in the same script call remain. SVG embeds raster images and rejects `RasterImageLocation.LINK`. `crates/engine/src/tests/script_screens.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: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips, and the same holds for a visible image or placed document whose frame encloses an area, unless deleting the paths makes a live geometry effect leave no clipping region where there was one before; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`.
@@ -1135,6 +1135,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: a document's 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: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. In a Shaper group, new empty groups and compound paths and turning clipping on are refused, since the group keeps its source art at the bottom. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
@@ -1142,12 +1143,12 @@ 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`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `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.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, converted through the profiles assigned to that document, while Cancel, and OK with both the color and its model unchanged, return a new object based on the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.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; once a script calls `setActiveArtboardIndex` on a document, untargeted paste and Fit to Artwork Bounds use that 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`.