Scripts: page items report their own members, and lists start with the topmost object

Scripts that check a member with hasOwnProperty before using it skipped
every page item, because the members live on the class prototype. Now
hasOwnProperty and propertyIsEnumerable are true for each member of an
object's class that is available, and for-in lists its properties but
not its methods. Members that only throw "not available yet" stay false.

- An empty selection is an empty list instead of null.
- pageItems lists art topmost first, as the CMYKColor example reads the
  frontmost path as pathItems[0]
  (https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/). A
  document's selection lists the selected objects in that order too,
  whatever order they were picked in. That selection order is
  VectorCraft's own rule.
- A collection read with a name, such as pageItems["Logo"], gives what
  getByName gives, as
  https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/
  shows. A name nothing has throws Not found, and assigning to such a
  name throws the same error.
- activeDocument, documents and selection can be named without app., as
  that page describes for the application's members.
- move() with the object itself and PLACEBEFORE or PLACEAFTER leaves it
  where it is and adds no undo step.
- move() keeps a compound path whose last path moves out, so a script
  that holds it can still read it.
- Assigning opacity to an object in a hidden or locked layer throws
  Cannot edit and changes nothing.
- name takes a number or a Boolean as its text.
- String() of an object gives its class and name, such as
  [PathItem Logo].

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-23 13:24:32 -08:00
1 parent dc9adb195d
commit 9872e6b679
12 files changed
+661 -138

No files matched your search

+121 -41
View File
@@ -13,11 +13,21 @@
//! changed document; a change that changes nothing runs no command. A change to a document that is
//! not the active one makes it active for the command and makes the other one active again after.
//!
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
//! `pathItems[0]`. A document's selection lists the selected objects in the same order, not in the
//! order they were selected (<https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/>).
//! A collection read with a name, `pageItems["name"]`, gives the object `getByName` gives, as that
//! page describes, and throws `Not found` when none has the name; `"name" in pageItems` is false then,
//! and assigning to such a name throws the same error. As that page also describes, a script may name
//! `activeDocument`, `documents` and `selection` without `app.`; assigning one of those names makes it
//! a variable of the script's own.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0.
//! `pageItems` lists every object, with the objects inside groups and compound paths after the
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
//! - Collections list documents in tab order. `pageItems` lists every object, with the objects
//! inside groups and compound paths after the group or compound path, and leaves out layers and
//! ruler guides. An index out of range gives `undefined`; `index` and `getByName` throw
//! `Not found` when nothing matches.
//! - Script coordinates are points with Y up from the bottom of the first artboard
//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of
//! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run.
@@ -26,6 +36,8 @@
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
//! must be one of that document's that can be selected, or nothing changes.
//! - Members the help pages list that are not here yet throw an error that says so.
//! - Assigning `opacity` to an object in a hidden or locked layer throws `Cannot edit` and changes
//! nothing. An object that is hidden or locked itself, or is in a hidden or locked group, takes it.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
@@ -206,7 +218,8 @@ fn method(link: &Link, f: Member) -> HostMember {
}
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document or page item `this` is still there.
/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it,
/// so a script that checks for the member first skips it.
fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
@@ -224,7 +237,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM
}
Err(HostError::Error(message.clone()))
});
(name.to_string(), HostMember::Property { get: f.clone(), set: f })
(name.to_string(), HostMember::Unavailable(f))
}
fn text(s: impl Into<String>) -> Data {
@@ -386,14 +399,14 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
}
/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last
/// documents read).
/// The ids of a document's page items, topmost first, each group or compound path before the
/// objects in it ([`State`] keeps the lists of the last documents read).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes {
for n in nodes.iter().rev() {
match &n.kind {
NodeKind::Layer { children, .. } => walk(children, out),
NodeKind::RulerGuide { .. } => {}
@@ -742,10 +755,15 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer {
Ok(host_ref("Application", &[]))
}
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
fn docs_at(h: &Host, a: &[Data]) -> Answer {
let s = h.session.borrow();
let at = match arg(a, 1) {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)),
Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) {
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
found => found,
},
_ => None,
};
Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid)))
@@ -1214,18 +1232,22 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
selection_of(h, doc.uid)
}
/// The selection of the document `uid`: `null` when nothing is selected, otherwise a new list of
/// the selected objects.
/// The selection of the document `uid`: a new list of the selected objects, topmost first as
/// `pageItems` lists them, empty when nothing is selected.
fn selection_of(h: &Host, uid: u64) -> Answer {
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let ids: Vec<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if ids.is_empty() {
return Ok(Data::Null);
}
if ids.len() > MAX_LISTED {
let picked: HashSet<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if picked.len() > MAX_LISTED {
return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects")));
}
let ids: Vec<NodeId> = if picked.is_empty() {
Vec::new()
} else {
let all = page_items(h, st);
h.charge_call(all.len() as u64)?;
all.iter().copied().filter(|i| picked.contains(i)).collect()
};
h.charge_call(16 * ids.len() as u64)?;
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
}
@@ -1320,8 +1342,21 @@ fn items_parent(h: &Host, a: &[Data]) -> Answer {
Ok(doc_ref(h, doc.uid))
}
/// Whether an indexer was called for `name in collection` ([`vectorcraft_js::HostClass::index`]),
/// where a name nothing has gives `undefined` instead of the `Not found` error a read throws.
fn probing(a: &[Data]) -> bool {
matches!(arg(a, 2), Data::Bool(true))
}
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
fn items_at(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
if let Data::String(_) = arg(a, 1) {
return match items_by_name(h, a) {
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
r => r,
};
}
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
@@ -1418,8 +1453,15 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) ->
Ok(Data::Undefined)
}
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) };
let name = match arg(a, 1) {
Data::String(s) => s.clone(),
Data::Number(n) => vectorcraft_js::number_to_string(*n),
Data::Bool(b) => b.to_string(),
_ => return Err(HostError::Type("name must be a string".into())),
};
let name = &name;
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
}
@@ -1479,6 +1521,14 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
// replaces the one the graph keeps for its series or kind.
let item = this_item(h, a)?;
let refused = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked));
d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item"))
});
if let Some(name) = refused {
return Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0)));
}
let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0));
let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v);
set_props(h, a, |_| false, json!({"opacity": v}))
@@ -1693,9 +1743,9 @@ struct Destination {
}
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
/// same document as `item`. A copy (`copy`) may go directly above or below `item` itself, as
/// `layer.move` puts copies.
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
/// `layer.move` puts copies, and a move there leaves the object where it is.
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
let how = placement_of(how)?;
let beside = matches!(how, Placement::Above | Placement::Below);
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
@@ -1714,7 +1764,7 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
let d = &st.doc;
let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target));
if inside || (target == item.id && !(copy && beside)) {
if inside || (target == item.id && !beside) {
return Err(HostError::Error("an object cannot go into itself".into()));
}
let (parent, beside) = match how {
@@ -1776,27 +1826,16 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a
/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An
/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard
/// is refused.
/// is refused. Moving an object directly above or below itself leaves it where it is, and a compound
/// path whose last path moves out stays, empty.
fn item_move(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
if matches!(arg(a, 1), Data::Undefined) {
return Err(HostError::Type("move needs a relative object".into()));
}
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
// When the last path leaves a compound path, the compound path is deleted in the same step
// rather than left empty.
let emptied = with_doc(h, item.doc, |_, st| {
let parent = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p))?;
(matches!(parent.kind, NodeKind::Compound { .. }) && parent.children().is_some_and(|c| c.len() == 1) && parent.id != to.parent)
.then_some(parent.id)
});
match emptied {
None => place(h, item.doc, item.id, &to)?,
Some(compound) => atomically(h, |h| {
place(h, item.doc, item.id, &to)?;
on_doc(h, item.doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": [compound.0]})))?;
Ok(())
})?,
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
if to.beside != Some(item.id) {
place(h, item.doc, item.id, &to)?;
}
Ok(arg(a, 0).clone())
}
@@ -1835,7 +1874,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
None
}
target => Some(destination(h, item, target, arg(a, 2), true)?),
target => Some(destination(h, item, target, arg(a, 2))?),
};
let id = atomically(h, |h| {
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
@@ -1894,6 +1933,31 @@ fn layer_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Layer"))
}
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
fn named_text(class: &str, name: Answer) -> Answer {
match name? {
Data::String(n) => Ok(text(format!("[{class} {n}]"))),
_ => Ok(text(format!("[{class} ]"))),
}
}
fn item_to_string(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(text(format!("[{} {}]", typename(n).unwrap_or("PageItem"), n.name.as_deref().unwrap_or("")))))
}
fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Document", doc_name(h, a))
}
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Layer", layer_name(h, a))
}
/// `toString()` of an object without a name: `[Class]`.
fn class_text(name: &'static str) -> HostMember {
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
}
fn typename_of(name: &'static str) -> HostMember {
HostMember::Get(Rc::new(move |_| Ok(text(name))))
}
@@ -1948,6 +2012,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("selection", get(l, app_selection)),
("coordinateSystem", property(l, app_coords, app_set_coords)),
("getIsFileOpen", method(l, app_is_open)),
("toString", class_text("Application")),
]);
application.push(later(l, "Application", "beep"));
let preset = {
@@ -1957,7 +2022,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
h.charge_call(64)?;
new_preset(&h)
});
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))];
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))];
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k))));
HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) }
};
@@ -1975,6 +2040,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("getByName", method(l, docs_by_name)),
("add", method(l, docs_add)),
("addDocument", method(l, docs_add_document)),
("toString", class_text("Documents")),
]),
Some(function(l, docs_at)),
),
@@ -1991,6 +2057,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("convertCoordinate", method(l, doc_convert)),
("pageItems", get(l, doc_page_items)),
("selection", property(l, doc_selection, doc_set_selection)),
("toString", method(l, doc_to_string)),
]);
document.extend(
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
@@ -2008,6 +2075,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("index", method(l, items_index)),
("getByName", method(l, items_by_name)),
("removeAll", method(l, items_remove_all)),
("toString", class_text("PageItems")),
]),
Some(function(l, items_at)),
));
@@ -2034,6 +2102,7 @@ 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)),
("toString", method(l, item_to_string)),
]);
page_item.extend(
[
@@ -2061,8 +2130,19 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
);
classes.push(class("PageItem", None, page_item, None));
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None)));
classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])
classes.push(class(
"Layer",
None,
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
None,
));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
// The application's members a script may name without `app.`.
realm.define_host_globals(vec![
("activeDocument".into(), function(l, app_active)),
("documents".into(), function(l, app_documents)),
("selection".into(), function(l, app_selection)),
])
}
#[cfg(test)]
+1 -7
View File
@@ -1583,16 +1583,10 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
fn explained(e: &RunError) -> String {
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
const APP_MEMBERS: &[&str] = &["activeDocument", "documents", "selection"];
let message = &e.message;
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
if e.kind == RunErrorKind::Thrown
&& !e.authored
&& let Some(member) = first.filter(|f| APP_MEMBERS.contains(f))
{
format!("{message} (use `app.{member}`)")
} else if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
} else {
message.to_string()
+310 -48
View File
@@ -82,14 +82,15 @@ fn page_items_are_live_and_typed_for_all_node_kinds() {
"var p = app.activeDocument.pageItems, t = [];\
for (var i = 0; i < p.length; i++) t.push(p[i].typename);\
vc.log(t.join(','));\
vc.log(p[1].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\
p[3].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\
vc.log(p[1] instanceof PathItem && p[1] instanceof PageItem);",
vc.log(p[3].parent.typename); vc.log(p[0].parent.typename); vc.log(p.parent.typename);\
p[1].remove(); vc.log(p.length); vc.log(p[-1] === undefined && p[1.5] === undefined && p[99] === undefined);\
vc.log(p[2] instanceof PathItem && p[2] instanceof PageItem);",
);
// Topmost first, each group before the objects in it.
assert_eq!(
out,
vec![
json!("GroupItem,PathItem,PathItem,PathItem,TextFrame"),
json!("TextFrame,PathItem,GroupItem,PathItem,PathItem"),
json!("GroupItem"),
json!("Layer"),
json!("Document"),
@@ -120,7 +121,7 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var i = app.activeDocument.pageItems[0];\
"var i = app.activeDocument.pageItems[1];\
vc.log(i.geometricBounds); vc.log(i.position); vc.log([i.left, i.top, i.width, i.height]);\
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(i.position);\
app.coordinateSystem = CoordinateSystem.DOCUMENTCOORDINATESYSTEM;\
@@ -198,7 +199,7 @@ fn page_item_properties_join_one_undo_step() {
let steps = undo_steps(&s);
let out = log(
&mut s,
"var i = app.activeDocument.pageItems[0];\
"var i = app.activeDocument.pageItems[1];\
i.name = 'box'; i.opacity = 40; i.locked = true; i.locked = false; i.hidden = true; i.hidden = false;\
vc.log([i.name, i.opacity, i.locked, i.hidden, i.editable, i.zOrderPosition]);\
vc.log(app.activeDocument.pageItems.getByName('box').name);",
@@ -209,7 +210,7 @@ fn page_item_properties_join_one_undo_step() {
assert_eq!((n.name.as_deref(), (n.opacity * 100.0).round()), (Some("box"), 40.0));
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
let steps = undo_steps(&s);
log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'box'; i.opacity = 40; i.hidden = false;");
log(&mut s, "var i = app.activeDocument.pageItems[1]; i.name = 'box'; i.opacity = 40; i.hidden = false;");
assert_eq!(undo_steps(&s), steps, "values that change nothing add no step");
for (source, part) in [
("app.activeDocument.pageItems[0].opacity = 101;", "opacity"),
@@ -251,7 +252,7 @@ fn assigning_the_reported_opacity_changes_nothing() {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap();
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.opacity); i.opacity = i.opacity;");
let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;");
assert_eq!(out, vec![json!(33.3333)]);
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
assert_eq!(undo_steps(&s), steps);
@@ -267,10 +268,10 @@ fn selection_assignment_is_atomic_across_invalid_items() {
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems; vc.log(d.selection === null);\
"var d = app.activeDocument, p = d.pageItems; vc.log(d.selection instanceof Array && d.selection.length === 0);\
d.selection = [p[1], p[0], p[1]]; vc.log(d.selection.length); vc.log(app.selection[0].selected);\
p[0].selected = false; vc.log(d.selection.length);\
d.selection = p[0]; vc.log(d.selection.length);",
d.selection = p[1]; vc.log(d.selection.length);",
);
assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]);
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
@@ -288,14 +289,14 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() {
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
// The assignment and `selected` refuse the guide path, and the selection stays as it was.
for source in ["app.activeDocument.selection = app.activeDocument.pageItems[0];", "app.activeDocument.pageItems[0].selected = true;"] {
for source in ["app.activeDocument.selection = app.activeDocument.pageItems[1];", "app.activeDocument.pageItems[1].selected = true;"] {
let e = failure(&mut s, source);
assert!(e.contains(&format!("Cannot select PathItem {}", a.0)), "{source}: {e}");
assert_eq!(s.active().unwrap().selection.objects, vec![b], "{source}");
}
// With the guides unlocked, the guide path is selected.
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];");
log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];");
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
}
@@ -303,7 +304,7 @@ fn a_guide_path_is_not_selected_while_guides_are_locked() {
fn an_inactive_document_changes_without_switching_tabs() {
let (mut s, a, _) = doc();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
log(&mut s, "var d = app.documents[0]; d.pageItems[0].name = 'far'; d.selection = d.pageItems[1];");
log(&mut s, "var d = app.documents[0]; d.pageItems[1].name = 'far'; d.selection = d.pageItems[0];");
assert_eq!(s.active_index(), Some(1));
let first = &s.documents()[0];
assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far"));
@@ -315,7 +316,7 @@ fn move_duplicate_and_zorder_obey_parent_order() {
let (mut s, a, b) = doc();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, first = p[0];\
"var p = app.activeDocument.pageItems, first = p[1];\
first.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log(first.zOrderPosition);\
var c = first.duplicate(); vc.log(c.zOrderPosition); vc.log(p.length); vc.log(app.activeDocument.selection.length);\
c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(c.zOrderPosition);",
@@ -341,31 +342,31 @@ fn move_and_duplicate_place_by_element_placement() {
let steps = undo_steps(&s);
// Before puts it directly above the relative object, after directly below.
let r =
log(&mut s, "var p = app.activeDocument.pageItems; var a = p[0], c = p[2]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);");
log(&mut s, "var p = app.activeDocument.pageItems; var a = p[2], c = p[0]; vc.log(a.move(c, ElementPlacement.PLACEBEFORE) === undefined);");
assert_eq!(r, vec![json!(false)]);
assert_eq!(layer_order(&s), [b, c, a]);
log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[0], ElementPlacement.PLACEAFTER);");
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[2], ElementPlacement.PLACEAFTER);");
assert_eq!(layer_order(&s), [a, b, c]);
// At the end of a container is under its contents, at the beginning on top.
log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[0].parent, ElementPlacement.PLACEATEND);");
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATEND);");
assert_eq!(layer_order(&s), [c, a, b]);
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].parent, ElementPlacement.PLACEATBEGINNING);");
log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[2].parent, ElementPlacement.PLACEATBEGINNING);");
assert_eq!(layer_order(&s), [a, b, c]);
assert_eq!(undo_steps(&s), steps + 4, "one step for each run that changed the order");
// Moving to where it is runs nothing.
let steps = undo_steps(&s);
log(&mut s, "var p = app.activeDocument.pageItems; p[2].move(p[1], ElementPlacement.PLACEBEFORE);");
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);");
assert_eq!(undo_steps(&s), steps);
// Into a group, and a copy beside an object.
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
log(&mut s, "var p = app.activeDocument.pageItems; p[3].move(p[0], ElementPlacement.INSIDE);");
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);");
let inside: Vec<NodeId> = s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect();
assert_eq!(inside, [a, b, c]);
let out = log(
&mut s,
"var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[1];\
"var g = app.activeDocument.pageItems[0], a = app.activeDocument.pageItems[3];\
var copy = a.duplicate(g, ElementPlacement.PLACEATEND); vc.log(copy.parent.typename); vc.log(copy.zOrderPosition);",
);
assert_eq!(out, vec![json!("GroupItem"), json!(1)]);
@@ -387,7 +388,7 @@ fn move_and_duplicate_place_by_element_placement() {
// A locked group takes nothing.
s.execute("object.setProps", &json!({"ids": [g.0], "locked": true})).unwrap();
rect(&mut s, 0.0, 0.0, 5.0, 5.0);
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[p.length - 1].move(p[0], ElementPlacement.INSIDE);");
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.INSIDE);");
assert!(e.contains("hidden or locked"), "{e}");
}
@@ -396,17 +397,21 @@ fn a_copy_goes_beside_its_source() {
let (mut s, a, b) = doc();
let out = log(
&mut s,
"var a = app.activeDocument.pageItems[0], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\
"var a = app.activeDocument.pageItems[1], c = a.duplicate(a, ElementPlacement.PLACEAFTER);\
vc.log([c.zOrderPosition, a.zOrderPosition]);",
);
assert_eq!(out, vec![json!([1, 2])]);
let order = layer_order(&s);
assert_eq!(order[1..], [a, b]);
// An object cannot go beside itself, and a copy cannot go into its source.
assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER);").contains("into itself"));
// An object moved directly above or below itself stays where it is with no undo step, and it
// cannot go into itself; a copy cannot go into its source.
let (order, steps) = (layer_order(&s), undo_steps(&s));
log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEAFTER); p[0].move(p[0], ElementPlacement.PLACEBEFORE);");
assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps));
assert!(failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[1], ElementPlacement.PLACEATBEGINNING);").contains("into itself"));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[1]; g.duplicate(g, ElementPlacement.INSIDE);");
let e = failure(&mut s, "var p = app.activeDocument.pageItems, g = p[0]; g.duplicate(g, ElementPlacement.INSIDE);");
assert!(e.contains("into itself"), "{e}");
}
@@ -425,7 +430,7 @@ fn a_copy_that_cannot_be_placed_is_deleted() {
// A Live Paint group takes no type, so the copy is refused after it was made.
let out = log(
&mut s,
"var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], m = '';\
"var p = app.activeDocument.pageItems, n = p.length, g = p[1], t = p[0], m = '';\
try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { m = e.message; }\
vc.log(m); vc.log(p.length === n);",
);
@@ -489,7 +494,7 @@ fn a_path_inside_a_compound_path_is_not_reordered() {
}
#[test]
fn moving_the_last_path_out_of_a_compound_path_deletes_the_compound_path() {
fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
@@ -498,16 +503,16 @@ fn moving_the_last_path_out_of_a_compound_path_deletes_the_compound_path() {
let steps = undo_steps(&s);
let out = log(
&mut s,
"var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[1], d.pageItems[2]];\
"var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[2], d.pageItems[1]];\
m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\
m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\
try { c.name; } catch (e) { vc.log(e.message); }",
vc.log([c.typename, c === d.pageItems[2]]);",
);
assert_eq!(out, vec![json!(3), json!(2), json!("Stale page item")]);
assert_eq!(out, vec![json!(3), json!(3), json!(["CompoundPathItem", true])]);
let doc = &s.active().unwrap().doc;
assert!(doc.node(compound).is_none(), "the empty compound path is deleted");
assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty");
// Each path went directly above the compound path, the second above the first.
assert_eq!(layer_order(&s), [b, a]);
assert_eq!(layer_order(&s), [compound, b, a]);
assert!([a, b].iter().all(|id| doc.parent_of(*id) == Some(layer)));
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
}
@@ -612,9 +617,9 @@ fn stale_documents_throw_on_every_member() {
fn hiding_or_locking_a_selected_item_deselects_it() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
log(&mut s, "app.activeDocument.pageItems[0].hidden = true;");
log(&mut s, "app.activeDocument.pageItems[1].hidden = true;");
assert_eq!(s.active().unwrap().selection.objects, vec![b]);
log(&mut s, "app.activeDocument.pageItems[1].locked = true;");
log(&mut s, "app.activeDocument.pageItems[0].locked = true;");
assert!(s.active().unwrap().selection.objects.is_empty());
}
@@ -648,7 +653,7 @@ fn assigning_the_selection_clears_a_layers_panel_target() {
let (mut s, a, _) = doc();
s.execute("layer.target", &json!({"id": a.0})).unwrap();
assert_eq!(s.active().unwrap().selection.target, Some(a));
log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[0];");
log(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[1];");
let sel = &s.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.target), (vec![a], None));
}
@@ -694,7 +699,7 @@ fn an_edit_keeps_the_current_layer() {
log(&mut s, "app.activeDocument.pageItems[0].left = 70;");
assert_eq!(layer(&s), (Some(back), vec![first]));
// Assigning the selection makes the layer of the selected object current, as a click does.
log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];");
log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[1];");
assert_eq!(s.active().unwrap().active_layer, Some(first));
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
}
@@ -817,7 +822,7 @@ fn assigning_the_same_objects_clears_the_key_and_guides() {
s.execute("select.key", &json!({"id": b.0})).unwrap();
s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap();
assert!(!s.active().unwrap().selection.guides.is_empty());
log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[0], d.pageItems[1]];");
log(&mut s, "var d = app.activeDocument; d.selection = [d.pageItems[1], d.pageItems[0]];");
let sel = &s.active().unwrap().selection;
assert_eq!((sel.objects.clone(), sel.key, sel.guides.len()), (vec![a, b], None, 0));
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
@@ -865,7 +870,7 @@ fn the_same_document_or_item_is_the_same_object() {
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems;\
vc.log([d === app.documents[0], p[0] === p[0], p[0] === d.selection[0], p[0] !== p[1], p === d.pageItems]);",
vc.log([d === app.documents[0], p[1] === p[1], p[1] === d.selection[0], p[0] !== p[1], p === d.pageItems]);",
);
assert_eq!(out, vec![json!([true, true, true, true, true])]);
}
@@ -903,11 +908,11 @@ fn placement_in_another_document_is_refused() {
fn note_is_the_attributes_note() {
let (mut s, a, _) = doc();
let steps = undo_steps(&s);
let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);");
let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.note); i.note = 'check bleed'; vc.log(i.note);");
assert_eq!(out, vec![json!(""), json!("check bleed")]);
assert_eq!(s.active().unwrap().doc.node(a).unwrap().extras().attrs.as_ref().unwrap().note, "check bleed");
assert_eq!(undo_steps(&s), steps + 1);
log(&mut s, "app.activeDocument.pageItems[0].note = 'check bleed';");
log(&mut s, "app.activeDocument.pageItems[1].note = 'check bleed';");
assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step");
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = 5;").contains("note must be a string"));
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
@@ -1135,7 +1140,7 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() {
(json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})),
] {
s.execute("object.setProps", &on).unwrap();
let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();");
let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();");
assert!(e.contains(&format!("cannot delete hidden or locked objects: {}", b.0)), "{on}: {e}");
assert!(s.active().unwrap().doc.node(b).is_some(), "{on}");
s.execute("object.setProps", &off).unwrap();
@@ -1180,7 +1185,7 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() {
assert_eq!(undo_steps(&s), steps);
// `editable` is false for art on the locked artboard and true for art on the unlocked one.
let editable = "var p = app.activeDocument.pageItems; vc.log([p[0].editable, p[1].editable, p[2].editable]);";
assert_eq!(log(&mut s, editable), vec![json!([false, false, true])]);
assert_eq!(log(&mut s, editable), vec![json!([true, false, false])]);
lock(&mut s, false);
assert_eq!(log(&mut s, editable), vec![json!([true, true, true])]);
let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);");
@@ -1199,17 +1204,17 @@ fn move_and_duplicate_refuse_art_on_a_locked_artboard() {
};
lock(&mut s, true);
let (order, steps) = (layer_order(&s), undo_steps(&s));
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);");
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);");
assert!(e.contains(&format!("Cannot move PathItem {}", a.0)), "{e}");
assert_eq!((layer_order(&s), undo_steps(&s)), (order.clone(), steps));
// `duplicate` refuses it too, with or without a relative object.
for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] {
for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] {
let e = failure(&mut s, source);
assert!(e.contains(&format!("Cannot duplicate PathItem {}", a.0)), "{source}: {e}");
}
assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps));
lock(&mut s, false);
log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);");
log(&mut s, "var p = app.activeDocument.pageItems; p[1].move(p[0], ElementPlacement.PLACEBEFORE);");
assert_eq!(layer_order(&s), [b, a]);
}
@@ -1223,14 +1228,14 @@ fn duplicate_refuses_hidden_or_locked_art() {
s.execute("object.setProps", &on).unwrap();
let (order, steps) = (layer_order(&s), undo_steps(&s));
// With no argument and with a relative object.
for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] {
for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] {
let e = failure(&mut s, source);
assert!(e.contains(&format!("Cannot duplicate PathItem {}", b.0)), "{on} {source}: {e}");
}
assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps), "{on}");
s.execute("object.setProps", &off).unwrap();
}
log(&mut s, "app.activeDocument.pageItems[1].duplicate();");
log(&mut s, "app.activeDocument.pageItems[0].duplicate();");
let order = layer_order(&s);
assert_eq!(order.len(), 3);
assert!(order.contains(&a) && order.contains(&b));
@@ -1319,3 +1324,260 @@ fn unsupported_members_say_so() {
let (mut s, _, _) = doc();
assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet"));
}
/// A script that lowers each selected object's opacity by 10 points, checking each member with
/// `hasOwnProperty` and the selection's `length` first, as scripts written for the object model do.
const LOWER_OPACITY: &str = "\
var doc = app.activeDocument;\
var sel = doc.selection;\
if (sel.length === 0) { alert('Nothing selected.'); }\
else {\
var done = 0;\
for (var i = 0; i < sel.length; i++) {\
var item = sel[i];\
if (item.hasOwnProperty('opacity') && typeof item.opacity === 'number') {\
item.opacity = Math.max(0, item.opacity - 10);\
done++;\
}\
if (item.hasOwnProperty('blendingMode')) { item.blendingMode; }\
}\
if (done === 0) { alert('No object with an opacity.'); }\
}";
#[test]
fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
let path = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let (g1, g2) = (rect(&mut s, 50.0, 10.0, 20.0, 20.0), rect(&mut s, 80.0, 10.0, 20.0, 20.0));
s.execute("select.set", &json!({"ids": [g1.0, g2.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
let (c1, c2) = (rect(&mut s, 150.0, 10.0, 20.0, 20.0), rect(&mut s, 155.0, 15.0, 20.0, 20.0));
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.active().unwrap().selection.objects[0];
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 55})).unwrap();
s.execute("object.setProps", &json!({"ids": [text.0], "opacity": 5})).unwrap();
let objects = [path, group, text, compound];
s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::<Vec<_>>()})).unwrap();
let opacities = |s: &Session| -> Vec<f64> {
let d = &s.active().unwrap().doc;
objects.iter().map(|n| (f64::from(d.node(*n).unwrap().opacity) * 1000.0).round() / 10.0).collect()
};
let before = opacities(&s);
let steps = undo_steps(&s);
// The run shows no alert: without an answer for one, it would stop there.
let r = run(&mut s, LOWER_OPACITY).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(r["dialogs"], json!([]), "{r}");
assert_eq!(opacities(&s), vec![90.0, 45.0, 0.0, 90.0]);
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(opacities(&s), before);
}
#[test]
fn the_selection_is_an_empty_list_when_nothing_is_selected() {
let (mut s, _, _) = doc();
s.execute("select.set", &json!({"ids": []})).unwrap();
let out = log(&mut s, "var d = app.activeDocument; vc.log([d.selection instanceof Array, d.selection.length, app.selection.length]);");
assert_eq!(out, vec![json!([true, 0, 0])]);
let steps = undo_steps(&s);
let r = s.execute("script.run", &json!({"source": LOWER_OPACITY, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap();
assert_eq!(r["dialogs"][0]["message"], json!("Nothing selected."), "{r}");
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn page_items_report_their_available_members_as_their_own() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems[0], d = app.activeDocument, keys = [];\
for (var k in p) keys.push(k);\
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
app.hasOwnProperty('activeDocument')]);\
vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);",
);
assert_eq!(out[0], json!([true, true, true, true, true, true, true]));
// Members that are not available yet, unknown names and inherited ones are not the object's own.
assert_eq!(out[1], json!([false, false, false, false, false, false]));
// `for`-`in` lists the properties, not the methods or the members that are not available yet.
assert_eq!(out[2], json!([true, true, -1, -1]));
}
/// A name a page item class's prototype has, such as `constructor`, or that a script tries to put on
/// the prototype, is not an object's own.
#[test]
fn a_property_added_to_a_class_prototype_is_not_an_objects_own() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems[0]; PathItem.prototype.foo = 1; PageItem.prototype.bar = 2;\
vc.log([p.hasOwnProperty('foo'), p.hasOwnProperty('bar'), p.propertyIsEnumerable('foo'), p.hasOwnProperty('constructor')]);",
);
assert_eq!(out, vec![json!([false, false, false, false])]);
}
/// Reading every property `for`-`in` lists calls each getter, and each call counts against the run:
/// a loop of such reads ends at `maxFuel` and at `script.stop`.
#[test]
fn reading_every_listed_property_is_charged_and_can_be_stopped() {
let (mut s, _, _) = doc();
let mut calls = |body: &str| {
let source = format!("var p = app.activeDocument.pageItems[0], n = 0; for (var k in p) {{ {body} n++; }} vc.log(n);");
let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}"));
(r["hostCalls"].as_u64().unwrap(), r["log"][0].as_u64().unwrap())
};
let (listed, n) = calls("");
let (read, m) = calls("p[k];");
assert_eq!(n, m);
assert!(n > 10, "{n} properties");
assert!(read >= listed + n, "{listed} host calls to list, {read} to read {n} properties");
let spin = "var p = app.activeDocument.pageItems[0]; while (true) for (var k in p) p[k];";
let e = s.execute("script.run", &json!({"source": spin, "name": "t.js", "maxFuel": 200_000})).unwrap_err();
assert!(e.to_string().ends_with("(limit)"), "{e}");
s.script_frames = true;
assert_eq!(run(&mut s, spin).unwrap()["running"], true);
assert!(s.script_pump().is_none());
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
assert!(s.script_pump().unwrap().is_err());
assert!(!s.script_running());
}
/// `pageItems` lists art topmost first, and the selection lists the selected objects in that
/// order whatever order they were selected in.
#[test]
fn page_items_and_the_selection_list_the_topmost_object_first() {
let (mut s, a, b) = doc();
s.execute("object.setProps", &json!({"ids": [a.0], "name": "bottom"})).unwrap();
s.execute("object.setProps", &json!({"ids": [b.0], "name": "top"})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
assert_eq!(s.active().unwrap().selection.objects, vec![a, b], "picked bottom first");
let out = log(
&mut s,
"var d = app.activeDocument; vc.log([d.pageItems[0].name, d.pageItems[1].name, d.selection[0].name, d.selection[1].name]);\
d.selection = [d.pageItems[1], d.pageItems[0]]; vc.log(d.selection[0].name);",
);
assert_eq!(out, vec![json!(["top", "bottom", "top", "bottom"]), json!("top")]);
}
/// A collection read with a name gives what `getByName` gives, and throws as it does for no match.
#[test]
fn a_collection_read_with_a_name_gives_the_named_object() {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems, m = [];\
vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\
vc.log([app.documents[d.name] === d, d.name in app.documents, 'nosuch' in app.documents]);\
try { p['nosuch']; } catch (e) { m.push(e.message); }\
try { app.documents.nosuch; } catch (e) { m.push(e.message); }\
vc.log(m);",
);
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
}
/// `opacity` on an object in a hidden or locked layer throws and the run changes nothing; an object
/// that is hidden or locked itself takes it.
#[test]
fn opacity_refuses_art_in_a_hidden_or_locked_layer() {
let (mut s, a, b) = doc();
let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap());
let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0);
for (id, name) in [(a, "locked"), (b, "free"), (c, "closed")] {
s.execute("object.setProps", &json!({"ids": [id.0], "name": name})).unwrap();
}
for (on, off) in [
(json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})),
(json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})),
] {
s.execute("object.setProps", &on).unwrap();
let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s));
// The change made before the refusal is put back with the rest of the run.
let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').opacity = 50;");
assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on}: {e}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on}");
assert_eq!(undo_steps(&s), steps, "{on}");
s.execute("object.setProps", &off).unwrap();
}
s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap();
s.execute("object.setProps", &json!({"ids": [b.0], "visible": false})).unwrap();
let out = log(
&mut s,
"var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\
vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);",
);
assert_eq!(out, vec![json!([50, 40])]);
}
/// `name` takes a number or a Boolean as the text `String` gives it, and nothing else.
#[test]
fn a_name_given_as_a_number_or_a_boolean_becomes_its_text() {
let (mut s, a, _) = doc();
let out = log(
&mut s,
"var i = app.activeDocument.pageItems[1]; i.name = 5; vc.log([typeof i.name, i.name]); i.name = 2.5e-7; vc.log(i.name);\
i.name = true; vc.log(i.name);",
);
assert_eq!(out, vec![json!(["string", "5"]), json!("2.5e-7"), json!("true")]);
assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("true"));
for value in ["null", "undefined", "{}"] {
assert!(failure(&mut s, &format!("app.activeDocument.pageItems[1].name = {value};")).contains("name must be a string"), "{value}");
}
}
/// `String` of an object of the object model names its class, and its name when it has one.
#[test]
fn objects_of_the_object_model_print_their_class_and_name() {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"ids": [a.0], "name": "Logo"})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems;\
vc.log([String(p[0]), String(p[1]), '' + p[1], p[1].toString(), String(p[1].parent) === '[Layer ' + p[1].parent.name + ']']);\
vc.log([String(d) === '[Document ' + d.name + ']', String(app), String(p), String(app.documents)]);",
);
assert_eq!(out[0], json!(["[PathItem ]", "[PathItem Logo]", "[PathItem Logo]", "[PathItem Logo]", true]));
assert_eq!(out[1], json!([true, "[Application]", "[PageItems]", "[Documents]"]));
}
/// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and
/// assigning one makes it the script's own variable.
#[test]
fn the_application_members_can_be_named_without_app() {
let (mut s, a, _) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let out = log(
&mut s,
"vc.log([activeDocument === app.activeDocument, documents === app.documents, documents.length,\
selection.length, selection[0] === app.activeDocument.pageItems[1], typeof activeDocument]);",
);
assert_eq!(out, vec![json!([true, true, 1, 1, true, "object"])]);
// A script's own variable of the same name holds what the script puts in it.
let out = log(&mut s, "var selection = 5, documents; vc.log([selection, typeof documents, app.selection.length]);");
assert_eq!(out, vec![json!([5, "object", 1])]);
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
// With no document open, reading `activeDocument` throws as `app.activeDocument` does.
let mut s = Session::new();
assert!(failure(&mut s, "activeDocument;").contains("No active document"));
}
/// Assigning to a name a collection does not have throws as reading it does; a page item keeps
/// no member it lacks and does not throw.
#[test]
fn assigning_a_name_a_collection_lacks_throws() {
let (mut s, _, _) = doc();
let steps = undo_steps(&s);
for source in ["app.activeDocument.pageItems.qux = 4;", "app.documents.qux = 4;"] {
assert!(failure(&mut s, source).contains("Not found"), "{source}");
}
let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.foo = 1; app.activeDocument.pageItems[0] = 3; vc.log([i.foo === undefined]);");
assert_eq!(out, vec![json!([true])]);
assert_eq!(undo_steps(&s), steps);
}
+2 -1
View File
@@ -166,7 +166,8 @@ fn an_error_names_the_script_its_place_and_kind() {
let e = run(&mut s, "var = 1;").unwrap_err().to_string();
assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}");
assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`"));
assert!(run(&mut s, "activeDocument;").unwrap_err().to_string().contains("`app.activeDocument`"));
// The application's members need no `app.`, so naming one alone is not an error.
assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true);
assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _"));
assert_eq!(s.script_report().unwrap()["line"], 1);
}
@@ -73,15 +73,15 @@ const INSIDE: &[(&str, &str)] = &[
),
(
"",
"app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \
PageItems RulerUnits ZOrderMethod",
"activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
documents= Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod",
),
("Application.", "prototype"),
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \
selection typename",
selection toString typename",
),
("DocumentPreset.", "prototype"),
(
@@ -89,29 +89,29 @@ const INSIDE: &[(&str, &str)] = &[
"artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \
colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \
height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \
transparencyGrid transparencyGrid= typename units units= width width=",
toString transparencyGrid transparencyGrid= typename units units= width width=",
),
("Documents.", "prototype"),
("Documents.prototype.", "add addDocument constructor getByName index length parent typename"),
("Documents.prototype.", "add addDocument constructor getByName index length parent toString typename"),
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \
views views= width",
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= toString \
typename views views= width",
),
("Layer.", "prototype"),
("Layer.prototype.", "constructor name typename"),
("Layer.prototype.", "constructor name toString typename"),
("PageItems.", "prototype"),
("PageItems.prototype.", "constructor getByName index length parent removeAll typename"),
("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"),
("PageItem.", "prototype"),
(
"PageItem.prototype.",
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= top top= transform \
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
),
@@ -154,6 +154,9 @@ const LIST: &str = r#"(function () {
var globals = Object.getOwnPropertyNames(g);
add(g, "");
for (var i = 0; i < globals.length; i++) {
// A global with a getter, such as `activeDocument`, is not read: it throws with no document open.
var gd = Object.getOwnPropertyDescriptor(g, globals[i]);
if (gd && gd.get) continue;
var v = g[globals[i]];
if (v !== null && (typeof v == "object" || typeof v == "function")) {
add(v, globals[i] + ".");
+2 -2
View File
@@ -433,7 +433,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some()))
Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some() || interp.is_host_member(o, &k)?))
}
fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -452,7 +452,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let k = interp.to_key(&arg(args, 0))?;
let o = interp.to_object(&this)?;
Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable())))
Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member(o, &k)?))
}
// ---- Function ----
+116 -17
View File
@@ -15,12 +15,22 @@
//! Every member function gets the object it is called on (`this`) as its first argument, or
//! `undefined` when `this` is not an object of a host class, followed by the call's arguments; a
//! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each
//! array index `i` with it, called with `this` and the index, and `i in object` is true when it
//! gives a value other than `undefined`; other names are looked up as usual.
//! array index `i` with it, called with `this` and the index as a number. Other names are looked up
//! as usual, and a name that the object and its prototypes lack goes to the indexer as a string (as
//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing has. Assigning to such a name reads it with the indexer
//! first, so the assignment throws what the read throws; otherwise the value is not kept. `k in
//! object` calls the indexer with `true` as a third argument, and is true when it gives a value other
//! than `undefined`.
//!
//! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each
//! member of its class and of the classes it descends from, apart from the members that are not
//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members,
//! and not the methods.
use std::collections::HashSet;
use std::rc::Rc;
use crate::heap::{Class, Func, ObjId, Object, Prop, key};
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, NativeKind, ObjId, Object, Prop, WRITABLE, key};
use crate::host::ArgRead;
use crate::interp::{Abrupt, ErrorType, Interp, JsResult};
use crate::value::Value;
@@ -38,6 +48,9 @@ pub enum HostMember {
Property { get: HostFunction, set: HostFunction },
/// A method.
Method(HostFunction),
/// A property the class lists that is not available yet: the function answers both a read and
/// an assignment, with an error. It is not reported as the object's own, and `for`-`in` skips it.
Unavailable(HostFunction),
}
/// A class [`crate::Realm::define_host_classes`] adds.
@@ -72,6 +85,10 @@ pub(crate) struct Entry {
/// The class without a parent this class descends from (itself for such a class), as an index
/// into the realm's classes.
family: u32,
/// The class this class's prototype inherits from, as an index into the realm's classes.
parent: Option<u32>,
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
own: Rc<HashSet<Key>>,
}
impl Entry {
@@ -123,6 +140,21 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
}
impl Interp {
/// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host
/// class, and `k` names an available member of that class or of a class it descends from.
pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult<bool> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(false) };
let mut class = Some(h.class);
while let Some(c) = class {
let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) };
if e.own.contains(k) {
return Ok(true);
}
class = e.parent;
}
Ok(false)
}
/// The [`Data`] for the object of a host class `id`, or `None` when it is not one.
pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult<Option<Data>> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
@@ -174,24 +206,45 @@ impl Interp {
Ok(self.host_classes.get(h.class as usize).and_then(|e| e.index.clone()))
}
/// `object[index]` of an object of a host class, which its class's indexer `f` answers.
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, index: u32) -> JsResult<Value> {
/// `object[k]` of an object of a host class, which its class's indexer `f` answers: `k` is an
/// array index as a number, or a name as a string. With `probe`, for `k in object`, the indexer
/// gets `true` as a third argument.
pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, k: Data, probe: bool) -> JsResult<Value> {
self.use_fuel()?;
let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) };
match f(vec![this, Data::Number(f64::from(index))]) {
let mut args = vec![this, k];
if probe {
args.push(Data::Bool(true));
}
match f(args) {
Ok(d) => self.write_hosted(d),
Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())),
Err(e) => Err(self.host_error(e)?),
}
}
/// [[HasProperty]] of `k` on `id`: for an array index of an object of a host class with an
/// indexer, whether the indexer gives a value other than `undefined` for it.
/// The key an indexer gets for `k`: a number for an array index and for any other key that is
/// the text of a number (`-1`, `1.5`, `NaN`), otherwise the name.
pub(crate) fn indexer_key(k: &[u16]) -> Data {
if let Some(i) = crate::value::array_index(k) {
return Data::Number(f64::from(i));
}
let name = String::from_utf16_lossy(k);
match name.parse::<f64>() {
Ok(n) if crate::number_to_string(n) == name => Data::Number(n),
_ => Data::String(name),
}
}
/// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index,
/// or a name that the object and its prototypes lack, is there when the indexer gives a value other
/// than `undefined` for it.
pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult<bool> {
if let Some(i) = crate::value::array_index(k)
let index = crate::value::array_index(k).is_some();
if (index || !self.has_property(id, k)?)
&& let Some(f) = self.host_indexer(id)?
{
return Ok(!matches!(self.host_index(&f, id, i)?, Value::Undefined));
return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined));
}
self.has_property(id, k)
}
@@ -218,15 +271,48 @@ pub(crate) fn install(i: &mut Interp, classes: Vec<HostClass>, instances: Vec<(S
Ok(())
}
/// Adds the global properties `getters`, each read with its function as a member of a host class is.
/// Assigning one, as `var name = value` at the top level does, replaces it with a plain global
/// variable that holds the value.
pub(crate) fn install_globals(i: &mut Interp, getters: Vec<(String, HostFunction)>) -> JsResult<()> {
let global = i.global;
let proto = i.intrinsics.function_proto;
for (name, f) in getters {
let mark = i.temp_roots.len();
let get = hosted_function(i, f, &name);
i.temp_roots.push(Value::Object(get));
let replace = i.heap.alloc_object(Object::new(
Class::Function(Func::Native { f: replace_global, kind: NativeKind::Plain, constructor: false, name: "" }),
Some(proto),
));
i.temp_roots.push(Value::Object(replace));
let args: Rc<[Value]> = Rc::from([Value::str(&name)]);
let set = i.heap.alloc_object(Object::new(Class::Function(Func::Bound { target: replace, this: Value::Undefined, args }), Some(proto)));
i.temp_roots.truncate(mark);
i.define(global, key(&name), Prop::Accessor { get: Some(get), set: Some(set), flags: CONFIGURABLE })?;
}
Ok(())
}
/// The setter of a global [`install_globals`] adds: makes the global `args[0]` a plain variable
/// holding `args[1]`.
fn replace_global(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let name = interp.to_key(args.first().unwrap_or(&Value::Undefined))?;
let value = args.get(1).cloned().unwrap_or(Value::Undefined);
let global = interp.global;
interp.define(global, name, Prop::Data { value, flags: WRITABLE | ENUMERABLE | CONFIGURABLE })?;
Ok(Value::Undefined)
}
fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
if i.host_classes.iter().any(|e| *e.name == *class.name) {
return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name)));
}
let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX);
let (parent, family) = match &class.parent {
None => (i.intrinsics.object_proto, own),
Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) {
Some(e) => (e.proto, e.family),
let (parent, family, parent_class) = match &class.parent {
None => (i.intrinsics.object_proto, own, None),
Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) {
Some((n, e)) => (e.proto, e.family, u32::try_from(n).ok()),
None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))),
},
};
@@ -236,7 +322,16 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> {
let r = fill_class(i, proto, &class);
i.temp_roots.truncate(mark);
let ctor = r?;
i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family });
let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect();
i.host_classes.push(Entry {
name: class.name.as_str().into(),
proto,
ctor,
index: class.index,
family,
parent: parent_class,
own: Rc::new(members),
});
let global = i.global;
i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
}
@@ -247,13 +342,17 @@ fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult<ObjId
for (name, member) in &class.members {
let full = format!("{path}.{name}");
let prop = match member {
HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: 0 },
HostMember::Get(f) => Prop::Accessor { get: Some(hosted_function(i, f.clone(), &full)), set: None, flags: ENUMERABLE },
HostMember::Property { get, set } => {
let get = hosted_function(i, get.clone(), &full);
i.temp_roots.push(Value::Object(get));
Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: 0 }
Prop::Accessor { get: Some(get), set: Some(hosted_function(i, set.clone(), &full)), flags: ENUMERABLE }
}
HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 },
HostMember::Unavailable(f) => {
let f = hosted_function(i, f.clone(), &full);
Prop::Accessor { get: Some(f), set: Some(f), flags: 0 }
}
};
i.define(proto, key(name), prop)?;
}
+41
View File
@@ -676,6 +676,47 @@ fn a_host_class_constructor_called_with_new_cannot_wait() {
assert_eq!(could.get(), Some(false));
}
#[test]
fn objects_of_a_host_class_report_its_available_members_as_their_own() {
let mut r = realm(1_000_000);
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
let base = HostClass {
name: "Base".into(),
parent: None,
members: vec![
("size".to_string(), HostMember::Get(value.clone())),
("shape".to_string(), HostMember::Property { get: value.clone(), set: value.clone() }),
("grow".to_string(), HostMember::Method(value.clone())),
("later".to_string(), HostMember::Unavailable(missing)),
],
index: None,
construct: None,
};
let leaf = HostClass {
name: "Leaf".into(),
parent: Some("Base".into()),
members: vec![("leaf".to_string(), HostMember::Get(value))],
index: None,
construct: None,
};
r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap();
r.start(
"var own = Object.prototype.hasOwnProperty, keys = [];\
for (var k in it) keys.push(k);\
[it.hasOwnProperty('size'), it.hasOwnProperty('shape'), it.hasOwnProperty('grow'), it.hasOwnProperty('leaf'),\
own.call(it, 'size'), it.propertyIsEnumerable('grow'),\
it.hasOwnProperty('later'), it.propertyIsEnumerable('later'), it.hasOwnProperty('nope'),\
it.hasOwnProperty('hasOwnProperty'), it.hasOwnProperty('constructor'), 'later' in it,\
keys.sort().join(' '), Leaf.prototype.hasOwnProperty('size'), ({}).hasOwnProperty('size')].join()",
)
.unwrap();
assert_eq!(
finish(&mut r, 1_000_000).0.unwrap(),
JsValue::String("true,true,true,true,true,true,false,false,false,false,false,true,leaf shape size,false,false".into())
);
}
#[test]
fn a_converted_function_reads_each_argument_as_its_list_says() {
let mut r = realm(1_000_000);
+16 -4
View File
@@ -1432,10 +1432,15 @@ impl Interp {
if let Some(i) = array_index(k)
&& let Some(f) = self.host_indexer(start)?
{
return self.host_index(&f, start, i);
return self.host_index(&f, start, crate::Data::Number(f64::from(i)), false);
}
match self.find_property(start, k)? {
None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
// A name the object and its prototypes lack is the indexer's answer too.
None => match self.host_indexer(start)? {
Some(f) => self.host_index(&f, start, Self::indexer_key(k), false),
None => Ok(Value::Undefined),
},
Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
Some(Prop::Data { value, .. }) => Ok(value),
Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
}
@@ -1728,10 +1733,17 @@ impl Interp {
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"),
_ => {}
}
let o = self.object(id)?;
if !o.extensible {
if !self.object(id)?.extensible {
// A name that an object of a host class with an indexer lacks is read with the indexer
// first, so assigning it throws what reading it throws.
if array_index(&k).is_none()
&& let Some(f) = self.host_indexer(id)?
{
self.host_index(&f, id, Self::indexer_key(&k), false)?;
}
return self.reject(throw, &k, "the object is not extensible");
}
let o = self.object(id)?;
if let Class::Array { length, length_writable: false } = o.class
&& array_index(&k).is_some_and(|i| i >= length)
{
+10
View File
@@ -522,6 +522,16 @@ impl Realm {
}
}
/// Adds the global properties `getters`, each read with its function, which gets `undefined` as
/// `this`. Assigning one, as `var name = value` at the top level does, makes it a plain global
/// variable that holds the value.
pub fn define_host_globals(&mut self, getters: Vec<(String, crate::HostFunction)>) -> Result<(), RunError> {
match crate::host_classes::install_globals(&mut self.interp, getters) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Sets `Folder.current` back to the host's `current`, for the next run of a realm that has
/// `File` and `Folder` ([`Realm::define_file_classes`]); a realm without them keeps its
/// `Folder.current`. The files an earlier run opened are no longer open. The last run's uncaught
+27 -6
View File
@@ -2622,7 +2622,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot
- `vc.log(value)` adds a value to the report and a line to the Script Console.
- `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/
describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one),
`app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents`
`app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. A script may name `activeDocument`,
`documents` and `selection` without `app.`, as
[Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)
describes; assigning one of those names, as `var selection = ...` does, makes it a variable of the script's own
(VectorCraft's own rule). `app.documents`
(https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)`
and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`,
which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of
@@ -2663,16 +2667,30 @@ app through the global object `vc`, and writes to the Script Console and runs ot
`node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and
the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or
locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an
object, with or without a relative object, throws `Cannot duplicate` and makes no copy. When `move` takes the last
path out of a compound path, the empty compound path is deleted in the same undo step. `duplicate` on a path inside a compound path throws
object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `opacity` to an
object in a hidden or locked layer throws `Cannot edit` and changes nothing; an object that is hidden or locked
itself takes it (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE`
or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of a compound
path, the compound path stays, empty, so a script that holds it can still read it. `duplicate` on a path inside a compound path throws
`Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws
`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"`.
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
`pageItems` lists the art topmost first, as the example on
[CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`,
and a document's `selection` lists the selected objects in the same order, not in the order they were selected
([Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)).
A collection read with a name, such as `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object
`getByName` gives, as that page describes, and throws `Not found` when none has the name, a name the collection
class lacks as a member included; `"name" in pageItems` is false then, and assigning to such a name throws
`Not found` too. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives
`[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document <name>]`,
`[Layer <name>]`, `[Application]` and `[PageItems]` (VectorCraft's own rule).
VectorCraft's own rules: documents are listed in tab order, and page items with the
objects inside groups and compound paths after their group and without layers and ruler guides. A document's
`selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates
are points with Y up from the bottom-left corner of the first artboard, or, with
`CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename`
is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem`
@@ -2694,7 +2712,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot
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
`app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members
`app.beep`, throw an error that says they are not available yet when they are read or assigned.
`hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an
object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the
other properties but not the methods. 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`.
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
+1 -1
View File
@@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, read a collection by name, and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`.