diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs
index cb901014b5..bef71437d4 100644
--- a/crates/engine/src/script/dom.rs
+++ b/crates/engine/src/script/dom.rs
@@ -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
+//! 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 ().
+//! 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) -> 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> {
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
}
fn walk(nodes: &[Arc], out: &mut Vec) {
- 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 = 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 = 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 = 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 {
+/// 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 {
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)]
diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs
index affacab584..c162f5e010 100644
--- a/crates/engine/src/script/mod.rs
+++ b/crates/engine/src/script/mod.rs
@@ -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()
diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs
index 60e3a71521..8d015d8727 100644
--- a/crates/engine/src/tests/script_dom.rs
+++ b/crates/engine/src/tests/script_dom.rs
@@ -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 = 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::>()})).unwrap();
+ let opacities = |s: &Session| -> Vec {
+ 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);
+}
diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs
index 02176c38c9..3e336062f2 100644
--- a/crates/engine/src/tests/script_run.rs
+++ b/crates/engine/src/tests/script_run.rs
@@ -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);
}
diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs
index d9b6b87103..09c4daa936 100644
--- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs
+++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs
@@ -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] + ".");
diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs
index 69c2ebf402..2c5fcfa9f4 100644
--- a/crates/js/src/builtins.rs
+++ b/crates/js/src/builtins.rs
@@ -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 {
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 {
@@ -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 {
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 ----
diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs
index e88bc3f454..c688a0512c 100644
--- a/crates/js/src/host_classes.rs
+++ b/crates/js/src/host_classes.rs
@@ -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,
+ /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
+ own: Rc>,
}
impl Entry {
@@ -123,6 +140,21 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> {
}
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 {
+ 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