Scripts: PageItem translate, rotate, resize and transform move and reshape objects

A page item's translate(deltaX, deltaY, ...), rotate(angle, ...),
resize(scaleX, scaleY, ...) and transform(matrix, ...) run
object.transform on the object inside the run's transaction, so the run
keeps one undo step and the selection stays as it was. Offsets, angles
and matrices have Y up, rotate, resize and transform act about the
center of the geometric bounds or a Transformation point, and
positions, patterns, gradients and line widths follow their arguments.
Locked art, art on a locked artboard, a scale of 0, a singular matrix
and a result past the canvas throw an error and change nothing, and a
call that changes nothing runs no command.

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-25 01:56:17 -08:00
1 parent 0ce36a1b79
commit 35e27e2224
9 files changed
+484 -21

No files matched your search

+6 -4
View File
@@ -41,6 +41,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session};
mod clipboard;
mod matrix;
pub mod preferences;
mod transform;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
@@ -1834,6 +1835,7 @@ const ENUMS: &[(&str, &[&str])] = &[
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
("DocumentColorSpace", &["CMYK", "RGB"]),
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]),
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]),
@@ -1959,6 +1961,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("move", method(l, item_move)),
("remove", method(l, item_remove)),
("zOrder", method(l, item_z_order)),
("translate", method(l, transform::translate)),
("rotate", method(l, transform::rotate)),
("resize", method(l, transform::resize)),
("transform", method(l, transform::transform)),
]);
page_item.extend(
[
@@ -1976,10 +1982,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
"wrapOffset",
"wrapped",
"bringInPerspective",
"resize",
"rotate",
"transform",
"translate",
]
.into_iter()
.map(|m| later(l, "PageItem", m)),
+6 -6
View File
@@ -24,7 +24,7 @@ use vectorcraft_js::{Data, HostError, HostMember};
use super::{Answer, Host, Link, arg, method, named, num, text};
/// A matrix's six values: `[a, b, c, d, tx, ty]`.
type Matrix = [f64; 6];
pub(super) type Matrix = [f64; 6];
const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"];
@@ -59,7 +59,7 @@ fn record(m: Matrix) -> Answer {
}
/// The matrix argument `d`.
fn matrix(d: &Data, what: &str) -> std::result::Result<Matrix, HostError> {
pub(super) fn matrix(d: &Data, what: &str) -> std::result::Result<Matrix, HostError> {
let bad = || HostError::Type(format!("{what} must be a Matrix"));
let Data::Object(items) = d else { return Err(bad()) };
let mut m = [0.0; 6];
@@ -187,18 +187,18 @@ fn nearest(sums: &[Wide]) -> f64 {
v
}
fn translate(dx: f64, dy: f64) -> Matrix {
pub(super) fn translate(dx: f64, dy: f64) -> Matrix {
[1.0, 0.0, 0.0, 1.0, dx, dy]
}
/// A scale by `sx` and `sy` percent.
fn scaled(sx: f64, sy: f64) -> Matrix {
pub(super) fn scaled(sx: f64, sy: f64) -> Matrix {
[sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0]
}
/// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of
/// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it.
fn rotate(degrees: f64) -> Matrix {
pub(super) fn rotate(degrees: f64) -> Matrix {
let turn = degrees % 360.0;
let (sin, cos) = match turn {
0.0 => (0.0, 1.0),
@@ -357,7 +357,7 @@ fn determinant(m: Matrix) -> Wide {
products_difference(m[0], m[3], m[1], m[2])
}
fn singular(m: Matrix) -> bool {
pub(super) fn singular(m: Matrix) -> bool {
determinant(m).m == 0.0
}
+216
View File
@@ -0,0 +1,216 @@
//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the
//! help page <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describes them. Each one
//! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo
//! step for the document; a call that changes nothing runs no command.
//!
//! VectorCraft's own rules, which the help page does not state:
//! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever
//! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns
//! it counterclockwise.
//! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds,
//! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the
//! bottom-left corner of the first artboard. A matrix's own translation is added after it acts
//! about that point.
//! - Positions, pattern fills and pattern strokes, and gradients each follow their argument:
//! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles
//! preference. Fill and stroke patterns transform together, and gradients with the object, so a
//! call whose values differ, counting the defaults of the arguments it leaves out, throws an error
//! that says so.
//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own
//! scale in percent, the square root of the area it scales by (stroke weights and effects scale
//! with it, as Scale Strokes & Effects does); any other value throws an error that says so.
//! - A locked object, one inside a locked layer or group, a group that holds one, and an object on
//! a locked artboard are refused with nothing changed, and so are a scale of 0, a matrix whose
//! determinant is 0 and a transformation that would take the object past the canvas.
use serde_json::json;
use vectorcraft_geom::{Affine, Point, Rect};
use vectorcraft_js::{Data, HostError};
use super::matrix::{self, Matrix};
use super::{Answer, Coords, Host, Item, arg, coordinate, edit_item, frame, number, this_item, with_doc};
/// The error for an object on a locked artboard.
const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
/// The error for a locked object.
const LOCKED: &str = "cannot transform locked objects";
/// What a transform method changes besides the object's geometry.
struct Options {
/// Positions and orientations (`changePositions`, `transformObjects`).
objects: bool,
/// Pattern fills and strokes.
patterns: bool,
/// Stroke weights and effects (`changeLineWidths`).
strokes: bool,
}
/// An optional `true` or `false` argument.
fn flag(d: &Data, what: &str) -> std::result::Result<Option<bool>, HostError> {
match d {
Data::Undefined => Ok(None),
Data::Bool(b) => Ok(Some(*b)),
_ => Err(HostError::Type(format!("{what} must be true or false"))),
}
}
/// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after,
/// with the names the method gives them.
fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result<Options, HostError> {
let tiles = h.session.borrow().prefs.transform_pattern_tiles;
let objects = flag(arg(a, at), names[0])?.unwrap_or(true);
let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles);
let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true);
let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles);
if fill != stroke {
return Err(HostError::Error(format!("{} and {} with different values are not available yet", names[1], names[3])));
}
if gradients != objects {
return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0])));
}
Ok(Options { objects, patterns: fill, strokes: false })
}
/// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix.
fn line_widths(d: &Data, m: Matrix) -> std::result::Result<bool, HostError> {
let lw = match d {
Data::Undefined => return Ok(false),
d => number(d, "changeLineWidths")?,
};
let own = (m[0] * m[3] - m[1] * m[2]).abs().sqrt() * 100.0;
if (lw - own).abs() <= 1e-9 * own.max(1.0) {
return Ok((own - 100.0).abs() > 1e-9);
}
if (lw - 100.0).abs() <= 1e-9 {
return Ok(false);
}
Err(HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet")))
}
/// The point of `r` (document coordinates, Y down) that the `Transformation` value `d` names.
fn anchor(h: &Host, item: Item, r: Rect, d: &Data) -> std::result::Result<Point, HostError> {
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
let name = match d {
Data::Undefined => return Ok(Point::new(cx, cy)),
Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""),
_ => "",
};
Ok(match name {
"CENTER" => Point::new(cx, cy),
"TOPLEFT" => Point::new(r.x0, r.y0),
"TOP" => Point::new(cx, r.y0),
"TOPRIGHT" => Point::new(r.x1, r.y0),
"LEFT" => Point::new(r.x0, cy),
"RIGHT" => Point::new(r.x1, cy),
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
"BOTTOM" => Point::new(cx, r.y1),
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?,
_ => return Err(HostError::Type("the point to transform about must be a Transformation value".into())),
})
}
/// The matrix `m` (Y up) as it acts on the page (Y down), about `o`.
fn on_page(m: Matrix, o: Point) -> Affine {
let [a, b, c, d, tx, ty] = m;
let page = Affine::new([a, 0.0 - b, 0.0 - c, d, tx, 0.0 - ty]);
Affine::translate(o.to_vec2()) * page * Affine::translate(-o.to_vec2())
}
/// Applies `m` (Y up) to the item `this` names, about the point `about` names (`None`: the matrix
/// acts as a move, which needs no point), with `opts`.
fn apply(h: &Host, a: &[Data], m: Matrix, about: Option<&Data>, opts: &Options) -> Answer {
let item = this_item(h, a)?;
if m.iter().any(|v| !v.is_finite()) {
return Err(HostError::Range("the transformation has a value too large for a number".into()));
}
if matrix::singular(m) {
return Err(HostError::Error("the transformation is singular and would flatten the object".into()));
}
let (locked, on_locked, bounds, uses_pattern) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let mut locked = d.ancestry(item.id).is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked)));
let mut uses = false;
if let Some(n) = d.node(item.id) {
n.walk(&mut |c| {
locked |= c.locked;
uses |= vectorcraft_doc::pattern::uses_pattern(c, None);
});
}
(locked, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses)
});
if locked {
return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0)));
}
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
let o = match (about, bounds) {
(Some(d), Some(r)) => anchor(h, item, r, d)?,
(Some(_), None) => return Err(HostError::Error("the object has no bounds".into())),
(None, _) => Point::ORIGIN,
};
let xf = on_page(m, o);
if let Some(r) = bounds.filter(|_| opts.objects) {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)];
if corners.iter().map(|p| xf * *p).any(|p| !(p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD)) {
return Err(HostError::Range("the transformation would take the object past the canvas".into()));
}
}
let c = xf.as_coeffs();
let identity = c.iter().zip([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).all(|(v, i)| (v - i).abs() <= 1e-12);
let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity };
if changes {
let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes});
edit_item(h, item, "object.transform", &p)?;
}
Ok(Data::Undefined)
}
/// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?,
/// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out).
pub(super) fn translate(h: &Host, a: &[Data]) -> Answer {
let delta = |i: usize, what: &str| match arg(a, i) {
Data::Undefined => Ok(0.0),
d => coordinate(d, what),
};
let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?);
let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"];
let opts = options(h, a, 3, names)?;
apply(h, a, matrix::translate(dx, dy), None, &opts)
}
const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"];
/// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?,
/// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive.
pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer {
let angle = number(arg(a, 1), "angle")?;
let opts = options(h, a, 2, CHANGE_NAMES)?;
apply(h, a, matrix::rotate(angle), Some(arg(a, 6)), &opts)
}
/// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?,
/// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and
/// `scaleY` percent along the page's axes.
pub(super) fn resize(h: &Host, a: &[Data]) -> Answer {
let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?);
if sx == 0.0 || sy == 0.0 {
return Err(HostError::Range("scaleX and scaleY must not be 0".into()));
}
let m = matrix::scaled(sx, sy);
let mut opts = options(h, a, 3, CHANGE_NAMES)?;
opts.strokes = line_widths(arg(a, 7), m)?;
apply(h, a, m, Some(arg(a, 8)), &opts)
}
/// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?,
/// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the
/// object.
pub(super) fn transform(h: &Host, a: &[Data]) -> Answer {
let m = matrix::matrix(arg(a, 1), "transformationMatrix")?;
let mut opts = options(h, a, 2, CHANGE_NAMES)?;
opts.strokes = line_widths(arg(a, 6), m)?;
apply(h, a, m, Some(arg(a, 7)), &opts)
}
+1
View File
@@ -174,6 +174,7 @@ mod script_dialogs;
mod script_dollar;
mod script_dom;
mod script_dom_prefs;
mod script_dom_transform;
mod script_engines;
mod script_folder;
mod script_include;
+5 -3
View File
@@ -700,9 +700,11 @@ fn a_startup_preset_alone_gives_its_first_size() {
#[test]
fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
let (mut s, _, _) = doc();
for source in
["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"]
{
for source in [
"app.activeDocument.pageItems[0].blendingMode;",
"app.activeDocument.pageItems[0].uuid = 'x';",
"app.activeDocument.pageItems[0].bringInPerspective(0, 0);",
] {
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
}
assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet"));
@@ -0,0 +1,220 @@
//! The script object model: a page item's `translate`, `rotate`, `resize` and `transform`.
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 rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
/// A 400 × 300 pt document with a 30 × 40 pt rectangle and a 50 × 50 pt one above it.
fn doc() -> (Session, NodeId, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
(s, a, b)
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
/// The numbers of a logged array, or a logged number as one.
fn numbers(v: &Value) -> Vec<f64> {
match v.as_array() {
Some(a) => a.iter().map(|n| n.as_f64().unwrap()).collect(),
None => vec![v.as_f64().unwrap()],
}
}
fn close(a: &[f64], b: &[f64]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6)
}
#[test]
fn translate_moves_by_the_offsets_with_y_up_in_one_undo_step() {
let (mut s, a, _) = doc();
let steps = undo_steps(&s);
let out = log(
&mut s,
"var i = app.activeDocument.pageItems[0]; var l = i.left, t = i.top;\
i.translate(10, 0); vc.log([i.left - l, i.top - t]);\
i.translate(0, 10); vc.log([i.left - l, i.top - t]);\
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var t2 = i.top;\
i.translate(0, 5); vc.log(i.top - t2);",
);
assert!(close(&numbers(&out[0]), &[10.0, 0.0]), "{out:?}");
assert!(close(&numbers(&out[1]), &[10.0, 10.0]), "{out:?}");
// With Y down from the artboard's top, a move up reads as a smaller top.
assert!(close(&numbers(&out[2]), &[-5.0]), "{out:?}");
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
s.execute("edit.undo", &json!({})).unwrap();
let r = s.active().unwrap().doc.bounds_of(&[a], false).unwrap();
assert!(close(&[r.x0, r.y0], &[10.0, 20.0]), "{r:?}");
}
#[test]
fn rotate_turns_counterclockwise_about_the_center_or_the_named_point() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let out = log(
&mut s,
"var g = app.activeDocument.pageItems[0], r = g.geometricBounds; vc.log(g.typename);\
vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);\
g.rotate(90); r = g.geometricBounds; vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);",
);
assert_eq!(out[0], json!("GroupItem"));
let (before, after) = (numbers(&out[1]), numbers(&out[2]));
// The width and height trade places, and the center stays.
assert!(close(&after, &[before[1], before[0], before[2], before[3]]), "{before:?} {after:?}");
// A positive angle about the bottom-left corner swings a rectangle to the left of that corner.
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var i = app.activeDocument.pageItems[0]; vc.log(i.geometricBounds);\
i.rotate(90, true, true, true, true, Transformation.BOTTOMLEFT); vc.log(i.geometricBounds);",
);
let (b0, b1) = (numbers(&out[0]), numbers(&out[1]));
// [left, top, right, bottom], Y up: the 30 pt wide side now stands up, and the 40 pt tall side
// lies to the left.
assert!(close(&b1, &[b0[0] - 40.0, b0[3] + 30.0, b0[0], b0[3]]), "{b0:?} {b1:?}");
}
#[test]
fn resize_scales_about_the_center_and_line_widths_follow_their_argument() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, i = p[0], j = p[1];\
function stroke(o) { return (o.visibleBounds[2] - o.visibleBounds[0]) - o.width; }\
var r = i.geometricBounds, s0 = stroke(i); i.resize(50, 50); var q = i.geometricBounds;\
vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3]), stroke(i) - s0]);\
var s1 = stroke(j); j.resize(50, 50, true, true, true, true, 50); vc.log([s0, stroke(j) / s1]);",
);
let first = numbers(&out[0]);
assert!(close(&first, &[15.0, 20.0, 0.0, 0.0, 0.0]), "{first:?}");
let second = numbers(&out[1]);
assert!(second[0] > 0.0, "the rectangles have a stroke: {second:?}");
assert!(close(&second[1..], &[0.5]), "{second:?}");
// A line width that is neither 100 nor the scale itself is refused.
let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(50, 50, true, true, true, true, 70);");
assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}");
}
#[test]
fn transform_applies_a_matrix_record_about_the_center() {
let (mut s, _, _) = doc();
let steps = undo_steps(&s);
let out = log(
&mut s,
"var i = app.activeDocument.pageItems[0], r = i.geometricBounds;\
i.transform(app.getRotationMatrix(45)); var q = i.geometricBounds;\
vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3])]);\
var l = i.left; i.transform(app.getTranslationMatrix(5, 0)); vc.log(i.left - l);",
);
let side = 70.0 / 2f64.sqrt();
assert!(close(&numbers(&out[0]), &[side, side, 0.0, 0.0]), "{out:?}");
assert!(close(&numbers(&out[1]), &[5.0]), "{out:?}");
assert_eq!(undo_steps(&s), steps + 1);
}
#[test]
fn transforms_that_change_nothing_add_no_undo_step() {
let (mut s, _, _) = doc();
let steps = undo_steps(&s);
log(
&mut s,
"var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\
i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\
i.translate(7000000, 0, false, false, false, false);",
);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn locked_art_and_art_on_a_locked_artboard_are_refused() {
let (mut s, a, b) = doc();
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
for call in ["translate(5, 0)", "rotate(30)", "resize(50, 50)", "transform(app.getScaleMatrix(200))"] {
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0]; i.locked = true; i.{call};"));
assert!(e.contains(&format!("cannot transform locked objects: {}", a.0)), "{call}: {e}");
}
assert_eq!(undo_steps(&s), steps);
assert_eq!(*s.active().unwrap().doc, *before);
// A group that holds a locked object is refused too.
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
let (before, steps) = (s.active().unwrap().doc.clone(), undo_steps(&s));
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(5, 0);");
assert!(e.contains("cannot transform locked objects"), "{e}");
assert_eq!(undo_steps(&s), steps);
assert_eq!(*s.active().unwrap().doc, *before);
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let e = failure(&mut s, "app.activeDocument.pageItems[1].rotate(45);");
assert!(e.contains("cannot transform objects on a locked artboard"), "{e}");
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn bad_arguments_throw_and_change_nothing() {
let (mut s, _, _) = doc();
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
for (call, says) in [
("rotate('x')", "angle must be a finite number"),
("rotate()", "angle must be a finite number"),
("resize(50)", "scaleY must be a finite number"),
("resize(0, 50)", "must not be 0"),
("transform({})", "transformationMatrix must be a Matrix"),
("transform(app.getScaleMatrix(0))", "singular"),
("translate(1, 0, 'yes')", "transformObjects must be true or false"),
("translate(7000000, 0)", "past the canvas"),
("translate('x')", "deltaX must be a finite number"),
("translate(NaN)", "is not a finite number"),
("rotate(5, true, false, false)", "changeFillGradients different from changePositions"),
("rotate(5, true, true, true, false)", "changeFillPatterns and changeStrokePattern"),
// Left out, the stroke pattern follows the Transform Pattern Tiles preference (off), and
// gradients default to true.
("rotate(5, true, true)", "changeFillPatterns and changeStrokePattern"),
("translate(10, 0, false)", "transformFillGradients different from transformObjects"),
("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"),
("rotate(5, true, true, true, true, 3)", "Transformation value"),
("resize(1e9, 1e9)", "past the canvas"),
] {
let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};"));
assert!(e.contains(says), "{call}: {e}");
}
assert_eq!(undo_steps(&s), steps);
assert_eq!(*s.active().unwrap().doc, *before);
// A deleted object is stale before its arguments are used.
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.rotate(10);");
assert!(e.contains("Stale page item"), "{e}");
}
@@ -82,7 +82,7 @@ const INSIDE: &[(&str, &str)] = &[
"",
"app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \
PageItems Preferences RulerUnits ZOrderMethod",
PageItems Preferences RulerUnits Transformation ZOrderMethod",
),
("Application.", "prototype"),
(
@@ -122,8 +122,8 @@ const INSIDE: &[(&str, &str)] = &[
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
position= remove resize rotate selected selected= sliced sliced= tags tags= top top= transform translate \
typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
),
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
@@ -139,6 +139,7 @@ const INSIDE: &[(&str, &str)] = &[
),
("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"),
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
];
+25 -5
View File
@@ -2657,8 +2657,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot
100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
visible bounds together with the anchors and direction points of the paths in the object; a clipping group counts
its clipping path only, and a blend, envelope or other live object gives its visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`,
`move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`
(https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs
`move(relativeObject, insertionLocation?)`, `remove()`, `zOrder(method)`, `translate`, `rotate`, `resize` and
`transform` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs
`edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same
document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a
group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER`
@@ -2671,8 +2671,28 @@ app through the global object `vc`, and writes to the Script Console and runs ot
`Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the
same object when the image is embedded: the next read gives that object, now a `RasterItem`. The
enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
`DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and
`DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`.
`Transformation`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution`
and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`.
`translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?,
transformStrokePatterns?)` moves the object by the offsets in points, `rotate(angle, changePositions?,
changeFillPatterns?, changeFillGradients?, changeStrokePattern?, rotateAbout?)` turns it by `angle` degrees,
`resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?,
changeLineWidths?, scaleAbout?)` scales it by the percentages, and `transform(transformationMatrix, changePositions?,
changeFillPatterns?, changeFillGradients?, changeStrokePattern?, changeLineWidths?, transformAbout?)` applies a
`Matrix` record (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each one runs `object.transform` on the
object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is,
so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and
`transform` act about the center of the geometric bounds unless a `Transformation` value names another point of
them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients
default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different
values, and gradients different from positions, counting the defaults of arguments left out, throw an error that
says they are not available yet.
`changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the
square root of the area it scales by (stroke weights and effects scale with it); another value throws the same
error. A locked object, one inside a locked layer or group, a group that holds one, and an object on a locked
artboard throw `cannot transform locked objects` or `cannot transform objects on a locked artboard`. A scale of 0, a
matrix whose determinant is 0 and a transformation that would take the object past the canvas also throw an error.
In each of these cases the document does not change. A call that changes nothing runs no command.
VectorCraft's own rules: documents are listed in tab order, and page items in paint order from the bottom, with the
objects inside groups and compound paths after their group and without layers and ruler guides. Script coordinates
are points with Y up from the bottom-left corner of the first artboard, or, with
@@ -2693,7 +2713,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot
letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when
the automation read roots allow its file, and that check can look the document's file up on disk. A path with
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application,
Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and
Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.bringInPerspective` and
`app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
themselves, such as a path's fill, are not defined yet and read as `undefined`.
+1
View File
@@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
- Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call runs `object.transform` inside the run's transaction; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
- Scripts: 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`.