From f2d3b09fe6d3b72462869437741ac72b40a54c7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 05:06:52 -0800 Subject: [PATCH 01/24] Scripts: app, documents, selection and page items for scripts Scripts get an app object with its documents, the active document and its selection, and the page items of a document, read and edited through commands so each edit is one undo step and is journaled. Host classes in the JavaScript engine give each document or item one object while a script holds it, answer `in` and indexed reads, and throw on stale objects and on members that are not available yet. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 1745 +++++++++++++++++++++++++ crates/engine/src/script/mod.rs | 28 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom.rs | 681 ++++++++++ crates/engine/src/tests/script_run.rs | 5 +- crates/js/src/builtins.rs | 2 +- crates/js/src/heap.rs | 4 +- crates/js/src/host.rs | 45 +- crates/js/src/host_classes.rs | 259 ++++ crates/js/src/interp.rs | 41 +- crates/js/src/lib.rs | 2 + crates/js/src/realm.rs | 11 + docs/mcp.md | 51 + docs/target-app-parity.md | 1 + 14 files changed, 2860 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/script/dom.rs create mode 100644 crates/engine/src/tests/script_dom.rs create mode 100644 crates/js/src/host_classes.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs new file mode 100644 index 0000000000..5763591ec7 --- /dev/null +++ b/crates/engine/src/script/dom.rs @@ -0,0 +1,1745 @@ +//! The script object model: the global `app`, the open documents, their selection and the art in +//! them, as the help pages , +//! , +//! , +//! and +//! describe them. +//! +//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the +//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the +//! document and the object up again. An object that was deleted, a document that was closed and an +//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each +//! 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. +//! +//! 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. +//! - 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. +//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. +//! - `app.activeDocument` with no document open throws `No active document`. +//! - 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. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; + +use super::{Host, Link, command, current, data_size}; +use crate::{DocState, Document, NodeId, NodeKind, Session}; + +/// The error for a member read or called with no document open. +pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; +/// The error for an object that was deleted, or that came from an earlier run. +pub const STALE_ITEM: &str = "Stale page item"; +/// The error for a document that was closed, or that came from an earlier run. +pub const STALE_DOCUMENT: &str = "Stale document"; +/// The error of `index` and `getByName` when nothing matches. +pub const NOT_FOUND: &str = "Not found"; +/// The most objects one read of a selection gives, and the most a selection assignment takes. +pub const MAX_LISTED: usize = 10_000; +/// The longest name an object or a path query may have, in bytes. +pub const MAX_TEXT_BYTES: usize = 4096; +/// The most artboards `Documents.add` makes. +pub const MAX_ARTBOARDS: f64 = 100.0; +/// The largest width or height `Documents.add` takes, in points, as `file.new` takes them. +pub const MAX_SIZE: f64 = 3_999_856.0; + +/// The page item classes, with the typename of each kind of object ([`typename`]). +const ITEM_CLASSES: &[&str] = &[ + "PathItem", + "CompoundPathItem", + "GroupItem", + "GraphItem", + "TextFrame", + "PlacedItem", + "RasterItem", + "SymbolItem", + "MeshItem", + "BlendItem", + "EnvelopeItem", + "RepeatItem", + "PlacedDocumentItem", + "IntertwineItem", +]; + +/// `app.coordinateSystem`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Coords { + #[default] + Document, + Artboard, +} + +const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; +const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; + +/// What the object model keeps for one run: its coordinate system and the last list of a +/// document's page items, kept while that document is unchanged. +#[derive(Default)] +pub(super) struct State { + coords: Cell, + items: RefCell>, +} + +/// A document's uid, the document as it was, and the ids of its page items then. +type ItemList = (u64, Arc, Rc>); + +type Answer = std::result::Result; + +/// A member function: the run's host and the call's arguments, `this` first. +type Member = fn(&Host, &[Data]) -> Answer; + +fn function(link: &Link, f: Member) -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(data_size).sum::())?; + f(&h, &a) + }) +} + +fn get(link: &Link, f: Member) -> HostMember { + HostMember::Get(function(link, f)) +} + +fn property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: function(link, g), set: function(link, s) } +} + +fn method(link: &Link, f: Member) -> HostMember { + HostMember::Method(function(link, f)) +} + +/// 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. +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(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + match class { + "Document" => { + doc_of(&h, arg(&a, 0), "Document")?; + } + "PageItem" => { + item_of(&h, arg(&a, 0))?; + } + _ => {} + } + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +fn text(s: impl Into) -> Data { + Data::String(s.into()) +} + +fn num(n: f64) -> Data { + Data::Number(n) +} + +fn pair(p: [f64; 2]) -> Data { + Data::Array(vec![num(p[0]), num(p[1])]) +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// A whole number from a handle or an argument, within 0 and 2^53. +#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] +fn whole(n: f64) -> Option { + (n.is_finite() && n.fract() == 0.0 && (0.0..=9_007_199_254_740_992.0).contains(&n)).then_some(n as u64) +} + +#[allow(clippy::cast_precision_loss)] +fn float(n: u64) -> f64 { + n as f64 +} + +/// A node id in a handle: its high and low 32 bits, each exact as a number. +fn id_parts(id: NodeId) -> [f64; 2] { + [float(id.0 >> 32), float(id.0 & 0xffff_ffff)] +} + +/// The node id [`id_parts`] gave as `high` and `low`. +fn id_of(high: f64, low: f64) -> Option { + let (high, low) = (whole(high)?, whole(low)?); + (high <= 0xffff_ffff && low <= 0xffff_ffff).then_some(NodeId((high << 32) | low)) +} + +/// A finite number argument, or a `TypeError` naming `what`. +fn number(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Number(n) if n.is_finite() => Ok(*n), + _ => Err(HostError::Type(format!("{what} must be a finite number"))), + } +} + +/// A coordinate argument: a finite number within the canvas. +fn coordinate(d: &Data, what: &str) -> std::result::Result { + let n = number(d, what)?; + if n.abs() > crate::MAX_COORD * 2.0 { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } + Ok(n) +} + +/// A point argument `[x, y]`. +fn point(d: &Data, what: &str) -> std::result::Result<[f64; 2], HostError> { + match d { + Data::Array(a) if a.len() == 2 => Ok([coordinate(&a[0], what)?, coordinate(&a[1], what)?]), + _ => Err(HostError::Type(format!("{what} must be an array of two numbers"))), + } +} + +fn boolean(d: &Data, what: &str) -> std::result::Result { + match d { + Data::Bool(b) => Ok(*b), + _ => Err(HostError::Type(format!("{what} must be true or false"))), + } +} + +/// The handle of `d` when it is an object of `class` (or of a page item class, for `"PageItem"`). +fn handle_of(d: &Data, class: &str) -> Option> { + let (c, handle) = host_ref_parts(d)?; + let matches = if class == "PageItem" { ITEM_CLASSES.contains(&c) } else { c == class }; + matches.then_some(handle) +} + +/// A document an object of the model names: its index among the open documents and its uid. +#[derive(Clone, Copy)] +struct Doc { + index: usize, + uid: u64, +} + +/// A page item: its document and its id. +#[derive(Clone, Copy)] +struct Item { + doc: Doc, + id: NodeId, +} + +/// The open document with `uid`, when the run's number in a handle is this run's. +fn find_doc(h: &Host, run: f64, uid: f64) -> Option { + if whole(run) != Some(h.run) { + return None; + } + let uid = whole(uid)?; + let s = h.session.borrow(); + s.documents().iter().position(|d| d.uid == uid).map(|index| Doc { index, uid }) +} + +/// The document `d` names: a `Document` or a `PageItems` object. +fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result { + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + match handle.as_slice() { + [run, uid] => find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())), + _ => Err(HostError::Type(format!("this is not a {class}"))), + } +} + +/// The page item `d` names, which must still be in its document. +fn item_of(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let s = h.session.borrow(); + let st = &s.documents()[doc.index]; + if st.doc.node(id).is_none_or(|n| typename(n).is_none()) { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok(Item { doc, id }) +} + +/// The typename of a node, or `None` for one that is not a page item (a layer or a ruler guide). +fn typename(n: &crate::doc::Node) -> Option<&'static str> { + Some(match &n.kind { + NodeKind::Layer { .. } | NodeKind::RulerGuide { .. } => return None, + NodeKind::Group { .. } if n.extras().graph.is_some() => "GraphItem", + NodeKind::Group { .. } => "GroupItem", + NodeKind::Path { .. } => "PathItem", + NodeKind::Compound { .. } => "CompoundPathItem", + NodeKind::Text(_) => "TextFrame", + NodeKind::Image(image) if image.link.is_some() => "PlacedItem", + NodeKind::Image(_) => "RasterItem", + NodeKind::SymbolInstance { .. } => "SymbolItem", + NodeKind::Mesh(_) => "MeshItem", + NodeKind::Blend { .. } => "BlendItem", + NodeKind::Envelope { .. } => "EnvelopeItem", + NodeKind::Repeat(_) => "RepeatItem", + NodeKind::PlacedDocument(_) => "PlacedDocumentItem", + NodeKind::Intertwine { .. } => "IntertwineItem", + }) +} + +fn doc_ref(h: &Host, uid: u64) -> Data { + host_ref("Document", &[float(h.run), float(uid)]) +} + +fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { + match st.doc.node(id) { + Some(n) => match typename(n) { + Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + }, + None => Data::Null, + } +} + +/// The ids of a document's page items in paint order ([`State`] keeps the last list). +fn page_items(h: &Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.items.borrow() + && *uid == st.uid + && Arc::ptr_eq(doc, &st.doc) + { + return ids.clone(); + } + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + out.push(n.id); + walk(children, out); + } + _ => out.push(n.id), + } + } + } + let mut ids = Vec::new(); + walk(&st.doc.layers, &mut ids); + let ids = Rc::new(ids); + *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + ids +} + +/// The objects directly in the layers and sublayers of a document: what deleting every page item +/// deletes. +fn top_items(d: &Document) -> Vec { + fn walk(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => out.push(n.id), + } + } + } + let mut out = Vec::new(); + walk(&d.layers, &mut out); + out +} + +/// Whether `n` and every object inside it are shown and unlocked. +fn all_editable(n: &crate::doc::Node) -> bool { + n.visible && !n.locked && n.children().is_none_or(|c| c.iter().all(|c| all_editable(c))) +} + +/// Whether the object and every layer and group it is in are shown and unlocked. +fn editable(d: &Document, id: NodeId) -> bool { + d.ancestry(id).is_some_and(|a| a.iter().chain(std::iter::once(&id)).all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked))) +} + +/// The two rectangles script coordinates are measured from. +struct Frame { + /// The first artboard's left edge and bottom edge. + left0: f64, + bottom0: f64, + /// The active artboard's left edge and top edge. + left: f64, + top: f64, +} + +/// The index of the active artboard of `st`, as the view keeps it. +fn active_artboard(st: &DocState) -> usize { + let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); + st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) +} + +fn frame(st: &DocState) -> std::result::Result { + let (Some(first), Some(active)) = (st.doc.artboards.first(), st.doc.artboards.get(active_artboard(st))) else { + return Err(HostError::Error("the document has no artboards".into())); + }; + Ok(Frame { left0: first.rect.x0, bottom0: first.rect.y1, left: active.rect.x0, top: active.rect.y0 }) +} + +impl Frame { + /// A point in document coordinates as the script sees it in `c`. + fn to_script(&self, c: Coords, p: Point) -> [f64; 2] { + match c { + Coords::Document => [p.x - self.left0, self.bottom0 - p.y], + Coords::Artboard => [p.x - self.left, p.y - self.top], + } + } + + /// A point the script gave in `c`, in document coordinates. + fn to_document(&self, c: Coords, p: [f64; 2]) -> Point { + match c { + Coords::Document => Point::new(p[0] + self.left0, self.bottom0 - p[1]), + Coords::Artboard => Point::new(p[0] + self.left, p[1] + self.top), + } + } + + /// `[left, top, right, bottom]` of `r` as the script sees it. + fn bounds(&self, c: Coords, r: Rect) -> Data { + let a = self.to_script(c, Point::new(r.x0, r.y0)); + let b = self.to_script(c, Point::new(r.x1, r.y1)); + Data::Array(vec![num(a[0]), num(a[1]), num(b[0]), num(b[1])]) + } +} + +fn coords_of(d: &Data) -> std::result::Result { + match d { + Data::String(s) if s == DOCUMENT_COORDS => Ok(Coords::Document), + Data::String(s) if s == ARTBOARD_COORDS => Ok(Coords::Artboard), + _ => Err(HostError::Type("give a CoordinateSystem value".into())), + } +} + +/// Selects `before` again in the active document `doc` with the selection commands, so that the +/// journal holds the change: the whole objects, then the direct-selected anchors and segments, the +/// ruler guides and the key object, guide or anchor. Objects that are now deleted, hidden or +/// locked are left out. +fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { + // Slices selected with the Slice Selection tool are the whole selection when there are any. + let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); + if !slices.is_empty() { + command(h, "object.slice.select", &json!({"slices": slices}))?; + return Ok(()); + } + let keep = |id: &NodeId| editable(doc, *id); + let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); + let whole: Vec = before.objects.iter().filter(|i| keep(i) && !partial(i)).map(|i| i.0).collect(); + if whole.is_empty() { + command(h, "select.none", &json!({}))?; + } else { + command(h, "select.set", &json!({"ids": whole}))?; + } + let items: Vec = before + .anchors + .iter() + .filter(|(i, _)| keep(i)) + .map(|(i, a)| json!({"id": i.0, "anchors": a.iter().map(|(p, k)| [p, k]).collect::>()})) + .collect(); + if !items.is_empty() { + command(h, "select.anchorsMany", &json!({"items": items, "mode": "add"}))?; + } + for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { + let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); + command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?; + } + let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); + let index = |id: &NodeId| guides.iter().position(|g| g == id); + let picked: Vec = before.guides.iter().filter_map(index).collect(); + // Guides that are locked now, and a key that no longer qualifies (the objects beside it are + // gone), stay unselected: those commands refuse them and change nothing. + if !picked.is_empty() { + let _ = command(h, "guide.select", &json!({"indexes": picked, "toggle": true})); + } + let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { + Some(json!({"id": id.0, "anchor": [p, k]})) + } else if let Some(id) = before.key.filter(keep) { + Some(json!({"id": id.0})) + } else { + before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) + }; + if let Some(key) = key { + let _ = command(h, "select.key", &key); + } + Ok(()) +} + +/// Runs `f` with the document `uid` active, and makes the document that was active before active +/// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s +/// commands changed it (commands given ids select them first), direct-selected anchors, segments, +/// ruler guides, slices and the key included, less the objects that are now deleted, hidden or +/// locked. +fn on_doc( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + let (index, active, before) = { + let s = h.session.borrow(); + let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + (index, s.active_index(), s.documents()[index].selection.clone()) + }; + let switch = active != Some(index); + if switch { + command(h, "document.activate", &json!({"index": index}))?; + } + let r = f(h); + if keep_selection { + let doc = { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) + }; + if let Some(doc) = doc { + let back = restore_selection(h, &doc, &before); + if r.is_ok() { + back?; + } + } + } + if switch && let Some(a) = active { + let back = command(h, "document.activate", &json!({"index": a})); + if r.is_ok() { + back?; + } + } + r +} + +/// Runs `id` with `params` on the item's document, its selection kept. +fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + on_doc(h, item.doc.uid, true, |h| command(h, id, params)) +} + +/// Reads the document of `doc` with `f`. +fn with_doc(h: &Host, doc: Doc, f: impl FnOnce(&Session, &DocState) -> T) -> T { + let s = h.session.borrow(); + f(&s, &s.documents()[doc.index]) +} + +// ---- Application ---- + +fn app_documents(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Documents", &[])) +} + +fn app_active(h: &Host, _: &[Data]) -> Answer { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn app_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 1), "Document")?; + if h.session.borrow().active_index() != Some(doc.index) { + command(h, "document.activate", &json!({"index": doc.index}))?; + } + Ok(Data::Undefined) +} + +fn app_selection(h: &Host, _: &[Data]) -> Answer { + let uid = h.session.borrow().active().map(|st| st.uid); + match uid { + Some(uid) => selection_of(h, uid), + None => Ok(Data::Null), + } +} + +fn app_coords(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS })) +} + +fn app_set_coords(h: &Host, a: &[Data]) -> Answer { + h.dom.coords.set(coords_of(arg(a, 1))?); + Ok(Data::Undefined) +} + +/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter +/// or a `\`) letters in one case. +fn path_key(p: &str) -> String { + let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); + let p = p.replace('\\', "/"); + let p = p.trim_end_matches('/').to_string(); + if windows { p.to_lowercase() } else { p } +} + +/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is +/// compared as text with the documents' files and is not resolved; a document whose file the +/// automation read roots do not allow does not count, and that check can look the file up on disk. +fn app_is_open(h: &Host, a: &[Data]) -> Answer { + let Data::String(path) = arg(a, 1) else { return Err(HostError::Type("getIsFileOpen needs a path, as a string".into())) }; + if path.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the path is too long".into())); + } + let unc = path.starts_with("\\\\") || path.starts_with("//"); + if path.is_empty() || path.contains('\0') || unc || path.split(['/', '\\']).any(|c| c == "..") { + return Err(HostError::Error("getIsFileOpen cannot check that path".into())); + } + let key = path_key(path); + let s = h.session.borrow(); + let open = s.documents().iter().filter_map(|d| d.path.as_deref()).any(|p| path_key(p) == key && crate::file_access::check_read(p).is_ok()); + Ok(Data::Bool(open)) +} + +// ---- Documents ---- + +fn docs_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(h.session.borrow().documents().len() as u64))) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +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)), + _ => None, + }; + Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid))) +} + +fn docs_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn docs_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => docs_by_name(h, a), + Data::Number(_) => match docs_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `file.new`'s `artboardLayout.layout` and whether it runs right to left, for a +/// `DocumentArtboardLayout` value. +fn layout_of(d: &Data) -> std::result::Result<(&'static str, bool), HostError> { + let Data::String(s) = d else { return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())) }; + Ok(match s.strip_prefix("DocumentArtboardLayout.").unwrap_or("") { + "GridByRow" => ("gridByRow", false), + "GridByCol" => ("gridByColumn", false), + "Row" => ("row", false), + "Column" => ("column", false), + "RLGridByRow" => ("gridByRow", true), + "RLGridByCol" => ("gridByColumn", true), + "RLRow" => ("row", true), + _ => return Err(HostError::Type("artboardLayout must be a DocumentArtboardLayout value".into())), + }) +} + +/// The settings of a new document a script gives, each `None` when it was left out. +#[derive(Default)] +struct NewDoc<'a> { + color_space: Option<&'a Data>, + width: Option<&'a Data>, + height: Option<&'a Data>, + artboards: Option<&'a Data>, + layout: Option<&'a Data>, + spacing: Option<&'a Data>, + rows_or_cols: Option<&'a Data>, + units: Option<&'a Data>, + title: Option<&'a Data>, + preview: Option<&'a Data>, + resolution: Option<&'a Data>, +} + +/// `d`, unless it is `undefined`. +fn given(d: &Data) -> Option<&Data> { + (!matches!(d, Data::Undefined)).then_some(d) +} + +impl NewDoc<'_> { + /// `file.new`'s params for these settings, checked before anything is made. + fn params(&self) -> std::result::Result, HostError> { + let mut p = serde_json::Map::new(); + if let Some(d) = self.color_space { + let mode = match d { + Data::String(s) if s == "DocumentColorSpace.RGB" => "rgb", + Data::String(s) if s == "DocumentColorSpace.CMYK" => "cmyk", + _ => return Err(HostError::Type("colorSpace must be a DocumentColorSpace value".into())), + }; + p.insert("colorMode".into(), json!(mode)); + } + for (d, key) in [(self.width, "width"), (self.height, "height")] { + if let Some(d) = d { + let v = number(d, key)?; + if v <= 0.0 || v > MAX_SIZE { + return Err(HostError::Range(format!("{key} must be more than 0 and at most 3999856 points"))); + } + p.insert(key.into(), json!(v)); + } + } + let count = match self.artboards { + Some(d) => { + let n = number(d, "numArtBoards")?; + if n.fract() != 0.0 || !(1.0..=MAX_ARTBOARDS).contains(&n) { + return Err(HostError::Range("numArtBoards must be a whole number from 1 to 100".into())); + } + p.insert("artboards".into(), json!(n)); + n + } + None => 1.0, + }; + let mut layout = serde_json::Map::new(); + if let Some(d) = self.layout { + let (name, rtl) = layout_of(d)?; + layout.insert("layout".into(), json!(name)); + layout.insert("rightToLeft".into(), json!(rtl)); + } + if let Some(d) = self.spacing { + let v = number(d, "artboardSpacing")?; + if !(0.0..=MAX_SIZE).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 3999856 points".into())); + } + layout.insert("spacing".into(), json!(v)); + } + if let Some(d) = self.rows_or_cols { + let n = number(d, "artboardRowsOrCols")?; + if n.fract() != 0.0 || n < 1.0 || n > count { + return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into())); + } + // A grid filled by column takes the number of rows; `file.new` takes columns. + let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn"); + let columns = if by_column { (count / n).ceil() } else { n }; + layout.insert("columns".into(), json!(columns)); + } + if !layout.is_empty() { + p.insert("artboardLayout".into(), Value::Object(layout)); + } + if let Some(d) = self.units { + let units = match d { + Data::String(s) => match s.strip_prefix("RulerUnits.").unwrap_or("") { + u @ ("Points" | "Picas" | "Inches" | "Millimeters" | "Centimeters" | "Pixels") => u, + "Qs" | "Unknown" => return Err(HostError::Range(format!("a new document cannot have the units {s}"))), + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }, + _ => return Err(HostError::Type("units must be a RulerUnits value".into())), + }; + p.insert("units".into(), json!(units)); + } + if let Some(d) = self.title { + let Data::String(t) = d else { return Err(HostError::Type("title must be a string".into())) }; + if t.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the title is too long".into())); + } + p.insert("name".into(), json!(t)); + } + if let Some(d) = self.preview { + let mode = match d { + Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", + Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", + _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), + }; + p.insert("previewMode".into(), json!(mode)); + } + if let Some(d) = self.resolution { + let ppi = match d { + Data::String(s) if s == "DocumentRasterResolution.ScreenResolution" => 72, + Data::String(s) if s == "DocumentRasterResolution.MediumResolution" => 150, + Data::String(s) if s == "DocumentRasterResolution.HighResolution" => 300, + _ => return Err(HostError::Type("rasterResolution must be a DocumentRasterResolution value".into())), + }; + p.insert("rasterEffectsPpi".into(), json!(ppi)); + } + Ok(p) + } +} + +/// Runs `file.new` with `p`. → the new document, which is the active one. +fn new_document(h: &Host, p: serde_json::Map) -> Answer { + command(h, "file.new", &Value::Object(p))?; + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +/// `documents.add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, +/// artboardRowsOrCols?)`: a new document from `file.new`, which becomes the active one. +fn docs_add(h: &Host, a: &[Data]) -> Answer { + let settings = NewDoc { + color_space: given(arg(a, 1)), + width: given(arg(a, 2)), + height: given(arg(a, 3)), + artboards: given(arg(a, 4)), + layout: given(arg(a, 5)), + spacing: given(arg(a, 6)), + rows_or_cols: given(arg(a, 7)), + ..NewDoc::default() + }; + new_document(h, settings.params()?) +} + +/// The error of `addDocument` with `showOptionsDialog` true: a script cannot open the New +/// Document dialog. +pub const DIALOG_UNAVAILABLE: &str = "Dialog unavailable"; + +/// The New Document profile a startup preset names (`None`: no profile), and the color mode the +/// basic presets give. +fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static str>)> { + let name = name.strip_prefix("DocumentPresetType.").unwrap_or(name); + let squashed: String = name.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + Some(match squashed.as_str() { + "basiccmyk" => (None, Some("cmyk")), + "basicrgb" => (None, Some("rgb")), + "video" | "film&video" => (Some("Film & Video"), None), + _ => { + let same = |p: &&str| p.chars().filter(|c| !c.is_whitespace()).collect::().eq_ignore_ascii_case(&squashed); + (Some(crate::cmd::newdoc::profile_names().find(same)?), None) + } + }) +} + +/// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from +/// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in +/// place of the profile's. +fn docs_add_document(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("addDocument needs a startup preset's name".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the startup preset's name is too long".into())); + } + let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + let settings = match given(arg(a, 2)) { + None | Some(Data::Null) => Vec::new(), + Some(Data::Object(o)) => o.clone(), + Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())), + }; + let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); + for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { + if field(k).is_some_and(|d| !matches!(d, Data::Null)) { + return Err(HostError::Error(format!("DocumentPreset.{k} is not available yet"))); + } + } + let new = NewDoc { + color_space: field("colorMode"), + width: field("width"), + height: field("height"), + artboards: field("numArtboards"), + layout: field("artboardLayout"), + spacing: field("artboardSpacing"), + rows_or_cols: field("artboardRowsOrCols"), + units: field("units"), + title: field("title"), + preview: field("previewMode"), + resolution: field("rasterResolution"), + }; + let mut p = new.params()?; + match given(arg(a, 3)) { + None => {} + Some(Data::Bool(false)) => {} + Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())), + Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), + } + // The document starts from the first preset of the profile's category (Print: Letter). + let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + if let Some(first) = first { + p.insert("preset".into(), json!(first.name)); + } + p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); + if let Some(m) = mode { + p.entry("colorMode").or_insert_with(|| json!(m)); + } + new_document(h, p) +} + +/// `new DocumentPreset()`: a record of new-document settings with the defaults the help page +/// gives; the other settings are +/// left out. +fn new_preset(_: &[Data]) -> Answer { + let item = |k: &str, v: Data| (k.to_string(), v); + Ok(Data::Object(vec![ + item("typename", text("DocumentPreset")), + item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), + item("artboardRowsOrCols", num(1.0)), + item("artboardSpacing", num(20.0)), + item("height", num(792.0)), + item("numArtboards", num(1.0)), + item("width", num(612.0)), + ])) +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_typename(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(text("Document")) +} + +fn doc_parent(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(host_ref("Application", &[])) +} + +fn doc_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(text(with_doc(h, doc, |_, st| st.title()))) +} + +fn doc_size(h: &Host, a: &[Data], width: bool) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let r = st.doc.artboards.first().map(|b| b.rect).ok_or_else(|| HostError::Error("the document has no artboards".into()))?; + Ok(num(if width { r.width() } else { r.height() })) + }) +} + +fn doc_width(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, true) +} + +fn doc_height(h: &Host, a: &[Data]) -> Answer { + doc_size(h, a, false) +} + +fn doc_units(h: &Host, a: &[Data]) -> Answer { + use crate::doc::Unit; + let doc = this_doc(h, a)?; + let unit = with_doc(h, doc, |_, st| st.doc.units); + Ok(text(match unit { + Unit::Points => "RulerUnits.Points", + Unit::Picas => "RulerUnits.Picas", + Unit::Inches => "RulerUnits.Inches", + Unit::Millimeters => "RulerUnits.Millimeters", + Unit::Centimeters => "RulerUnits.Centimeters", + Unit::Pixels => "RulerUnits.Pixels", + Unit::Q => "RulerUnits.Qs", + _ => "RulerUnits.Unknown", + })) +} + +fn doc_color_space(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let cmyk = with_doc(h, doc, |_, st| st.doc.color_mode == crate::doc::ColorMode::Cmyk); + Ok(text(if cmyk { "DocumentColorSpace.CMYK" } else { "DocumentColorSpace.RGB" })) +} + +fn doc_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(Coords::Document, st.doc.ruler_origin_for(active_artboard(st))))) + }) +} + +/// `rulerOrigin = [x, y]`, in document coordinates: `document.setRulerOrigin` for the active +/// artboard. The art stays where it is. +fn doc_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "rulerOrigin")?; + let (to, now, artboard) = with_doc(h, doc, |_, st| { + let f = frame(st)?; + let artboard = active_artboard(st); + Ok::<_, HostError>((f.to_document(Coords::Document, p), st.doc.ruler_origin_for(artboard), artboard)) + })?; + if to.distance(now) > 1e-9 { + on_doc(h, doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": artboard})))?; + } + Ok(Data::Undefined) +} + +/// `convertCoordinate(point, source, destination)`: `point` from one coordinate system of the +/// document to another. Nothing changes. +fn doc_convert(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let p = point(arg(a, 1), "point")?; + let (from, to) = (coords_of(arg(a, 2))?, coords_of(arg(a, 3))?); + with_doc(h, doc, |_, st| { + let f = frame(st)?; + Ok(pair(f.to_script(to, f.to_document(from, p)))) + }) +} + +fn doc_page_items(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("PageItems", &[float(h.run), float(doc.uid)])) +} + +fn doc_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + selection_of(h, doc.uid) +} + +/// The selection of the document `uid`: `null` when nothing is selected, otherwise a new list of +/// the selected objects. +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 { + return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) +} + +/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or +/// `[]`. Every one must be an object of that document that can be selected. +fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { + let list: Vec<&Data> = match v { + Data::Null | Data::Undefined => Vec::new(), + Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), + Data::Array(a) => a.iter().collect(), + d => vec![d], + }; + let mut ids: Vec = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + let ok = item.doc.uid == doc.uid + && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); + if !ok { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if !ids.contains(&item.id) { + ids.push(item.id); + } + } + Ok(ids) +} + +fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + +/// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each +/// selected as a whole, and no ruler guide, slice or key. +fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { + let same = with_doc(h, doc, |_, st| { + let sel = &st.selection; + sel.objects == ids + && sel.anchors.is_empty() + && sel.segments.is_empty() + && sel.guides.is_empty() + && sel.slices.is_empty() + && sel.key.is_none() + && sel.key_guide.is_none() + && sel.key_anchor.is_none() + }); + if same { + return Ok(Data::Undefined); + } + on_doc(h, doc.uid, false, |h| { + if ids.is_empty() { + command(h, "select.none", &json!({})) + } else { + command(h, "select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + } + })?; + Ok(Data::Undefined) +} + +// ---- PageItems ---- + +fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "PageItems") +} + +fn items_length(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let n = with_doc(h, doc, |_, st| page_items(h, st).len()); + Ok(num(float(n as u64))) +} + +fn items_typename(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("PageItems")) +} + +fn items_parent(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn items_at(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + 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)))) +} + +fn items_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = page_items(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn items_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => items_by_name(h, a), + Data::Number(_) => match items_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. +fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = top_items(&st.doc); + let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- PageItem ---- + +fn this_item(h: &Host, a: &[Data]) -> std::result::Result { + item_of(h, arg(a, 0)) +} + +/// Reads the item `this` names with `f`, given its document and node. +fn read_item(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let item = this_item(h, a)?; + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn item_typename(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(typename(n).unwrap_or("PageItem")))) +} + +fn item_parent(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).map_or(Data::Null, |p| item_ref(h, st, p)))) +} + +fn item_name(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +/// Runs `object.setProps` with `props` for the item, unless `unchanged` says the node has them. +fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> bool, props: Value) -> Answer { + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([item.id.0])); + } + edit_item(h, item, "object.setProps", &p)?; + } + Ok(Data::Undefined) +} + +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())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + set_props(h, a, |n| n.name.as_deref().unwrap_or("") == name, json!({"name": name})) +} + +fn note_of(n: &crate::doc::Node) -> &str { + n.extras().attrs.as_deref().map_or("", |a| a.note.as_str()) +} + +fn item_note(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(text(note_of(n)))) +} + +/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. +fn item_set_note(h: &Host, a: &[Data]) -> Answer { + let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) }; + if note.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the note is too long".into())); + } + let item = this_item(h, a)?; + let same = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| note_of(n) == note.trim())); + if !same { + edit_item(h, item, "attributes.set", &json!({"ids": [item.id.0], "note": note}))?; + } + Ok(Data::Undefined) +} + +fn item_hidden(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(!n.visible))) +} + +fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { + let hidden = boolean(arg(a, 1), "hidden")?; + set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) +} + +fn item_locked(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn item_set_locked(h: &Host, a: &[Data]) -> Answer { + let locked = boolean(arg(a, 1), "locked")?; + set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) +} + +fn item_opacity(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) +} + +fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + if !(0.0..=100.0).contains(&v) { + return Err(HostError::Range("opacity must be from 0 to 100".into())); + } + set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) +} + +fn item_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) +} + +fn item_set_selected(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let on = boolean(arg(a, 1), "selected")?; + let mut ids = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); + if ids.contains(&item.id) == on { + return Ok(Data::Undefined); + } + if on { + let mut given = selection_ids(h, item.doc, arg(a, 0))?; + ids.append(&mut given); + } else { + ids.retain(|i| *i != item.id); + } + set_selection(h, item.doc, ids) +} + +/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the +/// document's [`Frame`]. +fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Rect, Frame), HostError> { + with_doc(h, item.doc, |_, st| { + let r = st.doc.bounds_of(&[item.id], visual).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok((r, frame(st)?)) + }) +} + +fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, visual)?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + +fn item_geometric(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, false) +} + +fn item_visible(h: &Host, a: &[Data]) -> Answer { + bounds(h, a, true) +} + +fn item_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, false)?; + Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))) +} + +fn item_left(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().next().unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_top(h: &Host, a: &[Data]) -> Answer { + match item_position(h, a)? { + Data::Array(p) => Ok(p.into_iter().nth(1).unwrap_or(Data::Undefined)), + d => Ok(d), + } +} + +fn item_width(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.width())) +} + +fn item_height(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(num(item_rect(h, item, false)?.0.height())) +} + +/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one +/// stays). +fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, false)?; + let c = h.dom.coords.get(); + let now = f.to_script(c, Point::new(r.x0, r.y0)); + let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); + let (dx, dy) = (to.x - r.x0, to.y - r.y0); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; + } + Ok(Data::Undefined) +} + +fn item_set_position(h: &Host, a: &[Data]) -> Answer { + let p = point(arg(a, 1), "position")?; + move_to(h, a, Some(p[0]), Some(p[1])) +} + +fn item_set_left(h: &Host, a: &[Data]) -> Answer { + let x = coordinate(arg(a, 1), "left")?; + move_to(h, a, Some(x), None) +} + +fn item_set_top(h: &Host, a: &[Data]) -> Answer { + let y = coordinate(arg(a, 1), "top")?; + move_to(h, a, None, Some(y)) +} + +/// Scales the item about its top-left corner to `size` points wide (`width`) or tall. +fn resize(h: &Host, a: &[Data], width: bool) -> Answer { + let what = if width { "width" } else { "height" }; + let size = number(arg(a, 1), what)?; + if size <= 0.0 || size > MAX_SIZE { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); + } + let item = this_item(h, a)?; + let (r, _) = item_rect(h, item, false)?; + let now = if width { r.width() } else { r.height() }; + if now <= 0.0 { + return Err(HostError::Error(format!("the object has no {what} to scale"))); + } + if (now - size).abs() < 1e-9 { + return Ok(Data::Undefined); + } + let pct = size / now * 100.0; + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}); + edit_item(h, item, "object.scale", &p)?; + Ok(Data::Undefined) +} + +fn item_set_width(h: &Host, a: &[Data]) -> Answer { + resize(h, a, true) +} + +fn item_set_height(h: &Host, a: &[Data]) -> Answer { + resize(h, a, false) +} + +fn item_editable(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)))) +} + +/// The item's place in its parent's stacking order, from 1 at the bottom. +fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let at = with_doc(h, item.doc, |_, st| st.doc.position(item.id).map(|(_, i, _)| i)); + at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) +} + +fn item_remove(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; + Ok(Data::Undefined) +} + +/// The error of `move` and `duplicate` given an object of another document. +pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; + +/// An `ElementPlacement` value. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Placement { + /// `INSIDE` and `PLACEATBEGINNING`: on top of the container's contents. + Top, + /// `PLACEATEND`: under the container's contents. + Bottom, + /// `PLACEBEFORE`: directly above the relative object, in its parent. + Above, + /// `PLACEAFTER`: directly below the relative object, in its parent. + Below, +} + +fn placement_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(Placement::Top), + Data::String(s) => match s.as_str() { + "ElementPlacement.INSIDE" | "ElementPlacement.PLACEATBEGINNING" => Ok(Placement::Top), + "ElementPlacement.PLACEATEND" => Ok(Placement::Bottom), + "ElementPlacement.PLACEBEFORE" => Ok(Placement::Above), + "ElementPlacement.PLACEAFTER" => Ok(Placement::Below), + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + }, + _ => Err(HostError::Type("insertionLocation must be an ElementPlacement value".into())), + } +} + +/// Where `move` and `duplicate` put an object relative to `target`: the parent it goes into and +/// the target it goes beside, checked against the object `item` before anything changes. +struct Destination { + parent: NodeId, + beside: Option, + how: Placement, +} + +/// 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 { + 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")); + let Some(&[run, uid, high, low]) = handle.as_deref() else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if doc.uid != item.doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + with_doc(h, doc, |_, st| { + 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)) { + return Err(HostError::Error("an object cannot go into itself".into())); + } + let (parent, beside) = match how { + Placement::Top | Placement::Bottom => { + if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); + } + (target, None) + } + Placement::Above | Placement::Below => { + let parent = d.parent_of(target).ok_or_else(|| HostError::Error("an object cannot go beside a top-level layer".into()))?; + (parent, Some(target)) + } + }; + if !editable(d, parent) { + return Err(HostError::Error("the layer or group is hidden or locked".into())); + } + if !editable(d, item.id) { + let name = d.node(item.id).and_then(typename).unwrap_or("page item"); + return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); + } + Ok(Destination { parent, beside, how }) + }) +} + +/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. +fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { + let index = with_doc(h, doc, |_, st| { + let d = &st.doc; + let from = d.position(id); + let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); + let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + let at = match (to.how, to.beside) { + (Placement::Top, _) => count, + (Placement::Bottom, _) => 0, + (how, Some(b)) => { + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if let Some((Some(p), j, _)) = from + && p == to.parent + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (_, None) => count, + }; + Ok::<_, HostError>(if clips { at.max(1) } else { at }) + })?; + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { + return Ok(()); + } + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": to.parent.0, "index": index})))?; + Ok(()) +} + +/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a +/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). +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)?; + place(h, item.doc, item.id, &to)?; + Ok(arg(a, 0).clone()) +} + +/// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as +/// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. +/// When `node.move` refuses the place, the copy is deleted and the error is thrown. +fn item_duplicate(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let to = match arg(a, 1) { + Data::Undefined => { + if !matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("duplicate needs a relative object for an insertionLocation".into())); + } + None + } + target => Some(destination(h, item, target, arg(a, 2), true)?), + }; + let r = edit_item(h, item, "edit.duplicate", &json!({"ids": [item.id.0]}))?; + let id = match &r { + Data::Object(o) => o.iter().find(|(k, _)| k == "ids").and_then(|(_, v)| match v { + Data::Array(ids) => ids.first().and_then(|d| if let Data::Number(n) = d { whole(*n) } else { None }), + _ => None, + }), + _ => None, + }; + let id = id.ok_or_else(|| HostError::Error("the copy was not made".into()))?; + if let Some(to) = to + && let Err(e) = place(h, item.doc, NodeId(id), &to) + { + edit_item(h, item, "edit.clear", &json!({"ids": [id]}))?; + return Err(e); + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +/// `zOrder(method)`: one of the four Object › Arrange commands for the item. +fn item_z_order(h: &Host, a: &[Data]) -> Answer { + let id = match arg(a, 1) { + Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", + Data::String(s) if s == "ZOrderMethod.BRINGFORWARD" => "object.arrange.bringForward", + Data::String(s) if s == "ZOrderMethod.SENDBACKWARD" => "object.arrange.sendBackward", + Data::String(s) if s == "ZOrderMethod.SENDTOBACK" => "object.arrange.sendToBack", + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + let item = this_item(h, a)?; + let (before, after) = with_doc(h, item.doc, |_, st| { + let at = st.doc.position(item.id); + let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); + (at.map(|(_, i, _)| i), count) + }); + let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; + let top = i + 1 >= after; + let unchanged = match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => top, + _ => i == 0, + }; + if !unchanged { + edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + } + Ok(Data::Undefined) +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); + with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + layer_name(h, a)?; + Ok(text("Layer")) +} + +fn typename_of(name: &'static str) -> HostMember { + HostMember::Get(Rc::new(move |_| Ok(text(name)))) +} + +fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { + HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +} + +fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { + items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +} + +/// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. +const ENUMS: &[(&str, &[&str])] = &[ + ("ElementPlacement", &["INSIDE", "PLACEAFTER", "PLACEATBEGINNING", "PLACEATEND", "PLACEBEFORE"]), + ("ZOrderMethod", &["BRINGFORWARD", "SENDBACKWARD", "BRINGTOFRONT", "SENDTOBACK"]), + ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), + ("DocumentColorSpace", &["CMYK", "RGB"]), + ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), + ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), + ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), + ("DocumentRasterResolution", &["ScreenResolution", "HighResolution", "MediumResolution"]), + ( + "DocumentTransparencyGrid", + &[ + "TransparencyGridBlue", + "TransparencyGridDark", + "TransparencyGridGreen", + "TransparencyGridLight", + "TransparencyGridMedium", + "TransparencyGridNone", + "TransparencyGridOrange", + "TransparencyGridPurple", + "TransparencyGridRed", + ], + ), +]; + +/// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` +/// holds. +pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + let l = link; + let mut application = named(vec![ + ("typename", typename_of("Application")), + ("documents", get(l, app_documents)), + ("activeDocument", property(l, app_active, app_set_active)), + ("selection", get(l, app_selection)), + ("coordinateSystem", property(l, app_coords, app_set_coords)), + ("getIsFileOpen", method(l, app_is_open)), + ]); + application.push(later(l, "Application", "beep")); + let preset = { + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + current(&l)?.charge_call(64)?; + new_preset(&a) + }); + HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }; + let mut classes = vec![ + class("Application", None, application, None), + preset, + class( + "Documents", + None, + named(vec![ + ("typename", typename_of("Documents")), + ("length", get(l, docs_length)), + ("parent", get(l, app_ref)), + ("index", method(l, docs_index)), + ("getByName", method(l, docs_by_name)), + ("add", method(l, docs_add)), + ("addDocument", method(l, docs_add_document)), + ]), + Some(function(l, docs_at)), + ), + ]; + let mut document = named(vec![ + ("typename", get(l, doc_typename)), + ("parent", get(l, doc_parent)), + ("name", get(l, doc_name)), + ("width", get(l, doc_width)), + ("height", get(l, doc_height)), + ("rulerUnits", get(l, doc_units)), + ("documentColorSpace", get(l, doc_color_space)), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), + ("convertCoordinate", method(l, doc_convert)), + ("pageItems", get(l, doc_page_items)), + ("selection", property(l, doc_selection, doc_set_selection)), + ]); + document.extend( + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + .into_iter() + .map(|m| later(l, "Document", m)), + ); + classes.push(class("Document", None, document, None)); + classes.push(class( + "PageItems", + None, + named(vec![ + ("typename", get(l, items_typename)), + ("length", get(l, items_length)), + ("parent", get(l, items_parent)), + ("index", method(l, items_index)), + ("getByName", method(l, items_by_name)), + ("removeAll", method(l, items_remove_all)), + ]), + Some(function(l, items_at)), + )); + let mut page_item = named(vec![ + ("typename", get(l, item_typename)), + ("parent", get(l, item_parent)), + ("name", property(l, item_name, item_set_name)), + ("note", property(l, item_note, item_set_note)), + ("hidden", property(l, item_hidden, item_set_hidden)), + ("locked", property(l, item_locked, item_set_locked)), + ("selected", property(l, item_selected, item_set_selected)), + ("opacity", property(l, item_opacity, item_set_opacity)), + ("position", property(l, item_position, item_set_position)), + ("left", property(l, item_left, item_set_left)), + ("top", property(l, item_top, item_set_top)), + ("width", property(l, item_width, item_set_width)), + ("height", property(l, item_height, item_set_height)), + ("geometricBounds", get(l, item_geometric)), + ("visibleBounds", get(l, item_visible)), + ("controlBounds", get(l, item_visible)), + ("editable", get(l, item_editable)), + ("zOrderPosition", get(l, item_z_order_position)), + ("duplicate", method(l, item_duplicate)), + ("move", method(l, item_move)), + ("remove", method(l, item_remove)), + ("zOrder", method(l, item_z_order)), + ]); + page_item.extend( + [ + "artworkKnockout", + "blendingMode", + "isIsolated", + "layer", + "pixelAligned", + "sliced", + "tags", + "uRL", + "uuid", + "visibilityVariable", + "wrapInside", + "wrapOffset", + "wrapped", + "bringInPerspective", + "resize", + "rotate", + "transform", + "translate", + ] + .into_iter() + .map(|m| later(l, "PageItem", m)), + ); + 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", &[]))]) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..5ec5e2e92b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -51,6 +51,7 @@ pub mod console; pub mod dialogs; pub mod dollar; +pub mod dom; pub mod include; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; @@ -799,6 +800,8 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The run's state of the script object model (`app`). + dom: dom::State, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1293,6 +1296,15 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result { + let id = id.to_string(); + let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { @@ -1564,11 +1576,17 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; + const APP_MEMBERS: &[&str] = &["activeDocument", "documents", "selection"]; let message = &e.message; - let names_host_object = - message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); - if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { + 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 { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { message.to_string() @@ -2040,6 +2058,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + dom: dom::State::default(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2076,6 +2095,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d92bcb7d71..adcaefd59d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -172,6 +172,7 @@ mod scalestrokes; mod script_console; mod script_dialogs; mod script_dollar; +mod script_dom; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs new file mode 100644 index 0000000000..c3eaea7f4f --- /dev/null +++ b/crates/engine/src/tests/script_dom.rs @@ -0,0 +1,681 @@ +//! The script object model: `app`, its documents, their selection and page items. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +#[test] +fn app_documents_track_active_tab_and_new_document() { + let mut s = Session::new(); + assert_eq!(log(&mut s, "vc.log(app.documents.length); vc.log(app.typename);"), vec![json!(0), json!("Application")]); + assert!(failure(&mut s, "app.activeDocument;").contains("No active document")); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let out = log( + &mut s, + "var d = app.documents; vc.log(d.length); vc.log(app.activeDocument.width);\ + app.activeDocument = d[0]; vc.log(app.activeDocument.width); vc.log(d[0].parent.typename);\ + vc.log(d[5] === undefined); vc.log(app.activeDocument instanceof Document);\ + var n = d.add(DocumentColorSpace.CMYK, 50, 60, 2);\ + vc.log(d.length); vc.log(app.activeDocument.name === n.name); vc.log(n.documentColorSpace); vc.log(n.height);\ + vc.log(d.getByName(n.name).width);", + ); + let expected = [json!(2), json!(200), json!(400), json!("Application"), json!(true), json!(true), json!(3), json!(true)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("DocumentColorSpace.CMYK"), json!(60), json!(50)]); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active_index(), Some(2)); + assert_eq!(s.documents()[2].doc.artboards.len(), 2); + // A bad argument changes nothing. + assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); + assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); + assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); + assert_eq!(s.documents().len(), 3); +} + +#[test] +fn page_items_are_live_and_typed_for_all_node_kinds() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + let out = log( + &mut s, + "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);", + ); + assert_eq!( + out, + vec![ + json!("GroupItem,PathItem,PathItem,PathItem,TextFrame"), + json!("GroupItem"), + json!("Layer"), + json!("Document"), + json!(4), + json!(true), + json!(true) + ] + ); +} + +#[test] +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];\ + 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;\ + i.position = [20, 250]; i.width = 60; vc.log(i.geometricBounds);", + ); + assert_eq!(out[0], json!([10, 280, 40, 240])); + assert_eq!(out[1], json!([10, 280])); + assert_eq!(out[2], json!([10, 280, 30, 40])); + assert_eq!(out[3], json!([10, 20])); + assert_eq!(out[4], json!([20, 250, 80, 210])); +} + +#[test] +fn convert_coordinate_pair_is_inverse_and_y_up() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, D = CoordinateSystem.DOCUMENTCOORDINATESYSTEM, A = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + var p = d.convertCoordinate([10, 100], A, D); vc.log(p); vc.log(d.convertCoordinate(p, D, A));\ + vc.log(d.convertCoordinate([3, 4], D, D));", + ); + assert_eq!(out, vec![json!([10, 200]), json!([10, 100]), json!([3, 4])]); + assert!( + failure( + &mut s, + "app.activeDocument.convertCoordinate([1, NaN], CoordinateSystem.DOCUMENTCOORDINATESYSTEM, CoordinateSystem.DOCUMENTCOORDINATESYSTEM);" + ) + .contains("finite") + ); + assert!( + failure(&mut s, "app.activeDocument.convertCoordinate([1, 2], 'x', CoordinateSystem.DOCUMENTCOORDINATESYSTEM);").contains("CoordinateSystem") + ); +} + +#[test] +fn ruler_origin_round_trips_without_moving_art() { + let (mut s, a, _) = doc(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.rulerOrigin); d.rulerOrigin = [50, 60]; vc.log(d.rulerOrigin);"); + assert_eq!(out, vec![json!([0, 300]), json!([50, 60])]); + assert_eq!(s.active().unwrap().doc.ruler_origin_for(0), vectorcraft_geom::Point::new(50.0, 240.0)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); + assert!(s.active().unwrap().doc.node(a).is_some()); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.rulerOrigin = d.rulerOrigin;"); + assert_eq!(undo_steps(&s), steps, "setting the same origin adds no step"); + assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas")); +} + +#[test] +fn page_item_properties_join_one_undo_step() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[0];\ + 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);", + ); + assert_eq!(out, vec![json!(["box", 40, false, false, true, 1]), json!("box")]); + let st = s.active().unwrap(); + let n = st.doc.node(a).unwrap(); + 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;"); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + for (source, part) in [ + ("app.activeDocument.pageItems[0].opacity = 101;", "opacity"), + ("app.activeDocument.pageItems[0].hidden = 'yes';", "hidden"), + ("app.activeDocument.pageItems[0].width = 0;", "width"), + ("app.activeDocument.pageItems[0].position = [1];", "position"), + ] { + assert!(failure(&mut s, source).contains(part), "{source}"); + } +} + +#[test] +fn selection_assignment_is_atomic_across_invalid_items() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); + assert!(e.contains("Cannot select PathItem"), "{e}"); + assert!(s.active().unwrap().selection.objects.is_empty()); + 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);\ + 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);", + ); + assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // An item of another document cannot be selected here. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); + assert!(e.contains("Cannot select"), "{e}"); +} + +#[test] +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];"); + assert_eq!(s.active_index(), Some(1)); + let first = &s.documents()[0]; + assert_eq!(first.doc.node(a).unwrap().name.as_deref(), Some("far")); + assert_eq!(first.selection.objects.len(), 1); +} + +#[test] +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];\ + 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);", + ); + assert_eq!(out, vec![json!(2), json!(3), json!(3), json!(1), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); + let layer = &s.active().unwrap().doc.layers[0]; + let order: Vec = layer.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order[1..], [b, a]); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].zOrder('front');").contains("ZOrderMethod")); +} + +/// The ids of the children of the first layer, bottom first. +fn layer_order(s: &Session) -> Vec { + s.active().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn move_and_duplicate_place_by_element_placement() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + 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);"); + 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);"); + 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);"); + assert_eq!(layer_order(&s), [c, a, b]); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[0].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);"); + 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);"); + 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 copy = a.duplicate(g, ElementPlacement.PLACEATEND); vc.log(copy.parent.typename); vc.log(copy.zOrderPosition);", + ); + assert_eq!(out, vec![json!("GroupItem"), json!(1)]); + assert_eq!(s.active().unwrap().doc.node(g).unwrap().children().unwrap().len(), 4); + // Refused moves change nothing. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (source, part) in [ + ("var g = app.activeDocument.pageItems[0]; g.move(app.activeDocument.pageItems[1], ElementPlacement.INSIDE);", "into itself"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], ElementPlacement.INSIDE);", "cannot hold objects"), + ("var p = app.activeDocument.pageItems; p[1].move(p[2], 'inside');", "ElementPlacement"), + ("var p = app.activeDocument.pageItems; p[1].move();", "relative object"), + ("var p = app.activeDocument.pageItems; p[1].move(app.activeDocument);", "not available yet"), + ("var p = app.activeDocument.pageItems; p[1].duplicate(undefined, ElementPlacement.INSIDE);", "relative object"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // 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);"); + assert!(e.contains("hidden or locked"), "{e}"); +} + +#[test] +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);\ + 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")); + 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);"); + assert!(e.contains("into itself"), "{e}"); +} + +#[test] +fn a_copy_that_cannot_be_placed_is_deleted() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 30.0, 30.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 200, "y": 200, "text": "Hi"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + // 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 = '';\ + try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length === n);", + ); + assert!(out[0].as_str().is_some_and(|m| m.contains("Live Paint takes paths")), "{out:?}"); + assert_eq!(out[1], json!(true)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn a_grid_by_column_takes_the_number_of_rows() { + let mut s = Session::new(); + for (layout, rows, cols) in [("GridByCol", 2, 3), ("RLGridByCol", 2, 3), ("GridByRow", 3, 2)] { + run(&mut s, &format!("app.documents.add(DocumentColorSpace.RGB, 100, 100, 6, DocumentArtboardLayout.{layout}, 10, 2);")).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + let distinct = |mut v: Vec| { + v.sort_unstable(); + v.dedup(); + v.len() + }; + let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); + let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); + assert_eq!((tops, lefts), (rows, cols), "{layout}"); + } +} + +#[test] +fn stale_documents_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); + for (member, message) in + [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] + { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains(message), "{member}: {e}"); + } +} + +#[test] +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;"); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + log(&mut s, "app.activeDocument.pageItems[1].locked = true;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + +#[test] +fn an_edit_keeps_direct_selected_anchors() { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert!(!before.anchors.is_empty()); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!(s.active().unwrap().selection.anchors, before.anchors); + assert_eq!(s.active().unwrap().selection.objects, before.objects); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); +} + +#[test] +fn an_edit_keeps_the_key_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.key), (vec![a, b], Some(b))); +} + +#[test] +fn an_edit_keeps_selected_slices() { + let (mut s, a, _) = doc(); + s.execute("object.slice.make", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.slice.select", &json!({"slices": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.slices.clone(), sel.objects.len()), (vec![a], 0)); +} + +#[test] +fn a_startup_preset_alone_gives_its_first_size() { + let mut s = Session::new(); + for profile in ["Web", "Print", "Mobile"] { + let first = crate::cmd::newdoc::category(&s, profile).unwrap().remove(0); + let out = log(&mut s, &format!("var d = app.documents.addDocument('{profile}'); vc.log([d.width, d.height]);")); + let got = (out[0][0].as_f64(), out[0][1].as_f64()); + assert_eq!(got, (Some(first.width), Some(first.height)), "{profile}"); + } +} + +#[test] +fn page_item_members_not_built_yet_throw_on_read_and_assignment() { + let (mut s, _, _) = doc(); + for source in + ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + { + assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); + } + assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + // A deleted item or an earlier run's document is stale first. + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + assert!(e.contains("Stale page item"), "{e}"); + run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); + let e = failure(&mut s, "#targetengine keep\nd.layers;"); + assert!(e.contains("Stale document"), "{e}"); +} + +#[test] +fn assigning_the_same_objects_clears_the_key_and_guides() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + 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]];"); + 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(); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.guides.is_empty()); +} + +#[test] +fn a_page_item_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + assert_eq!(a.0, big); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.name = 'big'; vc.log(i.name); i.remove();"); + assert_eq!(out, vec![json!("big")]); + assert!(s.active().unwrap().doc.node(a).is_none()); +} + +#[test] +fn only_class_constructors_construct() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var m = [];\ + try { new app.documents.add(); } catch (e) { m.push(e.name); }\ + try { new app.activeDocument.pageItems[0].remove(); } catch (e) { m.push(e.name); }\ + vc.log(m); vc.log(app.documents.length); vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(["TypeError", "TypeError"]), json!(1), json!(2)]); +} + +#[test] +fn a_document_preset_is_an_instance_of_its_class() { + let mut s = Session::new(); + let out = log(&mut s, "var p = new DocumentPreset(); vc.log(p instanceof DocumentPreset); vc.log(p.typename); vc.log(p.width);"); + assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); +} + +#[test] +fn the_same_document_or_item_is_the_same_object() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + 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]);", + ); + assert_eq!(out, vec![json!([true, true, true, true, true])]); +} + +#[test] +fn collection_entries_are_found_by_in_and_array_methods() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, d = app.documents;\ + vc.log([0 in p, '1' in p, 2 in p, 0 in d, 1 in d]);\ + vc.log(Array.prototype.map.call(p, function (i) { return i.typename; }).join(','));", + ); + assert_eq!(out, vec![json!([true, true, false, true, false]), json!("PathItem,PathItem")]); +} + +#[test] +fn placement_in_another_document_is_refused() { + let (mut s, _, _) = doc(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + rect(&mut s, 0.0, 0.0, 5.0, 5.0); + let before: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + for source in [ + "app.documents[0].pageItems[0].move(app.documents[1].pageItems[0], ElementPlacement.PLACEBEFORE);", + "app.documents[0].pageItems[0].duplicate(app.documents[1].pageItems[0].parent, ElementPlacement.INSIDE);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cross-document placement is not available"), "{source}: {e}"); + } + let after: Vec = s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect(); + assert_eq!(after, before); +} + +#[test] +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);"); + 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';"); + 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")); +} + +#[test] +fn document_preset_applies_only_its_given_fields() { + let mut s = Session::new(); + let out = log( + &mut s, + "var p = new DocumentPreset(); vc.log([p.typename, p.width, p.height, p.numArtboards, p.artboardSpacing, p.artboardLayout]);\ + vc.log(p.colorMode === undefined && p.units === undefined);\ + p.width = 300; p.height = 200; p.numArtboards = 2; p.colorMode = DocumentColorSpace.CMYK; p.title = 'Flyer';\ + p.units = RulerUnits.Millimeters; p.rasterResolution = DocumentRasterResolution.HighResolution;\ + var d = app.documents.addDocument('Print', p); vc.log([d.name, d.width, d.height, d.documentColorSpace, d.rulerUnits]);\ + var e = app.documents.addDocument(DocumentPresetType.BasicRGB); vc.log(e.documentColorSpace);", + ); + assert_eq!(out[0], json!(["DocumentPreset", 612, 792, 1, 20, "DocumentArtboardLayout.GridByRow"])); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(["Flyer", 300, 200, "DocumentColorSpace.CMYK", "RulerUnits.Millimeters"])); + assert_eq!(out[3], json!("DocumentColorSpace.RGB")); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.documents()[0].doc.artboards.len(), 2); + assert!((s.documents()[0].doc.raster_effects_ppi - 300.0).abs() < 1e-9); + for (source, part) in [ + ("app.documents.addDocument('Nope');", "no startup preset"), + ("var p = new DocumentPreset(); p.numArtboards = 101; app.documents.addDocument('Print', p);", "numArtBoards"), + ("var p = new DocumentPreset(); p.units = RulerUnits.Qs; app.documents.addDocument('Print', p);", "units"), + ( + "var p = new DocumentPreset(); p.transparencyGrid = DocumentTransparencyGrid.TransparencyGridRed; app.documents.addDocument('Print', p);", + "not available yet", + ), + ("app.documents.addDocument('Print', 5);", "DocumentPreset"), + ("app.documents.addDocument(7);", "startup preset"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); +} + +#[test] +fn headless_add_document_dialog_fails_without_creating() { + let mut s = Session::new(); + let e = failure(&mut s, "app.documents.addDocument('Print', new DocumentPreset(), true);"); + assert!(e.contains("Dialog unavailable"), "{e}"); + assert!(s.documents().is_empty()); + let out = log(&mut s, "vc.log(app.documents.addDocument('Web', undefined, false).typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn wrappers_go_stale_after_delete_and_undo() { + let (mut s, _, _) = doc(); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.name;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var c = app.activeDocument.pageItems[0].duplicate(); vc.run('edit.undo'); c.position;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length); p[0].name;"); + assert!(e.contains("undefined"), "{e}"); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keep\nvar held = app.activeDocument.pageItems[0];").unwrap(); + let e = failure(&mut s, "#targetengine keep\nheld.name;"); + assert!(e.contains("Stale page item"), "{e}"); +} + +#[test] +fn remove_all_refuses_locked_art_before_deleting_anything() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&b.0.to_string()), "{e}"); + assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + // A locked object inside an unlocked group stops it too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + +#[test] +fn get_is_file_open_cannot_probe_outside_script_scope() { + let (mut s, _, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let p = path.to_string_lossy().replace('\\', "\\\\"); + let out = log(&mut s, &format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));")); + assert_eq!(out, vec![json!(true), json!(false)]); + for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { + assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); + } + assert!(failure(&mut s, "app.getIsFileOpen(new Array(5000).join('a'));").contains("too long")); + let _ = std::fs::remove_file(path); +} + +#[test] +fn hostile_dom_values_do_not_reenter_or_exceed_limits() { + let (mut s, _, _) = doc(); + let before = s.active().unwrap().selection.objects.clone(); + // A plain object shaped like an object of the model is not one. + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A getter in a value is refused before it runs. + let e = failure( + &mut s, + "var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\ + try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(hit); throw e; }", + ); + assert!(e.contains("rulerOrigin"), "{e}"); + let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;"); + assert!(e.contains("at most 10000"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, before); +} + +#[test] +fn prototype_changes_cannot_forge_a_page_item() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var f = Object.create(PathItem.prototype); var m = '';\ + try { f.name = 'x'; } catch (e) { m = e.message; } vc.log(m);\ + try { PathItem.prototype.name = 'y'; } catch (e) { m = e.message; } vc.log(m); PageItem = null; Document.prototype.pageItems = null;\ + vc.log(Object.isFrozen(PathItem.prototype) || !Object.isExtensible(PathItem.prototype));\ + vc.log(app.activeDocument.pageItems.length);\ + try { new PathItem(); } catch (e) { m = e.name; } vc.log(m);", + ); + assert_eq!(out, vec![json!("this is not a page item"), json!("this is not a page item"), json!(true), json!(2), json!("TypeError")]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); +} + +#[test] +fn unsupported_members_say_so() { + let (mut s, _, _) = doc(); + assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..02176c38c9 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,8 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); 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, "app.activeDocument;").unwrap_err().to_string().contains("`vc`")); + 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`")); 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); } @@ -204,7 +205,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "app.activeDocument;").unwrap_err(); + run(&mut s, "new Window('dialog');").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..69c2ebf402 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -176,7 +176,7 @@ fn get_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { } fn has_at(interp: &mut Interp, o: ObjId, k: f64) -> JsResult { - interp.has_property(o, &key_of(k)) + interp.has_property_indexed(o, &key_of(k)) } /// The estimated bytes a new element adds. diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..418a603e1c 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,8 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// An object of a class a host defined ([`crate::host_classes`]). + Host(crate::host_classes::HostObj), } /// What an XML value is. @@ -312,7 +314,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..312221986c 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -113,6 +113,10 @@ pub(crate) enum ArgRead { Each(Rc<[Arg]>), /// None: the function is given the [`CallSite`] of the code that calls it, as three numbers. Site, + /// A member of a host class ([`crate::host_classes`]): `this` first, then each argument as + /// [`Data`], objects of host classes in them as [`crate::host_ref`] gives them; the objects of + /// host classes in the result are made from theirs. + Hosted, } /// A member of an object the host adds to the global environment. @@ -186,6 +190,9 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, + /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object + /// that has [`crate::HOST_REF_KEY`] is refused. + hosted: bool, } impl Reading { @@ -255,6 +262,10 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { + Class::Host(_) if r.hosted => { + return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); + } + Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { let o = self.object(id)?; @@ -302,6 +313,9 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); + if r.hosted && name == crate::HOST_REF_KEY { + return Err(self.data_error(r, ErrorType::Type, "is not plain data")); + } r.path.push(Step::Name(k)); let item = match prop { // A property holding `undefined` reads as one left out. @@ -337,6 +351,9 @@ impl Interp { Data::Array(items) => { self.write_container(items.into_iter().enumerate().map(|(i, d)| (Slot::Index(i), d)).collect(), true, depth, frozen)? } + Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => { + self.write_host_ref(&Data::Object(items))? + } Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?, }) } @@ -376,9 +393,18 @@ impl Interp { /// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to /// the script. - pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult { + pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), + ArgRead::Hosted => { + let this = match this { + Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), + _ => Data::Undefined, + }; + let mut data = vec![this]; + data.extend(self.read_args(name, args, how)?); + data + } _ => self.read_args(name, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result. @@ -387,6 +413,7 @@ impl Interp { let result = f(data); self.can_wait.set(false); match result { + Ok(d) if matches!(how, ArgRead::Hosted) => self.write_hosted(d), Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; @@ -467,7 +494,15 @@ impl Interp { /// The arguments of host function `name` as [`Data`], read as `how` says. fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { - let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() }; + let mut reading = Reading { + limits: self.data_limits, + bytes: 0, + entries: 0, + ancestors: Vec::new(), + path: Vec::new(), + function: name.clone(), + hosted: matches!(how, ArgRead::Hosted), + }; let args = match how { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, @@ -475,14 +510,14 @@ impl Interp { let mut data = Vec::with_capacity(args.len()); // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); - if !matches!(how, ArgRead::Data | ArgRead::Frozen) { + if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { self.temp_roots.extend(args.iter().cloned()); } let mut read = Ok(()); for (i, a) in args.iter().enumerate() { reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX))); let d = match how { - ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading), + ArgRead::Data | ArgRead::Frozen | ArgRead::Site | ArgRead::Hosted => self.read_data(a, &mut reading), ArgRead::Text => self.read_text(a, &mut reading), ArgRead::Each(list) => match list.get(i) { Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined), @@ -507,7 +542,7 @@ impl Interp { /// What host error `e` throws, or the limit it ends the run with. A function that waits /// ([`HostError::Wait`]) where its caller does not handle the wait ends the run with an internal /// error. - fn host_error(&mut self, e: HostError) -> JsResult { + pub(crate) fn host_error(&mut self, e: HostError) -> JsResult { match e { HostError::Wait => Ok(Abrupt::Internal("a host function waited for its result where the run cannot pause".into())), HostError::Abort(message) => { diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs new file mode 100644 index 0000000000..1d03f981ff --- /dev/null +++ b/crates/js/src/host_classes.rs @@ -0,0 +1,259 @@ +//! Classes a host defines ([`crate::Realm::define_host_classes`]): objects that stand for something +//! the host keeps, such as an open document or an object in one, with members the host's functions +//! answer. +//! +//! Each object holds the name of its class and a handle, a list of numbers the host chose, in an +//! internal slot that a script cannot read, write or copy onto another object. A host function sees +//! such an object as the [`Data`] that [`host_ref`] makes, and gives one back the same way; a plain +//! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object +//! of a host class from its own data. A class's prototype and constructor are frozen. While a +//! script holds the object for a class and handle, each read of that class and handle gives the +//! same object. +//! +//! 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. + +use std::rc::Rc; + +use crate::heap::{Class, Func, ObjId, Object, Prop, key}; +use crate::host::ArgRead; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::value::Value; +use crate::{Data, HostError, HostFunction}; + +/// The one key of the [`Data`] object that stands for an object of a host class ([`host_ref`]). +pub const HOST_REF_KEY: &str = "\u{0}hostRef"; + +/// A member of a host class's prototype. +#[derive(Clone)] +pub enum HostMember { + /// A read-only property: the function gives its value each time it is read. + Get(HostFunction), + /// A property the function `get` reads and `set` assigns. + Property { get: HostFunction, set: HostFunction }, + /// A method. + Method(HostFunction), +} + +/// A class [`crate::Realm::define_host_classes`] adds. +#[derive(Clone)] +pub struct HostClass { + pub name: String, + /// A class defined before this one, or in the same call before it, whose prototype this + /// class's prototype inherits from. + pub parent: Option, + pub members: Vec<(String, HostMember)>, + /// What `object[i]` gives for an array index `i`. + pub index: Option, + /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. + pub construct: Option, +} + +/// The internal slot of an object of a host class: its class, as an index into the realm's +/// classes, and its handle. +#[derive(Clone, Debug)] +pub(crate) struct HostObj { + pub(crate) class: u32, + pub(crate) handle: Rc<[f64]>, +} + +/// A class the realm has. +#[derive(Clone)] +pub(crate) struct Entry { + name: Rc, + proto: ObjId, + ctor: ObjId, + index: Option, +} + +impl Entry { + pub(crate) fn objects(&self) -> [ObjId; 2] { + [self.proto, self.ctor] + } +} + +/// A class, as an index into the realm's classes, and the bits of a handle. +type MadeKey = (u32, Box<[u64]>); + +/// The object made for each class and handle ([`Interp::host_objects`]). +pub(crate) type Made = std::collections::HashMap; + +/// Whether `id` is still the object made for `key`, and not a freed cell or another object that +/// was given its cell. +fn is_made(heap: &crate::heap::Heap, id: ObjId, key: &MadeKey) -> bool { + heap.object(id).is_some_and(|o| match &o.class { + Class::Host(h) => h.class == key.0 && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()), + _ => false, + }) +} + +/// Drops the entries of `made` whose objects the last collection freed. +pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap) { + made.retain(|key, id| is_made(heap, *id, key)); +} + +/// The [`Data`] that stands for the object of host class `class` with `handle`. +pub fn host_ref(class: &str, handle: &[f64]) -> Data { + let mut list = Vec::with_capacity(handle.len() + 1); + list.push(Data::String(class.to_string())); + list.extend(handle.iter().map(|n| Data::Number(*n))); + Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) +} + +/// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. +pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { + let Data::Object(items) = d else { return None }; + let [(k, Data::Array(list))] = items.as_slice() else { return None }; + if k != HOST_REF_KEY { + return None; + } + let (Data::String(class), rest) = list.split_first()? else { return None }; + let handle = rest.iter().map(|d| if let Data::Number(n) = d { Some(*n) } else { None }).collect::>>()?; + Some((class.as_str(), handle)) +} + +impl Interp { + /// 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> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = + self.host_classes.get(h.class as usize).map(|e| e.name.clone()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some(host_ref(&name, &h.handle))) + } + + /// The object of a host class that `d`, which a host function gave, stands for. + pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { + let Some((name, handle)) = host_ref_parts(d) else { + return Err(self.throw(ErrorType::Type, "a host value names an object of a host class wrongly")); + }; + let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else { + return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); + }; + let proto = entry.proto; + let class = u32::try_from(class).unwrap_or(u32::MAX); + let made = (class, handle.iter().map(|n| n.to_bits()).collect::>()); + if let Some(&id) = self.host_objects.get(&made) + && is_made(&self.heap, id, &made) + { + return Ok(Value::Object(id)); + } + self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); + o.extensible = false; + let id = self.heap.alloc_object(o); + self.host_objects.insert(made, id); + Ok(Value::Object(id)) + } + + /// Whether `id` is the constructor of a host class (its other functions are not constructors). + pub(crate) fn is_host_constructor(&self, id: ObjId) -> bool { + self.host_classes.iter().any(|e| e.ctor == id) + } + + /// The indexer of the host class of `id`, when it is an object of a host class that has one. + pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + 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 { + 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))]) { + 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. + pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { + if let Some(i) = crate::value::array_index(k) + && let Some(f) = self.host_indexer(id)? + { + return Ok(!matches!(self.host_index(&f, id, i)?, Value::Undefined)); + } + self.has_property(id, k) + } + + /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. + pub(crate) fn write_hosted(&mut self, d: Data) -> JsResult { + let was = std::mem::replace(&mut self.write_hosted, true); + let r = self.write_data(d, 0, false); + self.write_hosted = was; + r + } +} + +/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. +pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>) -> JsResult<()> { + for class in classes { + install_class(i, class)?; + } + for (name, d) in instances { + let v = i.write_hosted(d)?; + let global = i.global; + i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; + } + Ok(()) +} + +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 parent = match &class.parent { + None => i.intrinsics.object_proto, + Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { + Some(e) => e.proto, + None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), + }, + }; + let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); + let mark = i.temp_roots.len(); + i.temp_roots.push(Value::Object(proto)); + 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 }); + let global = i.global; + i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) +} + +/// Puts the members of `class` on `proto` and makes its constructor. → the constructor. +fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { + let path = &class.name; + 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::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 } + } + HostMember::Method(f) => Prop::Data { value: Value::Object(hosted_function(i, f.clone(), &full)), flags: 0 }, + }; + i.define(proto, key(name), prop)?; + } + let construct = class.construct.clone().unwrap_or_else(|| { + let message = format!("{path} cannot be constructed by a script"); + Rc::new(move |_| Err(HostError::Type(message.clone()))) + }); + let ctor = hosted_function(i, construct, path); + i.define(ctor, key("prototype"), Prop::Data { value: Value::Object(proto), flags: 0 })?; + i.define(proto, key("constructor"), Prop::Data { value: Value::Object(ctor), flags: 0 })?; + i.object_mut(proto)?.extensible = false; + i.object_mut(ctor)?.extensible = false; + Ok(ctor) +} + +fn hosted_function(i: &mut Interp, f: HostFunction, name: &str) -> ObjId { + let proto = i.intrinsics.function_proto; + i.heap.alloc_object(Object::new(Class::Function(Func::Data { f, name: name.into(), read: ArgRead::Hosted }), Some(proto))) +} diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..874116d472 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -253,6 +253,14 @@ pub(crate) struct Interp { pub(crate) install_error: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, + /// The classes a host added ([`crate::Realm::define_host_classes`]), in the order it added them. + pub(crate) host_classes: Vec, + /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. + pub(crate) write_hosted: bool, + /// The object made for each class and handle ([`crate::host_classes`]), so that two reads of + /// the same one give the same object. It is not a root: an entry whose object was collected is + /// dropped after each collection. + pub(crate) host_objects: crate::host_classes::Made, /// The clock and time zone `Date` reads. pub(crate) date_host: crate::date_builtins::DateHost, /// The bytes native code holds outside the heap's cells through [`HeldBytes`]. @@ -518,6 +526,9 @@ impl Interp { held_bytes: 0, install_error: None, files: None, + host_classes: Vec::new(), + write_hosted: false, + host_objects: crate::host_classes::Made::default(), date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), flattened: std::cell::Cell::new(0), @@ -774,8 +785,10 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); + crate::host_classes::forget_collected(&mut self.host_objects, &self.heap); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); @@ -1408,6 +1421,12 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // An array index of an object of a host class with an indexer is the indexer's answer. + if let Some(i) = array_index(k) + && let Some(f) = self.host_indexer(start)? + { + return self.host_index(&f, start, i); + } match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -2262,7 +2281,7 @@ impl Interp { Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. - return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); + return Ok(Prepared::Done(self.call_data(&f, &name, &this, &args, &read)?)); } Func::Eval { f, end, strict_writes, name } => { return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); @@ -2371,6 +2390,22 @@ impl Interp { self.stack.truncate(start); self.push(v) } + // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain + // object it gives inherits from the class's prototype. The class's other functions are + // not constructors. + Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) + if f.as_object().is_some_and(|o| self.is_host_constructor(o)) => + { + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read)?; + if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) + && matches!(self.object(*o)?.class, Class::Ordinary) + && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? + { + self.object_mut(*o)?.proto = Some(proto); + } + self.stack.truncate(start); + self.push(v) + } _ => Err(self.type_error("the value is not a constructor")), } } @@ -2496,7 +2531,7 @@ impl Interp { self.temp_roots.extend(keep.iter().cloned()); let was_waiting = self.waiting; let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; self.temp_roots.truncate(mark); @@ -2933,7 +2968,7 @@ impl Interp { } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_key(a)?; - self.has_property(*o, &k).map(Value::Bool) + self.has_property_indexed(*o, &k).map(Value::Bool) } } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..1d7af9e4fb 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -58,6 +58,7 @@ mod error; mod file_classes; mod heap; mod host; +mod host_classes; mod interp; mod lexer; mod number; @@ -81,6 +82,7 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; +pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d675e82ec7..52952eb73e 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -504,6 +504,17 @@ impl Realm { } } + /// Adds the host classes `classes` ([`crate::HostClass`]), each a global constructor whose + /// prototype holds its members, and the global objects `instances`, each made from the + /// [`crate::host_ref`] given. Prototypes and constructors are frozen; the instances cannot be + /// replaced. A heap too small for them ends with the error the realm's next run would give. + pub fn define_host_classes(&mut self, classes: Vec, instances: Vec<(String, crate::Data)>) -> Result<(), RunError> { + match crate::host_classes::install(&mut self.interp, classes, instances) { + 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 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..94d8e728c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2620,6 +2620,57 @@ app through the global object `vc`, and writes to the Script Console and runs ot throws a `RangeError`. - `vc.commands` lists the commands a script may run. - `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` + (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 + columns for the other layouts), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new` + with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of + `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset + `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` + (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` + starts with the defaults that page gives; `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` + throw an error that says they are not available yet, and `showOptionsDialog` true throws `Dialog unavailable` + with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, + `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, + destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) + has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each + entry `[i]` gives. Each page item + (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the + Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected`, `opacity` (0 to + 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the + visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` + (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs + `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same + document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a + group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` + directly below it. An object of another document throws `Cross-document placement is not available`, and when + `node.move` refuses the place of a copy, `duplicate` deletes the copy and throws that error. 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 + 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` + for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each + changed document. A value that changes nothing runs no command, and a change to another document leaves the active + tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine + kept from an earlier run, throws `Stale page item`; `index` and `getByName` throw `Not found`; and + `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, + a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with + nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when + the automation read roots allow its file, and that check can look the document's file up on disk. A path with + `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members + those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds + themselves, such as a path's fill, are not defined yet and read as `undefined`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3b252b56a6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,6 +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: 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`. From f70d2ee7e6bdeb061cbfea3e9bb87d4ef0a99409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 08:43:10 -0800 Subject: [PATCH 02/24] Scripts: duplicate, selection and wrapper fixes for the object model - duplicate() runs Edit > Duplicate, the place and the selection restore under one savepoint, so a refused place leaves the documents, the selection and the undo history as they were. It reads the copy's id from the command's own result, so ids above 2^53 return the copy. A path inside a compound path throws an error instead of copying the whole compound path. - An edit restores a mixed selection (direct-selected anchors and whole objects) in its original order with one select.anchorsMany. - Assigning the selection clears a Layers panel target. - A call on an inactive document switches back even when the selection restore fails. - documents.add with a grid by column passes the row count to file.new, which takes a new artboardLayout.rows key: 5 artboards in 4 rows give columns of 4 and 1. A preset keeps the rows until columns without rows, or another layout, is given, and New Document drops them when Columns or the layout changes. - A held page item stays the same object when its class changes in the same family (a placed image that is embedded becomes a RasterItem). - A waiting class member's answer is read as a class instance, and a class constructor called with new cannot wait. Docs: docs/mcp.md (DocumentPreset, duplicate, file.new rows), docs/gaps.md (G6). --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 64 +++++++--- crates/engine/src/script/dom.rs | 136 ++++++++++++-------- crates/engine/src/script/mod.rs | 10 +- crates/engine/src/tests/newdoc.rs | 3 +- crates/engine/src/tests/script_dom.rs | 138 +++++++++++++++++++-- crates/js/src/host.rs | 6 +- crates/js/src/host_classes.rs | 44 ++++--- crates/js/src/host_tests.rs | 40 ++++++ crates/js/src/interp.rs | 18 ++- crates/js/src/realm.rs | 9 +- crates/ui-egui/src/dialogs/new_document.rs | 20 +++ docs/gaps.md | 5 +- docs/mcp.md | 17 ++- 14 files changed, 408 insertions(+), 104 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccebbfac88..bf9ff59c14 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index e74a570a5b..03be423cf3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "New Document Presets", [], None, - "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", + "{category?: \"Recent\"|\"Saved\"|\"Mobile\"|\"Web\"|\"Print\"|\"Film & Video\"|\"Art & Illustration\"|\"Branding\"|\"Social\"} the New Document presets by category (Recent: the last sizes used; Saved: the user's presets) → {categories: [{name, presets: [{name, size: \"1920 × 1080 px\", width: pt, height: pt, units, orientation, artboards, artboardLayout: {layout, columns, rows? (a grid by column made with rows), spacing, rightToLeft}, bleed, backgroundContents, colorMode, rasterEffectsPpi, previewMode, alignNewObjectsToPixelGrid (on in the Mobile and Web presets)}]}]}; file.new {preset: name} starts from one", always, list ), @@ -146,6 +146,11 @@ fn de_ppi<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result bool { + *n == 0 +} + /// Everything New Document sets: a preset (built-in, saved or recent) or `file.new`'s params. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -166,6 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, + /// Rows of a grid by column, in place of `columns` when more than 0. + #[serde(skip_serializing_if = "is_zero")] + pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). #[serde(deserialize_with = "de_spacing")] @@ -203,6 +211,7 @@ impl Default for DocSettings { artboards: 1, layout: ArtboardLayout::GridByRow, columns: 0, + rows: 0, spacing: 20.0, right_to_left: false, bleed: [0.0; 4], @@ -222,9 +231,17 @@ pub const MAX_ARTBOARDS: u32 = 1000; pub const RASTER_PPI: [(f64, &str); 3] = [(72.0, "Screen (72 ppi)"), (150.0, "Medium (150 ppi)"), (300.0, "High (300 ppi)")]; impl DocSettings { + /// The rows a grid by column with `rows` uses, at most one for each artboard. + fn grid_rows(&self) -> Option { + (self.layout == ArtboardLayout::GridByColumn && self.rows > 0).then(|| (self.rows as usize).min(self.artboards.max(1) as usize)) + } + /// The columns a grid actually uses (0 or more than the artboards: one row). pub fn grid_columns(&self) -> usize { let n = self.artboards.max(1) as usize; + if let Some(rows) = self.grid_rows() { + return n.div_ceil(rows); + } match self.layout { ArtboardLayout::Row => n, ArtboardLayout::Column => 1, @@ -246,6 +263,11 @@ impl DocSettings { /// As `file.newPresets` lists it (and `file.new` takes it back). pub fn to_json(&self) -> Value { + let mut layout = + json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}); + if let (Some(rows), Some(o)) = (self.grid_rows(), layout.as_object_mut()) { + o.insert("rows".into(), json!(rows)); + } json!({ "name": self.name, "size": self.size_label(), @@ -254,7 +276,7 @@ impl DocSettings { "units": self.units.label(), "orientation": self.orientation(), "artboards": self.artboards, - "artboardLayout": {"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}, + "artboardLayout": layout, "bleed": self.bleed, "backgroundContents": self.background.id(), "colorMode": color_mode_id(self.color_mode), @@ -337,25 +359,23 @@ impl DocSettings { Ok(self) } - /// `artboardLayout: {layout?, columns?, spacing?, rightToLeft?}` or just a layout id. + /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; + if self.layout != ArtboardLayout::GridByColumn { + self.rows = 0; + } return Ok(()); } let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32); for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, - "columns" => { - self.columns = v - .as_f64() - .filter(|c| c.is_finite() && *c >= 1.0) - .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? - .round() - .min(MAX_ARTBOARDS as f64) as u32 - } + "columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?, + "rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?, "spacing" => { self.spacing = v .as_f64() @@ -366,18 +386,30 @@ impl DocSettings { _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), } } + if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { + return Err(bad(cmd, "artboardLayout.rows needs the gridByColumn layout")); + } + // Columns without rows, or another layout, replace a preset's rows. + if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn { + self.rows = 0; + } + if self.grid_rows().is_some() { + self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); + } Ok(()) } - /// The artboard rectangles, the first at the origin's side. + /// The artboard rectangles, the first at the origin's side. A grid by column with `rows` has + /// that many rows (at most one for each artboard). pub fn boards(&self) -> Vec { let n = self.artboards.max(1) as usize; let sizes = vec![(self.width, self.height); n]; let by_column = self.layout == ArtboardLayout::GridByColumn; - grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left) - .into_iter() - .map(|o| Rect::from_origin_size(o, (self.width, self.height))) - .collect() + let origins = match self.grid_rows() { + Some(rows) => grid_origins_rc(&sizes, Point::ZERO, (rows, n.div_ceil(rows)), self.spacing, true, self.right_to_left), + None => grid_origins(&sizes, Point::ZERO, self.grid_columns(), self.spacing, by_column, self.right_to_left), + }; + origins.into_iter().map(|o| Rect::from_origin_size(o, (self.width, self.height))).collect() } /// The new document (title and swatches set by `file.new`). diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5763591ec7..dd17bb579e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -35,7 +35,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; -use super::{Host, Link, command, current, data_size}; +use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; /// The error for a member read or called with no document open. @@ -84,12 +84,41 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; -/// What the object model keeps for one run: its coordinate system and the last list of a -/// document's page items, kept while that document is unchanged. +/// What the object model keeps for one run: its coordinate system, the last list of a document's +/// page items, kept while that document is unchanged, and whether a call's own savepoint +/// ([`atomically`]) is open. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, + saving: Cell, +} + +impl State { + /// Whether a call's own savepoint is open: its commands take none of their own. + pub(super) fn saving(&self) -> bool { + self.saving.get() + } +} + +/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every +/// document, the selection and the undo histories are as they were before it, with no undo step +/// and no change to the document's saved state. +fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { + if h.dom.saving.get() { + return f(h); + } + let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + h.dom.saving.set(true); + let r = f(h); + h.dom.saving.set(false); + let mut s = h.session.borrow_mut(); + if r.is_ok() { + save.keep(&mut s); + } else if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } + r } /// A document's uid, the document as it was, and the ids of its page items then. @@ -414,9 +443,9 @@ fn coords_of(d: &Data) -> std::result::Result { } /// Selects `before` again in the active document `doc` with the selection commands, so that the -/// journal holds the change: the whole objects, then the direct-selected anchors and segments, the -/// ruler guides and the key object, guide or anchor. Objects that are now deleted, hidden or -/// locked are left out. +/// journal holds the change: the objects in their order with their direct-selected anchors, then +/// the segments, the ruler guides and the key object, guide or anchor. Objects that are now +/// deleted, hidden or locked are left out. fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { // Slices selected with the Slice Selection tool are the whole selection when there are any. let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); @@ -426,20 +455,25 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - } let keep = |id: &NodeId| editable(doc, *id); let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); - let whole: Vec = before.objects.iter().filter(|i| keep(i) && !partial(i)).map(|i| i.0).collect(); - if whole.is_empty() { + let kept: Vec = before.objects.iter().copied().filter(keep).collect(); + if kept.is_empty() { command(h, "select.none", &json!({}))?; + } else if !kept.iter().any(partial) { + command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; } else { - command(h, "select.set", &json!({"ids": whole}))?; - } - let items: Vec = before - .anchors - .iter() - .filter(|(i, _)| keep(i)) - .map(|(i, a)| json!({"id": i.0, "anchors": a.iter().map(|(p, k)| [p, k]).collect::>()})) - .collect(); - if !items.is_empty() { - command(h, "select.anchorsMany", &json!({"items": items, "mode": "add"}))?; + // One `select.anchorsMany` selects every object in its order: a partly selected path with + // its anchors, a whole path with all of them and any other object with none. + let items: Vec = kept + .iter() + .map(|i| { + let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { + Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), + }; + json!({"id": i.0, "anchors": anchors}) + }) + .collect(); + command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?; } for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); @@ -487,25 +521,26 @@ fn on_doc( command(h, "document.activate", &json!({"index": index}))?; } let r = f(h); + let mut restored = Ok(()); if keep_selection { let doc = { let s = h.session.borrow(); s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) }; if let Some(doc) = doc { - let back = restore_selection(h, &doc, &before); - if r.is_ok() { - back?; - } + restored = restore_selection(h, &doc, &before); } } - if switch && let Some(a) = active { - let back = command(h, "document.activate", &json!({"index": a})); - if r.is_ok() { - back?; - } - } - r + // The document that was active is active again before any error is given: `f`'s error first, + // then the selection's, then the switch back's. + let back = match active { + Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), + _ => Ok(()), + }; + let v = r?; + restored?; + back?; + Ok(v) } /// Runs `id` with `params` on the item's document, its selection kept. @@ -707,10 +742,9 @@ impl NewDoc<'_> { if n.fract() != 0.0 || n < 1.0 || n > count { return Err(HostError::Range("artboardRowsOrCols must be a whole number from 1 to numArtBoards".into())); } - // A grid filled by column takes the number of rows; `file.new` takes columns. + // A grid filled by column takes the number of rows. let by_column = layout.get("layout").is_some_and(|l| l == "gridByColumn"); - let columns = if by_column { (count / n).ceil() } else { n }; - layout.insert("columns".into(), json!(columns)); + layout.insert((if by_column { "rows" } else { "columns" }).into(), json!(n)); } if !layout.is_empty() { p.insert("artboardLayout".into(), Value::Object(layout)); @@ -1020,11 +1054,12 @@ fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { } /// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each -/// selected as a whole, and no ruler guide, slice or key. +/// selected as a whole, and no ruler guide, slice, key or Layers panel target. fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { let same = with_doc(h, doc, |_, st| { let sel = &st.selection; sel.objects == ids + && sel.target.is_none() && sel.anchors.is_empty() && sel.segments.is_empty() && sel.guides.is_empty() @@ -1502,11 +1537,21 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { Ok(arg(a, 0).clone()) } +/// The error of `duplicate` on a path inside a compound path. +pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet"; + /// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as /// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. -/// When `node.move` refuses the place, the copy is deleted and the error is thrown. +/// When `node.move` refuses the place, the copy and every change it made are put back, and the +/// error is thrown. fn item_duplicate(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; + let in_compound = with_doc(h, item.doc, |_, st| { + st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })) + }); + if in_compound { + return Err(HostError::Error(COMPOUND_MEMBER.into())); + } let to = match arg(a, 1) { Data::Undefined => { if !matches!(arg(a, 2), Data::Undefined) { @@ -1516,21 +1561,14 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } target => Some(destination(h, item, target, arg(a, 2), true)?), }; - let r = edit_item(h, item, "edit.duplicate", &json!({"ids": [item.id.0]}))?; - let id = match &r { - Data::Object(o) => o.iter().find(|(k, _)| k == "ids").and_then(|(_, v)| match v { - Data::Array(ids) => ids.first().and_then(|d| if let Data::Number(n) = d { whole(*n) } else { None }), - _ => None, - }), - _ => None, - }; - let id = id.ok_or_else(|| HostError::Error("the copy was not made".into()))?; - if let Some(to) = to - && let Err(e) = place(h, item.doc, NodeId(id), &to) - { - edit_item(h, item, "edit.clear", &json!({"ids": [id]}))?; - return Err(e); - } + 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]})))?; + let id = made["ids"].get(0).and_then(Value::as_u64).ok_or_else(|| HostError::Error("the copy was not made".into()))?; + if let Some(to) = to { + place(h, item.doc, NodeId(id), &to)?; + } + Ok(id) + })?; let s = h.session.borrow(); let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; Ok(item_ref(h, st, NodeId(id))) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 5ec5e2e92b..d228ff848f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1237,7 +1237,8 @@ fn note_ids(s: &mut Session) { fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); let mutating = waits_for_tool_edit(id); - let save = mutating.then(|| Savepoint::take(s, id)); + // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. + let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); @@ -1303,6 +1304,11 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result { + command_value(host, id, params).map(|(data, _)| data) +} + +/// [`command`], with the command's result as it gave it as well as the script's copy of it. +fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { let id = id.to_string(); let params = params.clone(); let session = host.session.clone(); @@ -1340,7 +1346,7 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result| { v.sort_unstable(); @@ -352,7 +390,43 @@ fn a_grid_by_column_takes_the_number_of_rows() { }; let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); - assert_eq!((tops, lefts), (rows, cols), "{layout}"); + assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + } +} + +#[test] +fn file_new_takes_the_rows_of_a_grid_by_column() { + let mut s = Session::new(); + let first_column = |s: &mut Session, layout: Value| { + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": layout})).unwrap(); + let boards = &s.active().unwrap().doc.artboards; + boards.iter().filter(|b| b.rect.x0.round() as i64 == boards[0].rect.x0.round() as i64).count() + }; + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4})), 4); + // Rows take the place of columns given beside them. + assert_eq!(first_column(&mut s, json!({"layout": "gridByColumn", "rows": 4, "columns": 1})), 4); + // A preset keeps and lists the rows, with the columns they give. + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 5, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(2), &json!(4)), "{listed}"); + let stored: DocSettings = serde_json::from_value(serde_json::to_value(&settings).unwrap()).unwrap(); + assert_eq!(stored.rows, 4); + // More artboards keep the rows; columns alone, or another layout, replace them. + let more = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); + let by_columns = stored.clone().with_params(&json!({"artboardLayout": {"columns": 1}}), "file.new").unwrap(); + assert_eq!((by_columns.rows, by_columns.boards().iter().filter(|b| b.x0 == by_columns.boards()[0].x0).count()), (0, 5)); + for layout in [json!({"layout": "gridByRow"}), json!("gridByRow")] { + let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); + } + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); + assert!(e.contains("rows must be 1 or more"), "{e}"); + for layout in ["gridByRow", "row", "column"] { + let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); + assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); } } @@ -390,6 +464,47 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +#[test] +fn an_edit_keeps_the_order_of_a_mixed_selection() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + assert_eq!(before.objects, vec![a, b]); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); +} + +#[test] +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];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); +} + +#[test] +fn a_held_image_stays_the_same_object_when_it_is_embedded() { + let dir = super::links::Folder::new("dom-embed"); + let photo = dir.file("photo.png"); + super::links::write(&photo, &super::links::png(20, 10, [255, 0, 0])); + let mut s = super::links::session(); + let id = super::links::place(&mut s, &photo); + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[0]; vc.log(i.typename); vc.run('links.embed', {{ids: [{}]}});\ + var j = app.activeDocument.pageItems[0]; vc.log([i === j, i.typename, i instanceof RasterItem, i instanceof PlacedItem]);", + id.0 + ), + ); + assert_eq!(out, vec![json!("PlacedItem"), json!([true, "RasterItem", true, false])]); +} + #[test] fn an_edit_keeps_the_key_object() { let (mut s, a, b) = doc(); @@ -630,8 +745,16 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); let p = path.to_string_lossy().replace('\\', "\\\\"); - let out = log(&mut s, &format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));")); + let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); + // Read roots that leave out the document's file: the same path does not count. + let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[&elsewhere], &[]).unwrap().unwrap(); + let out = crate::file_access::confine(Some(&roots), || log(&mut s, &query)); + assert_eq!(out, vec![json!(false), json!(false)]); + let _ = std::fs::remove_dir_all(&elsewhere); for bad in ["../x.svg", "a/../b.svg", "\\\\\\\\host\\\\share\\\\x.svg", "//host/share/x.svg", "a\\u0000b", ""] { assert!(failure(&mut s, &format!("app.getIsFileOpen('{bad}');")).contains("cannot check"), "{bad}"); } @@ -647,12 +770,13 @@ fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['PathItem', 0, 1, 1]; app.activeDocument.selection = f;"); assert!(e.contains("not plain data"), "{e}"); // A getter in a value is refused before it runs. - let e = failure( + let out = log( &mut s, "var hit = 0, v = {}; Object.defineProperty(v, 0, {get: function () { hit++; return 1; }, enumerable: true});\ - try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(hit); throw e; }", + try { app.activeDocument.rulerOrigin = v; } catch (e) { vc.log(e.message); } vc.log(hit);", ); - assert!(e.contains("rulerOrigin"), "{e}"); + assert!(out[0].as_str().is_some_and(|m| m.contains("rulerOrigin")), "{out:?}"); + assert_eq!(out[1], json!(0)); let e = failure(&mut s, "var a = []; for (var i = 0; i < 10001; i++) a.push(app.activeDocument.pageItems[0]); app.activeDocument.selection = a;"); assert!(e.contains("at most 10000"), "{e}"); assert_eq!(s.active().unwrap().selection.objects, before); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 312221986c..f34c9cff8e 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -407,8 +407,9 @@ impl Interp { } _ => self.read_args(name, args, how)?, }; - // Only the script's own code, in a run that can pause, can wait for a result. - let can_wait = self.in_slice && self.reentry == 0; + // Only the script's own code, in a run that can pause, can wait for a result, and a host + // class's constructor called with `new` cannot. + let can_wait = self.in_slice && self.reentry == 0 && !self.constructing; self.can_wait.set(can_wait); let result = f(data); self.can_wait.set(false); @@ -417,6 +418,7 @@ impl Interp { Ok(d) => self.write_data(d, 0, matches!(how, ArgRead::Frozen)), Err(HostError::Wait) if can_wait => { self.waiting = true; + self.waiting_hosted = matches!(how, ArgRead::Hosted); self.pause.set(true); Ok(Value::Undefined) } diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 1d03f981ff..e88bc3f454 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -8,7 +8,9 @@ //! object a script made that carries [`HOST_REF_KEY`] is refused, so a script cannot make an object //! of a host class from its own data. A class's prototype and constructor are frozen. While a //! script holds the object for a class and handle, each read of that class and handle gives the -//! same object. +//! same object. Classes that descend from the same class without a parent share their objects: a +//! read of another of them with the same handle gives the object the script holds, now of the +//! class that read names. //! //! 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 @@ -67,6 +69,9 @@ pub(crate) struct Entry { proto: ObjId, ctor: ObjId, index: Option, + /// The class without a parent this class descends from (itself for such a class), as an index + /// into the realm's classes. + family: u32, } impl Entry { @@ -75,24 +80,26 @@ impl Entry { } } -/// A class, as an index into the realm's classes, and the bits of a handle. +/// A family of classes ([`Entry::family`]) and the bits of a handle. type MadeKey = (u32, Box<[u64]>); -/// The object made for each class and handle ([`Interp::host_objects`]). +/// The object made for each family of classes and handle ([`Interp::host_objects`]). pub(crate) type Made = std::collections::HashMap; /// Whether `id` is still the object made for `key`, and not a freed cell or another object that /// was given its cell. -fn is_made(heap: &crate::heap::Heap, id: ObjId, key: &MadeKey) -> bool { +fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool { heap.object(id).is_some_and(|o| match &o.class { - Class::Host(h) => h.class == key.0 && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()), + Class::Host(h) => { + classes.get(h.class as usize).is_some_and(|e| e.family == key.0) && h.handle.iter().map(|n| n.to_bits()).eq(key.1.iter().copied()) + } _ => false, }) } /// Drops the entries of `made` whose objects the last collection freed. -pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap) { - made.retain(|key, id| is_made(heap, *id, key)); +pub(crate) fn forget_collected(made: &mut Made, heap: &crate::heap::Heap, classes: &[Entry]) { + made.retain(|key, id| is_made(heap, classes, *id, key)); } /// The [`Data`] that stands for the object of host class `class` with `handle`. @@ -132,12 +139,20 @@ impl Interp { let Some((class, entry)) = self.host_classes.iter().enumerate().find(|(_, e)| &*e.name == name) else { return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); }; - let proto = entry.proto; + let (proto, family) = (entry.proto, entry.family); let class = u32::try_from(class).unwrap_or(u32::MAX); - let made = (class, handle.iter().map(|n| n.to_bits()).collect::>()); + let made = (family, handle.iter().map(|n| n.to_bits()).collect::>()); if let Some(&id) = self.host_objects.get(&made) - && is_made(&self.heap, id, &made) + && is_made(&self.heap, &self.host_classes, id, &made) { + // An object of another class of the family becomes one of `class`. + let o = self.object_mut(id)?; + if let Class::Host(h) = &mut o.class + && h.class != class + { + h.class = class; + o.proto = Some(proto); + } return Ok(Value::Object(id)); } self.reserve_heap(crate::heap::OBJECT_BYTES)?; @@ -207,10 +222,11 @@ 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 parent = match &class.parent { - None => i.intrinsics.object_proto, + 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, + Some(e) => (e.proto, e.family), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; @@ -220,7 +236,7 @@ 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 }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..1da0d53002 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -636,6 +636,46 @@ fn a_host_function_that_waits_where_it_cannot_ends_the_run() { assert_eq!(e.kind, RunErrorKind::Internal); } +/// The host class `Thing` with the method `fetch`, which waits for its answer where it can, the +/// getter `id`, the first number of the object's handle, and the constructor `make`; and the +/// global `thing`, the `Thing` with the handle `[1]`. +fn with_thing(r: &mut Realm, make: Option) { + let can_wait = r.wait_flag(); + let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); + let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); + let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; + let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); +} + +#[test] +fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.start("var t = thing.fetch(), u = thing.fetch(); [t instanceof Thing, t.id, t === u, t === thing].join()").unwrap(); + for _ in 0..2 { + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(host_ref("Thing", &[2.0])).unwrap(); + } + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); +} + +#[test] +fn a_host_class_constructor_called_with_new_cannot_wait() { + let mut r = realm(1_000_000); + let could: Rc>> = Rc::default(); + let (seen, can_wait) = (could.clone(), r.wait_flag()); + let make: HostFunction = Rc::new(move |_| { + seen.set(Some(can_wait.get())); + if can_wait.get() { Err(HostError::Wait) } else { Ok(Data::Object(Vec::new())) } + }); + with_thing(&mut r, Some(make)); + r.start("var c = new Thing(); c instanceof Thing").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); + assert_eq!(could.get(), Some(false)); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 874116d472..63e6251dd7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -257,7 +257,7 @@ pub(crate) struct Interp { pub(crate) host_classes: Vec, /// Whether [`Self::write_data`] makes objects of host classes from their [`crate::host_ref`]. pub(crate) write_hosted: bool, - /// The object made for each class and handle ([`crate::host_classes`]), so that two reads of + /// The object made for each family of classes and handle ([`crate::host_classes`]), so that two reads of /// the same one give the same object. It is not a root: an entry whose object was collected is /// dropped after each collection. pub(crate) host_objects: crate::host_classes::Made, @@ -281,6 +281,11 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its + /// answer is read as such a member's result is ([`Interp::write_hosted`]). + pub(crate) waiting_hosted: bool, + /// A host class's constructor runs with `new`: it may not wait for its result. + pub(crate) constructing: bool, /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, @@ -538,6 +543,8 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + waiting_hosted: false, + constructing: false, resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), @@ -788,7 +795,7 @@ impl Interp { roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); - crate::host_classes::forget_collected(&mut self.host_objects, &self.heap); + crate::host_classes::forget_collected(&mut self.host_objects, &self.heap, &self.host_classes); // The collection counts the live total again, so bytes already released are not in it. self.held.released.set(0); self.flattened.set(0); @@ -2392,11 +2399,14 @@ impl Interp { } // A host class's constructor ([`crate::host_classes`]) gives the object it makes. A plain // object it gives inherits from the class's prototype. The class's other functions are - // not constructors. + // not constructors. A constructor called with `new` cannot wait for its result. Some(Func::Data { f: host, name, read: read @ crate::host::ArgRead::Hosted }) if f.as_object().is_some_and(|o| self.is_host_constructor(o)) => { - let v = self.call_data(&host, &name, &Value::Undefined, &args, &read)?; + let was = std::mem::replace(&mut self.constructing, true); + let v = self.call_data(&host, &name, &Value::Undefined, &args, &read); + self.constructing = was; + let v = v?; if let (Some(callee), Value::Object(o)) = (f.as_object(), &v) && matches!(self.object(*o)?.class, Class::Ordinary) && let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))? diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 52952eb73e..f1ca6b570d 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -255,6 +255,8 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; @@ -291,6 +293,8 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.waiting_hosted = false; + interp.constructing = false; interp.resuming = None; interp.passing = Value::Undefined; match result { @@ -406,8 +410,11 @@ impl Realm { }); } interp.waiting = false; + // A member of a host class gets its answer as it gets an immediate result. + let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. - let r = interp.write_data(d, 0, false).and_then(|v| { + let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; + let r = written.and_then(|v| { interp.stack.pop(); interp.push(v) }); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 4f48d4ad2f..f64f2f6be2 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -245,8 +245,13 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { ) } +/// Sets one artboard layout field. A new layout or column count replaces the rows of a preset +/// made with `file.new`'s `rows`. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) { + o.remove("rows"); + } l[key] = v; d.fields.insert("artboardLayout".into(), l); } @@ -890,6 +895,21 @@ mod tests { app.ui.dialog.as_ref().unwrap().fields.get(k).cloned().unwrap_or_default() } + /// A preset's rows stay until Columns or the layout changes. + #[test] + fn a_new_column_count_replaces_a_presets_rows() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 4})); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "spacing", json!(5.0)); + assert_eq!(field(&app, "artboardLayout")["rows"], json!(4)); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "columns", json!(3)); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0})); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4})); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] diff --git a/docs/gaps.md b/docs/gaps.md index 549d74f46b..cd23b3096c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,8 +807,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the document object model for scripts and the `#engine` script directive (#1183 is - open). File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the + other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new + documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 94d8e728c0..5f873fe10a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2631,9 +2631,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives; `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` - throw an error that says they are not available yet, and `showOptionsDialog` true throws `Dialog unavailable` - with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, + starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when + the preset it is given holds one of them with a value other than `null`, and makes no document. + `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each @@ -2648,7 +2649,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when - `node.move` refuses the place of a copy, `duplicate` deletes the copy and throws that error. The + `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. `duplicate` on a path inside a compound path throws + `Duplicating a path inside a compound path is not available yet`. 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"`. @@ -8847,7 +8851,10 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -spacing, rightToLeft}`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's +rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +an error with another layout; a preset keeps the rows until `columns` without `rows`, or another layout, is given, +and New Document drops them when Columns or the layout changes), +`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, From 6cce980e2bb5e1781b72452983716ed659775575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:46:14 -0800 Subject: [PATCH 03/24] Scripts: keep targets and chosen parts when edits restore the selection - An edit a script makes puts back a Layers panel target, an object chosen inside a dynamic symbol instance and an object chosen in an Objects on Path group, each with its own selection command. - Assigning a document's selection selects a symbol instance or an Objects on Path group as a whole when one of its objects was chosen. - file.newPresets lists a grid by column's rows as set, also when there are fewer artboards than rows, and New Document's Columns shows the columns those rows give the current number of artboards. - docs/roadmap.md's M13 row names the script object model that is available. --- crates/engine/src/cmd/newdoc.rs | 5 +- crates/engine/src/script/dom.rs | 35 +++++++++-- crates/engine/src/tests/script_dom.rs | 71 ++++++++++++++++++++++ crates/ui-egui/src/dialogs/new_document.rs | 35 ++++++++--- docs/mcp.md | 5 +- docs/roadmap.md | 2 +- 6 files changed, 135 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 03be423cf3..a242b1fd20 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -265,8 +265,9 @@ impl DocSettings { pub fn to_json(&self) -> Value { let mut layout = json!({"layout": self.layout.id(), "columns": self.grid_columns(), "spacing": self.spacing, "rightToLeft": self.right_to_left}); - if let (Some(rows), Some(o)) = (self.grid_rows(), layout.as_object_mut()) { - o.insert("rows".into(), json!(rows)); + // The rows as set, also when there are fewer artboards than rows. + if let Some(o) = layout.as_object_mut().filter(|_| self.grid_rows().is_some()) { + o.insert("rows".into(), json!(self.rows)); } json!({ "name": self.name, diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd17bb579e..0883e94099 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -443,9 +443,10 @@ fn coords_of(d: &Data) -> std::result::Result { } /// Selects `before` again in the active document `doc` with the selection commands, so that the -/// journal holds the change: the objects in their order with their direct-selected anchors, then -/// the segments, the ruler guides and the key object, guide or anchor. Objects that are now -/// deleted, hidden or locked are left out. +/// journal holds the change: a Layers panel target, a dynamic symbol instance's object or an Objects +/// on Path group's object with its own command, else the objects in their order with their +/// direct-selected anchors, then the segments, the ruler guides and the key object, guide or anchor. +/// Objects that are now deleted, hidden or locked are left out. fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -> std::result::Result<(), HostError> { // Slices selected with the Slice Selection tool are the whole selection when there are any. let slices: Vec = before.slices.iter().filter(|i| doc.is_slice(**i)).map(|i| i.0).collect(); @@ -454,6 +455,24 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - return Ok(()); } let keep = |id: &NodeId| editable(doc, *id); + // Each of these commands sets the whole selection. One that refuses (its object is no longer + // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the + // objects are selected as below. + if let Some(t) = before.target.filter(keep) + && command(h, "layer.target", &json!({"id": t.0})).is_ok() + { + return Ok(()); + } + if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) + && command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})).is_ok() + { + return Ok(()); + } + if let Some(m) = before.on_path_member.filter(keep) + && command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})).is_ok() + { + return Ok(()); + } let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); let kept: Vec = before.objects.iter().copied().filter(keep).collect(); if kept.is_empty() { @@ -503,8 +522,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, -/// ruler guides, slices and the key included, less the objects that are now deleted, hidden or -/// locked. +/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic +/// symbol instance or an Objects on Path group included, less the objects that are now deleted, +/// hidden or locked. fn on_doc( h: &Host, uid: u64, @@ -1054,12 +1074,15 @@ fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { } /// Makes `ids` the selection of `doc`, with no command when it already is: the same objects, each -/// selected as a whole, and no ruler guide, slice, key or Layers panel target. +/// selected as a whole (no dynamic symbol instance's object or Objects on Path group's object +/// chosen in it), and no ruler guide, slice, key or Layers panel target. fn set_selection(h: &Host, doc: Doc, ids: Vec) -> Answer { let same = with_doc(h, doc, |_, st| { let sel = &st.selection; sel.objects == ids && sel.target.is_none() + && sel.symbol_part.is_none() + && sel.on_path_member.is_none() && sel.anchors.is_empty() && sel.segments.is_empty() && sel.guides.is_empty() diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 15a8e2e950..63cebea042 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -430,6 +430,18 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn a_listed_preset_keeps_more_rows_than_artboards() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + let listed = settings.to_json(); + assert_eq!((&listed["artboardLayout"]["columns"], &listed["artboardLayout"]["rows"]), (&json!(1), &json!(4)), "{listed}"); + // Five artboards from the listing fill four rows, not two. + let more = settings.with_params(&json!({"artboards": 5, "artboardLayout": listed["artboardLayout"]}), "file.new").unwrap(); + assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); +} + #[test] fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); @@ -487,6 +499,65 @@ fn assigning_the_selection_clears_a_layers_panel_target() { assert_eq!((sel.objects.clone(), sel.target), (vec![a], None)); } +#[test] +fn an_edit_keeps_a_layers_panel_target() { + let (mut s, a, b) = doc(); + s.execute("layer.target", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.target), (vec![a], Some(a))); + // A targeted layer stays targeted, with its art selected. + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); +} + +/// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two +/// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the +/// group's rectangle). +fn chosen_parts() -> (Session, NodeId, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + rect(&mut s, 300.0, 200.0, 20.0, 20.0); + let (x, y) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 50.0, 10.0, 20.0, 20.0)); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [x.0, y.0], "type": "dynamic"})).unwrap()); + let member = rect(&mut s, 10.0, 100.0, 20.0, 20.0); + let line = id(s.execute("shape.line", &json!({"x1": 50, "y1": 250, "x2": 350, "y2": 250})).unwrap()); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = id(s.execute("object.objectsOnPath.attach", &json!({"path": line.0})).unwrap()); + (s, inst, group, member) +} + +#[test] +fn an_edit_keeps_an_object_chosen_inside_a_symbol_or_on_a_path() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (before.objects, before.symbol_part)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], Some(member))); +} + +#[test] +fn assigning_the_selection_selects_a_symbol_or_on_path_group_as_a_whole() { + let (mut s, inst, group, member) = chosen_parts(); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.symbol_part.clone()), (vec![inst], None)); + s.execute("object.objectsOnPath.selectMember", &json!({"member": member.0})).unwrap(); + log(&mut s, "var d = app.activeDocument; d.selection = d.selection[0];"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.on_path_member), (vec![group], None)); +} + #[test] fn a_held_image_stays_the_same_object_when_it_is_embedded() { let dir = super::links::Folder::new("dom-embed"); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index f64f2f6be2..6b9abbcb2f 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -233,16 +233,21 @@ fn unit(d: &Dialog) -> Unit { Unit::named(&d.str("units")).unwrap_or_default() } -/// The artboard layout fields. +/// The artboard layout fields. A grid by column with rows shows the columns those rows give the +/// current number of artboards, as `file.new` lays them out. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); - ( - get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(), - get("columns").and_then(Value::as_u64).unwrap_or(1), - get("spacing").and_then(Value::as_f64).unwrap_or(20.0), - get("rightToLeft").and_then(Value::as_bool).unwrap_or(false), - ) + let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); + let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let columns = match rows { + Some(rows) => { + let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; + n.div_ceil(rows.min(n)) + } + None => get("columns").and_then(Value::as_u64).unwrap_or(1), + }; + (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset @@ -910,6 +915,22 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); } + /// Columns shows what a preset's rows give the current number of artboards. + #[test] + fn columns_follow_a_presets_rows_as_artboards_change() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 4})); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] { + set(&mut app, "artboards", json!(artboards)); + assert_eq!(columns(&app), shown, "{artboards} artboards"); + } + // Without rows, Columns shows the stored count. + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5f873fe10a..50e8af3d40 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8852,8 +8852,9 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is -an error with another layout; a preset keeps the rows until `columns` without `rows`, or another layout, is given, -and New Document drops them when Columns or the layout changes), +an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are +fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns +the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). diff --git a/docs/roadmap.md b/docs/roadmap.md index 27c4f78e25..3ddf3459a4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 626d84352049b897d8e9e77e5e14078b1bfd2d0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:34:09 -0800 Subject: [PATCH 04/24] Scripts: list the object model in the host name check, refuse zOrder inside a compound path The host name test now has rows for app, the document model classes and the enumerations the script host adds. zOrder on a path inside a compound path throws an error and leaves the document unchanged, as duplicate does. --- crates/engine/src/script/dom.rs | 19 ++++-- crates/engine/src/tests/script_dom.rs | 36 +++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 61 ++++++++++++++++++- docs/mcp.md | 3 +- 4 files changed, 111 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0883e94099..b986dfcf2d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1563,16 +1563,21 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { /// The error of `duplicate` on a path inside a compound path. pub const COMPOUND_MEMBER: &str = "Duplicating a path inside a compound path is not available yet"; +/// The error of `zOrder` on a path inside a compound path. +pub const COMPOUND_MEMBER_ORDER: &str = "Reordering a path inside a compound path is not available yet"; + +/// Whether `item` is a path inside a compound path. +fn in_compound(h: &Host, item: Item) -> bool { + with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }))) +} + /// `duplicate(relativeObject?, insertionLocation?)`: a copy of the item, directly above it as /// Edit › Duplicate makes one, or into or beside `relativeObject` as `move` puts it. → the copy. /// When `node.move` refuses the place, the copy and every change it made are put back, and the /// error is thrown. fn item_duplicate(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let in_compound = with_doc(h, item.doc, |_, st| { - st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })) - }); - if in_compound { + if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER.into())); } let to = match arg(a, 1) { @@ -1597,7 +1602,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { Ok(item_ref(h, st, NodeId(id))) } -/// `zOrder(method)`: one of the four Object › Arrange commands for the item. +/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a +/// compound path is refused. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -1607,6 +1613,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), }; let item = this_item(h, a)?; + if in_compound(h, item) { + return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); + } let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 63cebea042..67bd373e2d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -358,6 +358,42 @@ fn a_path_inside_a_compound_path_is_not_duplicated() { assert_eq!(out, vec![json!(["CompoundPathItem", 6])]); } +#[test] +fn a_path_inside_a_compound_path_is_not_reordered() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [], out = [];\ + for (var i = 0; i < p.length; i++) if (p[i].parent.typename == 'CompoundPathItem') m.push(p[i]);\ + var ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD, ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + for (var j = 0; j < m.length; j++) for (var k = 0; k < ways.length; k++) {\ + try { m[j].zOrder(ways[k]); out.push('ran'); } catch (e) { out.push(e.message); }\ + }\ + vc.log(m.length); vc.log(out);", + ); + assert_eq!(out[0], json!(2)); + let messages = out[1].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 8, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("Reordering a path inside a compound path is not available yet")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // The compound path itself still moves. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c;\ + for (var i = 0; i < p.length; i++) if (p[i].typename == 'CompoundPathItem') c = p[i];\ + var at = c.zOrderPosition; c.zOrder(ZOrderMethod.BRINGTOFRONT); vc.log([at, c.zOrderPosition]);", + ); + assert_eq!(out, vec![json!([1, 2])]); +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { let mut s = Session::new(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..ef7c97e951 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -41,7 +41,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// outside it. The document model (`app`, its classes and the enumerations) acts on the open +/// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -70,8 +71,63 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI modified name parent path relativeURI resolve selectDlg toString", ), + ( + "", + "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ + DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ + PageItems RulerUnits ZOrderMethod", + ), + ("Application.", "prototype"), + ( + "Application.prototype.", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ + selection typename", + ), + ("Documents.", "prototype"), + ("Documents.prototype.", "add addDocument constructor getByName index length parent 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", + ), + ("Layer.", "prototype"), + ("Layer.prototype.", "constructor name typename"), + ("PageItems.", "prototype"), + ("PageItems.prototype.", "constructor getByName index length parent removeAll 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 \ + transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ + width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", + ), + ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), + ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), + ("DocumentColorSpace.", "CMYK RGB"), + ("DocumentPresetType.", "BasicCMYK BasicRGB Mobile Print Video Web"), + ("DocumentPreviewMode.", "DefaultPreview OverprintPreview PixelPreview"), + ("DocumentRasterResolution.", "HighResolution MediumResolution ScreenResolution"), + ( + "DocumentTransparencyGrid.", + "TransparencyGridBlue TransparencyGridDark TransparencyGridGreen TransparencyGridLight TransparencyGridMedium \ + TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", + ), + ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; +/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` +/// and the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. const NOT_CHECKED: &str = "vc"; @@ -118,7 +174,8 @@ fn language_names() -> BTreeSet { fn table_names() -> BTreeSet { let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}"))); - OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect() + let bare = BARE_CLASSES.split_whitespace().flat_map(|c| [c.to_string(), format!("{c}.prototype"), format!("{c}.prototype.constructor")]); + OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain(bare).chain([NOT_CHECKED.to_string()]).collect() } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 50e8af3d40..c305916f6f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2651,7 +2651,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot directly below it. An object of another document throws `Cross-document placement is not available`, and when `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. `duplicate` on a path inside a compound path throws - `Duplicating a path inside a compound path is not available yet`. A script that holds a placed image keeps the + `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 From 4b97cc84926ee4dd9c807dcc1e2181017452d16c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:18:44 -0800 Subject: [PATCH 05/24] Scripts: a failed selection restore ends the run unless the command refused When an edit puts the selection back, the Layers panel target, symbol part, Objects on Path member, ruler guide and key object commands fall back or skip only when the command refuses with an ordinary error. An internal failure or a request to stop now ends the run instead of being treated as a refusal. --- crates/engine/src/script/dom.rs | 35 ++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b986dfcf2d..9d4acfa798 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -459,17 +459,17 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the // objects are selected as below. if let Some(t) = before.target.filter(keep) - && command(h, "layer.target", &json!({"id": t.0})).is_ok() + && done_unless_refused(command(h, "layer.target", &json!({"id": t.0})))? { return Ok(()); } if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) - && command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})).is_ok() + && done_unless_refused(command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})))? { return Ok(()); } if let Some(m) = before.on_path_member.filter(keep) - && command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})).is_ok() + && done_unless_refused(command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})))? { return Ok(()); } @@ -504,7 +504,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - // Guides that are locked now, and a key that no longer qualifies (the objects beside it are // gone), stay unselected: those commands refuse them and change nothing. if !picked.is_empty() { - let _ = command(h, "guide.select", &json!({"indexes": picked, "toggle": true})); + done_unless_refused(command(h, "guide.select", &json!({"indexes": picked, "toggle": true})))?; } let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { Some(json!({"id": id.0, "anchor": [p, k]})) @@ -514,11 +514,22 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) }; if let Some(key) = key { - let _ = command(h, "select.key", &key); + done_unless_refused(command(h, "select.key", &key))?; } Ok(()) } +/// The result `r` of a selection command that [`restore_selection`] runs: `true` when it ran and +/// `false` when it refused (an `Error`, which changes nothing). Any other error, such as an +/// internal failure or a request to stop, is returned, so the run ends with it. +fn done_unless_refused(r: std::result::Result) -> std::result::Result { + match r { + Ok(_) => Ok(true), + Err(HostError::Error(_)) => Ok(false), + Err(e) => Err(e), + } +} + /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, @@ -1813,3 +1824,17 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), 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", &[]))]) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restoring_the_selection_falls_back_only_on_a_refusal() { + assert_eq!(done_unless_refused(Ok(Data::Undefined)), Ok(true)); + assert_eq!(done_unless_refused(Err(HostError::Error("refused".into()))), Ok(false)); + // An internal failure or a stop ends the run instead of being taken for a refusal. + assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); + assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); + } +} From 4bc1f7a187439606160a91b03be7add43a1cd4a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:40:55 -0800 Subject: [PATCH 06/24] Scripts: Documents.add takes the artboard spacing file.new takes artboardSpacing is refused above 100,000 points, the limit file.new applies, so a value file.new would refuse throws a RangeError that names artboardSpacing. --- crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/script/dom.rs | 4 ++-- crates/engine/src/tests/script_dom.rs | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index a242b1fd20..983ef4041d 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -561,7 +561,7 @@ pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError { bad(cmd, format!("width and height must be more than 0 and at most {limit}")) } /// Largest artboard spacing, points. -const MAX_SPACING: f64 = 1.0e5; +pub(crate) const MAX_SPACING: f64 = 1.0e5; pub fn color_mode_id(m: ColorMode) -> &'static str { match m { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9d4acfa798..55073e70ec 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -763,8 +763,8 @@ impl NewDoc<'_> { } if let Some(d) = self.spacing { let v = number(d, "artboardSpacing")?; - if !(0.0..=MAX_SIZE).contains(&v) { - return Err(HostError::Range("artboardSpacing must be from 0 to 3999856 points".into())); + if !(0.0..=crate::cmd::newdoc::MAX_SPACING).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 100000 points".into())); } layout.insert("spacing".into(), json!(v)); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 67bd373e2d..0324e81339 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -62,6 +62,9 @@ fn app_documents_track_active_tab_and_new_document() { assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + // The spacing is refused at file.new's limit, with the script's own name for it. + let spacing = "app.documents.add(undefined, 10, 10, 2, DocumentArtboardLayout.Row, 100001);"; + assert!(failure(&mut s, spacing).contains("artboardSpacing must be from 0 to 100000 points")); assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); assert_eq!(s.documents().len(), 3); } From a8d1b297664811f37ec5ab206824dea1ed77aeb2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:46:08 -0800 Subject: [PATCH 07/24] Tests: the script corpus failure test reads an undefined name Scripts now have an app object, so app.activeDocument no longer throws a ReferenceError. The test reads a name the host does not define instead. --- crates/engine/tests/script_corpus.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..c2ca9a38f6 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -89,9 +89,9 @@ fn a_script_that_ends_well_passes() { fn a_failure_gives_its_kind_and_place() { let r = result(&mut session(), &source("var a = 1;\nvar = ;")); assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2))); - let r = result(&mut session(), &source("var d = app.activeDocument;")); + let r = result(&mut session(), &source("var d = undefinedHost.activeDocument;")); assert_eq!(r["kind"], "thrown"); - assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}"); + assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: undefinedHost"), "{r}"); let r = result(&mut session(), &source("while (true) {}")); assert_eq!(r["kind"], "limit"); assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL); From 76aee609f1458c53e0c32c8ae3f53d849469d24b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:21:32 -0800 Subject: [PATCH 08/24] Tests: page item width and height setters give the page-aligned size on rotated objects A rotated rectangle given a width and then a height through the scripting object model reads back the values set, its geometric bounds have that size, and other objects stay as they were. The resize doc comment names the page's axes. --- crates/engine/src/script/dom.rs | 4 +++- crates/engine/src/tests/script_dom.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 55073e70ec..fb72785a23 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1392,7 +1392,9 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer { move_to(h, a, None, Some(y)) } -/// Scales the item about its top-left corner to `size` points wide (`width`) or tall. +/// Scales the item about its top-left corner along the page's axes to `size` points wide (`width`) +/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated +/// objects included. fn resize(h: &Host, a: &[Data], width: bool) -> Answer { let what = if width { "width" } else { "height" }; let size = number(arg(a, 1), what)?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0324e81339..3c5a2f4df0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,27 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +#[test] +fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let other = format!("{:?}", s.active().unwrap().doc.node(b)); + let out = log( + &mut s, + "var i = app.activeDocument.selection[0], h = i.height;\ + i.width = 80; vc.log([i.width, i.height - h]);\ + i.height = 90; vc.log([i.width, i.height]);\ + var g = i.geometricBounds; vc.log([g[2] - g[0], g[1] - g[3]]);", + ); + let pairs: Vec<[f64; 2]> = out.iter().map(|v| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]).collect(); + for (got, want) in pairs.iter().zip([[80.0, 0.0], [80.0, 90.0], [80.0, 90.0]]) { + assert!((got[0] - want[0]).abs() < 1e-6 && (got[1] - want[1]).abs() < 1e-6, "{out:?}"); + } + assert_eq!(pairs.len(), 3, "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); +} + #[test] fn convert_coordinate_pair_is_inverse_and_y_up() { let mut s = Session::new(); From f33e0cb16d13ed6f2c934e1a63074b7fabf2c94c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:37:34 -0800 Subject: [PATCH 09/24] Scripts: PageItem.remove refuses hidden or locked art as removeAll does remove() on an object that is hidden or locked, sits in a hidden or locked layer or group, or is a group holding such an object now throws and deletes nothing, the same rule pageItems.removeAll() applies. docs/mcp.md states both rules and that width and height scale along the page's axes. --- crates/engine/src/script/dom.rs | 6 ++++++ crates/engine/src/tests/script_dom.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 6 +++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fb72785a23..241720f786 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1437,8 +1437,14 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) } +/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or +/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; + let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + if !whole { + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 3c5a2f4df0..795161ac1c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -870,6 +870,31 @@ fn remove_all_refuses_locked_art_before_deleting_anything() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (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();"); + 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(); + } + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(s.active().unwrap().doc.node(b).is_none()); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..9bc2be8efc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2665,7 +2665,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`; `index` and `getByName` throw `Not found`; and + kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a + hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw + `cannot delete hidden or locked objects` and delete nothing. Setting `width` or `height` scales the object along + the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw + `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, From ba0441c458a6496b9152924ce895475cfc5e0ae5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:33:43 -0800 Subject: [PATCH 10/24] Scripts: addDocument takes only a DocumentPreset and throws when its profile cannot be read - new DocumentPreset() now makes an object of the DocumentPreset class whose settings the run keeps, so addDocument refuses a plain object, one with a typename of DocumentPreset included, with a TypeError naming presetSettings. - When file.new reports a profileError, addDocument throws an error that names the profile and the reason, and the document made with the defaults is put back. - A script's file.new reads the New Document profile file in the app's own profiles folder; the automation roots in force still apply. Before, the script's file gate refused the folder, so a scripted addDocument never used an edited profile. Docs: docs/mcp.md. --- crates/engine/src/cmd/newdoc.rs | 17 ++- crates/engine/src/file_access.rs | 9 +- crates/engine/src/script/dom.rs | 113 +++++++++++++++--- crates/engine/src/tests/script_dom.rs | 60 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 15 ++- docs/mcp.md | 10 +- 6 files changed, 197 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..fb26b13c68 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -984,13 +984,18 @@ impl Session { let file = path.to_string_lossy().to_string(); // Checked before the file is looked for, so a request that may not read the folder learns // nothing of its files, nor where the folder is. + // A script's gate does not apply to reads of the app's own folder; the automation roots in + // force still do. let denied = |_| PROFILE_DENIED.to_string(); - crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); - } - crate::file_access::check_read(&file).map_err(denied)?; - let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let read = crate::file_access::app_folder_read(|| { + crate::file_access::check_read(&file).map_err(denied)?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&file).map_err(denied)?; + crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + })?; + let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..7c246c6a64 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -206,9 +206,16 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) } +/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of +/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply. +pub(crate) fn app_folder_read(f: impl FnOnce() -> T) -> T { + with_gate_reads_exempt(true, f) +} + thread_local! { /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an - /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + /// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force + /// ([`with_script_gate`]). static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..f8caab9adb 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -85,13 +85,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + presets: RefCell>>, } impl State { @@ -873,10 +874,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Range("the startup preset's name is too long".into())); } let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused. let settings = match given(arg(a, 2)) { None | Some(Data::Null) => Vec::new(), - Some(Data::Object(o)) => o.clone(), - Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())), + Some(d) => { + let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + h.dom.presets.borrow()[i].clone() + } }; let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { @@ -913,23 +917,101 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { if let Some(m) = mode { p.entry("colorMode").or_insert_with(|| json!(m)); } - new_document(h, p) + // A profile whose file could not be read throws, and the document `file.new` made with the + // defaults is put back, with the Recent sizes as they were. + atomically(h, |h| { + let (_, value) = command_value(h, "file.new", &Value::Object(p))?; + if let Some(e) = value.get("profileError") { + let profile = e["profile"].as_str().unwrap_or_default(); + let reason = e["reason"].as_str().unwrap_or_default(); + return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); + } + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) + }) } /// `new DocumentPreset()`: a record of new-document settings with the defaults the help page /// gives; the other settings are -/// left out. -fn new_preset(_: &[Data]) -> Answer { +/// left out. The settings stay with the run, which hands the script an object of the +/// `DocumentPreset` class. +fn new_preset(h: &Host) -> Answer { + let mut presets = h.dom.presets.borrow_mut(); + if presets.len() >= MAX_PRESETS { + return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); + } let item = |k: &str, v: Data| (k.to_string(), v); - Ok(Data::Object(vec![ - item("typename", text("DocumentPreset")), + presets.push(vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ])) + ]); + Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) +} + +/// The most `DocumentPreset` objects one run can make. +const MAX_PRESETS: usize = 10_000; + +/// The settings a `DocumentPreset` has, each a property a script reads and assigns. +const PRESET_FIELDS: &[&str] = &[ + "artboardLayout", + "artboardRowsOrCols", + "artboardSpacing", + "colorMode", + "documentBleedLink", + "documentBleedOffsetRect", + "height", + "numArtboards", + "previewMode", + "rasterResolution", + "title", + "transparencyGrid", + "units", + "width", +]; + +/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made. +fn preset_of(h: &Host, d: &Data) -> Option { + let handle = handle_of(d, "DocumentPreset")?; + let [run, i] = handle.as_slice() else { return None }; + if whole(*run) != Some(h.run) { + return None; + } + let i = usize::try_from(whole(*i)?).ok()?; + (i < h.dom.presets.borrow().len()).then_some(i) +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and +/// a value is checked when `addDocument` uses it. +fn preset_field(link: &Link, key: &'static str) -> HostMember { + let not_preset = || HostError::Type("this is not a DocumentPreset".into()); + let l = link.clone(); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let presets = h.dom.presets.borrow(); + Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) + }); + let l = link.clone(); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + let value = arg(&a, 1).clone(); + h.charge_call(16 + data_size(&value))?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let mut presets = h.dom.presets.borrow_mut(); + let fields = &mut presets[i]; + match fields.iter_mut().find(|(k, _)| k == key) { + Some((_, v)) => *v = value, + None => fields.push((key.to_string(), value)), + } + Ok(Data::Undefined) + }); + HostMember::Property { get, set } } // ---- Document ---- @@ -1723,11 +1805,14 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); - let f: HostFunction = Rc::new(move |a: Vec| { - current(&l)?.charge_call(64)?; - new_preset(&a) + let f: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + new_preset(&h) }); - HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("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) } }; let mut classes = vec![ class("Application", None, application, None), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 795161ac1c..a0e63a5d06 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,66 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn add_document_takes_only_a_document_preset() { + let mut s = Session::new(); + for source in [ + "app.documents.addDocument('Print', {width: 500});", + "app.documents.addDocument('Print', {});", + "app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});", + "var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);", + "app.documents.addDocument('Print', [612, 792]);", + "app.documents.addDocument('Print', 'DocumentPreset');", + ] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}"); + } + assert!(s.documents().is_empty(), "a refused preset makes no document"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);"); + assert_eq!(out, vec![json!(500)]); +} + +#[test] +fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + // A profile with no file gives the defaults. + let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.doc().unwrap().links_from, None); + // A script reads the profile's file in the app's own folder. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + log(&mut s, "app.documents.addDocument('Print');"); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + // file.new itself makes the document with the defaults and reports the profile it could not read. + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + s.execute("file.close", &json!({})).unwrap(); + let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(); + let e = failure(&mut s, "app.documents.addDocument('Print');"); + assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}"); + assert!(s.documents().is_empty(), "the document made with the defaults is put back"); + // A script that catches the error finds nothing changed. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.width = 333;\ + try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);", + ); + assert_eq!(out, vec![json!("Error"), json!(0)]); + assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were"); + // A startup preset with no profile reads no file. + let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); + assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..d9b6b87103 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,7 +73,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ + "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ PageItems RulerUnits ZOrderMethod", ), @@ -83,6 +83,14 @@ const INSIDE: &[(&str, &str)] = &[ "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ selection typename", ), + ("DocumentPreset.", "prototype"), + ( + "DocumentPreset.prototype.", + "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=", + ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), ("Document.", "prototype"), @@ -123,9 +131,8 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ +/// The classes the host adds with nothing but a prototype and its constructor: the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..182e0fe1c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2633,7 +2633,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. + the preset it is given holds one of them with a value other than `null`, and makes no document. A + `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a + `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the + profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) @@ -9045,7 +9049,9 @@ The profile is read on every `file.new`, so a replayed journal or a recorded act runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the folder (whether or not the file exists), the document starts with the defaults and -`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. The +`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and +a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's +file. The reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the From 5cb64802585f18dcbaeb3c4bea6136d87172b297 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:53:28 -0800 Subject: [PATCH 11/24] Scripts: assigning PageItem.selected keeps how the other objects are selected Setting selected to true or false runs select.add or select.toggle for that one object, so the other objects keep their direct-selected anchors and segments and the key object. Before, it replaced the selection with whole objects. --- crates/engine/src/script/dom.rs | 16 +++++++--------- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index f8caab9adb..e70dfbb86a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1378,17 +1378,15 @@ fn item_selected(h: &Host, a: &[Data]) -> Answer { fn item_set_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let on = boolean(arg(a, 1), "selected")?; - let mut ids = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); - if ids.contains(&item.id) == on { + if with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)) == on { return Ok(Data::Undefined); } - if on { - let mut given = selection_ids(h, item.doc, arg(a, 0))?; - ids.append(&mut given); - } else { - ids.retain(|i| *i != item.id); - } - set_selection(h, item.doc, ids) + // Adding or removing the one object keeps how the others are selected (their direct-selected + // anchors and segments, and the key object). + let ids = if on { selection_ids(h, item.doc, arg(a, 0))? } else { vec![item.id] }; + let id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, item.doc.uid, false, |h| command(h, id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a0e63a5d06..9d933378ea 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,24 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn setting_selected_keeps_how_the_other_objects_are_selected() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert!(anchors.is_some()); + log( + &mut s, + "var p = app.activeDocument.pageItems;\ + for (var i = 0; i < p.length; i++) { if (p[i].left == 200) p[i].selected = true; if (p[i].left == 100) p[i].selected = false; }", + ); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, vec![a, c]); + assert_eq!(sel.anchors.get(&a).cloned(), anchors, "the direct-selected anchors stay"); +} + #[test] fn add_document_takes_only_a_document_preset() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 182e0fe1c8..a826f5b3b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2644,7 +2644,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each entry `[i]` gives. Each page item (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the - Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected`, `opacity` (0 to + Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds + or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they + were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` From e15e3e083d652d9dd1b9145663d9b7838a07215e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:35:17 -0800 Subject: [PATCH 12/24] New Document: Columns reads float rows and columns as file.new does The dialog read artboardLayout's rows and columns as whole numbers only, so a value stored as a float (4.0 from ui.dialog.set) fell back to the stored columns while file.new made the grid from it. The dialog now reads both as file.new does: a number of 1 or more, rounded and kept to the artboard limit. --- crates/ui-egui/src/dialogs/new_document.rs | 28 +++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 6b9abbcb2f..d7c20c0137 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -234,18 +234,20 @@ fn unit(d: &Dialog) -> Unit { } /// The artboard layout fields. A grid by column with rows shows the columns those rows give the -/// current number of artboards, as `file.new` lays them out. +/// current number of artboards, as `file.new` lays them out. Rows and columns are read as +/// `file.new` reads them: a number of 1 or more, rounded and kept to [`MAX_ARTBOARDS`]. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); + let count = |k: &str| get(k).and_then(Value::as_f64).filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u64); let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); - let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let rows = count("rows").filter(|_| lay == ArtboardLayout::GridByColumn); let columns = match rows { Some(rows) => { let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; n.div_ceil(rows.min(n)) } - None => get("columns").and_then(Value::as_u64).unwrap_or(1), + None => count("columns").unwrap_or(1), }; (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } @@ -931,6 +933,26 @@ mod tests { assert_eq!(columns(&app), 2); } + /// Rows and columns stored as floats, as `ui.dialog.set` stores them, show what `file.new` + /// makes of them: rounded, at least 1 and at most the artboard limit. + #[test] + fn columns_read_float_rows_and_columns_as_file_new_does() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(5)); + for (rows, shown) in [(json!(4.0), 2), (json!(3.5), 2), (json!(2.4), 3)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 1, "rows": rows})); + assert_eq!(columns(&app), shown, "rows {rows}"); + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 3.0})); + assert_eq!(columns(&app), 3); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 1e9})); + assert_eq!(columns(&app), super::MAX_ARTBOARDS as u64); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 0.4})); + assert_eq!(columns(&app), 1); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] From abe8b303ded7186796ad1ac8647f142a02ef1375 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:14:01 -0800 Subject: [PATCH 13/24] Scripts: remove and removeAll keep art on a locked artboard PageItem.remove() and PageItems.removeAll() checked only whether the object and its layers and groups were shown and unlocked, then passed the ids to edit.clear, which deletes named objects without checking artboard locks. Both now throw "cannot delete objects on a locked artboard" with the object ids and delete nothing, as art on a locked artboard is not editable elsewhere in the document. --- crates/engine/src/script/dom.rs | 26 +++++++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e70dfbb86a..bce4edad74 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1249,19 +1249,26 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { } /// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or -/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, +/// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -1518,17 +1525,26 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { } /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or -/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. +/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] +/// refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + let (whole, on_locked) = with_doc(h, item.doc, |_, st| { + (editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable), st.doc.on_locked_artboard(item.id)) + }); if !whole { return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } +/// The error of `remove()` and `removeAll()` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; + /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 9d933378ea..26632b7055 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -973,6 +973,30 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { assert!(s.active().unwrap().doc.node(b).is_none()); } +/// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. +#[test] +fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index a826f5b3b8..51cd09fdbb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2673,7 +2673,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw - `cannot delete hidden or locked objects` and delete nothing. Setting `width` or `height` scales the object along + `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` + when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, From 71aaa752a03dd40e4cbc7faef551022c6dd2f9a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:52:56 -0800 Subject: [PATCH 14/24] New Document: a new layout keeps the columns a preset's rows showed A preset made with file.new's rows under gridByColumn shows the column count those rows give the current number of artboards. Changing the Layout field removed the rows and kept the preset's stored columns, so Create laid out a different number of columns than the dialog showed. The layout change now writes the shown count into columns, for rows stored as integers or floats. Under gridByRow the dialog shows the stored columns and file.new rejects rows, so a layout change from it keeps the stored columns, as it does for rows file.new would reject. --- crates/ui-egui/src/dialogs/new_document.rs | 41 +++++++++++++++++++--- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index d7c20c0137..cf10f0035e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,16 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. fn set_layout(d: &mut Dialog, key: &str, v: Value) { + let (lay, shown, ..) = layout(d); let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) { - o.remove("rows"); + if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) + && key == "layout" + && lay == ArtboardLayout::GridByColumn + { + o.insert("columns".into(), json!(shown)); } l[key] = v; d.fields.insert("artboardLayout".into(), l); @@ -914,7 +919,35 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0})); set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4})); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 1})); + } + + /// A new layout keeps the columns a preset's rows showed, so Create lays out what the dialog + /// showed. Under a grid by row the dialog shows the stored columns, and they stay. + #[test] + fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(9)); + for to in ["gridByRow", "gridByColumn", "row", "column"] { + for rows in [json!(4), json!(4.0), json!(3.6)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); + assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + } + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 2})); + assert_eq!(columns(&app), 2); + // Rows file.new would reject leave the stored columns the dialog showed. + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 0})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } /// Columns shows what a preset's rows give the current number of artboards. From 67633efb4d4a2c537600e1b237cc87c3c4d18259 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:36:54 -0800 Subject: [PATCH 15/24] Scripts: a linked profile file is refused and preset values count as passed data A New Document profile file that is a link or a folder is no longer read: the read is exempt from a script's file gate, which never checked where a link leads. file.new reports it as a profileError with the reason "not a plain file". Reading a DocumentPreset setting now counts the value it returns toward the data a run may pass, as assigning it does, and addDocument counts the preset's settings before copying them. The removeAll() test on a locked artboard now also holds an object on an unlocked artboard and checks it is still there after the call throws. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 12 ++++++++---- crates/engine/src/script/dom.rs | 10 ++++++++-- crates/engine/src/script/mod.rs | 13 ++++++++++++- crates/engine/src/tests/newdoc.rs | 16 ++++++++++++++++ crates/engine/src/tests/script_dom.rs | 26 +++++++++++++++++++++++++- docs/mcp.md | 4 ++-- 7 files changed, 72 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bf9ff59c14..c8b9785fe9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index fb26b13c68..073de104cc 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -977,8 +977,9 @@ impl Session { /// Profile `name`'s document, its file's path and a warning for each color profile the file /// carries that can't be used: `None` when it has no file (the shipped profile, the defaults), - /// the reason when the request being served may not read it, or its file can't be read, is - /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + /// the reason when the request being served may not read it, or its file is a link or a folder, + /// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft + /// reads. fn read_profile(&self, name: &str) -> std::result::Result, String> { let Some(path) = self.profile_path(name) else { return Ok(None) }; let file = path.to_string_lossy().to_string(); @@ -989,8 +990,11 @@ impl Session { let denied = |_| PROFILE_DENIED.to_string(); let read = crate::file_access::app_folder_read(|| { crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); + match std::fs::symlink_metadata(&path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + // A link is refused: the script's gate does not check where it leads. + Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), + _ => {} } crate::file_access::check_read(&file).map_err(denied)?; crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bce4edad74..675ab3fb5a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -879,6 +879,9 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { None | Some(Data::Null) => Vec::new(), Some(d) => { let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + // The settings are charged as data passed to the call before they are copied. + let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(); + h.charge_call(bytes)?; h.dom.presets.borrow()[i].clone() } }; @@ -992,8 +995,11 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let l = link.clone(); let get: HostFunction = Rc::new(move |a: Vec| { let h = current(&l)?; - h.charge_call(16)?; - let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + // The value handed back is charged as the setter charges it, before it is copied. + let i = preset_of(&h, arg(&a, 0)); + let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v))); + h.charge_call(16 + bytes)?; + let i = i.ok_or_else(not_preset)?; let presets = h.dom.presets.borrow(); Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) }); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..affacab584 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1046,7 +1046,7 @@ impl Host { } let bridge = self.bridge.get().saturating_add(bytes); self.bridge.set(bridge); - if bridge > MAX_BRIDGE_BYTES { + if bridge > bridge_bytes() { return Err(self.over(OVER_BRIDGE)); } let n = self.calls_this_slice.get() + 1; @@ -2509,6 +2509,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The data a run may pass to and from commands. +fn bridge_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) { + return n; + } + MAX_BRIDGE_BYTES +} + /// The limits of a command's result on its way to the script. fn result_limits() -> DataLimits { #[cfg(test)] @@ -2526,6 +2535,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. + pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index edf27aaf2a..11330bac10 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -906,6 +906,22 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let _ = std::fs::remove_dir_all(&dir); } +#[cfg(unix)] +#[test] +fn a_profile_that_is_a_link_is_not_followed() { + let (mut s, dir) = with_profiles("link"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + // A profile the folder held, moved out and linked back in. + let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); + assert!(r.get("profile").is_none(), "{r}"); + let _ = std::fs::remove_file(&outside); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_names_are_checked_and_editing_needs_the_folder() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..bb283e7dab 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -913,6 +913,23 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn document_preset_values_count_toward_the_data_a_run_passes() { + // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let mut s = Session::new(); + let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + for e in [read, added] { + assert!(e.contains("passed more data"), "{e}"); + } + within.unwrap(); + assert!(s.documents().is_empty()); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); @@ -985,12 +1002,19 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { .unwrap(); }; lock(&mut s, true); + // An object on a second, unlocked artboard is not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let c = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); let steps = undo_steps(&s); let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); - assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); + let out = + log(&mut s, "try { app.activeDocument.pageItems.removeAll(); } catch (e) { vc.log(e.name); } vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!("Error"), json!(3)]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); assert_eq!(undo_steps(&s), steps); lock(&mut s, false); let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); diff --git a/docs/mcp.md b/docs/mcp.md index 51cd09fdbb..095975a485 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9050,8 +9050,8 @@ with the defaults. The profile is read on every `file.new`, so a replayed journal or a recorded action uses the profile as it is when it runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. -When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the -folder (whether or not the file exists), the document starts with the defaults and +When the file is a link or a folder, cannot be read, is too large or is not a native document, or the request's read +roots leave out the folder (whether or not the file exists), the document starts with the defaults and `file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's file. The From 341f7644587d578512f454cfb3b169ce72dad98b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:26:18 -0800 Subject: [PATCH 16/24] Scripts: editable is false on a locked artboard, page item lists kept for several documents - PageItem.editable is false for art on a locked artboard, as remove() refuses it. A group on a locked artboard is measured once for all its members. - The lists of page items are kept for the last four documents read, so a script that reads two documents in turn does not walk each one again on every index. --- crates/engine/Cargo.toml | 5 +- crates/engine/src/script/dom.rs | 103 +++++++++++++++++++++++--- crates/engine/src/tests/script_dom.rs | 23 ++++++ docs/mcp.md | 3 +- 4 files changed, 119 insertions(+), 15 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..460893a7c8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -104,8 +104,9 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# How many times the symbol list is read to find symbols by name. -vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } +# How many times the symbol list is read to find symbols by name, and how many objects are +# measured against locked artboards. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 675ab3fb5a..830351f375 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -28,6 +28,7 @@ //! - Members the help pages list that are not here yet throw an error that says so. use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; @@ -84,13 +85,15 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; -/// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// What the object model keeps for one run: its coordinate system, the lists of page items and the +/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, +/// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is +/// open, and the settings of each `DocumentPreset` the run made. #[derive(Default)] pub(super) struct State { coords: Cell, - items: RefCell>, + items: RefCell>, + locked: RefCell>, saving: Cell, presets: RefCell>>, } @@ -125,6 +128,57 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); +/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for +/// each object of a layer or sublayer asked about then, whether it was on a locked artboard. +type LockedList = (u64, Arc, Arc>, HashMap); + +/// How many documents' lists [`State`] keeps at once, of each kind. +const ITEM_LISTS: usize = 4; + +/// The kept list of the document `uid` as `doc` is, if there is one. +fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc) -> Option>> { + lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone()) +} + +/// Keeps `list` in place of any earlier list of the same document, dropping the least recently +/// kept list beyond [`ITEM_LISTS`]. +fn keep_items(lists: &mut Vec, list: ItemList) { + lists.retain(|(u, _, _)| *u != list.0); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push(list); +} + +/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each +/// object of a layer or sublayer is measured once while the document and its new art stay as they +/// are, so the members of a group are answered with one measurement of the group. +fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool { + if !st.doc.artboards.iter().any(|a| a.locked) { + return false; + } + let Some(object) = st.doc.layer_object(id).map(|n| n.id) else { + return false; + }; + let new_art = st.doc.new_art.get(); + let mut lists = h.dom.locked.borrow_mut(); + let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) { + Some(at) => at, + None => { + lists.retain(|(u, ..)| *u != st.uid); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), new_art, HashMap::new())); + lists.len() - 1 + } + }; + match lists.get_mut(at) { + Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)), + None => st.doc.on_locked_artboard(object), + } +} + type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. @@ -332,13 +386,11 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { } } -/// The ids of a document's page items in paint order ([`State`] keeps the last list). +/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last +/// documents read). fn page_items(h: &Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.items.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - { - return ids.clone(); + 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 { @@ -356,7 +408,7 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); let ids = Rc::new(ids); - *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); ids } @@ -1518,9 +1570,11 @@ fn item_set_height(h: &Host, a: &[Data]) -> Answer { resize(h, a, false) } +/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group, +/// or on a locked artboard. fn item_editable(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)))) + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id)))) } /// The item's place in its parent's stacking order, from 1 at the bottom. @@ -1950,4 +2004,29 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + #[test] + fn page_item_lists_are_kept_for_several_documents() { + let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); + let ids = |n: u64| Rc::new(vec![NodeId(n)]); + let mut lists = Vec::new(); + keep_items(&mut lists, (1, docs[0].clone(), ids(1))); + keep_items(&mut lists, (2, docs[1].clone(), ids(2))); + // Reading two documents in turn keeps both lists. + assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1))); + assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2))); + // A changed document has no kept list, and its new list replaces the old one. + let changed = Arc::new(Document::new(100.0, 100.0)); + assert_eq!(kept_items(&lists, 1, &changed), None); + keep_items(&mut lists, (1, changed.clone(), ids(3))); + assert_eq!(lists.len(), 2); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + // Past the limit, the list kept longest ago goes. + for (uid, d) in (10..).zip(&docs[2..]) { + keep_items(&mut lists, (uid, d.clone(), ids(uid))); + } + assert_eq!(lists.len(), ITEM_LISTS); + assert_eq!(kept_items(&lists, 2, &docs[1]), None); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index bb283e7dab..7ebad8e3f2 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1016,11 +1016,34 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { let doc = &s.active().unwrap().doc; assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); 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])]); 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);"); assert_eq!(out, vec![json!(0)]); } +/// Reading `editable` on every member of a group on a locked artboard measures the group once. +#[test] +fn editable_measures_a_group_on_a_locked_artboard_once() { + let (mut s, a, b) = doc(); + let mut ids = vec![a.0, b.0]; + ids.extend((0..20).map(|i| rect(&mut s, 10.0 + f64::from(i), 200.0, 5.0, 5.0).0)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_doc::locked_artboard_measures(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, n = 0; for (var i = 0; i < p.length; i++) if (!p[i].editable) n++; vc.log(n);"); + assert_eq!(out, vec![json!(23)], "the group and its 22 members are on the locked artboard"); + assert_eq!(vectorcraft_doc::locked_artboard_measures() - before, 1); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 095975a485..90591ae2ea 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2648,7 +2648,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same From b6bb1329cd95be72f64d6a3e8f6218fece31e5ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:58:20 -0800 Subject: [PATCH 17/24] New Document: choosing the selected Grid by Column keeps a preset's rows Clicking the layout that is already selected removed the rows of a preset made with file.new's rows and kept only the columns they showed, so Create put a different number of artboards in each column. With five artboards and rows 4, the first column got three artboards instead of four. A different layout or a new column count still replaces the rows. --- crates/ui-egui/src/dialogs/new_document.rs | 25 ++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cf10f0035e..a36c1fb589 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,14 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. Choosing +/// the layout that is already selected keeps the rows. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let (lay, shown, ..) = layout(d); let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + let same = key == "layout" && v.as_str().and_then(ArtboardLayout::parse) == Some(lay); if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && !same && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) && key == "layout" && lay == ArtboardLayout::GridByColumn @@ -930,7 +933,7 @@ mod tests { app.run("file.newDialog", json!({})).unwrap(); let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; set(&mut app, "artboards", json!(9)); - for to in ["gridByRow", "gridByColumn", "row", "column"] { + for to in ["gridByRow", "row", "column"] { for rows in [json!(4), json!(4.0), json!(3.6)] { set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); @@ -950,6 +953,24 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } + /// Choosing the grid by column that is already selected keeps a preset's rows, so Create puts + /// as many artboards in each column as before. + #[test] + fn choosing_the_selected_layout_keeps_a_presets_rows() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboards", json!(5)); + let preset = json!({"layout": "gridByColumn", "columns": 2, "rows": 4, "spacing": 10}); + set(&mut app, "artboardLayout", preset.clone()); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), preset); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.artboards.len(), 5); + let first: Vec<_> = st.doc.artboards.iter().filter(|a| a.rect.x0 == 0.0).map(|a| a.rect.y0).collect(); + assert_eq!(first.len(), 4, "four artboards in the first column: {first:?}"); + } + /// Columns shows what a preset's rows give the current number of artboards. #[test] fn columns_follow_a_presets_rows_as_artboards_change() { From e48b8117075f3b4b9d50820212ba1724cc746a57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:02:06 -0800 Subject: [PATCH 18/24] Scripts: an opacity a graph mark already has replaces the one its series keeps Assigning PageItem.opacity skipped object.setProps when the item already had that opacity, so a graph mark or label set to the opacity it shows left the graph keeping the opacity another mark of its series or kind had set. The setter now leaves the no-op check to object.setProps, as the command does for that case. A value within the getter's rounding of the item's opacity sends the opacity the item has, so assigning the opacity a script read back still changes nothing and adds no undo step. --- crates/engine/src/script/dom.rs | 8 +++++- crates/engine/src/tests/script_dom.rs | 36 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 830351f375..e073a791ff 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1432,7 +1432,13 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + // A value the getter reports for the item's opacity sends the opacity it has, and + // `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 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})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7ebad8e3f2..f517312983 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -206,6 +206,42 @@ fn page_item_properties_join_one_undo_step() { } } +/// An opacity a graph mark already has still replaces the opacity another mark of its series left on +/// the graph, as `object.setProps` does. +#[test] +fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let kept = + |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().series_paints.first().and_then(|p| p.opacity); + let series = |s: &Session| { + let n = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = n.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + group.children().unwrap().iter().map(|m| m.id).collect::>() + }; + let marks = series(&s); + s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); + assert_eq!(kept(&s), Some(0.5)); + s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); + assert_eq!(kept(&s), None); +} + +/// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. +#[test] +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;"); + assert_eq!(out, vec![json!(33.3333)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); From 3d460c1697193bc990534bab1144f0232d6193d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:55:45 -0800 Subject: [PATCH 19/24] Scripts: guide, layer, move and addDocument fixes for the object model - Document.selection and PageItem.selected refuse a path made into a guide while Lock Guides is on, instead of passing the check and then selecting nothing. The locked artboards are measured once per assignment. - An edit whose command selects the objects it changes puts the current layer and the highlighted Layers panel rows back as they were. layer.setCurrent takes keepRows, which leaves the highlighted rows as they are. - move on an object on a locked artboard throws Cannot move, as editable reads false for it. duplicate, with or without a relative object, on a hidden or locked object or an object on a locked artboard 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. - addDocument writes each warning from reading the profile's file to the Script Console as addDocument: , and a previewMode of PixelPreview throws an error that says it is not available yet. --- crates/engine/src/cmd/layer.rs | 7 +- crates/engine/src/script/dom.rs | 84 ++++++++++++-- crates/engine/src/tests/layers.rs | 7 ++ crates/engine/src/tests/script_dom.rs | 160 ++++++++++++++++++++++++++ docs/mcp.md | 20 +++- 5 files changed, 261 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 73c92877e9..d2258f4e4a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Set Current Layer", [], None, - "{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}", + "{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}", has_doc, set_current ), @@ -633,10 +633,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result { fn set_current(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.setCurrent"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let keep_rows = switch_or(p, "keepRows", false, C)?; let st = s.doc_mut()?; let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?; st.active_layer = Some(layer); - st.layer_rows = vec![id]; + if !keep_rows { + st.layer_rows = vec![id]; + } st.revision += 1; Ok(json!({ "id": id.0, "layer": layer.0 })) } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e073a791ff..8079107fd8 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -583,6 +583,31 @@ fn done_unless_refused(r: std::result::Result) -> std::result:: } } +/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted +/// Layers panel rows, after selecting objects made the layer of the last of them current and +/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when +/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not. +fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> std::result::Result<(), HostError> { + let Some(layer) = layer else { return Ok(()) }; + let rows = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + if st.doc.node(layer).is_none() { + return Ok(()); + } + let rows: Vec = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect(); + (st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::>()) + }; + if let Some(rows) = rows { + command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?; + } + let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer)); + if !current { + command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?; + } + Ok(()) +} + /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, @@ -595,10 +620,11 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before) = { + let (index, active, before, layer) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - (index, s.active_index(), s.documents()[index].selection.clone()) + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) }; let switch = active != Some(index); if switch { @@ -614,6 +640,9 @@ fn on_doc( if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); } + if restored.is_ok() { + restored = restore_layer(h, uid, layer.0, &layer.1); + } } // The document that was active is active again before any error is given: `f`'s error first, // then the selection's, then the switch back's. @@ -854,7 +883,10 @@ impl NewDoc<'_> { if let Some(d) = self.preview { let mode = match d { Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", - Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", + // Pixel Preview is a setting of the app's view, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => { + return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into())); + } Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), }; @@ -981,6 +1013,10 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { let reason = e["reason"].as_str().unwrap_or_default(); return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); } + // Each warning from reading the profile's file goes to the console. + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); + } let s = h.session.borrow(); let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) @@ -1203,10 +1239,16 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; + // The document is read once for every object: nothing changes it while the list is checked. + let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); + let locks = d.locked_artboards(); + for v in list { + let item = item_of(h, v)?; + // A path made into a guide is not selected while Lock Guides is on, as the selection + // commands leave it out. let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); + && crate::cmd::select::is_selectable(&d, isolation, &locks, item.id) + && !(guides_locked && crate::is_guide_path(&d, item.id)); if !ok { let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); @@ -1689,7 +1731,8 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s if !editable(d, parent) { return Err(HostError::Error("the layer or group is hidden or locked".into())); } - if !editable(d, item.id) { + // An object on a locked artboard is not moved, as `editable` reads false for it. + if !editable(d, item.id) || on_locked_artboard(h, st, item.id) { let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } @@ -1730,14 +1773,30 @@ 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`). +/// 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. 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)?; - place(h, item.doc, item.id, &to)?; + // 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(()) + })?, + } Ok(arg(a, 0).clone()) } @@ -1761,6 +1820,13 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER.into())); } + // `edit.duplicate` copies only what it can select. + let refused = with_doc(h, item.doc, |_, st| { + (!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item")) + }); + if let Some(name) = refused { + return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0))); + } let to = match arg(a, 1) { Data::Undefined => { if !matches!(arg(a, 2), Data::Undefined) { diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index c3bba6803b..2fde78bd10 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -157,6 +157,13 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { let n = rect(&mut s, 50.0); assert_eq!(parent(&s, n), Some(sub)); assert!(s.execute("layer.setCurrent", &json!({"id": 9999})).is_err()); + // `keepRows` makes the layer current and leaves the highlighted rows. + run(&mut s, "layer.setCurrent", json!({"id": b.0})); + run(&mut s, "layer.setCurrent", json!({"id": c.0, "keepRows": true})); + let st = s.doc().unwrap(); + assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![b], Some(layer))); + assert!(s.execute("layer.setCurrent", &json!({"id": a.0, "keepRows": 1})).is_err()); + assert_eq!(s.doc().unwrap().current_layer(), Some(layer), "a bad keepRows changes nothing"); // Shift/Ctrl: several rows. run(&mut s, "layer.highlight", json!({"ids": [a.0, g.0], "mode": "set"})); run(&mut s, "layer.highlight", json!({"ids": [c.0], "mode": "add"})); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f517312983..e80e973626 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -265,6 +265,25 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +#[test] +fn a_guide_path_is_not_selected_while_guides_are_locked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + 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;"] { + 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];"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); @@ -454,6 +473,30 @@ fn a_path_inside_a_compound_path_is_not_reordered() { assert_eq!(out, vec![json!([1, 2])]); } +#[test] +fn moving_the_last_path_out_of_a_compound_path_deletes_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(); + let compound = layer_order(&s)[0]; + let layer = s.active().unwrap().doc.layers[0].id; + 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]];\ + 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); }", + ); + assert_eq!(out, vec![json!(3), json!(2), json!("Stale page item")]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(compound).is_none(), "the empty compound path is deleted"); + // Each path went directly above the compound path, the second above the first. + assert_eq!(layer_order(&s), [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"); +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { let mut s = Session::new(); @@ -610,6 +653,37 @@ fn an_edit_keeps_a_layers_panel_target() { assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); } +#[test] +fn an_edit_keeps_the_current_layer() { + let (mut s, a, b) = doc(); + let first = s.active().unwrap().doc.layers[0].id; + let back = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session| (s.active().unwrap().active_layer, s.active().unwrap().highlighted_rows()); + assert_eq!(layer(&s), (Some(back), vec![back])); + // Moving an object of the first layer selects it for the command; the new layer stays current. + log(&mut s, "app.activeDocument.pageItems[0].left = 50;"); + assert_eq!(layer(&s), (Some(back), vec![back])); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // With nothing selected and no row highlighted, the layer stays current and no row is highlighted. + s.execute("select.none", &json!({})).unwrap(); + s.execute("layer.setCurrent", &json!({"id": back.0})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [], "mode": "set"})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![])); + log(&mut s, "app.activeDocument.pageItems[1].left = 120;"); + assert_eq!(layer(&s), (Some(back), vec![])); + assert!(s.active().unwrap().selection.objects.is_empty()); + // Targeting a layer makes it current and leaves another layer's row highlighted; both stay. + s.execute("layer.highlight", &json!({"ids": [first.0], "mode": "set"})).unwrap(); + s.execute("layer.target", &json!({"id": back.0})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![first])); + 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];"); + assert_eq!(s.active().unwrap().active_layer, Some(first)); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + /// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two /// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the /// group's rectangle). @@ -949,6 +1023,43 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + let file = dir.join("Print.vectorcraft"); + let mut v: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let broken = format!("Script profile broken {}", std::process::id()); + v["profiles"] = json!({ &broken: {"mime": "application/vnd.iccprofile", "data": "AAAA"} }); + std::fs::write(&file, serde_json::to_vec(&v).unwrap()).unwrap(); + let r = run(&mut s, "vc.log(app.documents.addDocument('Print').typename);").unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); + assert!(named, "{lines:?}"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_refuses_pixel_preview() { + let mut s = Session::new(); + let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.PixelPreview; app.documents.addDocument('Web', p);"); + assert!(e.contains("DocumentPreviewMode.PixelPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.DefaultPreview; vc.log(app.documents.addDocument('Web', p).typename);", + ); + assert_eq!(out, vec![json!("Document")]); +} + #[test] fn document_preset_values_count_toward_the_data_a_run_passes() { // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. @@ -1061,6 +1172,55 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn move_and_duplicate_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + 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);"); + 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]);"] { + 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);"); + assert_eq!(layer_order(&s), [b, a]); +} + +#[test] +fn duplicate_refuses_hidden_or_locked_art() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + 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]);"] { + 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();"); + let order = layer_order(&s); + assert_eq!(order.len(), 3); + assert!(order.contains(&a) && order.contains(&b)); +} + /// Reading `editable` on every member of a group on a locked artboard measures the group once. #[test] fn editable_measures_a_group_on_a_locked_artboard_once() { diff --git a/docs/mcp.md b/docs/mcp.md index 90591ae2ea..c805cacaa9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2637,7 +2637,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the - profile and the reason, and makes no document. + profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it + that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of + `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) @@ -2657,7 +2659,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when `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. `duplicate` on a path inside a compound path throws + 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 `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 @@ -2671,7 +2676,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active - tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine + tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers + panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` @@ -2680,7 +2686,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or + with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, @@ -6363,8 +6370,9 @@ itself, and each sublayer has its own colour for the selection highlight. `docum report `color`, `template`, `printable`, `preview`, `dimImages` and `clip`), the `currentLayer` (where new art goes) and `layerRows`, the rows highlighted in the panel. -- **Clicking rows** (not undo steps): `layer.setCurrent {id}` is a plain click on any row: it alone is highlighted - and its layer (the row itself when it is a layer or sublayer) becomes current. `layer.highlight {ids, mode?: +- **Clicking rows** (not undo steps): `layer.setCurrent {id, keepRows?}` is a plain click on any row: it alone is + highlighted and its layer (the row itself when it is a layer or sublayer) becomes current; with `keepRows` true the + highlighted rows stay as they are. `layer.highlight {ids, mode?: set|add|toggle}` is Shift-click (a range) and Ctrl/Cmd-click (toggle). Selecting art makes its layer current. Without `ids`, the panel commands below act on the highlighted rows, else on the current layer. - **Selection column**: `layer.selectAll {id, add?}` selects a row's visible, unlocked art (a layer's sublayers' From dc9adb195d0cadbb5153da28cd8e08a76fbe3784 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 14:10:57 -0800 Subject: [PATCH 20/24] Scripts: pageItems lists the art inside blends, envelopes, repeats and intertwines pageItems walked into groups and compound paths only, so the objects inside a blend, an envelope, a repeat or an intertwine were missing from length, [i], index and getByName, although each of them reports that container as its parent. The walk now goes into every container's children. --- crates/engine/src/script/dom.rs | 7 ++++--- crates/engine/src/tests/script_dom.rs | 15 +++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8079107fd8..cb901014b5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -397,11 +397,12 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { match &n.kind { NodeKind::Layer { children, .. } => walk(children, out), NodeKind::RulerGuide { .. } => {} - NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + _ => { out.push(n.id); - walk(children, out); + if let Some(children) = n.children() { + walk(children, out); + } } - _ => out.push(n.id), } } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e80e973626..60e3a71521 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -100,6 +100,21 @@ fn page_items_are_live_and_typed_for_all_node_kinds() { ); } +#[test] +fn page_items_list_the_art_inside_a_blend() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].name = 'first';"); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 2})).unwrap(); + let out = log( + &mut s, + "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.getByName('first').parent.typename); vc.log(p.index('first').typename);", + ); + assert_eq!(out, vec![json!("BlendItem,PathItem,PathItem"), json!("BlendItem"), json!("PathItem")]); +} + #[test] fn page_item_geometry_uses_document_coordinates_with_y_up() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c805cacaa9..4685f408d7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2643,7 +2643,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) - has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each + lists every object in the document's layers, the objects inside groups, compound paths, blends, envelopes, repeats + and intertwines included, and has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either + collection is true for each entry `[i]` gives. Each page item (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds From 9872e6b6795edc3551a655cf4c7af8f9102a5847 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:24:32 -0800 Subject: [PATCH 21/24] 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. --- crates/engine/src/script/dom.rs | 162 ++++++-- crates/engine/src/script/mod.rs | 8 +- crates/engine/src/tests/script_dom.rs | 358 +++++++++++++++--- crates/engine/src/tests/script_run.rs | 3 +- .../tests/it/script_host_vs_scriptcheck.rs | 25 +- crates/js/src/builtins.rs | 4 +- crates/js/src/host_classes.rs | 133 ++++++- crates/js/src/host_tests.rs | 41 ++ crates/js/src/interp.rs | 20 +- crates/js/src/realm.rs | 10 + docs/mcp.md | 33 +- docs/target-app-parity.md | 2 +- 12 files changed, 661 insertions(+), 138 deletions(-) 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> { 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 { + /// `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 { 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::() { + 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 { - 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, 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 { + 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 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)?; } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..ba0e005ce0 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -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); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 63e6251dd7..f91eaae0ef 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -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) { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index f1ca6b570d..ac58574087 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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 diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..9d6b02e10c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 ]`, + `[Layer ]`, `[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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..597b3ca6b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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`. From 6b778a4c7073927760bdcf88fb3e044900eeacf6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:24:33 -0800 Subject: [PATCH 22/24] Scripts: setters refuse art in a hidden or locked layer, and empty objects read zero bounds - Assigning hidden, locked, position, left, top, width or height to an object in a hidden or locked layer throws Cannot edit, as opacity does, and changes nothing. Its name and note still change. - An object with nothing in it, such as an empty group or a compound path whose paths moved out, reads its bounds, position, width and height as zeros, and assigning them does nothing, so reading every property for-in lists does not throw on it. - Assigning selection without app. sets the active document's selection, and app.selection can be assigned the same way. Assigning activeDocument without app. activates a document, and assigning documents keeps its value. - JSON.stringify writes a collection, or data that holds one, without reading toJSON through the collection's name lookup, which threw Not found. - The docs state that Object.keys, Object.getOwnPropertyNames and Object.getOwnPropertyDescriptor do not report the members, that a value assigned to a member the class lacks is not kept, and that the selection order is VectorCraft's own rule. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 105 ++++++++++++------ crates/engine/src/tests/script_dom.rs | 97 +++++++++++----- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/js/src/builtins/json.rs | 2 +- crates/js/src/host_classes.rs | 47 +++----- crates/js/src/interp.rs | 11 ++ crates/js/src/realm.rs | 10 +- docs/mcp.md | 39 ++++--- docs/target-app-parity.md | 2 +- 9 files changed, 200 insertions(+), 117 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bef71437d4..7b9df28106 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -15,15 +15,18 @@ //! //! 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. +//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` +//! gives, and a script may name the application's members without `app.`, as +//! describes; here +//! that holds for `activeDocument`, `documents` and `selection`. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever +//! order they were selected or made in. +//! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is +//! false then. Assigning to such a name throws the same error. +//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the +//! active document's selection. Assigning `documents` keeps its value. //! - 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 @@ -36,8 +39,12 @@ //! - 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. +//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an +//! object in a hidden or locked layer throws `Cannot edit` and changes nothing; its `name` and +//! `note` still change. An object that is hidden or locked itself, or is in a hidden or locked +//! group, takes them. +//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out, +//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; @@ -709,6 +716,18 @@ fn app_selection(h: &Host, _: &[Data]) -> Answer { } } +/// `app.selection = objects`: the active document's selection, as `selection` of that document is +/// assigned. +fn app_set_selection(h: &Host, a: &[Data]) -> Answer { + let doc = { + let s = h.session.borrow(); + let active = s.active_index().and_then(|index| s.documents().get(index).map(|st| Doc { index, uid: st.uid })); + active.ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))? + }; + let ids = selection_ids(h, doc, arg(a, 1))?; + set_selection(h, doc, ids) +} + fn app_coords(h: &Host, _: &[Data]) -> Answer { Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS })) } @@ -1490,12 +1509,27 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// Refuses a change to the item's appearance, place or size while a layer it is in is hidden or +/// locked. Its name and note may still change. +fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { + 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")) + }); + match refused { + Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))), + None => Ok(()), + } +} + fn item_hidden(h: &Host, a: &[Data]) -> Answer { read_item(h, a, |_, n| Ok(Data::Bool(!n.visible))) } fn item_set_hidden(h: &Host, a: &[Data]) -> Answer { let hidden = boolean(arg(a, 1), "hidden")?; + refuse_in_closed_layer(h, this_item(h, a)?)?; set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden})) } @@ -1505,6 +1539,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer { fn item_set_locked(h: &Host, a: &[Data]) -> Answer { let locked = boolean(arg(a, 1), "locked")?; + refuse_in_closed_layer(h, this_item(h, a)?)?; set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } @@ -1521,14 +1556,7 @@ 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))); - } + refuse_in_closed_layer(h, item)?; 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})) @@ -1554,18 +1582,19 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer { } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the -/// document's [`Frame`]. -fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Rect, Frame), HostError> { - with_doc(h, item.doc, |_, st| { - let r = st.doc.bounds_of(&[item.id], visual).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; - Ok((r, frame(st)?)) - }) +/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path +/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does +/// nothing. +fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option, Frame), HostError> { + with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?))) } fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, visual)?; - Ok(f.bounds(h.dom.coords.get(), r)) + match item_rect(h, item, visual)? { + (Some(r), f) => Ok(f.bounds(h.dom.coords.get(), r)), + (None, _) => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } } fn item_geometric(h: &Host, a: &[Data]) -> Answer { @@ -1578,8 +1607,10 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, false)?; - Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))) + match item_rect(h, item, false)? { + (Some(r), f) => Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))), + (None, _) => Ok(pair([0.0, 0.0])), + } } fn item_left(h: &Host, a: &[Data]) -> Answer { @@ -1598,19 +1629,20 @@ fn item_top(h: &Host, a: &[Data]) -> Answer { fn item_width(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(num(item_rect(h, item, false)?.0.width())) + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.width()))) } fn item_height(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(num(item_rect(h, item, false)?.0.height())) + Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height()))) } /// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one /// stays). fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; - let (r, f) = item_rect(h, item, false)?; + refuse_in_closed_layer(h, item)?; + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let c = h.dom.coords.get(); let now = f.to_script(c, Point::new(r.x0, r.y0)); let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); @@ -1646,7 +1678,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points"))); } let item = this_item(h, a)?; - let (r, _) = item_rect(h, item, false)?; + refuse_in_closed_layer(h, item)?; + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; let now = if width { r.width() } else { r.height() }; if now <= 0.0 { return Err(HostError::Error(format!("the object has no {what} to scale"))); @@ -2009,7 +2042,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("typename", typename_of("Application")), ("documents", get(l, app_documents)), ("activeDocument", property(l, app_active, app_set_active)), - ("selection", get(l, app_selection)), + ("selection", property(l, app_selection, app_set_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), ("toString", class_text("Application")), @@ -2137,11 +2170,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), None, )); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?; - // The application's members a script may name without `app.`. + // The application's members a script may name without `app.`, assigned as `app.` is. realm.define_host_globals(vec![ - ("activeDocument".into(), function(l, app_active)), - ("documents".into(), function(l, app_documents)), - ("selection".into(), function(l, app_selection)), + ("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))), + ("documents".into(), function(l, app_documents), None), + ("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))), ]) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 8d015d8727..68a485c8de 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -506,9 +506,16 @@ fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { "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);\ - vc.log([c.typename, c === d.pageItems[2]]);", + vc.log([c.typename, c === d.pageItems[2]]);\ + var bad = []; for (var k in c) { try { c[k]; } catch (e) { bad.push(k + ': ' + e.message); } } vc.log(bad);\ + vc.log([c.geometricBounds, c.visibleBounds, c.position, c.width, c.height]);\ + c.left = 5; c.top = 5; c.position = [1, 2]; c.width = 10; c.height = 10; vc.log(c.geometricBounds);", ); - assert_eq!(out, vec![json!(3), json!(3), json!(["CompoundPathItem", true])]); + let zeros = json!([0, 0, 0, 0]); + assert_eq!(out[..3], [json!(3), json!(3), json!(["CompoundPathItem", true])]); + // Every property `for`-`in` lists reads, and the emptied compound path has zero bounds that + // moving or resizing leaves as they are. + assert_eq!(out[3..], [json!([]), json!([zeros, zeros, [0, 0], 0, 0]), zeros]); let doc = &s.active().unwrap().doc; 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. @@ -1409,17 +1416,18 @@ fn page_items_report_their_available_members_as_their_own() { 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. +/// A name a page item class's prototype has, such as `constructor`, is not an object's own, and a +/// script cannot put a name on the prototype. #[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([PathItem.prototype.foo === undefined, PageItem.prototype.bar === undefined, 'foo' in p]);\ vc.log([p.hasOwnProperty('foo'), p.hasOwnProperty('bar'), p.propertyIsEnumerable('foo'), p.hasOwnProperty('constructor')]);", ); - assert_eq!(out, vec![json!([false, false, false, false])]); + assert_eq!(out, vec![json!([true, true, false]), json!([false, false, false, false])]); } /// Reading every property `for`-`in` lists calls each getter, and each call counts against the run: @@ -1449,7 +1457,7 @@ fn reading_every_listed_property_is_charged_and_can_be_stopped() { } /// `pageItems` lists art topmost first, and the selection lists the selected objects in that -/// order whatever order they were selected in. +/// order whatever order they were selected or made in. #[test] fn page_items_and_the_selection_list_the_topmost_object_first() { let (mut s, a, b) = doc(); @@ -1464,6 +1472,16 @@ fn page_items_and_the_selection_list_the_topmost_object_first() { 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")]); + // An object made last and sent to the back comes after the others it is selected with. + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("object.setProps", &json!({"ids": [c.0], "name": "last"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems.getByName('last'); c.zOrder(ZOrderMethod.SENDTOBACK);\ + d.selection = null; c.selected = true; d.pageItems.getByName('top').selected = true;\ + vc.log([d.selection[0].name, d.selection[1].name, d.pageItems[2].name]);", + ); + assert_eq!(out, vec![json!(["top", "last", "last"])]); } /// A collection read with a name gives what `getByName` gives, and throws as it does for no match. @@ -1483,10 +1501,11 @@ fn a_collection_read_with_a_name_gives_the_named_object() { 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. +/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// locked layer throw and the run changes nothing, while its name and note still change; an object +/// that is hidden or locked itself takes them. #[test] -fn opacity_refuses_art_in_a_hidden_or_locked_layer() { +fn setters_refuse_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); @@ -1498,12 +1517,20 @@ fn opacity_refuses_art_in_a_hidden_or_locked_layer() { (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}"); + for set in ["opacity = 50", "hidden = true", "locked = true", "left = 5", "top = 5", "position = [5, 5]", "width = 10", "height = 10"] { + 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, &format!("var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').{set};")); + assert!(e.contains(&format!("Cannot edit PathItem {}", c.0)), "{on} {set}: {e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{on} {set}"); + assert_eq!(undo_steps(&s), steps, "{on} {set}"); + } + let out = log( + &mut s, + "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; vc.log([c.name, c.note]);\ + c.name = 'closed'; c.note = '';", + ); + assert_eq!(out, vec![json!(["renamed", "n"])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -1548,10 +1575,10 @@ fn objects_of_the_object_model_print_their_class_and_name() { } /// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and -/// assigning one makes it the script's own variable. +/// assigning one assigns the member: `selection` selects, `documents` keeps its value. #[test] fn the_application_members_can_be_named_without_app() { - let (mut s, a, _) = doc(); + let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let out = log( &mut s, @@ -1559,17 +1586,24 @@ fn the_application_members_can_be_named_without_app() { 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]); + let out = log( + &mut s, + "var d = app.activeDocument; selection = null; vc.log(d.selection.length);\ + selection = [d.pageItems[0], d.pageItems[1]]; vc.log(d.selection.length);\ + app.selection = d.pageItems[0]; vc.log([d.selection.length, selection[0] === d.pageItems[0]]);\ + var selection = d.selection; documents = 5; activeDocument = d; vc.log([selection.length, typeof documents]);", + ); + assert_eq!(out, vec![json!(0), json!(2), json!([1, true]), json!([1, "object"])]); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); + failure(&mut s, "'use strict'; documents = 5;"); // 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. +/// Assigning to a name a collection does not have throws as reading it does, and assigning an +/// index does not replace the object there. #[test] fn assigning_a_name_a_collection_lacks_throws() { let (mut s, _, _) = doc(); @@ -1577,7 +1611,20 @@ fn assigning_a_name_a_collection_lacks_throws() { 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])]); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);"); + assert_eq!(out, vec![json!("object")]); assert_eq!(undo_steps(&s), steps); } + +/// `JSON.stringify` writes a collection, or data that holds one, without reading a `toJSON` the +/// collection lacks, while a script that reads `toJSON` itself gets `Not found`. +#[test] +fn json_stringify_writes_a_collection() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = ''; vc.log([JSON.stringify(p), JSON.stringify({list: [p, app.documents]})]);\ + try { p.toJSON; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(["{}", "{\"list\":[{},{}]}"]), json!("Not found")]); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 09c4daa936..4426cbaaf5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,13 +75,13 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - documents= Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", ), ("Application.", "prototype"), ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection toString typename", + selection selection= toString typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 364ec99696..df9cbba9ee 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -538,7 +538,7 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K keep(interp, &v); let name = Value::String(Str::from_rc(k.clone())); if let Value::Object(o) = v { - let to_json = interp.get_from(o, &key("toJSON"), &v)?; + let to_json = interp.get_property_only(o, &key("toJSON"), &v)?; if interp.is_callable(&to_json) { v = interp.call(&to_json, &v, std::slice::from_ref(&name))?; keep(interp, &v); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index c688a0512c..206f781ef3 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -17,20 +17,22 @@ //! 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 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`. +//! a number when it is the text of one, such as `-1`), so the indexer may throw for a name nothing +//! has. Names the engine looks up itself, such as `toJSON` in `JSON.stringify`, do not go to the +//! indexer. 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. +//! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and +//! `Object.getOwnPropertyDescriptor` do not report the members. use std::collections::HashSet; use std::rc::Rc; -use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, NativeKind, ObjId, Object, Prop, WRITABLE, key}; +use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -271,39 +273,22 @@ pub(crate) fn install(i: &mut Interp, classes: Vec, 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<()> { +/// Adds the global properties `globals`, each read with its getter and assigned with its setter as +/// a member of a host class is. Assigning one without a setter keeps its value, and throws in strict +/// mode code. +pub(crate) fn install_globals(i: &mut Interp, globals: Vec<(String, HostFunction, Option)>) -> JsResult<()> { let global = i.global; - let proto = i.intrinsics.function_proto; - for (name, f) in getters { + for (name, get, set) in globals { let mark = i.temp_roots.len(); - let get = hosted_function(i, f, &name); + let get = hosted_function(i, get, &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))); + let set = set.map(|f| hosted_function(i, f, &name)); i.temp_roots.truncate(mark); - i.define(global, key(&name), Prop::Accessor { get: Some(get), set: Some(set), flags: CONFIGURABLE })?; + i.define(global, key(&name), Prop::Accessor { get: Some(get), 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 { - 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))); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f91eaae0ef..423039d3b8 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1446,6 +1446,17 @@ impl Interp { } } + /// [[Get]] of a name that is not an array index, without the indexer of an object of a host + /// class: a name the object and its prototypes lack is `undefined`. For names the engine looks + /// up itself, such as `toJSON`, which a collection's indexer would answer with an error. + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + match self.find_property(start, k)? { + None | 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, &[]), + } + } + /// The prototype a primitive's properties are looked up on. fn primitive_proto(&mut self, v: &Value, k: &[u16]) -> JsResult { match v { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ac58574087..600068fd4c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -522,11 +522,11 @@ 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) { + /// Adds the global properties `globals`: a name, the function that answers a read, and the + /// function that answers an assignment, each called with `undefined` as `this` (and the value + /// assigned). Assigning one without a setter keeps its value, and throws in strict mode code. + pub fn define_host_globals(&mut self, globals: Vec<(String, crate::HostFunction, Option)>) -> Result<(), RunError> { + match crate::host_classes::install_globals(&mut self.interp, globals) { Ok(()) => Ok(()), Err(e) => self.outcome(Err(e)).map(drop), } diff --git a/docs/mcp.md b/docs/mcp.md index 9d6b02e10c..cef9a0af60 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,11 +2622,12 @@ 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)`. A script may name `activeDocument`, - `documents` and `selection` without `app.`, as + `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and + `app.getIsFileOpen(path)`. A script may name the application's members 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` + describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. Assigning `activeDocument` or `selection` without `app.`, as `var selection = ...` at the top level also + does, assigns the application's member, and assigning `documents` keeps its value (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 @@ -2667,11 +2668,14 @@ 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. 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 + object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, + `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer + throws `Cannot edit` and changes nothing, while its `name` and `note` still change; an object that is hidden or + locked itself takes them (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. An object with + nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` + as zeros, and assigning them does nothing (VectorCraft's own rule). `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 @@ -2680,12 +2684,13 @@ app through the global object `vc`, and writes to the Script Console and runs ot `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. `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 + and a document's `selection` lists the selected objects in the same order, whatever order they were selected or + made in (VectorCraft's own rule). A collection read with a name, such as `pageItems["Logo"]` or + `documents["Untitled-1"]`, gives the object `getByName` gives, as + [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) + shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws + `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too + (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `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 ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). VectorCraft's own rules: documents are listed in tab order, and page items with the @@ -2715,7 +2720,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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 + other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and + `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that an object's class does not + have does not keep the value and does not throw. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 597b3ca6b3..f062c9d54b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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`). 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). 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`. From fe0e4086078c53b0321a482ccf180952f665acfb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:15:50 -0800 Subject: [PATCH 23/24] Scripts: zOrder refuses art in a hidden or locked layer, and the same opacity may be assigned - zOrder() on an object in a hidden or locked layer throws Cannot edit and changes nothing, as the other setters do. - Assigning an object the opacity it already has no longer throws when its layer is hidden or locked. hidden and locked are still refused there, whatever the value. - The docs say that a top-level var selection = ... assigns the selection, that the selection order and the tab order of documents differ from the objectReferences page, and that assigning a member a collection lacks throws Not found. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 40 ++++++++++++++++++--------- crates/engine/src/tests/script_dom.rs | 29 +++++++++++++++---- docs/mcp.md | 23 +++++++++------ 3 files changed, 65 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7b9df28106..8b68a39250 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -20,17 +20,20 @@ //! describes; here //! that holds for `activeDocument`, `documents` and `selection`. //! -//! VectorCraft's own rules, which the help pages do not state: +//! VectorCraft's own rules: //! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever -//! order they were selected or made in. +//! order they were selected or made in. The objectReferences page above says instead that the +//! first object is the one last added to the page; VectorCraft does not follow that sentence. //! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is //! false then. Assigning to such a name throws the same error. //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the -//! active document's selection. Assigning `documents` keeps its value. -//! - 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. +//! active document's selection. A top-level `var selection = ...` does the same and does +//! not make a variable of the script. Assigning `documents` keeps its value. +//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is +//! always the active document; VectorCraft does not follow that yet. +//! - `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. @@ -1265,7 +1268,14 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } else { let all = page_items(h, st); h.charge_call(all.len() as u64)?; - all.iter().copied().filter(|i| picked.contains(i)).collect() + let mut ids: Vec = all.iter().copied().filter(|i| picked.contains(i)).collect(); + // A selected object that `pageItems` does not list still comes last, in the order it was + // selected. + if ids.len() < picked.len() { + let mut listed: HashSet = ids.iter().copied().collect(); + ids.extend(st.selection.objects.iter().copied().filter(|i| picked.contains(i) && listed.insert(*i))); + } + ids }; h.charge_call(16 * ids.len() as u64)?; Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) @@ -1509,8 +1519,8 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// Refuses a change to the item's appearance, place or size while a layer it is in is hidden or -/// locked. Its name and note may still change. +/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in +/// is hidden or locked. Its name and note may still change. fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> { let refused = with_doc(h, item.doc, |_, st| { let d = &st.doc; @@ -1555,10 +1565,13 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // A value the getter reports for the item's opacity sends the opacity it has, and // `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. + // The opacity the item already has may be assigned while its layer is hidden or locked. let item = this_item(h, a)?; - refuse_in_closed_layer(h, item)?; 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); + let Some(v) = now.filter(|now| (now - v).abs() < 1e-4) else { + refuse_in_closed_layer(h, item)?; + return set_props(h, a, |_| false, json!({"opacity": v})); + }; set_props(h, a, |_| false, json!({"opacity": v})) } @@ -1923,7 +1936,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } /// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a -/// compound path is refused. +/// compound path is refused, and so is an object in a hidden or locked layer. fn item_z_order(h: &Host, a: &[Data]) -> Answer { let id = match arg(a, 1) { Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront", @@ -1936,6 +1949,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into())); } + refuse_in_closed_layer(h, item)?; let (before, after) = with_doc(h, item.doc, |_, st| { let at = st.doc.position(item.id); let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 68a485c8de..e2a61ec18d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1509,6 +1509,7 @@ fn setters_refuse_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); + rect(&mut s, 300.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(); } @@ -1517,7 +1518,20 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), ] { s.execute("object.setProps", &on).unwrap(); - for set in ["opacity = 50", "hidden = true", "locked = true", "left = 5", "top = 5", "position = [5, 5]", "width = 10", "height = 10"] { + // `hidden` and `locked` are refused even when the value is the one the object has. + for set in [ + "opacity = 50", + "hidden = true", + "hidden = false", + "locked = true", + "locked = false", + "left = 5", + "top = 5", + "position = [5, 5]", + "width = 10", + "height = 10", + "zOrder(ZOrderMethod.BRINGTOFRONT)", + ] { 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, &format!("var p = app.activeDocument.pageItems; p.getByName('free').opacity = 20; p.getByName('closed').{set};")); @@ -1527,10 +1541,10 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { } let out = log( &mut s, - "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; vc.log([c.name, c.note]);\ - c.name = 'closed'; c.note = '';", + "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ + vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", ); - assert_eq!(out, vec![json!(["renamed", "n"])], "{on}"); + assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -1595,8 +1609,13 @@ fn the_application_members_can_be_named_without_app() { ); assert_eq!(out, vec![json!(0), json!(2), json!([1, true]), json!([1, "object"])]); assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // A top-level `var selection = []` clears the selection; a push goes to a list nobody keeps. + let out = log(&mut s, "var selection = []; selection.push(app.activeDocument.pageItems[0]); vc.log(selection.length);"); + assert_eq!(out, vec![json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); - failure(&mut s, "'use strict'; documents = 5;"); + let e = failure(&mut s, "'use strict'; documents = 5;"); + assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); // 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")); diff --git a/docs/mcp.md b/docs/mcp.md index cef9a0af60..d05579f7e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2625,9 +2625,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.selection` (assigning it sets the active document's selection), `app.coordinateSystem` and `app.getIsFileOpen(path)`. A script may name the application's members without `app.`, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) - describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. Assigning `activeDocument` or `selection` without `app.`, as `var selection = ...` at the top level also - does, assigns the application's member, and assigning `documents` keeps its value (VectorCraft's own rule). - `app.documents` + describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: + assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level + `var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its + value. `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 @@ -2670,8 +2671,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer - throws `Cannot edit` and changes nothing, while its `name` and `note` still change; an object that is hidden or - locked itself takes them (VectorCraft's own rule). `move` with the object itself as the relative object and + throws `Cannot edit` and changes nothing, even when the value is the one the object has, except for `opacity`, and + `zOrder()` on such an object throws `Cannot edit` too. Its `name` and `note` still change, and an object that is + hidden or locked itself takes all of them (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. An object with nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` @@ -2685,7 +2687,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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, whatever order they were selected or - made in (VectorCraft's own rule). A collection read with a name, such as `pageItems["Logo"]` or + made in. This is VectorCraft's own rule: the page cited below says the first object in a selection is the one last + added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object `getByName` gives, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws @@ -2693,7 +2696,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `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 ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). - VectorCraft's own rules: documents are listed in tab order, and page items with the + Documents are listed in tab order; the same page says `documents[0]` is always the active document, and + VectorCraft does not follow that yet. VectorCraft's own rules: page items are listed 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 @@ -2721,8 +2725,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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. `Object.keys`, `Object.getOwnPropertyNames` and - `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that an object's class does not - have does not keep the value and does not throw. Other members + `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that a page item, a layer, a + document or the application does not have does not keep the value and does not throw; on a collection it throws `Not found`, + as described above. 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 From 112eacbb1c50da15169de201932f30d91f293f00 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:15:51 -0800 Subject: [PATCH 24/24] Scripts: remove() keeps an emptied compound path, and note takes numbers - remove() on the last path of a compound path keeps the compound path, empty, as move() does, so a script that holds it can still read it. edit.clear takes keepEmpty: true for this, and passes it on to path.deleteAnchors when it deletes direct-selected anchors; without it, Clear still deletes a compound path it empties. - note, like name, takes a number or a Boolean as the text String() gives it. - Assigning a graph mark or label the opacity it already has throws Cannot edit in a hidden or locked layer when the graph keeps another opacity for its series or kind, since the assignment would still change the graph. - Only the exact opacity the getter reports counts as the opacity an object already has; a value that differs from it by less than 0.0001 is now applied instead of being dropped. - Reading a document's selection orders only the selected objects, by their place in the tree, so its cost no longer grows with the size of the document. - docs/mcp.md: the opacity exception, note, keepEmpty, and that strict-mode code throws a TypeError when it assigns a member an object lacks. Docs: docs/mcp.md. --- crates/engine/src/cmd/edit.rs | 10 +- crates/engine/src/cmd/path.rs | 19 ++- crates/engine/src/script/dom.rs | 94 ++++++++----- crates/engine/src/tests/script_dom.rs | 187 ++++++++++++++++++++++---- docs/mcp.md | 54 ++++---- 5 files changed, 268 insertions(+), 96 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index c8b9785fe9..6e08795146 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1221,6 +1221,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; + let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; // An object of a symbol instance's art can't be removed from the instance alone. if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() { @@ -1252,8 +1253,11 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { - let parents: Vec<_> = - ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect(); + let parents: Vec<_> = if keep_empty { + Vec::new() + } else { + ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect() + }; d.remove_many(&ids)?; for p in parents { if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) { diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d32594d92d..9c41b7c78d 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Delete Anchor Points", [], None, - "{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)", + "{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)", has_anchors, delete_anchors ), @@ -1654,6 +1654,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?; + let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?; let st = s.doc()?; let sel = st.selection.anchors.clone(); let segments = st.selection.segments.clone(); @@ -1671,12 +1672,16 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); - // The compound paths that hold a deleted object; one left with no members goes too. - let compounds: BTreeSet = whole_ids - .iter() - .chain(sel.keys()) - .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) - .collect(); + // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. + let compounds: BTreeSet = if keep_empty { + BTreeSet::new() + } else { + whole_ids + .iter() + .chain(sel.keys()) + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect() + }; if !whole_ids.is_empty() { d.remove_many(&whole_ids)?; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b68a39250..39c740cb2e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -43,9 +43,14 @@ //! 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 `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an -//! object in a hidden or locked layer throws `Cannot edit` and changes nothing; its `name` and -//! `note` still change. An object that is hidden or locked itself, or is in a hidden or locked -//! group, takes them. +//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change +//! nothing, even for the value the object has. The exception is `opacity` given the value the +//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps +//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! still change. An object that is hidden or locked itself, or is in a hidden or locked group, +//! takes them. +//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. +//! - A compound path whose last path `move` or `remove()` takes out stays, empty. //! - An object with nothing in it, such as an empty group or a compound path whose paths moved out, //! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing. @@ -1263,21 +1268,28 @@ fn selection_of(h: &Host, uid: u64) -> Answer { 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)?; - let mut ids: Vec = all.iter().copied().filter(|i| picked.contains(i)).collect(); - // A selected object that `pageItems` does not list still comes last, in the order it was - // selected. - if ids.len() < picked.len() { - let mut listed: HashSet = ids.iter().copied().collect(); - ids.extend(st.selection.objects.iter().copied().filter(|i| picked.contains(i) && listed.insert(*i))); + // Only the selected objects are ordered, by their place in the tree, so the cost follows the + // size of the selection and not of the document. `pageItems` walks each list of children + // topmost first and puts a group before the objects in it: a higher index comes first, and an + // ancestor's path, a prefix of its descendants' paths, sorts before them. + let mut placed: Vec<(Vec>, NodeId)> = Vec::with_capacity(picked.len()); + let mut unplaced: Vec = Vec::new(); + let mut seen: HashSet = HashSet::with_capacity(picked.len()); + let mut steps = 0u64; + for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) { + match st.doc.index_path(id) { + Some(path) => { + steps += path.len() as u64; + placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id)); + } + // A selected object outside the tree's walk still comes last, in the order it was + // selected. + None => unplaced.push(id), } - ids - }; - h.charge_call(16 * ids.len() as u64)?; + } + placed.sort(); + let ids: Vec = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect(); + h.charge_call(steps + 16 * ids.len() as u64)?; Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) } @@ -1482,15 +1494,20 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) -> Ok(Data::Undefined) } +/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the +/// text `String(value)` gives, and any other value that is not a string is refused. +fn text_arg(v: &Data, what: &str) -> std::result::Result { + match v { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type(format!("{what} must be a string"))), + } +} + /// `name = value`: a number or a Boolean becomes the text `String(value)` gives. fn item_set_name(h: &Host, a: &[Data]) -> Answer { - 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; + let name = &text_arg(arg(a, 1), "name")?; if name.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } @@ -1505,9 +1522,10 @@ fn item_note(h: &Host, a: &[Data]) -> Answer { read_item(h, a, |_, n| Ok(text(note_of(n)))) } -/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. +/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number +/// or a Boolean becomes the text `String(value)` gives. fn item_set_note(h: &Host, a: &[Data]) -> Answer { - let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) }; + let note = &text_arg(arg(a, 1), "note")?; if note.len() > MAX_TEXT_BYTES { return Err(HostError::Range("the note is too long".into())); } @@ -1565,14 +1583,21 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // A value the getter reports for the item's opacity sends the opacity it has, and // `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. - // The opacity the item already has may be assigned while its layer is hidden or locked. + // The opacity the item already has may be assigned while its layer is hidden or locked, unless + // it would still replace the opacity a graph keeps for the item's series or kind. let item = this_item(h, a)?; - let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let Some(v) = now.filter(|now| (now - v).abs() < 1e-4) else { + let (now, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + // Only the exact number the getter reports counts as the same opacity. + let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (now, keeps_other) + }); + if now.is_none() || keeps_other { refuse_in_closed_layer(h, item)?; - return set_props(h, a, |_| false, json!({"opacity": v})); - }; - set_props(h, a, |_| false, json!({"opacity": v})) + } + set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -1731,7 +1756,7 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or /// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] -/// refuses it. +/// refuses it. A compound path whose last path this is stays, empty. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (whole, on_locked) = with_doc(h, item.doc, |_, st| { @@ -1743,7 +1768,8 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } - edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; + // A compound path whose last path this is stays, empty, as it does after `move`. + edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e2a61ec18d..4e705538d9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -242,6 +242,20 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); assert_eq!(kept(&s), Some(0.5)); s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + // In a hidden or locked layer the same assignment would still change the graph, so it is refused. + let layer = s.active().unwrap().doc.layers[0].id; + 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 steps = undo_steps(&s); + let e = failure(&mut s, "var m = app.activeDocument.pageItems.getByName('mark'); m.opacity = m.opacity;"); + assert!(e.contains("Cannot edit"), "{on}: {e}"); + assert_eq!(kept(&s), Some(0.5), "{on}"); + assert_eq!(undo_steps(&s), steps, "{on}"); + s.execute("object.setProps", &off).unwrap(); + } log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); assert_eq!(kept(&s), None); } @@ -256,6 +270,12 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); + // A value close to the reported one but not equal to it is still applied. + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + log(&mut s, "app.activeDocument.pageItems[1].opacity = 50.00005;"); + assert!(s.active().unwrap().doc.node(a).unwrap().opacity > before, "the assigned opacity was applied"); + assert_eq!(undo_steps(&s), steps + 1); } #[test] @@ -524,6 +544,54 @@ fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); } +/// `remove()` on the last path of a compound path keeps the compound path, empty, as `move` does, +/// and a document holding it saves, reopens, exports and releases it. +#[test] +fn removing_the_last_path_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(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0]; d.pageItems[2].remove(); d.pageItems[1].remove();\ + vc.log([c.typename, d.pageItems.length, c === d.pageItems[0]]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 1, true])]); + let doc = s.active().unwrap().doc.clone(); + assert!(doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + assert!(s.execute("edit.clear", &json!({"ids": [compound.0], "keepEmpty": 1})).is_err(), "keepEmpty must be a boolean"); + // The native format keeps it, and the other writers and Release Compound Path accept it. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert!(back.node(compound).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.is_empty()))); + for format in ["svg", "pdf", "vectorcraft"] { + s.execute("document.export", &json!({"format": format})).unwrap_or_else(|e| panic!("{format}: {e}")); + } + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + s.execute("object.compoundPath.release", &json!({})).unwrap(); +} + +/// Clear with `keepEmpty` keeps the emptied compound path also when it deletes direct-selected +/// anchors, and without it deletes the compound path as before. +#[test] +fn clearing_anchors_with_keep_empty_keeps_the_compound_path() { + for keep in [true, false] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + for (id, mode) in [(a, "set"), (b, "add")] { + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": mode})).unwrap(); + } + s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted"); + assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}"); + } +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { let mut s = Session::new(); @@ -921,7 +989,12 @@ fn note_is_the_attributes_note() { assert_eq!(undo_steps(&s), steps + 1); 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")); + // A number or a Boolean becomes its text, as it does for `name`. + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.note = 5; vc.log([typeof i.note, i.note]); i.note = true; vc.log(i.note);"); + assert_eq!(out, vec![json!(["string", "5"]), json!("true")]); + for value in ["null", "undefined", "{}"] { + assert!(failure(&mut s, &format!("app.activeDocument.pageItems[0].note = {value};")).contains("note must be a string"), "{value}"); + } assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } @@ -1332,24 +1405,20 @@ fn unsupported_members_say_so() { 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.'); }\ - }"; +/// A script that names each visible selected object after its place in `app.selection`, testing +/// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not +/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// never read. +const NAME_PICKED: &str = "\ + var picked = app.selection, k = picked.length, named = 0;\ + if (!k) alert('Select something first.');\ + while (k--) {\ + var obj = picked[k];\ + var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ + if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (usable) { obj.name = 'picked ' + k; named += 1; }\ + }\ + if (picked.length && named < picked.length) alert('Some objects were skipped.');"; #[test] fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() { @@ -1364,20 +1433,40 @@ fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() 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 names = |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() + objects.iter().map(|n| d.node(*n).unwrap().name.clone()).collect() + }; + let before = names(&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, NAME_PICKED).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["dialogs"], json!([]), "{r}"); + let after = names(&s); + assert!(after.iter().all(|n| n.as_deref().is_some_and(|n| n.starts_with("picked "))), "every kind was named: {after:?}"); + assert_eq!(after.iter().collect::>().len(), objects.len(), "each got its own name: {after:?}"); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(names(&s), before); + // Opacity reads and writes on every kind too: each object goes to its own value, read back from the script. + 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| d.node(*n).unwrap().opacity).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]); + let out = log( + &mut s, + "var sel = app.activeDocument.selection, read = [];\ + for (var i = 0; i < sel.length; i++) { sel[i].opacity = 20 + 10 * i; read.push(sel[i].opacity); }\ + vc.log(read);", + ); + assert_eq!(out, vec![json!([20, 30, 40, 50])]); + let after = opacities(&s); + assert!(after.iter().zip(&before).all(|(a, b)| a < b), "every kind got a lower opacity: {before:?} -> {after:?}"); assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(opacities(&s), before); @@ -1390,8 +1479,8 @@ fn the_selection_is_an_empty_list_when_nothing_is_selected() { 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}"); + let r = s.execute("script.run", &json!({"source": NAME_PICKED, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap(); + assert_eq!(r["dialogs"][0]["message"], json!("Select something first."), "{r}"); assert_eq!(undo_steps(&s), steps); } @@ -1484,6 +1573,41 @@ fn page_items_and_the_selection_list_the_topmost_object_first() { assert_eq!(out, vec![json!(["top", "last", "last"])]); } +/// The selection lists a group before the objects in it, in `pageItems`' order, and reading it +/// costs as much in a large document as in a small one. +#[test] +fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, c.0, group]})).unwrap(); + let source = "var d = app.activeDocument, want = [], got = [];\ + for (var i = 0; i < d.pageItems.length; i++) if (d.pageItems[i].selected) want.push(d.pageItems[i].typename + i);\ + for (var i = 0; i < d.pageItems.length; i++) for (var j = 0; j < d.selection.length; j++)\ + if (d.selection[j] === d.pageItems[i]) got[j] = d.pageItems[i].typename + i;\ + vc.log([want, got]);"; + let out = log(&mut s, source); + assert_eq!(out[0][0], out[0][1], "the selection is in pageItems' order"); + assert_eq!(out[0][0].as_array().map(Vec::len), Some(3)); + // Each pass edits the document, so nothing kept from the last read can be reused. + let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;"; + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap(); + // 3 objects doubled 11 times: 6,144. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..11 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let large = run(&mut s, edits); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap(); + assert_eq!(small, large); +} + /// 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() { @@ -1632,6 +1756,11 @@ fn assigning_a_name_a_collection_lacks_throws() { } let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);"); assert_eq!(out, vec![json!("object")]); + // On a page item the value is not kept; strict-mode code throws instead. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.qux = 4; vc.log(typeof i.qux);"); + assert_eq!(out, vec![json!("undefined")]); + let e = failure(&mut s, "'use strict'; app.activeDocument.pageItems[0].qux = 4;"); + assert!(e.contains("TypeError") && e.contains("qux"), "{e}"); assert_eq!(undo_steps(&s), steps); } diff --git a/docs/mcp.md b/docs/mcp.md index d05579f7e3..d3e47680f1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2671,29 +2671,33 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer - throws `Cannot edit` and changes nothing, even when the value is the one the object has, except for `opacity`, and - `zOrder()` on such an object throws `Cannot edit` too. Its `name` and `note` still change, and an object that is - hidden or locked itself takes all of them (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. An object with - nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` - as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws + throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such + an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which + changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that + value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an + object that is hidden or locked itself takes all of them (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` + or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds + it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such + as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and + assigning them does nothing (VectorCraft's own rule). `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`, + `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"`. `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, whatever order they were selected or made in. This is VectorCraft's own rule: the page cited below says the first object in a selection is the one last - added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as `pageItems["Logo"]` or - `documents["Untitled-1"]`, gives the object `getByName` gives, as + added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as + `pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object `getByName` gives, as [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too - (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives + (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` + take 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 ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). Documents are listed in tab order; the same page says `documents[0]` is always the active document, and @@ -2706,11 +2710,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers - panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a - hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw - `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` - when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along + panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was + deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that + is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` + when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on + a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` + and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, @@ -2725,9 +2730,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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. `Object.keys`, `Object.getOwnPropertyNames` and - `Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that a page item, a layer, a - document or the application does not have does not keep the value and does not throw; on a collection it throws `Not found`, - as described above. Other members + `Object.getOwnPropertyDescriptor` do not report any member of the class. Assigning a member that a page item, a + layer, a document or the application does not have does not keep the value; it does not throw, except in + strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. 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 @@ -3381,7 +3386,8 @@ or unknown id leaves the document unchanged. An empty `ids` array does nothing. are kept, and selecting an ancestor together with its descendants deletes that subtree once. Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a -boolean. +boolean. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, +also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean is rejected. `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's @@ -6992,7 +6998,9 @@ their facing handles are refitted so one cubic follows the two old segments; two The anchor after each removed one is then selected (the one before at an open path's end), so running `path.removeAnchors` again goes on along the path. `path.removeAnchor {id, subpath?, anchor}` (the Delete Anchor Point tool) removes one anchor the same way, and -`path.deleteAnchors {}` (the Delete key) deletes the selected anchors with their segments, opening closed paths there. +`path.deleteAnchors {keepEmpty?}` (the Delete key) deletes the selected anchors with their segments, opening closed paths +there. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given; `edit.clear` passes its +`keepEmpty` on when it deletes direct-selected anchors. ```json {"name":"run_command","arguments":{"command":"select.anchors","params":{"id":12,"anchors":[[0,1],[0,3]]}}}