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.
This commit is contained in:
dotCooCoo committed 2026-11-21 18:07:11 -08:00
1 parent 185517dac1
commit 9ffec7e72d
10 files changed
+607 -3

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,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<PerspectiveGrid> {
let st = s.doc_mut()?;
+1 -1
View File
@@ -801,7 +801,7 @@ pub fn find(s: &Session, name: &str) -> Option<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() }
}
}
+7
View File
@@ -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<Data>| {
@@ -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",
+252
View File
@@ -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 <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.
//!
//! 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` 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<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.
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<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 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
}
+5 -1
View File
@@ -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 {
+1
View File
@@ -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;
@@ -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<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_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}");
}
}
+26
View File
@@ -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
+1
View File
@@ -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`.