From 4ac416d7d011bf6f26c2fc83d0f6bfc64352190d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:21:26 -0800 Subject: [PATCH 001/213] Scripts: swatches, spots, color groups, symbols, graphic styles and brushes Each document gains the swatches, spots, swatchGroups, symbols, symbolItems, graphicStyles and brushes collections that the scripting reference lists (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). Each change runs the existing Swatches, Symbols, Graphic Styles or Brushes command inside the run's transaction. - Resource objects follow renames made through them and throw Stale once the resource is removed, or renamed or deleted with vc.run, so a new resource with the old name is not theirs. - Swatches, spots and color groups share their names: a name one of them already has throws instead of taking a numbered name. - None, Registration and the Default Graphic Style cannot be renamed or removed, and removeAll() keeps them. - spots.add() converts the current fill to the document's color space unless it is Lab; a spot's color stays in that space or Lab. - A tint of a spot reads as a SpotColor of that spot at its tint. - Brush.applyTo throws for a guide, a clipping path and a path in a compound path, which brush.apply does not brush. - Objects of another document throw before any command runs. - Document.gradients, Document.patterns and assigning a SpotColor to art are not available yet. The host name check lists the new classes, members and enumerations. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 27 +- crates/engine/src/script/dom/resources.rs | 1130 +++++++++++++++++ crates/engine/src/script/mod.rs | 4 +- crates/engine/src/tests.rs | 1 + .../engine/src/tests/script_dom_resources.rs | 433 +++++++ .../tests/it/script_host_vs_scriptcheck.rs | 56 +- docs/mcp.md | 40 + docs/target-app-parity.md | 1 + 8 files changed, 1675 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/script/dom/resources.rs create mode 100644 crates/engine/src/tests/script_dom_resources.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 03b236c0e1..27291ec818 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -40,6 +40,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; mod paths; +mod resources; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -96,6 +97,8 @@ pub(super) struct State { items: RefCell>, /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. paths: RefCell>, + /// The swatches, symbols, styles and brushes the run's objects name ([`resources`]). + resources: RefCell, saving: Cell, } @@ -126,6 +129,12 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); @@ -1750,10 +1759,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, doc_selection, doc_set_selection)), ("pathItems", get(l, paths::doc_path_items)), ]); + document.extend(resources::document_members(l)); document.extend( - ["layers", "artboards", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] - .into_iter() - .map(|m| later(l, "Document", m)), + ["layers", "artboards", "groupItems", "textFrames", "views", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)), ); classes.push(class("Document", None, document, None)); classes.push(class( @@ -1818,12 +1826,19 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .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"), if *c == "PathItem" { paths::path_item_members(l) } else { Vec::new() }, None)), - ); + classes.extend(ITEM_CLASSES.iter().map(|c| { + let members = match *c { + "PathItem" => paths::path_item_members(l), + "SymbolItem" => resources::symbol_item_members(l), + _ => Vec::new(), + }; + class(c, Some("PageItem"), members, None) + })); classes.extend(paths::classes(l)); classes.extend(colors::classes(l)); + classes.extend(resources::classes(l)); paths::install_enums(realm)?; + resources::install_enums(realm)?; 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/dom/resources.rs b/crates/engine/src/script/dom/resources.rs new file mode 100644 index 0000000000..503d5e5abe --- /dev/null +++ b/crates/engine/src/script/dom/resources.rs @@ -0,0 +1,1130 @@ +//! The document resources of the script object model: swatches, color groups, spots, symbols and +//! symbol instances, graphic styles and brushes, as the help pages +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe them. +//! +//! Every change runs the command the Swatches, Symbols, Graphic Styles or Brushes panel runs, so it +//! joins the run's transaction; a change that changes nothing runs no command. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A resource object holds the run, the document and a slot of the run's [`Table`], which names +//! the resource. Renaming it through the object model keeps the object; removing it, or a rename +//! or deletion that `vc.run` makes, leaves the object stale, and every member then throws +//! `Stale Swatch` (`Stale Symbol`, and so on). +//! - `swatches` lists the swatches in the Swatches panel's order: None, Registration, the other +//! ungrouped swatches, then each color group's. `swatchGroups` lists the color groups only. +//! - `swatches.add()` saves the current fill (a color, gradient or pattern) as a swatch, or black +//! when the fill is None; `spots.add()` saves the current fill, in the document's color space +//! unless it is Lab, or black when it is not a solid color, as a spot color. `getSelected()` gives +//! `[]`, since a script has no Swatches panel selection. +//! - None and Registration cannot be renamed, recolored, grouped or removed, and `removeAll()` +//! keeps them. The Default Graphic Style cannot be renamed or removed, and +//! `graphicStyles.removeAll()` keeps it. +//! - `SwatchGroup.remove()` deletes the group and its swatches; `removeAll()` deletes its swatches +//! and keeps the group. A group holds solid colors only. +//! - A spot's color must be in the document's color space (RGB or CMYK) or Lab. `colorType` reads +//! `ColorModel.SPOT` and takes only that value. `spotKind` reads `SpotColorKind.SPOTCMYK` for a +//! gray spot. `getInternalColor()` gives the components on the scale of the color classes +//! (0 to 255 for RGB, 0 to 100 for CMYK and gray, L*a*b* as is). +//! - `symbols.add(art)` keeps the art where it is and does not make it an instance. +//! `Symbol.remove()` and `symbols.removeAll()` turn the instances into plain art. +//! - `applyTo` and `mergeTo` take one page item of the same document that can be edited; +//! `Brush.applyTo` takes a path that is not a guide, a clipping path or a path in a compound path. +//! - A name is 1 to 1024 bytes, not blank, with no control characters. + +use std::collections::{HashMap, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::swatch::{self, Swatch}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; + +use super::{ + Answer, CROSS_DOCUMENT, Doc, Host, Item, Link, NOT_FOUND, arg, class, colors, command, current, data_size, doc_of, doc_ref, editable, find_doc, + float, given, handle_of, item_of, item_ref, later, named, num, on_doc, page_items, text, this_doc, typename_of, whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The longest resource name a script may give, in bytes. +pub const MAX_NAME_BYTES: usize = 1024; +/// The most resource objects one run may hold. +pub const MAX_SLOTS: usize = 100_000; + +/// The kinds of resource object. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum Kind { + Swatch, + Spot, + Group, + Symbol, + Style, + Brush, +} + +impl Kind { + fn class(self) -> &'static str { + match self { + Kind::Swatch => "Swatch", + Kind::Spot => "Spot", + Kind::Group => "SwatchGroup", + Kind::Symbol => "Symbol", + Kind::Style => "GraphicStyle", + Kind::Brush => "Brush", + } + } + + fn collection(self) -> &'static str { + match self { + Kind::Swatch => "Swatches", + Kind::Spot => "Spots", + Kind::Group => "SwatchGroups", + Kind::Symbol => "Symbols", + Kind::Style => "GraphicStyles", + Kind::Brush => "Brushes", + } + } + + /// The kinds that name the same records: a spot is also a swatch. + fn family(self) -> &'static [Kind] { + match self { + Kind::Swatch | Kind::Spot => &[Kind::Swatch, Kind::Spot], + Kind::Group => &[Kind::Group], + Kind::Symbol => &[Kind::Symbol], + Kind::Style => &[Kind::Style], + Kind::Brush => &[Kind::Brush], + } + } + + fn stale(self) -> HostError { + HostError::Error(format!("Stale {}", self.class())) + } +} + +const KINDS: [Kind; 6] = [Kind::Swatch, Kind::Spot, Kind::Group, Kind::Symbol, Kind::Style, Kind::Brush]; + +/// The resources a run's objects name: each slot holds a document's uid, a kind and the +/// resource's name, or `None` once it was removed. +#[derive(Default)] +pub(super) struct Table { + slots: Vec<(u64, Kind, Option)>, + index: HashMap<(u64, Kind, String), usize>, + /// Each document as [`forget_removed`] last checked it. + checked: HashMap>, +} + +impl Table { + /// Marks every slot stale whose document is no longer open, or whose resource `docs` no + /// longer has. A document unchanged since the last check is skipped. + fn forget(&mut self, docs: &[DocState]) { + if self.index.is_empty() { + return; + } + let uids: HashSet = self.index.keys().map(|(u, ..)| *u).collect(); + for uid in uids { + let st = docs.iter().find(|d| d.uid == uid); + if let (Some(st), Some(seen)) = (st, self.checked.get(&uid)) + && Arc::ptr_eq(seen, &st.doc) + { + continue; + } + let mut present: HashMap> = HashMap::new(); + let gone: Vec<(u64, Kind, String)> = self + .index + .keys() + .filter(|(u, k, n)| { + *u == uid && st.is_none_or(|st| !present.entry(*k).or_insert_with(|| names(&st.doc, *k).into_iter().collect()).contains(n)) + }) + .cloned() + .collect(); + for key in gone { + if let Some(i) = self.index.remove(&key) { + self.slots[i].2 = None; + } + } + match st { + Some(st) => self.checked.insert(uid, st.doc.clone()), + None => self.checked.remove(&uid), + }; + } + } + + /// The slot of `name`, made when there is none. + fn slot(&mut self, uid: u64, kind: Kind, name: &str) -> std::result::Result { + if let Some(i) = self.index.get(&(uid, kind, name.to_string())) { + return Ok(*i); + } + if self.slots.len() >= MAX_SLOTS { + return Err(HostError::Range(format!("a script may hold at most {MAX_SLOTS} swatches, symbols, styles and brushes"))); + } + self.slots.push((uid, kind, Some(name.to_string()))); + self.index.insert((uid, kind, name.to_string()), self.slots.len() - 1); + Ok(self.slots.len() - 1) + } + + /// The name slot `i` holds for `uid` and `kind`. + fn name(&self, i: usize, uid: u64, kind: Kind) -> Option<&str> { + match self.slots.get(i) { + Some((u, k, Some(n))) if *u == uid && *k == kind => Some(n), + _ => None, + } + } + + /// The resource `from` of the family of `kind` is now called `to`; objects that named `to` + /// before go stale. + fn rename(&mut self, uid: u64, kind: Kind, from: &str, to: &str) { + self.remove(uid, kind, to); + for k in kind.family() { + if let Some(i) = self.index.remove(&(uid, *k, from.to_string())) { + self.slots[i].2 = Some(to.to_string()); + self.index.insert((uid, *k, to.to_string()), i); + } + } + } + + /// The resource `name` of the family of `kind` is gone. + fn remove(&mut self, uid: u64, kind: Kind, name: &str) { + for k in kind.family() { + if let Some(i) = self.index.remove(&(uid, *k, name.to_string())) { + self.slots[i].2 = None; + } + } + } +} + +/// After a `vc.run` command: the objects whose resource the command removed or renamed go stale. +pub(super) fn forget_removed(h: &Host) { + let s = h.session.borrow(); + h.dom.resources.borrow_mut().forget(s.documents()); +} + +type Kfn = fn(&Host, Kind, &[Data]) -> Answer; + +fn kfunction(link: &Link, kind: Kind, f: Kfn) -> 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, kind, &a) + }) +} + +fn kget(l: &Link, kind: Kind, f: Kfn) -> HostMember { + HostMember::Get(kfunction(l, kind, f)) +} + +fn kproperty(l: &Link, kind: Kind, g: Kfn, s: Kfn) -> HostMember { + HostMember::Property { get: kfunction(l, kind, g), set: kfunction(l, kind, s) } +} + +fn kmethod(l: &Link, kind: Kind, f: Kfn) -> HostMember { + HostMember::Method(kfunction(l, kind, f)) +} + +/// A name a script gave: a string of 1 to [`MAX_NAME_BYTES`] bytes, not blank, without control +/// characters. +fn name_arg(d: &Data, what: &str) -> std::result::Result { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_NAME_BYTES { + return Err(HostError::Range(format!("{what} is longer than {MAX_NAME_BYTES} bytes"))); + } + if s.chars().any(char::is_control) { + return Err(HostError::Range(format!("{what} cannot hold control characters"))); + } + if s.trim().is_empty() { + return Err(HostError::Range(format!("{what} cannot be empty"))); + } + Ok(s.clone()) +} + +// ---- reading the records ---- + +/// The swatches in panel order, each with its color group. +fn all_swatches(d: &Document) -> Vec<(&Swatch, Option<&str>)> { + let none = d.swatches.iter().take_while(|w| w.paint.is_none()).count(); + let (specials, rest) = d.swatches.split_at(none); + let ungrouped = specials.iter().chain([swatch::registration()]).chain(rest).map(|w| (w, None)); + let grouped = d.swatch_groups.iter().flat_map(|g| g.swatches.iter().map(|w| (w, Some(g.name.as_str())))); + ungrouped.chain(grouped).collect() +} + +fn find_swatch<'a>(d: &'a Document, name: &str) -> Option<(&'a Swatch, Option<&'a str>)> { + all_swatches(d).into_iter().find(|(w, _)| w.name == name) +} + +/// The names of the resources of `kind` in `d`, in their panel's order. +fn names(d: &Document, kind: Kind) -> Vec { + match kind { + Kind::Swatch => all_swatches(d).into_iter().map(|(w, _)| w.name.clone()).collect(), + Kind::Spot => all_swatches(d).into_iter().filter(|(w, _)| w.spot).map(|(w, _)| w.name.clone()).collect(), + Kind::Group => d.swatch_groups.iter().map(|g| g.name.clone()).collect(), + Kind::Symbol => d.symbols.iter().map(|s| s.name.clone()).collect(), + Kind::Style => d.graphic_styles.iter().map(|g| g.name.clone()).collect(), + Kind::Brush => vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect(), + } +} + +/// Whether `d` has the resource `name` of `kind`. +fn exists(d: &Document, kind: Kind, name: &str) -> bool { + match kind { + Kind::Swatch => find_swatch(d, name).is_some(), + Kind::Spot => find_swatch(d, name).is_some_and(|(w, _)| w.spot), + Kind::Group => d.swatch_groups.iter().any(|g| g.name == name), + Kind::Symbol => d.symbols.iter().any(|s| s.name == name), + Kind::Style => d.graphic_style(name).is_some(), + Kind::Brush => vectorcraft_brush::find(d, name).is_some(), + } +} + +/// The object for the resource `name` of `kind` in the document `uid`. +fn resource_ref(h: &Host, uid: u64, kind: Kind, name: &str) -> Answer { + let slot = h.dom.resources.borrow_mut().slot(uid, kind, name)?; + Ok(host_ref(kind.class(), &[float(h.run), float(uid), float(slot as u64)])) +} + +/// A resource an object names: its document and its name now. +struct Res { + doc: Doc, + name: String, +} + +/// The resource `d` names, which must be an object of `kind` that is not stale. +fn resource_of(h: &Host, d: &Data, kind: Kind) -> std::result::Result { + let Some(handle) = handle_of(d, kind.class()) else { return Err(HostError::Type(format!("this is not a {}", kind.class()))) }; + let [run, uid, slot] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {}", kind.class()))) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| kind.stale())?; + let slot = whole(*slot).and_then(|s| usize::try_from(s).ok()).ok_or_else(|| kind.stale())?; + let name = h.dom.resources.borrow().name(slot, doc.uid, kind).map(str::to_string).ok_or_else(|| kind.stale())?; + if !with_doc(h, doc, |_, st| exists(&st.doc, kind, &name)) { + return Err(kind.stale()); + } + Ok(Res { doc, name }) +} + +fn this_res(h: &Host, a: &[Data], kind: Kind) -> std::result::Result { + resource_of(h, arg(a, 0), kind) +} + +/// Runs `id` with `params` on the document `doc`, its selection kept. +fn run_on(h: &Host, doc: Doc, id: &str, params: &Value) -> Answer { + on_doc(h, doc.uid, true, |h| command(h, id, params)) +} + +/// The string `key` of a command's result. +fn result_name(r: &Data, key: &str) -> std::result::Result { + match r { + Data::Object(o) => o.iter().find(|(k, _)| k == key).and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None }), + _ => None, + } + .ok_or_else(|| HostError::Error("the command gave no name".into())) +} + +// ---- the collections ---- + +fn coll_doc(h: &Host, a: &[Data], kind: Kind) -> std::result::Result { + doc_of(h, arg(a, 0), kind.collection()) +} + +/// The names of the collection `this`, charged to the run. +fn coll_names(h: &Host, a: &[Data], kind: Kind) -> std::result::Result<(Doc, Vec), HostError> { + let doc = coll_doc(h, a, kind)?; + let list = with_doc(h, doc, |_, st| names(&st.doc, kind)); + h.charge_call(list.len() as u64)?; + Ok((doc, list)) +} + +fn coll_length(h: &Host, kind: Kind, a: &[Data]) -> Answer { + Ok(num(float(coll_names(h, a, kind)?.1.len() as u64))) +} + +fn coll_parent(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + Ok(doc_ref(h, doc.uid)) +} + +fn coll_at(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let (doc, list) = coll_names(h, a, kind)?; + 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) }; + match list.get(i) { + Some(name) => resource_ref(h, doc.uid, kind, name), + None => Ok(Data::Undefined), + } +} + +fn coll_by_name(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let (doc, list) = coll_names(h, a, kind)?; + if !list.iter().any(|n| n == name) { + return Err(HostError::Error(NOT_FOUND.into())); + } + resource_ref(h, doc.uid, kind, name) +} + +fn coll_index(h: &Host, kind: Kind, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => coll_by_name(h, kind, a), + Data::Number(_) => match coll_at(h, kind, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The names `removeAll()` deletes from the collection of `kind`. +fn removable(d: &Document, kind: Kind) -> Vec { + match kind { + Kind::Swatch | Kind::Spot => { + let only_spots = kind == Kind::Spot; + all_swatches(d).into_iter().filter(|(w, _)| !w.is_reserved() && (!only_spots || w.spot)).map(|(w, _)| w.name.clone()).collect() + } + Kind::Style => d.graphic_styles.iter().filter(|g| g.name != crate::doc::DEFAULT_GRAPHIC_STYLE).map(|g| g.name.clone()).collect(), + _ => names(d, kind), + } +} + +/// `removeAll()`: deletes the collection's members in one command. +fn coll_remove_all(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + let (list, members) = with_doc(h, doc, |_, st| { + let list = removable(&st.doc, kind); + let members: Vec = match kind { + Kind::Group => st.doc.swatch_groups.iter().flat_map(|g| g.swatches.iter().map(|w| w.name.clone())).collect(), + _ => Vec::new(), + }; + (list, members) + }); + h.charge_call(16 * list.len() as u64)?; + if list.is_empty() { + return Ok(Data::Undefined); + } + let (id, params) = match kind { + Kind::Swatch | Kind::Spot | Kind::Group => ("swatch.delete", json!({"names": list, "unlink": true})), + Kind::Symbol => ("symbol.delete", json!({"names": list})), + Kind::Style => ("graphicStyle.delete", json!({"names": list})), + Kind::Brush => return Err(HostError::Error("Brushes.removeAll is not available".into())), + }; + run_on(h, doc, id, ¶ms)?; + let mut t = h.dom.resources.borrow_mut(); + for n in &list { + t.remove(doc.uid, kind, n); + } + for n in &members { + t.remove(doc.uid, Kind::Swatch, n); + } + Ok(Data::Undefined) +} + +/// The current fill when it is a solid color. +fn current_solid(h: &Host) -> Option { + let s = h.session.borrow(); + match s.new_art().fill_paint() { + Paint::Solid { color, .. } => Some(color), + _ => None, + } +} + +/// `swatches.add()`: the current fill (a color, gradient or pattern) as a new swatch, or black when +/// the fill is None. +fn swatches_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + let none = h.session.borrow().new_art().fill_paint().is_none(); + let params = if none { json!({"color": colors::param(&Color::BLACK)}) } else { json!({}) }; + let r = run_on(h, doc, "swatch.new", ¶ms)?; + let name = result_name(&r, "name")?; + resource_ref(h, doc.uid, Kind::Swatch, &name) +} + +/// Black in the color space of `doc`. +fn black_in(h: &Host, doc: Doc) -> Color { + if is_cmyk(h, doc) { Color::cmyk(0.0, 0.0, 0.0, 1.0) } else { Color::BLACK } +} + +/// Whether the document `doc` is in CMYK. +fn is_cmyk(h: &Host, doc: Doc) -> bool { + with_doc(h, doc, |_, st| st.doc.color_mode == crate::doc::ColorMode::Cmyk) +} + +/// Whether `color` may be a spot's color in a document that is in CMYK (`cmyk`) or RGB: a color of +/// that space, or Lab. +fn fits_spot(cmyk: bool, color: Color) -> bool { + matches!(color, Color::Lab { .. }) || matches!((cmyk, color), (true, Color::Cmyk { .. }) | (false, Color::Rgb { .. })) +} + +/// `spots.add()`: the current fill, or black, as a new spot color. A color that is neither Lab nor +/// in the document's color space is converted to that space with `swatch.new`'s `mode`. +fn spots_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + let color = current_solid(h).unwrap_or_else(|| black_in(h, doc)); + let cmyk = is_cmyk(h, doc); + let mut params = json!({"color": colors::param(&color), "spot": true}); + if !fits_spot(cmyk, color) { + params["mode"] = json!(if cmyk { "cmyk" } else { "rgb" }); + } + let r = run_on(h, doc, "swatch.new", ¶ms)?; + let name = result_name(&r, "name")?; + resource_ref(h, doc.uid, Kind::Spot, &name) +} + +/// `swatchGroups.add()`: a new, empty color group. +fn groups_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + let r = run_on(h, doc, "swatch.newGroup", &json!({}))?; + let name = result_name(&r, "name")?; + resource_ref(h, doc.uid, Kind::Group, &name) +} + +fn swatches_selected(h: &Host, kind: Kind, a: &[Data]) -> Answer { + coll_doc(h, a, kind)?; + Ok(Data::Array(Vec::new())) +} + +/// The registration point index of a `SymbolRegistrationPoint` value, 4 (the center) when left out. +fn registration(d: &Data) -> std::result::Result { + let Some(d) = given(d) else { return Ok(4) }; + let Data::String(s) = d else { return Err(HostError::Type("registrationPoint must be a SymbolRegistrationPoint value".into())) }; + let at = REGISTRATION.iter().position(|r| s.strip_prefix("SymbolRegistrationPoint.") == Some(*r)); + at.and_then(|i| u8::try_from(i).ok()).ok_or_else(|| HostError::Type("registrationPoint must be a SymbolRegistrationPoint value".into())) +} + +/// `SymbolRegistrationPoint`, in the order of the 9-point grid `symbol.new` takes. +const REGISTRATION: [&str; 9] = [ + "SYMBOLTOPLEFTPOINT", + "SYMBOLTOPMIDDLEPOINT", + "SYMBOLTOPRIGHTPOINT", + "SYMBOLMIDDLELEFTPOINT", + "SYMBOLCENTERPOINT", + "SYMBOLMIDDLERIGHTPOINT", + "SYMBOLBOTTOMLEFTPOINT", + "SYMBOLBOTTOMMIDDLEPOINT", + "SYMBOLBOTTOMRIGHTPOINT", +]; + +/// The page item `d` names, which must be in the document `doc`. +fn same_doc_item(h: &Host, doc: Doc, d: &Data) -> std::result::Result { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + Ok(item) +} + +/// `symbols.add(sourceArt, registrationPoint?)`: a symbol made from a copy of `sourceArt`, which +/// stays as it is. +fn symbols_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + if matches!(arg(a, 1), Data::Undefined) { + return Err(HostError::Type("symbols.add needs the source art".into())); + } + let item = same_doc_item(h, doc, arg(a, 1))?; + let reg = registration(arg(a, 2))?; + let r = run_on(h, doc, "symbol.new", &json!({"ids": [item.id.0], "keepArt": true, "registration": reg}))?; + let name = result_name(&r, "name")?; + resource_ref(h, doc.uid, Kind::Symbol, &name) +} + +// ---- Swatch and Spot ---- + +fn res_name(h: &Host, kind: Kind, a: &[Data]) -> Answer { + Ok(text(this_res(h, a, kind)?.name)) +} + +fn res_typename(h: &Host, kind: Kind, a: &[Data]) -> Answer { + this_res(h, a, kind)?; + Ok(text(kind.class())) +} + +fn res_parent(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + Ok(doc_ref(h, r.doc.uid)) +} + +fn reserved(name: &str) -> HostError { + HostError::Error(format!("{name} is built in and cannot change")) +} + +/// The swatch `r` names, cloned. +fn swatch_now(h: &Host, r: &Res, kind: Kind) -> std::result::Result { + with_doc(h, r.doc, |_, st| find_swatch(&st.doc, &r.name).map(|(w, _)| w.clone())).ok_or_else(|| kind.stale()) +} + +/// Renames the resource `this` names with the command of its kind. +fn res_set_name(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let new = name_arg(arg(a, 1), "name")?.trim().to_string(); + let r = this_res(h, a, kind)?; + if new == r.name { + return Ok(Data::Undefined); + } + let (id, params, key) = match kind { + Kind::Swatch | Kind::Spot => { + if swatch_now(h, &r, kind)?.is_reserved() { + return Err(reserved(&r.name)); + } + ("swatch.edit", json!({"name": r.name, "newName": new}), "name") + } + Kind::Group => ("swatch.renameGroup", json!({"group": r.name, "name": new}), "name"), + Kind::Symbol => ("symbol.options", json!({"name": r.name, "newName": new}), "name"), + Kind::Style if r.name == crate::doc::DEFAULT_GRAPHIC_STYLE => return Err(reserved(&r.name)), + Kind::Style => ("graphicStyle.rename", json!({"name": r.name, "to": new}), "name"), + Kind::Brush => return Err(HostError::Error("Brush.name is read-only".into())), + }; + // Swatches, spots and color groups share one set of names. + let (taken, what) = with_doc(h, r.doc, |_, st| match kind { + Kind::Swatch | Kind::Spot | Kind::Group => { + (exists(&st.doc, Kind::Swatch, &new) || exists(&st.doc, Kind::Group, &new), "a swatch or color group") + } + _ => (exists(&st.doc, kind, &new), if kind == Kind::Symbol { "a Symbol" } else { "a GraphicStyle" }), + }); + if taken { + return Err(HostError::Error(format!("{what} named {new} already exists"))); + } + let out = run_on(h, r.doc, id, ¶ms)?; + let to = result_name(&out, key)?; + h.dom.resources.borrow_mut().rename(r.doc.uid, kind, &r.name, &to); + Ok(Data::Undefined) +} + +/// Deletes the resource `this` names with the command of its kind. +fn res_remove(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + let mut members = Vec::new(); + let (id, params) = match kind { + Kind::Swatch | Kind::Spot => { + if swatch_now(h, &r, kind)?.is_reserved() { + return Err(reserved(&r.name)); + } + ("swatch.delete", json!({"name": r.name, "unlink": true})) + } + Kind::Group => { + members = group_members(h, &r); + ("swatch.delete", json!({"name": r.name, "unlink": true})) + } + Kind::Symbol => ("symbol.delete", json!({"name": r.name})), + Kind::Style if r.name == crate::doc::DEFAULT_GRAPHIC_STYLE => return Err(reserved(&r.name)), + Kind::Style => ("graphicStyle.delete", json!({"name": r.name})), + Kind::Brush => return Err(HostError::Error("Brush.remove is not available".into())), + }; + run_on(h, r.doc, id, ¶ms)?; + let mut t = h.dom.resources.borrow_mut(); + t.remove(r.doc.uid, kind, &r.name); + for m in &members { + t.remove(r.doc.uid, Kind::Swatch, m); + } + Ok(Data::Undefined) +} + +/// `Swatch.color`: a new color object. A spot swatch gives a `SpotColor` of the spot at 100%, and +/// a tint of a spot a `SpotColor` of that spot at the tint. +fn swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + let w = swatch_now(h, &r, kind)?; + if w.spot && w.tint_of().is_none() { + let spot = resource_ref(h, r.doc.uid, Kind::Spot, &w.name)?; + return Ok(Data::Object(vec![("typename".into(), text("SpotColor")), ("spot".into(), spot), ("tint".into(), num(100.0))])); + } + let color = colors::of_paint(&w.paint); + let base = match &w.paint { + Paint::Solid { swatch: Some(base), .. } => { + with_doc(h, r.doc, |_, st| find_swatch(&st.doc, base).is_some_and(|(b, _)| b.spot)).then(|| base.clone()) + } + _ => None, + }; + match (color, base) { + (Data::Object(mut o), Some(base)) => { + o.insert(1, ("spot".into(), resource_ref(h, r.doc.uid, Kind::Spot, &base)?)); + Ok(Data::Object(o)) + } + (color, _) => Ok(color), + } +} + +/// `Spot.color`: the spot's own color, as a new color object. +fn spot_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + Ok(colors::of_paint(&swatch_now(h, &r, kind)?.paint)) +} + +/// Gives the swatch `this` names the solid color `color`, with `swatch.edit`. +fn set_swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let what = if kind == Kind::Spot { "Spot.color" } else { "Swatch.color" }; + let color = colors::assigned(arg(a, 1), what)?.ok_or_else(|| HostError::Error(format!("{what} cannot be NoColor")))?; + let r = this_res(h, a, kind)?; + let w = swatch_now(h, &r, kind)?; + if w.is_reserved() { + return Err(reserved(&r.name)); + } + let now = match &w.paint { + Paint::Solid { color, swatch: None, .. } => *color, + Paint::Solid { .. } => return Err(HostError::Error(format!("{} is a tint of another swatch; change that swatch's color", r.name))), + _ => return Err(HostError::Error(format!("{} is not a solid color", r.name))), + }; + if w.spot { + let cmyk = is_cmyk(h, r.doc); + if !fits_spot(cmyk, color) { + let space = if cmyk { "a CMYKColor" } else { "an RGBColor" }; + return Err(HostError::Error(format!("a spot's color must be {space} in this document, or a LabColor"))); + } + } + if now == color { + return Ok(Data::Undefined); + } + run_on(h, r.doc, "swatch.edit", &json!({"name": r.name, "color": colors::param(&color)}))?; + Ok(Data::Undefined) +} + +fn spot_color_type(h: &Host, kind: Kind, a: &[Data]) -> Answer { + this_res(h, a, kind)?; + Ok(text("ColorModel.SPOT")) +} + +fn spot_set_color_type(h: &Host, kind: Kind, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(s) if s == "ColorModel.SPOT" => { + this_res(h, a, kind)?; + Ok(Data::Undefined) + } + Data::String(s) if s == "ColorModel.PROCESS" || s == "ColorModel.REGISTRATION" => { + Err(HostError::Error("a Spot stays a spot color; edit it through its Swatch".into())) + } + _ => Err(HostError::Type("colorType must be a ColorModel value".into())), + } +} + +fn spot_color_of(h: &Host, kind: Kind, a: &[Data]) -> std::result::Result { + let r = this_res(h, a, kind)?; + match swatch_now(h, &r, kind)?.paint { + Paint::Solid { color, .. } => Ok(color), + _ => Err(HostError::Error(format!("{} is not a solid color", r.name))), + } +} + +fn spot_kind(h: &Host, kind: Kind, a: &[Data]) -> Answer { + Ok(text(match spot_color_of(h, kind, a)? { + Color::Rgb { .. } => "SpotColorKind.SPOTRGB", + Color::Lab { .. } => "SpotColorKind.SPOTLAB", + Color::Cmyk { .. } | Color::Gray { .. } => "SpotColorKind.SPOTCMYK", + })) +} + +/// `getInternalColor()`: the components of the spot's color, as a new array. +fn spot_internal(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let o = match colors::of_paint(&Paint::solid(spot_color_of(h, kind, a)?)) { + Data::Object(o) => o, + _ => Vec::new(), + }; + Ok(Data::Array(o.into_iter().filter(|(k, _)| k != "typename").map(|(_, v)| v).collect())) +} + +// ---- SwatchGroup ---- + +fn group_members(h: &Host, r: &Res) -> Vec { + with_doc(h, r.doc, |_, st| { + st.doc.swatch_groups.iter().find(|g| g.name == r.name).map(|g| g.swatches.iter().map(|w| w.name.clone()).collect()).unwrap_or_default() + }) +} + +fn group_all(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + let members = group_members(h, &r); + h.charge_call(16 * members.len() as u64)?; + members.iter().map(|n| resource_ref(h, r.doc.uid, Kind::Swatch, n)).collect::, _>>().map(Data::Array) +} + +/// Moves the swatch or spot argument 1 into the group `this` names, with `swatch.move`. +fn group_add(h: &Host, kind: Kind, a: &[Data], member: Kind) -> Answer { + let g = this_res(h, a, kind)?; + let w = resource_of(h, arg(a, 1), member)?; + if w.doc.uid != g.doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + let (sw, group) = + with_doc(h, w.doc, |_, st| find_swatch(&st.doc, &w.name).map(|(s, g)| (s.clone(), g.map(str::to_string)))).ok_or_else(|| member.stale())?; + if sw.is_reserved() { + return Err(reserved(&w.name)); + } + if !matches!(sw.paint, Paint::Solid { .. }) { + return Err(HostError::Error(format!("a color group holds solid colors only, and {} is not one", w.name))); + } + if group.as_deref() == Some(g.name.as_str()) { + return Ok(Data::Undefined); + } + run_on(h, g.doc, "swatch.move", &json!({"names": [w.name], "group": g.name}))?; + Ok(Data::Undefined) +} + +fn group_add_swatch(h: &Host, kind: Kind, a: &[Data]) -> Answer { + group_add(h, kind, a, Kind::Swatch) +} + +fn group_add_spot(h: &Host, kind: Kind, a: &[Data]) -> Answer { + group_add(h, kind, a, Kind::Spot) +} + +/// `SwatchGroup.removeAll()`: deletes the group's swatches and keeps the group. +fn group_remove_all(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + let members = group_members(h, &r); + h.charge_call(16 * members.len() as u64)?; + if members.is_empty() { + return Ok(Data::Undefined); + } + run_on(h, r.doc, "swatch.delete", &json!({"names": members, "unlink": true}))?; + let mut t = h.dom.resources.borrow_mut(); + for m in &members { + t.remove(r.doc.uid, Kind::Swatch, m); + } + Ok(Data::Undefined) +} + +// ---- Symbol and SymbolItem ---- + +fn symbol_duplicate(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + let out = run_on(h, r.doc, "symbol.duplicate", &json!({"name": r.name}))?; + let name = result_name(&out, "name")?; + resource_ref(h, r.doc.uid, Kind::Symbol, &name) +} + +/// The ids of a document's symbol instances, in the order of its page items. +fn instances(h: &Host, st: &DocState) -> Vec { + page_items(h, st).iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))).collect() +} + +fn instances_of(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Vec), HostError> { + let doc = doc_of(h, arg(a, 0), "SymbolItems")?; + let ids = with_doc(h, doc, |_, st| instances(h, st)); + h.charge_call(ids.len() as u64)?; + Ok((doc, ids)) +} + +fn sitems_length(h: &Host, _: Kind, a: &[Data]) -> Answer { + Ok(num(float(instances_of(h, a)?.1.len() as u64))) +} + +fn sitems_parent(h: &Host, _: Kind, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "SymbolItems")?; + Ok(doc_ref(h, doc.uid)) +} + +fn sitems_at(h: &Host, _: Kind, a: &[Data]) -> Answer { + let (doc, ids) = instances_of(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| ids.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn sitems_by_name(h: &Host, _: Kind, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + let (doc, ids) = instances_of(h, a)?; + with_doc(h, doc, |_, st| { + 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 sitems_index(h: &Host, kind: Kind, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => sitems_by_name(h, kind, a), + Data::Number(_) => match sitems_at(h, kind, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `symbolItems.add(symbol)`: an instance of `symbol` at the center of the first artboard. +fn sitems_add(h: &Host, _: Kind, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "SymbolItems")?; + let sym = resource_of(h, arg(a, 1), Kind::Symbol)?; + if sym.doc.uid != doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + let out = run_on(h, doc, "symbol.place", &json!({"name": sym.name}))?; + let id = match &out { + Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), + _ => None, + } + .ok_or_else(|| HostError::Error("the instance was not made".into()))?; + Ok(with_doc(h, doc, |_, st| item_ref(h, st, NodeId(id)))) +} + +/// `symbolItems.removeAll()`: deletes every instance in one command; a hidden or locked one stops +/// it before anything is deleted. The symbols stay. +fn sitems_remove_all(h: &Host, _: Kind, a: &[Data]) -> Answer { + let (doc, ids) = instances_of(h, a)?; + let refused: Vec = with_doc(h, doc, |_, st| ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect()); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked symbol instances: {list}"))); + } + if !ids.is_empty() { + run_on(h, doc, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()}))?; + } + Ok(Data::Undefined) +} + +/// The symbol instance `this` names and its symbol's name. +fn this_instance(h: &Host, a: &[Data]) -> std::result::Result<(Item, String), HostError> { + let item = item_of(h, arg(a, 0))?; + let name = with_doc(h, item.doc, |_, st| match st.doc.node(item.id).map(|n| &n.kind) { + Some(NodeKind::SymbolInstance { symbol, .. }) => Some(symbol.clone()), + _ => None, + }); + name.map(|n| (item, n)).ok_or_else(|| HostError::Type("this is not a SymbolItem".into())) +} + +fn sitem_symbol(h: &Host, _: Kind, a: &[Data]) -> Answer { + let (item, name) = this_instance(h, a)?; + resource_ref(h, item.doc.uid, Kind::Symbol, &name) +} + +/// `SymbolItem.symbol = symbol`: `symbol.replace` for this instance. +fn sitem_set_symbol(h: &Host, _: Kind, a: &[Data]) -> Answer { + let sym = resource_of(h, arg(a, 1), Kind::Symbol)?; + let (item, now) = this_instance(h, a)?; + if sym.doc.uid != item.doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + if sym.name == now { + return Ok(Data::Undefined); + } + check_editable(h, item)?; + run_on(h, item.doc, "symbol.replace", &json!({"name": sym.name, "ids": [item.id.0]}))?; + Ok(Data::Undefined) +} + +// ---- GraphicStyle and Brush ---- + +fn check_editable(h: &Host, item: Item) -> std::result::Result<(), HostError> { + if with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + Ok(()) + } else { + Err(HostError::Error(format!("Cannot edit page item {}: it, or a layer or group it is in, is hidden or locked", item.id.0))) + } +} + +/// How many objects the object `id` is, with those inside it. +fn object_count(d: &Document, id: NodeId) -> u64 { + fn count(n: &crate::doc::Node) -> u64 { + 1 + n.children().map_or(0, |c| c.iter().map(|c| count(c)).sum()) + } + d.node(id).map_or(0, count) +} + +/// The page item argument 1 of `applyTo` or `mergeTo`: one object of the resource's document that +/// can be edited, charged to the run by the objects it holds. +fn target(h: &Host, r: &Res, a: &[Data]) -> std::result::Result { + if matches!(arg(a, 1), Data::Array(_)) { + return Err(HostError::Type("give one page item".into())); + } + let item = same_doc_item(h, r.doc, arg(a, 1))?; + check_editable(h, item)?; + let n = with_doc(h, item.doc, |_, st| object_count(&st.doc, item.id)); + h.charge_call(16 * n)?; + Ok(item) +} + +fn style_apply(h: &Host, kind: Kind, a: &[Data], add: bool) -> Answer { + let r = this_res(h, a, kind)?; + let item = target(h, &r, a)?; + run_on(h, r.doc, "graphicStyle.apply", &json!({"name": r.name, "ids": [item.id.0], "add": add}))?; + Ok(Data::Undefined) +} + +fn style_apply_to(h: &Host, kind: Kind, a: &[Data]) -> Answer { + style_apply(h, kind, a, false) +} + +fn style_merge_to(h: &Host, kind: Kind, a: &[Data]) -> Answer { + style_apply(h, kind, a, true) +} + +/// `Brush.applyTo(path)`: `brush.apply` for one path, unless its stroke already draws this brush +/// and the brush is the current one. A guide, a clipping path and a path in a compound path take no +/// brush from `brush.apply`, so they throw. +fn brush_apply_to(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let r = this_res(h, a, kind)?; + let item = target(h, &r, a)?; + let (path, brushable, same) = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id); + let path = n.is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })); + let in_compound = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + let brushable = n.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. })) && !in_compound; + let stroke = n.and_then(|n| n.appearance.stroke()); + let drawn = + stroke.is_some_and(|s| s.brush.as_deref() == Some(r.name.as_str()) && s.brush_options.is_empty() && s.width > 0.0 && !s.paint.is_none()); + (path, brushable, drawn && vectorcraft_brush::current(&st.doc).as_deref() == Some(r.name.as_str())) + }); + if !path { + return Err(HostError::Type("a brush applies to a PathItem only".into())); + } + if !brushable { + return Err(HostError::Error("a brush does not apply to a guide, a clipping path or a path in a compound path".into())); + } + if !same { + run_on(h, r.doc, "brush.apply", &json!({"name": r.name, "ids": [item.id.0]}))?; + } + Ok(Data::Undefined) +} + +// ---- registration ---- + +/// The enumerations of resources, as frozen objects whose members are `"Name.MEMBER"` strings. +const ENUMS: &[(&str, &[&str])] = &[ + ("SymbolRegistrationPoint", ®ISTRATION), + ("ColorModel", &["PROCESS", "REGISTRATION", "SPOT"]), + ("SpotColorKind", &["SPOTCMYK", "SPOTLAB", "SPOTRGB"]), +]; + +pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(Data::String(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +fn doc_collection(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref(kind.collection(), &[float(h.run), float(doc.uid)])) +} + +fn doc_symbol_items(h: &Host, _: Kind, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("SymbolItems", &[float(h.run), float(doc.uid)])) +} + +/// The members `Document` gets: one collection for each kind, `symbolItems`, and `gradients` and +/// `patterns`, which are not available yet. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![ + ("swatches", kget(l, Kind::Swatch, doc_collection)), + ("spots", kget(l, Kind::Spot, doc_collection)), + ("swatchGroups", kget(l, Kind::Group, doc_collection)), + ("symbols", kget(l, Kind::Symbol, doc_collection)), + ("graphicStyles", kget(l, Kind::Style, doc_collection)), + ("brushes", kget(l, Kind::Brush, doc_collection)), + ("symbolItems", kget(l, Kind::Symbol, doc_symbol_items)), + ]); + m.extend(["gradients", "patterns"].into_iter().map(|n| later(l, "Document", n))); + m +} + +/// The members `SymbolItem` adds to `PageItem`'s. +pub(super) fn symbol_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("symbol", kproperty(l, Kind::Symbol, sitem_symbol, sitem_set_symbol))]) +} + +/// The collection classes, and one class for each kind of resource. +pub(super) fn classes(l: &Link) -> Vec { + let mut out = Vec::new(); + for kind in KINDS { + let mut m = named(vec![ + ("typename", typename_of(kind.collection())), + ("length", kget(l, kind, coll_length)), + ("parent", kget(l, kind, coll_parent)), + ("index", kmethod(l, kind, coll_index)), + ("getByName", kmethod(l, kind, coll_by_name)), + ]); + if kind != Kind::Brush { + m.push(("removeAll".into(), kmethod(l, kind, coll_remove_all))); + } + match kind { + Kind::Swatch => { + m.push(("add".into(), kmethod(l, kind, swatches_add))); + m.push(("getSelected".into(), kmethod(l, kind, swatches_selected))); + } + Kind::Spot => m.push(("add".into(), kmethod(l, kind, spots_add))), + Kind::Group => m.push(("add".into(), kmethod(l, kind, groups_add))), + Kind::Symbol => m.push(("add".into(), kmethod(l, kind, symbols_add))), + Kind::Style | Kind::Brush => {} + } + out.push(class(kind.collection(), None, m, Some(kfunction(l, kind, coll_at)))); + + let mut m = named(vec![("typename", kget(l, kind, res_typename)), ("parent", kget(l, kind, res_parent))]); + if kind == Kind::Brush { + m.push(("name".into(), kget(l, kind, res_name))); + } else { + m.push(("name".into(), kproperty(l, kind, res_name, res_set_name))); + m.push(("remove".into(), kmethod(l, kind, res_remove))); + } + let extra = match kind { + Kind::Swatch => vec![("color", kproperty(l, kind, swatch_color, set_swatch_color))], + Kind::Spot => vec![ + ("color", kproperty(l, kind, spot_color, set_swatch_color)), + ("colorType", kproperty(l, kind, spot_color_type, spot_set_color_type)), + ("spotKind", kget(l, kind, spot_kind)), + ("getInternalColor", kmethod(l, kind, spot_internal)), + ], + Kind::Group => vec![ + ("addSwatch", kmethod(l, kind, group_add_swatch)), + ("addSpot", kmethod(l, kind, group_add_spot)), + ("getAllSwatches", kmethod(l, kind, group_all)), + ("removeAll", kmethod(l, kind, group_remove_all)), + ], + Kind::Symbol => vec![("duplicate", kmethod(l, kind, symbol_duplicate))], + Kind::Style => vec![("applyTo", kmethod(l, kind, style_apply_to)), ("mergeTo", kmethod(l, kind, style_merge_to))], + Kind::Brush => vec![("applyTo", kmethod(l, kind, brush_apply_to))], + }; + m.extend(named(extra)); + out.push(class(kind.class(), None, m, None)); + } + let k = Kind::Symbol; + out.push(class( + "SymbolItems", + None, + named(vec![ + ("typename", typename_of("SymbolItems")), + ("length", kget(l, k, sitems_length)), + ("parent", kget(l, k, sitems_parent)), + ("index", kmethod(l, k, sitems_index)), + ("getByName", kmethod(l, k, sitems_by_name)), + ("add", kmethod(l, k, sitems_add)), + ("removeAll", kmethod(l, k, sitems_remove_all)), + ]), + Some(kfunction(l, k, sitems_at)), + )); + out +} + +#[cfg(test)] +mod tests { + use super::{Kind, MAX_SLOTS, Table}; + + #[test] + fn a_run_holds_a_bounded_number_of_resource_objects() { + let mut t = Table::default(); + for i in 0..MAX_SLOTS { + assert!(t.slot(1, Kind::Swatch, &format!("s{i}")).is_ok()); + } + assert_eq!(t.slot(1, Kind::Swatch, "s0").ok(), Some(0), "a resource already held takes no new slot"); + assert!(t.slot(1, Kind::Swatch, "one more").is_err()); + } + + #[test] + fn a_rename_onto_a_held_name_leaves_the_old_object_stale() { + let mut t = Table::default(); + let (a, b) = (t.slot(1, Kind::Swatch, "A").unwrap_or(9), t.slot(1, Kind::Swatch, "B").unwrap_or(9)); + let spot = t.slot(1, Kind::Spot, "A").unwrap_or(9); + t.rename(1, Kind::Swatch, "A", "B"); + assert_eq!(t.name(a, 1, Kind::Swatch), Some("B")); + assert_eq!(t.name(spot, 1, Kind::Spot), Some("B"), "the spot object follows the swatch's rename"); + assert_eq!(t.name(b, 1, Kind::Swatch), None); + assert_eq!(t.name(a, 2, Kind::Swatch), None, "a slot answers for its own document only"); + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..05f8c30aa6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1297,7 +1297,9 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result 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 RGB document with one rectangle. +fn doc() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + (s, a) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn swatch_names(s: &mut Session) -> Vec { + let l = s.execute("swatch.list", &json!({})).unwrap(); + l["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap().to_string()).collect() +} + +/// The document's resources, to show that a failed call changed nothing. +fn resources(s: &Session) -> String { + let d = &s.active().unwrap().doc; + format!("{:?}{:?}{:?}{:?}{:?}", *d.swatches, *d.swatch_groups, *d.graphic_styles, d.symbols, d.layers) +} + +#[test] +fn swatches_are_live_and_keep_reserved_entries() { + let (mut s, _) = doc(); + let names = swatch_names(&mut s); + let out = log( + &mut s, + "var w = app.activeDocument.swatches; vc.log(w.length); vc.log(w.typename); vc.log(w.parent.typename);\ + vc.log(w[0].name); vc.log(w[1].name); vc.log(w[1].typename); vc.log(w[w.length] === undefined);\ + vc.log(w.getByName('Black').color.typename); vc.log(w.getSelected().length);", + ); + assert_eq!( + out, + vec![ + json!(names.len()), + json!("Swatches"), + json!("Document"), + json!(names[0]), + json!("[Registration]"), + json!("Swatch"), + json!(true), + json!("RGBColor"), + json!(0) + ] + ); + let out = log( + &mut s, + "var w = app.activeDocument.swatches, n = w.add(); n.name = 'Script Ink';\ + var c = new RGBColor(); c.red = 10; c.green = 20; c.blue = 30; n.color = c;\ + vc.log(w.getByName('Script Ink').color.green); vc.log(n.name);", + ); + assert_eq!(out, vec![json!(20), json!("Script Ink")]); + assert!(swatch_names(&mut s).contains(&"Script Ink".to_string())); + let steps = undo_steps(&s); + log(&mut s, "app.activeDocument.swatches.removeAll();"); + assert_eq!(undo_steps(&s), steps + 1); + let left = swatch_names(&mut s); + assert_eq!(left, vec![names[0].clone(), "[Registration]".to_string()]); + for script in ["app.activeDocument.swatches[1].name = 'R';", "app.activeDocument.swatches[0].remove();"] { + assert!(failure(&mut s, script).contains("is built in"), "{script}"); + } + let steps = undo_steps(&s); + log(&mut s, "app.activeDocument.swatches.removeAll();"); + assert_eq!(undo_steps(&s), steps, "a removeAll with nothing to remove records no step"); +} + +#[test] +fn swatches_add_saves_a_gradient_fill_as_a_gradient() { + let (mut s, _) = doc(); + let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"gradient": ramp})).unwrap(); + let out = log(&mut s, "vc.log(app.activeDocument.swatches.add().color.typename);"); + assert_eq!(out, vec![json!("GradientColor")]); +} + +#[test] +fn resource_objects_go_stale_after_remove_and_follow_renames() { + let (mut s, _) = doc(); + let out = log( + &mut s, + "var w = app.activeDocument.swatches.getByName('Black'); w.name = 'Ink'; vc.log(w.name);\ + var again = app.activeDocument.swatches.getByName('Ink'); vc.log(again.name);", + ); + assert_eq!(out, vec![json!("Ink"), json!("Ink")]); + let cases = [ + ("var w = app.activeDocument.swatches.getByName('Ink'); w.remove(); w.name;", "Stale Swatch"), + ("var w = app.activeDocument.swatches.getByName('White'); w.remove(); w.typename;", "Stale Swatch"), + ("var w = app.activeDocument.swatches.getByName('White'); vc.run('swatch.delete', {name: 'White'}); w.color;", "Stale Swatch"), + ( + "var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('graphicStyle.rename', {name: g.name, to: 'X'}); g.name;", + "Stale GraphicStyle", + ), + ("var w = app.activeDocument.swatches.getByName('Red'); w.remove(); app.activeDocument.swatches.add().name = 'Red'; w.name;", "Stale Swatch"), + ( + "var w = app.activeDocument.swatches.getByName('Lime'); vc.run('swatch.delete', {name: 'Lime'}); vc.run('swatch.new', {name: 'Lime', color: '#00ff00'}); w.name;", + "Stale Swatch", + ), + ]; + for (script, message) in cases { + let e = failure(&mut s, script); + assert!(e.contains(message), "{script}: {e}"); + } +} + +#[test] +fn hostile_names_and_values_are_refused_without_change() { + let (mut s, _) = doc(); + let before = resources(&s); + let steps = undo_steps(&s); + let long = "x".repeat(1025); + let cases = [ + ("app.activeDocument.swatches.getByName('Black').name = 'a\\u0007b';".to_string(), "control characters"), + ("app.activeDocument.swatches.getByName('Black').name = ' ';".to_string(), "cannot be empty"), + (format!("app.activeDocument.swatches.getByName('Black').name = '{long}';"), "longer than 1024 bytes"), + ("app.activeDocument.swatches.getByName('Black').name = 7;".to_string(), "must be a string"), + ("app.activeDocument.swatches.getByName('Black').name = 'White';".to_string(), "already exists"), + ("var d = app.activeDocument, p = d.spots.add(); p.name = 'Black';".to_string(), "a swatch or color group named Black already exists"), + ( + "var d = app.activeDocument; d.swatchGroups.add().name = 'Mine'; d.swatches.getByName('White').name = 'Mine';".to_string(), + "a swatch or color group named Mine already exists", + ), + ("app.activeDocument.swatches.getByName('Black').color = new NoColor();".to_string(), "cannot be NoColor"), + ("app.activeDocument.swatches.getByName('Black').color = {typename: 'RGBColor', red: 300};".to_string(), "from 0 to 255"), + ("app.activeDocument.swatches.getByName('nope');".to_string(), "Not found"), + ("app.activeDocument.swatches.index({});".to_string(), "name or an index"), + ("app.activeDocument.symbols.add(app.activeDocument);".to_string(), "not a page item"), + ("app.activeDocument.symbols.add(app.activeDocument.pageItems[0], 'SymbolRegistrationPoint.NOPE');".to_string(), "SymbolRegistrationPoint"), + ("app.activeDocument.symbolItems.add(app.activeDocument.swatches[2]);".to_string(), "not a Symbol"), + ("app.activeDocument.graphicStyles[0].applyTo([app.activeDocument.pageItems[0]]);".to_string(), "one page item"), + ]; + for (script, message) in &cases { + let e = failure(&mut s, script); + assert!(e.contains(message), "{script}: {e}"); + } + assert_eq!(resources(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn spots_keep_their_kind_and_their_document_color_space() { + let (mut s, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.spots.add(); p.name = 'Pea'; p.colorType = ColorModel.SPOT;\ + var c = new RGBColor(); c.red = 90; c.green = 200; c.blue = 30; p.color = c;\ + vc.log(d.spots.length); vc.log(p.typename); vc.log(p.colorType); vc.log(p.spotKind); vc.log(p.getInternalColor());\ + var w = d.swatches.getByName('Pea').color; vc.log(w.typename); vc.log(w.spot.name); vc.log(w.tint);", + ); + assert_eq!( + out, + vec![ + json!(1), + json!("Spot"), + json!("ColorModel.SPOT"), + json!("SpotColorKind.SPOTRGB"), + json!([90, 200, 30]), + json!("SpotColor"), + json!("Pea"), + json!(100) + ] + ); + let before = resources(&s); + for (script, message) in [ + ("var p = app.activeDocument.spots[0]; p.color = new CMYKColor();", "must be an RGBColor"), + ("app.activeDocument.spots[0].colorType = ColorModel.PROCESS;", "stays a spot color"), + ("app.activeDocument.spots[0].colorType = 3;", "ColorModel value"), + ] { + let e = failure(&mut s, script); + assert!(e.contains(message), "{script}: {e}"); + } + assert_eq!(resources(&s), before); + log(&mut s, "var p = app.activeDocument.spots[0]; var l = new LabColor(); l.l = 50; p.color = l;"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots[0].spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]); + log(&mut s, "app.activeDocument.spots.removeAll();"); + assert!(!swatch_names(&mut s).contains(&"Pea".to_string())); +} + +#[test] +fn a_tint_of_a_spot_reads_as_that_spot_at_the_tint() { + let (mut s, _) = doc(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + let tint = s.execute("swatch.new", &json!({"tint": 40})).unwrap()["name"].as_str().unwrap().to_string(); + let out = log( + &mut s, + &format!("var c = app.activeDocument.swatches.getByName('{tint}').color; vc.log(c.typename); vc.log(c.spot.name); vc.log(c.tint);"), + ); + assert_eq!(out, vec![json!("SpotColor"), json!("Ink"), json!(40)]); +} + +#[test] +fn spots_add_converts_the_fill_to_the_document_color_space() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000", "keepModel": true})).unwrap(); + let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }); + assert!(rgb, "the current fill is RGB in a CMYK document"); + let out = log(&mut s, "var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename);"); + assert_eq!(out, vec![json!("SpotColorKind.SPOTCMYK"), json!("CMYKColor")]); +} + +#[test] +fn spots_add_converts_a_cmyk_or_gray_fill_in_an_rgb_document() { + for fill in [json!({"c": 0, "m": 100, "y": 100, "k": 0}), json!({"gray": 40})] { + let (mut s, _) = doc(); + s.execute("paint.setFill", &json!({"color": fill})).unwrap(); + let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }); + assert!(!rgb, "the current fill {fill} is not RGB in an RGB document"); + let out = log( + &mut s, + "var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename); p.color = p.color; vc.log(p.name == '');", + ); + assert_eq!(out, vec![json!("SpotColorKind.SPOTRGB"), json!("RGBColor"), json!(false)], "{fill}"); + } +} + +#[test] +fn color_groups_hold_solid_swatches_only() { + let (mut s, _) = doc(); + s.execute( + "swatch.new", + &json!({"name": "Ramp", "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), + ) + .unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.swatchGroups.add(); g.name = 'Script Group';\ + g.addSwatch(d.swatches.getByName('Black')); g.addSwatch(d.swatches.getByName('Black'));\ + var all = g.getAllSwatches(); vc.log(all.length); vc.log(all[0].name); vc.log(d.swatchGroups.getByName('Script Group').typename);", + ); + assert_eq!(out, vec![json!(1), json!("Black"), json!("SwatchGroup")]); + let before = resources(&s); + for (script, message) in [ + ("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches.getByName('Ramp'));", "solid colors only"), + ("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches[0]);", "is built in"), + ("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSpot(d.swatches.getByName('Black'));", "not a Spot"), + ] { + let e = failure(&mut s, script); + assert!(e.contains(message), "{script}: {e}"); + } + assert_eq!(resources(&s), before); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.swatchGroups.getByName('Script Group'), b = g.getAllSwatches()[0];\ + g.removeAll(); vc.log(g.getAllSwatches().length); try { b.name; } catch (e) { vc.log(String(e.message)); }\ + g.remove(); try { g.name; } catch (e) { vc.log(String(e.message)); }", + ); + assert_eq!(out, vec![json!(0), json!("Stale Swatch"), json!("Stale SwatchGroup")]); +} + +#[test] +fn symbols_add_keeps_the_source_and_instances_follow_their_symbol() { + let (mut s, a) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, n = d.pageItems.length, sym = d.symbols.add(d.pageItems[0], SymbolRegistrationPoint.SYMBOLTOPLEFTPOINT);\ + vc.log(d.pageItems.length === n); vc.log(sym.typename); vc.log(d.symbols.length);\ + sym.name = 'Mark'; var copy = sym.duplicate(); vc.log(copy.name);\ + var inst = d.symbolItems.add(sym); vc.log(inst.typename); vc.log(inst.symbol.name); vc.log(d.symbolItems.length);\ + inst.symbol = copy; vc.log(inst.symbol.name); vc.log(d.selection === null);", + ); + assert_eq!( + out, + vec![ + json!(true), + json!("Symbol"), + json!(1), + json!("Mark copy"), + json!("SymbolItem"), + json!("Mark"), + json!(1), + json!("Mark copy"), + json!(true) + ] + ); + assert!(s.active().unwrap().doc.node(a).is_some(), "the source art stays"); + let l = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!(l["symbols"][0]["registration"], json!(0)); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.symbolItems.removeAll(); vc.log(d.symbols.length);"); + assert_eq!(undo_steps(&s), steps + 1); + let out = log( + &mut s, + "var d = app.activeDocument, sym = d.symbols[0]; d.symbols.removeAll(); vc.log(d.symbols.length); try { sym.name; } catch (e) { vc.log(String(e.message)); }", + ); + assert_eq!(out, vec![json!(0), json!("Stale Symbol")]); +} + +#[test] +fn resources_refuse_objects_of_another_document() { + let (mut s, _) = doc(); + log(&mut s, "var d = app.activeDocument; d.symbols.add(d.pageItems[0]);"); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let before = resources(&s); + for script in [ + "var a = app.documents[0], b = app.documents[1]; b.symbolItems.add(a.symbols[0]);", + "var a = app.documents[0], b = app.documents[1]; a.graphicStyles[0].applyTo(b.pageItems[0]);", + "var a = app.documents[0], b = app.documents[1]; b.swatchGroups.add().addSwatch(a.swatches.getByName('Black'));", + "var a = app.documents[0], b = app.documents[1]; a.symbols.add(b.pageItems[0]);", + ] { + let e = failure(&mut s, script); + assert!(e.contains("Cross-document"), "{script}: {e}"); + } + assert_eq!(resources(&s), before); +} + +#[test] +fn graphic_styles_apply_replaces_and_merge_adds() { + let (mut s, a) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Red"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.graphicStyles.getByName('Red'); vc.log(g.typename); vc.log(d.graphicStyles.typename);\ + g.applyTo(d.pageItems[1]);", + ); + assert_eq!(out, vec![json!("GraphicStyle"), json!("GraphicStyles")]); + let id = s.active().unwrap().doc.graphic_style("Red").unwrap().id; + let n = s.active().unwrap().doc.node(b).unwrap().clone(); + assert_eq!(n.extras().graphic_style, Some(id)); + let fills = n.appearance.items.len(); + log(&mut s, "var d = app.activeDocument; d.graphicStyles.getByName('Red').mergeTo(d.pageItems[1]);"); + let n = s.active().unwrap().doc.node(b).unwrap().clone(); + assert!(n.appearance.items.len() > fills, "merge adds the style's rows"); + assert_eq!(n.extras().graphic_style, None); + let before = resources(&s); + for script in [ + "app.activeDocument.graphicStyles.getByName('Default Graphic Style').name = 'Plain';", + "app.activeDocument.graphicStyles.getByName('Default Graphic Style').remove();", + ] { + let e = failure(&mut s, script); + assert!(e.contains("is built in"), "{script}: {e}"); + } + assert_eq!(resources(&s), before); + log(&mut s, "app.activeDocument.graphicStyles.removeAll();"); + let left: Vec = s.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect(); + assert_eq!(left, vec![crate::doc::DEFAULT_GRAPHIC_STYLE.to_string()]); +} + +#[test] +fn brushes_apply_to_paths_only_and_once() { + let (mut s, a) = doc(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let first = s.execute("brush.list", &json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string(); + let out = log( + &mut s, + "var b = app.activeDocument.brushes; vc.log(b.typename); vc.log(b[0].typename); vc.log(b[0].name); vc.log(b.removeAll === undefined);", + ); + assert_eq!(out, vec![json!("Brushes"), json!("Brush"), json!(first), json!(true)]); + let before = resources(&s); + let e = failure(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pageItems[1]);"); + assert!(e.contains("PathItem only"), "{e}"); + assert_eq!(resources(&s), before); + log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);"); + let st = s.active().unwrap().doc.node(a).unwrap().appearance.stroke().cloned().unwrap(); + assert_eq!(st.brush.as_deref(), Some(first.as_str())); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);"); + assert_eq!(undo_steps(&s), steps, "applying the brush a path already draws runs no command"); +} + +#[test] +fn brushes_refuse_guides_clipping_paths_and_compound_members() { + let (mut s, a) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let (m1, m2) = (rect(&mut s, 100.0, 20.0, 30.0, 40.0), rect(&mut s, 150.0, 20.0, 30.0, 40.0)); + s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let (c1, c2) = (rect(&mut s, 200.0, 20.0, 30.0, 40.0), rect(&mut s, 210.0, 30.0, 10.0, 10.0)); + s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let pick = |test: &str| { + format!( + "var d = app.activeDocument, p = null; for (var i = 0; i < d.pathItems.length; i++) {{ var q = d.pathItems[i]; if ({test}) p = q; }}\ + d.brushes[0].applyTo(p);" + ) + }; + for test in ["q.guides", "q.clipping", "q.parent.typename == 'CompoundPathItem'"] { + let before = resources(&s); + let steps = undo_steps(&s); + let e = failure(&mut s, &pick(test)); + assert!(e.contains("does not apply to a guide"), "{test}: {e}"); + assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "{test}"); + } +} + +#[test] +fn several_resource_edits_are_one_undo_step_and_a_failure_puts_them_back() { + let (mut s, _) = doc(); + let steps = undo_steps(&s); + log(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'One'; d.spots.add().name = 'Two'; d.swatchGroups.add().name = 'Three';"); + assert_eq!(undo_steps(&s), steps + 1); + let before = resources(&s); + let e = failure(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'Four'; d.swatches.removeAll(); throw new Error('stop');"); + assert!(e.contains("stop"), "{e}"); + assert_eq!(resources(&s), before); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 828a97f585..1417bafd98 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,10 +73,11 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ - DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType PolarityValues RulerUnits StrokeCap \ - StrokeJoin Transformation ZOrderMethod", + "app Application Brush Brushes ColorModel CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement \ + GraphicStyle GraphicStyles Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \ + PointType PolarityValues RulerUnits Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \ + Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Transformation ZOrderMethod", ), ("Application.", "prototype"), ( @@ -89,10 +90,10 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ - views views= width", + "activeLayer activeLayer= artboards artboards= brushes close close= constructor convertCoordinate \ + documentColorSpace gradients gradients= graphicStyles groupItems groupItems= height layers layers= name pageItems \ + parent pathItems patterns patterns= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= spots \ + swatchGroups swatches symbolItems symbols textFrames textFrames= typename views views= width", ), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name typename"), @@ -127,6 +128,35 @@ const INSIDE: &[(&str, &str)] = &[ "anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \ rightDirection= selected selected= typename", ), + ("Swatches.", "prototype"), + ("Swatches.prototype.", "add constructor getByName getSelected index length parent removeAll typename"), + ("Swatch.", "prototype"), + ("Swatch.prototype.", "color color= constructor name name= parent remove typename"), + ("Spots.", "prototype"), + ("Spots.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Spot.", "prototype"), + ("Spot.prototype.", "color color= colorType colorType= constructor getInternalColor name name= parent remove spotKind typename"), + ("SwatchGroups.", "prototype"), + ("SwatchGroups.prototype.", "add constructor getByName index length parent removeAll typename"), + ("SwatchGroup.", "prototype"), + ("SwatchGroup.prototype.", "addSpot addSwatch constructor getAllSwatches name name= parent remove removeAll typename"), + ("Symbols.", "prototype"), + ("Symbols.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Symbol.", "prototype"), + ("Symbol.prototype.", "constructor duplicate name name= parent remove typename"), + ("SymbolItems.", "prototype"), + ("SymbolItems.prototype.", "add constructor getByName index length parent removeAll typename"), + ("SymbolItem.", "prototype"), + ("SymbolItem.prototype.", "constructor symbol symbol="), + ("GraphicStyles.", "prototype"), + ("GraphicStyles.prototype.", "constructor getByName index length parent removeAll typename"), + ("GraphicStyle.", "prototype"), + ("GraphicStyle.prototype.", "applyTo constructor mergeTo name name= parent remove typename"), + ("Brushes.", "prototype"), + ("Brushes.prototype.", "constructor getByName index length parent typename"), + ("Brush.", "prototype"), + ("Brush.prototype.", "applyTo constructor name parent typename"), + ("ColorModel.", "PROCESS REGISTRATION SPOT"), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), @@ -143,17 +173,23 @@ const INSIDE: &[(&str, &str)] = &[ ("PointType.", "CORNER SMOOTH"), ("PolarityValues.", "NEGATIVE POSITIVE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("SpotColorKind.", "SPOTCMYK SPOTLAB SPOTRGB"), ("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"), ("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"), + ( + "SymbolRegistrationPoint.", + "SYMBOLBOTTOMLEFTPOINT SYMBOLBOTTOMMIDDLEPOINT SYMBOLBOTTOMRIGHTPOINT SYMBOLCENTERPOINT SYMBOLMIDDLELEFTPOINT \ + SYMBOLMIDDLERIGHTPOINT SYMBOLTOPLEFTPOINT SYMBOLTOPMIDDLEPOINT SYMBOLTOPRIGHTPOINT", + ), ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, -/// the page item types other than `PathItem`, and the color classes. +/// the page item types other than `PathItem` and `SymbolItem`, and the color classes. const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem DocumentPreset EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ - SymbolItem TextFrame cmykColor"; + TextFrame cmykColor"; /// 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. diff --git a/docs/mcp.md b/docs/mcp.md index 44d375ae2c..6be7ad8868 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2724,6 +2724,46 @@ app through the global object `vc`, and writes to the Script Console and runs ot shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `selectedPathPoints`, `PathPoint.selected`, `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. +- A `Document` also has `swatches`, `spots`, `swatchGroups`, `symbols`, `symbolItems`, `graphicStyles` and `brushes` + (https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, + https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroups/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, + https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItems/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyles/ + and https://ai-scripting.docsforadobe.dev/jsobjref/Brushes/). Each has `length`, `parent`, `[i]`, `index(key)` and + `getByName(name)`; all but `brushes` have `removeAll()`. `swatches.add()` and `spots.add()` run `swatch.new`, + `swatchGroups.add()` runs `swatch.newGroup`, `symbols.add(sourceArt, registrationPoint?)` runs `symbol.new` with + `keepArt: true` (the default point is `SymbolRegistrationPoint.SYMBOLCENTERPOINT`), and `symbolItems.add(symbol)` + runs `symbol.place`. `swatches.getSelected()` gives `[]`. A `Swatch` (https://ai-scripting.docsforadobe.dev/jsobjref/Swatch/) + has `name` and `color` (`swatch.edit`) and `remove()` (`swatch.delete`); a spot swatch's `color` reads as a + `SpotColor` with its `spot` and a `tint` of 100, and a tint of a spot as that `spot` at its `tint`. A `Spot` (https://ai-scripting.docsforadobe.dev/jsobjref/Spot/) has + `name`, `color`, `colorType`, `spotKind`, `getInternalColor()` and `remove()`. A `SwatchGroup` + (https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/) has `name` (`swatch.renameGroup`), `addSwatch(swatch)` + and `addSpot(spot)` (`swatch.move`), `getAllSwatches()`, `remove()` and `removeAll()`. A `Symbol` + (https://ai-scripting.docsforadobe.dev/jsobjref/Symbol/) has `name` (`symbol.options`), `duplicate()` + (`symbol.duplicate`) and `remove()` (`symbol.delete`), and a `SymbolItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/) adds `symbol` to the page item members, which + `symbol.replace` changes. A `GraphicStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/) has `name` + (`graphicStyle.rename`), `applyTo(item)` and `mergeTo(item)` (`graphicStyle.apply`, with `add: true` for `mergeTo`) + and `remove()` (`graphicStyle.delete`). A `Brush` (https://ai-scripting.docsforadobe.dev/jsobjref/Brush/) has a + read-only `name` and `applyTo(item)` (`brush.apply`). The enumerations `SymbolRegistrationPoint`, `ColorModel` and + `SpotColorKind` hold strings such as `"ColorModel.SPOT"`. + VectorCraft's own rules: `swatches` lists None, Registration, the other ungrouped swatches and then each color + group's, and `swatchGroups` lists the color groups. `swatches.add()` saves the current fill (a color, gradient or + pattern) or black when the fill is None, and `spots.add()` the current fill, converted to the document's color + space unless it is Lab, or black when it is not a solid color. None and Registration cannot change or be removed, + and `removeAll()` keeps them; the Default Graphic Style cannot be renamed or removed, and + `graphicStyles.removeAll()` keeps it. A color group takes solid + colors only; `SwatchGroup.remove()` deletes the group with its swatches, and its `removeAll()` deletes the swatches + and keeps the group. A spot's color is in the document's color space or Lab, its `colorType` takes only + `ColorModel.SPOT`, a gray spot's `spotKind` is `SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the + components on the color classes' scales. `symbols.add` leaves the source art as it is, and removing a symbol turns + its instances into plain art. `applyTo` and `mergeTo` take one page item of the same document that can be edited, + and `Brush.applyTo` a path that is not a guide, a clipping path or a path in a compound path; applying the brush a + path already draws runs no command. A name is 1 to 1,024 bytes, not blank, with no control characters, and a name a + swatch, spot or color group already has throws for any of the three. Renaming a resource through these objects keeps the object; after it is + removed, or renamed or deleted with `vc.run`, every member throws `Stale Swatch` (`Stale Spot`, `Stale SwatchGroup`, + `Stale Symbol`, `Stale GraphicStyle`, `Stale Brush`). A run holds at most 100,000 of these objects. An object of + another document throws `Cross-document placement is not available`. `Document.gradients`, `Document.patterns` and + assigning a `SpotColor` to art are not available yet. - `$.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 81abb83e94..887c7323f5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.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 d0f3a07cc92a655783c3156f0c066a0302feae56 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:28:06 -0800 Subject: [PATCH 002/213] Scripts: charge resource checks and symbolItems scans to the run - After each vc.run, the check that leaves removed swatches, symbols, styles and brushes stale visits only the documents that changed since the last check, and the slots and names it compares are charged to the run. - SymbolItems charges the page items it scans for symbol instances, as pageItems.getByName does. - ROADMAP's M13 row lists the swatches, spots, color groups, symbols, graphic styles and brushes scripts now have. --- crates/engine/src/script/dom.rs | 7 +- crates/engine/src/script/dom/resources.rs | 119 +++++++++++++++------- crates/engine/src/script/mod.rs | 5 +- docs/roadmap.md | 2 +- 4 files changed, 89 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1e8f503634..c2df2bb1f1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -133,9 +133,10 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result std::result::Result<(), HostError> { + resources::forget_removed(h) } /// A document's uid, the document as it was, and the ids of its page items then. diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index 503d5e5abe..fd4ff75d41 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -121,57 +121,61 @@ const KINDS: [Kind; 6] = [Kind::Swatch, Kind::Spot, Kind::Group, Kind::Symbol, K #[derive(Default)] pub(super) struct Table { slots: Vec<(u64, Kind, Option)>, - index: HashMap<(u64, Kind, String), usize>, + /// For each document's uid, the slot of each kind and name it holds. + index: HashMap>, /// Each document as [`forget_removed`] last checked it. checked: HashMap>, } impl Table { /// Marks every slot stale whose document is no longer open, or whose resource `docs` no - /// longer has. A document unchanged since the last check is skipped. - fn forget(&mut self, docs: &[DocState]) { - if self.index.is_empty() { - return; - } - let uids: HashSet = self.index.keys().map(|(u, ..)| *u).collect(); - for uid in uids { - let st = docs.iter().find(|d| d.uid == uid); - if let (Some(st), Some(seen)) = (st, self.checked.get(&uid)) + /// longer has. A document unchanged since the last check is skipped, and its slots are not + /// visited. → how many slots and resource names it compared. + fn forget(&mut self, docs: &[DocState]) -> u64 { + let mut work = 0u64; + for (uid, held) in &mut self.index { + let st = docs.iter().find(|d| d.uid == *uid); + if let (Some(st), Some(seen)) = (st, self.checked.get(uid)) && Arc::ptr_eq(seen, &st.doc) { continue; } + work += held.len() as u64; let mut present: HashMap> = HashMap::new(); - let gone: Vec<(u64, Kind, String)> = self - .index - .keys() - .filter(|(u, k, n)| { - *u == uid && st.is_none_or(|st| !present.entry(*k).or_insert_with(|| names(&st.doc, *k).into_iter().collect()).contains(n)) - }) - .cloned() - .collect(); - for key in gone { - if let Some(i) = self.index.remove(&key) { - self.slots[i].2 = None; + let slots = &mut self.slots; + held.retain(|(k, n), i| { + let kept = st.is_some_and(|st| present.entry(*k).or_insert_with(|| names(&st.doc, *k).into_iter().collect()).contains(n)); + if !kept { + slots[*i].2 = None; } - } + kept + }); + work += present.values().map(|p| p.len() as u64).sum::(); match st { - Some(st) => self.checked.insert(uid, st.doc.clone()), - None => self.checked.remove(&uid), + Some(st) => self.checked.insert(*uid, st.doc.clone()), + None => self.checked.remove(uid), }; } + let checked = &mut self.checked; + self.index.retain(|uid, held| { + if held.is_empty() { + checked.remove(uid); + } + !held.is_empty() + }); + work } /// The slot of `name`, made when there is none. fn slot(&mut self, uid: u64, kind: Kind, name: &str) -> std::result::Result { - if let Some(i) = self.index.get(&(uid, kind, name.to_string())) { + if let Some(i) = self.index.get(&uid).and_then(|held| held.get(&(kind, name.to_string()))) { return Ok(*i); } if self.slots.len() >= MAX_SLOTS { return Err(HostError::Range(format!("a script may hold at most {MAX_SLOTS} swatches, symbols, styles and brushes"))); } self.slots.push((uid, kind, Some(name.to_string()))); - self.index.insert((uid, kind, name.to_string()), self.slots.len() - 1); + self.index.entry(uid).or_default().insert((kind, name.to_string()), self.slots.len() - 1); Ok(self.slots.len() - 1) } @@ -187,18 +191,20 @@ impl Table { /// before go stale. fn rename(&mut self, uid: u64, kind: Kind, from: &str, to: &str) { self.remove(uid, kind, to); + let Some(held) = self.index.get_mut(&uid) else { return }; for k in kind.family() { - if let Some(i) = self.index.remove(&(uid, *k, from.to_string())) { + if let Some(i) = held.remove(&(*k, from.to_string())) { self.slots[i].2 = Some(to.to_string()); - self.index.insert((uid, *k, to.to_string()), i); + held.insert((*k, to.to_string()), i); } } } /// The resource `name` of the family of `kind` is gone. fn remove(&mut self, uid: u64, kind: Kind, name: &str) { + let Some(held) = self.index.get_mut(&uid) else { return }; for k in kind.family() { - if let Some(i) = self.index.remove(&(uid, *k, name.to_string())) { + if let Some(i) = held.remove(&(*k, name.to_string())) { self.slots[i].2 = None; } } @@ -206,9 +212,16 @@ impl Table { } /// After a `vc.run` command: the objects whose resource the command removed or renamed go stale. -pub(super) fn forget_removed(h: &Host) { - let s = h.session.borrow(); - h.dom.resources.borrow_mut().forget(s.documents()); +/// The slots and names the check compares are charged to the run. +pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> { + let work = { + let s = h.session.borrow(); + h.dom.resources.borrow_mut().forget(s.documents()) + }; + if work > 0 { + h.charge_call(work)?; + } + Ok(()) } type Kfn = fn(&Host, Kind, &[Data]) -> Answer; @@ -799,15 +812,20 @@ fn symbol_duplicate(h: &Host, kind: Kind, a: &[Data]) -> Answer { resource_ref(h, r.doc.uid, Kind::Symbol, &name) } -/// The ids of a document's symbol instances, in the order of its page items. -fn instances(h: &Host, st: &DocState) -> Vec { - page_items(h, st).iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))).collect() +/// The ids of a document's symbol instances, in the order of its page items, and how many page +/// items it looked at. +fn instances(h: &Host, st: &DocState) -> (Vec, usize) { + let items = page_items(h, st); + let ids = items.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))).collect(); + (ids, items.len()) } +/// The document of `SymbolItems` and its symbol instances; the page items scanned for them are +/// charged to the run. fn instances_of(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Vec), HostError> { let doc = doc_of(h, arg(a, 0), "SymbolItems")?; - let ids = with_doc(h, doc, |_, st| instances(h, st)); - h.charge_call(ids.len() as u64)?; + let (ids, scanned) = with_doc(h, doc, |_, st| instances(h, st)); + h.charge_call(scanned as u64)?; Ok((doc, ids)) } @@ -1104,7 +1122,32 @@ pub(super) fn classes(l: &Link) -> Vec { #[cfg(test)] mod tests { - use super::{Kind, MAX_SLOTS, Table}; + use std::sync::Arc; + + use super::{Kind, MAX_SLOTS, Table, names}; + use crate::{DocState, Document}; + + #[test] + fn a_check_visits_only_the_documents_that_changed() { + let mut docs = vec![DocState::new(Document::new(612.0, 792.0), None), DocState::new(Document::new(612.0, 792.0), None)]; + let (one, two) = (docs[0].uid, docs[1].uid); + let held = names(&docs[0].doc, Kind::Swatch); + assert!(held.len() > 1, "a new document has swatches"); + let mut t = Table::default(); + let slots: Vec = held.iter().map(|n| t.slot(one, Kind::Swatch, n).unwrap_or(usize::MAX)).collect(); + let other = t.slot(two, Kind::Swatch, &held[0]).unwrap_or(usize::MAX); + assert!(t.forget(&docs) > 0, "the first check compares every held slot"); + assert_eq!(t.forget(&docs), 0, "documents unchanged since the last check are not visited"); + docs[1].doc = Arc::new((*docs[1].doc).clone()); + let names_of_two = names(&docs[1].doc, Kind::Swatch).len() as u64; + assert_eq!(t.forget(&docs), 1 + names_of_two, "only the changed document's slot and names are compared"); + assert_eq!(t.name(other, two, Kind::Swatch), Some(held[0].as_str())); + assert!(slots.iter().zip(&held).all(|(s, n)| t.name(*s, one, Kind::Swatch) == Some(n.as_str()))); + docs.remove(0); + assert_eq!(t.forget(&docs), held.len() as u64, "a closed document's slots are compared once"); + assert!(slots.iter().all(|s| t.name(*s, one, Kind::Swatch).is_none()), "a closed document's objects go stale"); + assert_eq!(t.forget(&docs), 0); + } #[test] fn a_run_holds_a_bounded_number_of_resource_objects() { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index eac3b1fbc2..cb03379adb 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1298,8 +1298,9 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result`/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; scripts have `app`, the open documents, new documents, each document's selection and its page items, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, type, the selected path points, gradient stops and the other classes) 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, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms, and each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; the rest of the script document model (layers, artboards, type, the selected path points, gradient stops, gradients, patterns 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 3d074c864fcfb38613c9619266cb3f57cf080145 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 10:29:07 -0800 Subject: [PATCH 003/213] Scripts: paths take a SpotColor, and spots take a color of either space and list Registration - Assigning a SpotColor to a path's fillColor or strokeColor links the paint to its spot at its tint with paint.setFill or paint.setStroke (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). The spot must be a Spot of the path's document, and the tint runs from 0 to 100. Reading the paint back gives the SpotColor with its spot, so assigning it again records no undo step. - Spot.color takes an RGBColor, a CMYKColor or a LabColor in a document of either color space, and the spot keeps that color space, as the Swatches panel's spots do. A GrayColor still throws. - doc.spots lists Registration, whose colorType reads ColorModel.REGISTRATION and which cannot be renamed, recolored or removed; removeAll() keeps it. Registration's swatch color reads as a SpotColor of it. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/colors.rs | 19 +++- crates/engine/src/script/dom/paths.rs | 22 ++++- crates/engine/src/script/dom/resources.rs | 90 ++++++++++++------- crates/engine/src/tests/script_dom_paths.rs | 55 +++++++++++- .../engine/src/tests/script_dom_resources.rs | 58 ++++++++++-- docs/mcp.md | 13 ++- docs/target-app-parity.md | 2 +- 7 files changed, 207 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 34c1496054..272a3aa9a8 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -13,8 +13,9 @@ //! VectorCraft's own rules, which the help pages do not state: components left out count as 0; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page -//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not -//! assigned yet. +//! says. A `SpotColor` () can be +//! assigned to a path's `fillColor` and `strokeColor`, not to a swatch's `color`. `GradientColor` +//! and `PatternColor` can be read from an object but not assigned yet. use std::rc::Rc; @@ -100,8 +101,20 @@ fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) - } } +/// The `spot` and the `tint` (0 to 100, 0 when left out) of `d` when it is a `SpotColor`, else +/// `None`. +pub(super) fn spot_parts(d: &Data) -> std::result::Result, HostError> { + let Data::Object(o) = d else { return Ok(None) }; + if !matches!(o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v), Some(Data::String(s)) if s == "SpotColor") { + return Ok(None); + } + let tint = component(o, "SpotColor", "tint", 0.0, 100.0)?; + let spot = o.iter().find(|(k, _)| k == "spot").map_or(&Data::Undefined, |(_, v)| v); + Ok(Some((spot, tint))) +} + #[allow(clippy::cast_possible_truncation)] -fn unit(v: f64, scale: f64) -> f32 { +pub(super) fn unit(v: f64, scale: f64) -> f32 { (v / scale) as f32 } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 29b0c909be..58bbad61fd 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -738,14 +738,32 @@ fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer { } fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer { - Ok(colors::of_paint(&this_look(h, a)?.1.fill)) + let (item, look) = this_look(h, a)?; + super::resources::paint_color(h, item.doc, &look.fill) } fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer { - Ok(colors::of_paint(&this_look(h, a)?.1.stroke)) + let (item, look) = this_look(h, a)?; + super::resources::paint_color(h, item.doc, &look.stroke) +} + +/// Links the fill (`fill`) or the stroke to the Spot `spot` at `tint` (0 to 100), unless it is +/// linked to it at that tint already. +fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer { + let (item, look) = this_look(h, a)?; + let name = super::resources::assigned_spot(h, spot, item.doc)?; + let now = if fill { &look.fill } else { &look.stroke }; + let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && *t == colors::unit(tint, 100.0)); + if !same { + edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?; + } + Ok(Data::Undefined) } fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer { + if let Some((spot, tint)) = colors::spot_parts(arg(a, 1))? { + return set_spot_color(h, a, fill, spot, tint); + } let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?; let (item, look) = this_look(h, a)?; let now = if fill { &look.fill } else { &look.stroke }; diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index fd4ff75d41..58e35759af 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -24,7 +24,8 @@ //! or deletion that `vc.run` makes, leaves the object stale, and every member then throws //! `Stale Swatch` (`Stale Symbol`, and so on). //! - `swatches` lists the swatches in the Swatches panel's order: None, Registration, the other -//! ungrouped swatches, then each color group's. `swatchGroups` lists the color groups only. +//! ungrouped swatches, then each color group's. `spots` lists Registration and the spot colors in +//! the same order. `swatchGroups` lists the color groups only. //! - `swatches.add()` saves the current fill (a color, gradient or pattern) as a swatch, or black //! when the fill is None; `spots.add()` saves the current fill, in the document's color space //! unless it is Lab, or black when it is not a solid color, as a spot color. `getSelected()` gives @@ -34,10 +35,13 @@ //! `graphicStyles.removeAll()` keeps it. //! - `SwatchGroup.remove()` deletes the group and its swatches; `removeAll()` deletes its swatches //! and keeps the group. A group holds solid colors only. -//! - A spot's color must be in the document's color space (RGB or CMYK) or Lab. `colorType` reads -//! `ColorModel.SPOT` and takes only that value. `spotKind` reads `SpotColorKind.SPOTCMYK` for a -//! gray spot. `getInternalColor()` gives the components on the scale of the color classes -//! (0 to 255 for RGB, 0 to 100 for CMYK and gray, L*a*b* as is). +//! - `Spot.color` takes an RGB, CMYK or Lab color in a document of either color space, and the +//! spot keeps that color space. `colorType` reads `ColorModel.SPOT`, or +//! `ColorModel.REGISTRATION` for Registration, and takes only that value. `spotKind` reads +//! `SpotColorKind.SPOTCMYK` for a gray spot. `getInternalColor()` gives the components on the +//! scale of the color classes (0 to 255 for RGB, 0 to 100 for CMYK and gray, L*a*b* as is). +//! - A `SpotColor` assigned to a path's `fillColor` or `strokeColor` links the paint to its `spot`, +//! a Spot of the path's document, at its `tint`; reading the paint back gives that `spot`. //! - `symbols.add(art)` keeps the art where it is and does not make it an instance. //! `Symbol.remove()` and `symbols.removeAll()` turn the instances into plain art. //! - `applyTo` and `mergeTo` take one page item of the same document that can be edited; @@ -278,11 +282,16 @@ fn find_swatch<'a>(d: &'a Document, name: &str) -> Option<(&'a Swatch, Option<&' all_swatches(d).into_iter().find(|(w, _)| w.name == name) } +/// Whether `spots` lists `w`: a spot color, or Registration. +fn is_spot(w: &Swatch) -> bool { + w.spot || w.name == swatch::REGISTRATION +} + /// The names of the resources of `kind` in `d`, in their panel's order. fn names(d: &Document, kind: Kind) -> Vec { match kind { Kind::Swatch => all_swatches(d).into_iter().map(|(w, _)| w.name.clone()).collect(), - Kind::Spot => all_swatches(d).into_iter().filter(|(w, _)| w.spot).map(|(w, _)| w.name.clone()).collect(), + Kind::Spot => all_swatches(d).into_iter().filter(|(w, _)| is_spot(w)).map(|(w, _)| w.name.clone()).collect(), Kind::Group => d.swatch_groups.iter().map(|g| g.name.clone()).collect(), Kind::Symbol => d.symbols.iter().map(|s| s.name.clone()).collect(), Kind::Style => d.graphic_styles.iter().map(|g| g.name.clone()).collect(), @@ -294,7 +303,7 @@ fn names(d: &Document, kind: Kind) -> Vec { fn exists(d: &Document, kind: Kind, name: &str) -> bool { match kind { Kind::Swatch => find_swatch(d, name).is_some(), - Kind::Spot => find_swatch(d, name).is_some_and(|(w, _)| w.spot), + Kind::Spot => find_swatch(d, name).is_some_and(|(w, _)| is_spot(w)), Kind::Group => d.swatch_groups.iter().any(|g| g.name == name), Kind::Symbol => d.symbols.iter().any(|s| s.name == name), Kind::Style => d.graphic_style(name).is_some(), @@ -645,26 +654,43 @@ fn res_remove(h: &Host, kind: Kind, a: &[Data]) -> Answer { fn swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { let r = this_res(h, a, kind)?; let w = swatch_now(h, &r, kind)?; - if w.spot && w.tint_of().is_none() { + if is_spot(&w) && w.tint_of().is_none() { let spot = resource_ref(h, r.doc.uid, Kind::Spot, &w.name)?; return Ok(Data::Object(vec![("typename".into(), text("SpotColor")), ("spot".into(), spot), ("tint".into(), num(100.0))])); } - let color = colors::of_paint(&w.paint); - let base = match &w.paint { - Paint::Solid { swatch: Some(base), .. } => { - with_doc(h, r.doc, |_, st| find_swatch(&st.doc, base).is_some_and(|(b, _)| b.spot)).then(|| base.clone()) - } + paint_color(h, r.doc, &w.paint) +} + +/// What reading `paint` in the document `doc` gives: a new color object, whose `spot` names the +/// Spot when `paint` is linked to one. +pub(super) fn paint_color(h: &Host, doc: Doc, paint: &Paint) -> Answer { + let color = colors::of_paint(paint); + let base = match paint { + Paint::Solid { swatch: Some(base), .. } => with_doc(h, doc, |_, st| exists(&st.doc, Kind::Spot, base)).then(|| base.clone()), _ => None, }; match (color, base) { (Data::Object(mut o), Some(base)) => { - o.insert(1, ("spot".into(), resource_ref(h, r.doc.uid, Kind::Spot, &base)?)); + o.insert(1, ("spot".into(), resource_ref(h, doc.uid, Kind::Spot, &base)?)); Ok(Data::Object(o)) } (color, _) => Ok(color), } } +/// The name of the Spot that the `spot` of a `SpotColor` assigned to a page item of the document +/// `doc` names. +pub(super) fn assigned_spot(h: &Host, spot: &Data, doc: Doc) -> std::result::Result { + if handle_of(spot, Kind::Spot.class()).is_none() { + return Err(HostError::Type("SpotColor.spot must be a Spot".into())); + } + let r = resource_of(h, spot, Kind::Spot)?; + if r.doc.uid != doc.uid { + return Err(HostError::Error(CROSS_DOCUMENT.into())); + } + Ok(r.name) +} + /// `Spot.color`: the spot's own color, as a new color object. fn spot_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { let r = this_res(h, a, kind)?; @@ -685,12 +711,8 @@ fn set_swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { Paint::Solid { .. } => return Err(HostError::Error(format!("{} is a tint of another swatch; change that swatch's color", r.name))), _ => return Err(HostError::Error(format!("{} is not a solid color", r.name))), }; - if w.spot { - let cmyk = is_cmyk(h, r.doc); - if !fits_spot(cmyk, color) { - let space = if cmyk { "a CMYKColor" } else { "an RGBColor" }; - return Err(HostError::Error(format!("a spot's color must be {space} in this document, or a LabColor"))); - } + if w.spot && matches!(color, Color::Gray { .. }) { + return Err(HostError::Error("a spot's color must be an RGBColor, a CMYKColor or a LabColor".into())); } if now == color { return Ok(Data::Undefined); @@ -699,22 +721,28 @@ fn set_swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// The `ColorModel` of the Spot `name`: Registration's own, or `SPOT`. +fn spot_model(name: &str) -> &'static str { + if name == swatch::REGISTRATION { "ColorModel.REGISTRATION" } else { "ColorModel.SPOT" } +} + fn spot_color_type(h: &Host, kind: Kind, a: &[Data]) -> Answer { - this_res(h, a, kind)?; - Ok(text("ColorModel.SPOT")) + Ok(text(spot_model(&this_res(h, a, kind)?.name))) } fn spot_set_color_type(h: &Host, kind: Kind, a: &[Data]) -> Answer { - match arg(a, 1) { - Data::String(s) if s == "ColorModel.SPOT" => { - this_res(h, a, kind)?; - Ok(Data::Undefined) - } - Data::String(s) if s == "ColorModel.PROCESS" || s == "ColorModel.REGISTRATION" => { - Err(HostError::Error("a Spot stays a spot color; edit it through its Swatch".into())) - } - _ => Err(HostError::Type("colorType must be a ColorModel value".into())), + let model = match arg(a, 1) { + Data::String(s) if ["ColorModel.SPOT", "ColorModel.PROCESS", "ColorModel.REGISTRATION"].contains(&s.as_str()) => s.as_str(), + _ => return Err(HostError::Type("colorType must be a ColorModel value".into())), + }; + let r = this_res(h, a, kind)?; + if model == spot_model(&r.name) { + return Ok(Data::Undefined); } + if r.name == swatch::REGISTRATION { + return Err(reserved(&r.name)); + } + Err(HostError::Error("a Spot stays a spot color; edit it through its Swatch".into())) } fn spot_color_of(h: &Host, kind: Kind, a: &[Data]) -> std::result::Result { diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 004c02f4fc..baaab3f531 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -334,12 +334,59 @@ fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() { let (mut s, a) = doc_with_paints(); s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap(); let before = node(&s, a).appearance.fill_paint(); - let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.tint]);"); - assert_eq!(rounded(&out[0]), json!(["SpotColor", 40])); - assert!(failure(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").contains("SpotColor is not available yet")); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint]);"); + assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 40])); + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;"); + assert_eq!(undo_steps(&s), steps, "assigning the spot color the fill has records no step"); assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch"); } +#[test] +fn a_spot_color_paints_its_spot_at_its_tint() { + let (mut s, a) = doc_with_paints(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink'); c.tint = 50;\ + p.fillColor = c; p.strokeColor = c; vc.log([p.fillColor.typename, p.fillColor.spot.name, p.fillColor.tint, p.strokeColor.tint]);", + ); + assert_eq!(rounded(&out[0]), json!(["SpotColor", "Ink", 50, 50])); + let n = node(&s, a); + for paint in [n.appearance.fill_paint(), n.appearance.stroke_paint()] { + match paint { + Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - 0.5).abs() < 1e-6, "{name} at {tint}"), + p => panic!("the paint is {p:?}"), + } + } +} + +#[test] +fn a_spot_color_without_a_spot_of_the_document_is_refused() { + let (mut s, _) = doc_with_paints(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let layers = |s: &Session| s.documents().iter().map(|d| format!("{:?}", d.doc.layers)).collect::>(); + let before = layers(&s); + let steps = undo_steps(&s); + for (source, part) in [ + ("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot"), + ("var a = app.documents[0], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"), + ( + "var a = app.documents[0], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;", + "SpotColor.tint", + ), + ( + "var a = app.documents[0], b = app.documents[1], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); b.pathItems[0].fillColor = c;", + "Cross-document", + ), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(layers(&s), before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn filled_true_on_a_filled_path_runs_no_command() { let (mut s, _, _) = doc(); @@ -718,7 +765,7 @@ fn bad_color_components_throw_and_change_nothing() { ("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"), ("app.activeDocument.pathItems[0].fillColor = 5;", "color object"), ("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"), - ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "not available yet"), + ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); diff --git a/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs index eecb56fb53..9defb29ff7 100644 --- a/crates/engine/src/tests/script_dom_resources.rs +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -165,7 +165,7 @@ fn hostile_names_and_values_are_refused_without_change() { } #[test] -fn spots_keep_their_kind_and_their_document_color_space() { +fn spots_keep_their_kind_and_their_color_space() { let (mut s, _) = doc(); let out = log( &mut s, @@ -177,7 +177,7 @@ fn spots_keep_their_kind_and_their_document_color_space() { assert_eq!( out, vec![ - json!(1), + json!(2), json!("Spot"), json!("ColorModel.SPOT"), json!("SpotColorKind.SPOTRGB"), @@ -189,20 +189,64 @@ fn spots_keep_their_kind_and_their_document_color_space() { ); let before = resources(&s); for (script, message) in [ - ("var p = app.activeDocument.spots[0]; p.color = new CMYKColor();", "must be an RGBColor"), - ("app.activeDocument.spots[0].colorType = ColorModel.PROCESS;", "stays a spot color"), - ("app.activeDocument.spots[0].colorType = 3;", "ColorModel value"), + ("var p = app.activeDocument.spots.getByName('Pea'); p.color = new GrayColor();", "must be an RGBColor, a CMYKColor or a LabColor"), + ("app.activeDocument.spots.getByName('Pea').colorType = ColorModel.PROCESS;", "stays a spot color"), + ("app.activeDocument.spots.getByName('Pea').colorType = 3;", "ColorModel value"), ] { let e = failure(&mut s, script); assert!(e.contains(message), "{script}: {e}"); } assert_eq!(resources(&s), before); - log(&mut s, "var p = app.activeDocument.spots[0]; var l = new LabColor(); l.l = 50; p.color = l;"); - assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots[0].spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]); + log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); var l = new LabColor(); l.l = 50; p.color = l;"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.getByName('Pea').spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]); log(&mut s, "app.activeDocument.spots.removeAll();"); assert!(!swatch_names(&mut s).contains(&"Pea".to_string())); } +#[test] +fn a_spot_takes_a_cmyk_color_in_an_rgb_document() { + let (mut s, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.spots.add(); p.name = 'Pea'; var c = new CMYKColor(); c.cyan = 35; c.yellow = 50; p.color = c;\ + var q = app.activeDocument.spots.getByName('Pea'); vc.log(q.color.typename); vc.log([q.color.cyan, q.color.yellow]); vc.log(q.spotKind);", + ); + assert_eq!(out, vec![json!("CMYKColor"), json!([35, 50]), json!("SpotColorKind.SPOTCMYK")]); + let d = &s.active().unwrap().doc; + let cmyk = + matches!(d.swatch("Pea").map(|w| &w.paint), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. })); + assert!(cmyk, "the spot keeps its CMYK color in the RGB document"); + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.spots.getByName('Pea'); p.color = p.color;"); + assert_eq!(undo_steps(&s), steps, "assigning the color the spot has records no step"); +} + +#[test] +fn spots_list_registration_and_keep_it() { + let (mut s, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, r = d.spots.getByName('[Registration]'); vc.log(r.typename); vc.log(r.colorType);\ + vc.log(d.spots[0].name); vc.log(d.spots.length); r.colorType = ColorModel.REGISTRATION;\ + vc.log(d.swatches.getByName('[Registration]').color.spot.name);", + ); + assert_eq!(out, vec![json!("Spot"), json!("ColorModel.REGISTRATION"), json!("[Registration]"), json!(1), json!("[Registration]")]); + let before = resources(&s); + let steps = undo_steps(&s); + for script in [ + "app.activeDocument.spots.getByName('[Registration]').name = 'R';", + "app.activeDocument.spots.getByName('[Registration]').remove();", + "app.activeDocument.spots.getByName('[Registration]').color = new CMYKColor();", + "app.activeDocument.spots.getByName('[Registration]').colorType = ColorModel.SPOT;", + ] { + assert!(failure(&mut s, script).contains("is built in"), "{script}"); + } + log(&mut s, "app.activeDocument.spots.removeAll();"); + assert_eq!(resources(&s), before); + assert_eq!(undo_steps(&s), steps, "removeAll with only Registration left records no step"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots.length);"), vec![json!(1)]); +} + #[test] fn a_tint_of_a_spot_reads_as_that_spot_at_the_tint() { let (mut s, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c362851a01..30b1ba11d4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2727,7 +2727,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a - global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new + global or spot swatch reads as a `SpotColor` with its `tint`, and with its `spot` when the swatch is a spot color or + Registration). Assigning a `SpotColor` (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/) links the fill or + stroke to its `spot`, a `Spot` of the path's document, at its `tint` (0 to 100, 0 when left out), with `paint.setFill` + or `paint.setStroke`; assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. @@ -2753,7 +2756,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot `swatchGroups.add()` runs `swatch.newGroup`, `symbols.add(sourceArt, registrationPoint?)` runs `symbol.new` with `keepArt: true` (the default point is `SymbolRegistrationPoint.SYMBOLCENTERPOINT`), and `symbolItems.add(symbol)` runs `symbol.place`. `swatches.getSelected()` gives `[]`. A `Swatch` (https://ai-scripting.docsforadobe.dev/jsobjref/Swatch/) - has `name` and `color` (`swatch.edit`) and `remove()` (`swatch.delete`); a spot swatch's `color` reads as a + has `name` and `color` (`swatch.edit`) and `remove()` (`swatch.delete`); the `color` of a spot swatch or of Registration reads as a `SpotColor` with its `spot` and a `tint` of 100, and a tint of a spot as that `spot` at its `tint`. A `Spot` (https://ai-scripting.docsforadobe.dev/jsobjref/Spot/) has `name`, `color`, `colorType`, `spotKind`, `getInternalColor()` and `remove()`. A `SwatchGroup` (https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/) has `name` (`swatch.renameGroup`), `addSwatch(swatch)` @@ -2773,8 +2776,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot and `removeAll()` keeps them; the Default Graphic Style cannot be renamed or removed, and `graphicStyles.removeAll()` keeps it. A color group takes solid colors only; `SwatchGroup.remove()` deletes the group with its swatches, and its `removeAll()` deletes the swatches - and keeps the group. A spot's color is in the document's color space or Lab, its `colorType` takes only - `ColorModel.SPOT`, a gray spot's `spotKind` is `SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the + and keeps the group. `spots` lists Registration and the spot colors. `Spot.color` takes an `RGBColor`, a `CMYKColor` + or a `LabColor` in a document of either color space, and the spot keeps that color space. A spot's `colorType` reads + and takes only `ColorModel.SPOT` (`ColorModel.REGISTRATION` for Registration), a gray spot's `spotKind` is + `SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the components on the color classes' scales. `symbols.add` leaves the source art as it is, and removing a symbol turns its instances into plain art. `applyTo` and `mergeTo` take one page item of the same document that can be edited, and `Brush.applyTo` a path that is not a guide, a clipping path or a path in a compound path; applying the brush a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c5e86abe73..4996ef9f3b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - - Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`. + - Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.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 3aaea54d868e714578561a8ee7b90b498cb83372 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:30:55 -0800 Subject: [PATCH 004/213] Scripts: a SpotColor without a spot throws, and a spot keeps an RGB color in a CMYK document - A fill or stroke linked to a global process swatch reads as a SpotColor without a spot. That color does not name its swatch, so assigning it to any fill or stroke throws an error that says it is not available yet, and the path keeps its paint. - A spot's color, set through Spot.color or Swatch.color, keeps an RGBColor in a CMYK document as RGB, as it keeps a CMYKColor in an RGB document, and assigning the color it has again records no undo step. A process swatch's Swatch.color still stores an RGBColor in a CMYK document as CMYK, and assigning that RGBColor again records no step. - docs/mcp.md and the module notes state that a spot keeping a color of the other color space is VectorCraft's own rule: the Spot page (https://ai-scripting.docsforadobe.dev/jsobjref/Spot/) says a color in another space than the document's gives an error, and spots.add() converts the fill to the document's space as that page asks. They also state VectorCraft's own SpotColor tint defaults: 100 from new SpotColor(), 0 for a color object without a tint. - Tests cover a path painted with Registration through a SpotColor, a SpotColor without a tint, and spot and process swatch colors in a CMYK document. Docs: docs/mcp.md. --- crates/engine/src/script/dom/colors.rs | 3 +- crates/engine/src/script/dom/paths.rs | 11 ++- crates/engine/src/script/dom/resources.rs | 48 ++++++++++--- crates/engine/src/tests/script_dom_paths.rs | 67 ++++++++++++++++++- .../engine/src/tests/script_dom_resources.rs | 34 ++++++++++ docs/mcp.md | 13 ++-- 6 files changed, 158 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 272a3aa9a8..f2ed0c0b24 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -10,7 +10,8 @@ //! Components are checked when a color is assigned to an object, and a value out of range throws a //! `RangeError` with nothing changed. //! -//! VectorCraft's own rules, which the help pages do not state: components left out count as 0; +//! VectorCraft's own rules, which the help pages do not state: components left out count as 0, +//! and `new SpotColor()` starts with a `tint` of 100; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page //! says. A `SpotColor` () can be diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 58bbad61fd..32793a0828 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -748,12 +748,17 @@ fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer { } /// Links the fill (`fill`) or the stroke to the Spot `spot` at `tint` (0 to 100), unless it is -/// linked to it at that tint already. +/// linked to it at that tint already. A `SpotColor` without a `spot`, as a color linked to a global +/// process swatch reads, throws: it does not name the swatch it was read from. fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer { + if matches!(spot, Data::Undefined) { + return Err(HostError::Error("assigning a SpotColor without a spot is not available yet".into())); + } let (item, look) = this_look(h, a)?; - let name = super::resources::assigned_spot(h, spot, item.doc)?; let now = if fill { &look.fill } else { &look.stroke }; - let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && *t == colors::unit(tint, 100.0)); + let at_tint = |t: &f32| *t == colors::unit(tint, 100.0); + let name = super::resources::assigned_spot(h, spot, item.doc)?; + let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && at_tint(t)); if !same { edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?; } diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index 58e35759af..dc3985f5c6 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -35,13 +35,20 @@ //! `graphicStyles.removeAll()` keeps it. //! - `SwatchGroup.remove()` deletes the group and its swatches; `removeAll()` deletes its swatches //! and keeps the group. A group holds solid colors only. -//! - `Spot.color` takes an RGB, CMYK or Lab color in a document of either color space, and the -//! spot keeps that color space. `colorType` reads `ColorModel.SPOT`, or +//! - A spot's color, set through `Spot.color` or `Swatch.color`, takes an RGB, CMYK or Lab color +//! in a document of either color space, and the spot keeps that color space. The Spot page says +//! a color in another space than the document's gives an error; `spots.add()` follows it, and a +//! spot's color does not. A process swatch's `Swatch.color` stores an RGB color in a CMYK +//! document as CMYK. `colorType` reads `ColorModel.SPOT`, or //! `ColorModel.REGISTRATION` for Registration, and takes only that value. `spotKind` reads //! `SpotColorKind.SPOTCMYK` for a gray spot. `getInternalColor()` gives the components on the //! scale of the color classes (0 to 255 for RGB, 0 to 100 for CMYK and gray, L*a*b* as is). //! - A `SpotColor` assigned to a path's `fillColor` or `strokeColor` links the paint to its `spot`, -//! a Spot of the path's document, at its `tint`; reading the paint back gives that `spot`. +//! a Spot of the path's document, at its `tint` (VectorCraft's own defaults: 100 from +//! `new SpotColor()`, 0 for a color object without a `tint`); +//! reading the paint back gives that `spot`. A paint linked to a global process swatch reads as +//! a `SpotColor` without a `spot`, which does not name the swatch, so assigning it throws an +//! error that says it is not available yet, with nothing changed. //! - `symbols.add(art)` keeps the art where it is and does not make it an instance. //! `Symbol.remove()` and `symbols.removeAll()` turn the instances into plain art. //! - `applyTo` and `mergeTo` take one page item of the same document that can be edited; @@ -649,8 +656,8 @@ fn res_remove(h: &Host, kind: Kind, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// `Swatch.color`: a new color object. A spot swatch gives a `SpotColor` of the spot at 100%, and -/// a tint of a spot a `SpotColor` of that spot at the tint. +/// `Swatch.color`: a new color object. A spot swatch or Registration gives a `SpotColor` of that +/// Spot at 100%, and a tint of a spot a `SpotColor` of that spot at the tint. fn swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { let r = this_res(h, a, kind)?; let w = swatch_now(h, &r, kind)?; @@ -666,7 +673,7 @@ fn swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { pub(super) fn paint_color(h: &Host, doc: Doc, paint: &Paint) -> Answer { let color = colors::of_paint(paint); let base = match paint { - Paint::Solid { swatch: Some(base), .. } => with_doc(h, doc, |_, st| exists(&st.doc, Kind::Spot, base)).then(|| base.clone()), + Paint::Solid { swatch: Some(base), .. } => is_spot_of(h, doc, base).then(|| base.clone()), _ => None, }; match (color, base) { @@ -678,6 +685,11 @@ pub(super) fn paint_color(h: &Host, doc: Doc, paint: &Paint) -> Answer { } } +/// Whether the document `doc` has a Spot named `name`. +pub(super) fn is_spot_of(h: &Host, doc: Doc, name: &str) -> bool { + with_doc(h, doc, |_, st| exists(&st.doc, Kind::Spot, name)) +} + /// The name of the Spot that the `spot` of a `SpotColor` assigned to a page item of the document /// `doc` names. pub(super) fn assigned_spot(h: &Host, spot: &Data, doc: Doc) -> std::result::Result { @@ -714,13 +726,33 @@ fn set_swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { if w.spot && matches!(color, Color::Gray { .. }) { return Err(HostError::Error("a spot's color must be an RGBColor, a CMYKColor or a LabColor".into())); } - if now == color { + // A spot keeps the color space it is given; a process swatch stores an RGB color in a CMYK + // document as CMYK, as `swatch.edit` does without `keepModel`. + let stored = if w.spot { color } else { stored_in(h, r.doc, color) }; + if now == stored { return Ok(Data::Undefined); } - run_on(h, r.doc, "swatch.edit", &json!({"name": r.name, "color": colors::param(&color)}))?; + let mut params = json!({"name": r.name, "color": colors::param(&color)}); + if w.spot { + params["keepModel"] = json!(true); + } + run_on(h, r.doc, "swatch.edit", ¶ms)?; Ok(Data::Undefined) } +/// `color` as `swatch.edit` stores it in the document `doc` without `keepModel`: an RGB color in a +/// CMYK document becomes CMYK through the color settings. +fn stored_in(h: &Host, doc: Doc, color: Color) -> Color { + let mode = with_doc(h, doc, |_, st| st.doc.color_mode); + match color { + Color::Rgb { .. } if mode != crate::doc::ColorMode::Rgb => { + let cms = vectorcraft_color::cms::active(); + cms.convert(&color, mode.model(), cms.settings().intent) + } + _ => color, + } +} + /// The `ColorModel` of the Spot `name`: Registration's own, or `SPOT`. fn spot_model(name: &str) -> &'static str { if name == swatch::REGISTRATION { "ColorModel.REGISTRATION" } else { "ColorModel.SPOT" } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index baaab3f531..db2a6223e1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -360,6 +360,68 @@ fn a_spot_color_paints_its_spot_at_its_tint() { } } +#[test] +fn a_spot_color_left_without_a_tint_paints_at_its_default() { + let (mut s, a) = doc_with_paints(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('Ink');\ + p.fillColor = c; vc.log([p.fillColor.spot.name, p.fillColor.tint]);\ + p.strokeColor = {typename: 'SpotColor', spot: d.spots.getByName('Ink')}; vc.log([p.strokeColor.spot.name, p.strokeColor.tint]);", + ); + assert_eq!(rounded(&Value::Array(out)), json!([["Ink", 100], ["Ink", 0]]), "new SpotColor() starts at 100, a color without a tint is 0"); + let n = node(&s, a); + for (paint, want) in [(n.appearance.fill_paint(), 1.0), (n.appearance.stroke_paint(), 0.0)] { + match paint { + Paint::Solid { swatch: Some(name), tint, .. } => assert!(name == "Ink" && (tint - want).abs() < 1e-6, "{name} at {tint}"), + p => panic!("the paint is {p:?}"), + } + } +} + +#[test] +fn a_global_process_link_read_as_a_spot_color_is_not_assigned() { + let (mut s, a) = doc_with_paints(); + s.execute("swatch.new", &json!({"name": "Leaf", "color": "#3a9a40", "global": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Moss", "color": "#405a20", "global": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Leaf", "tint": 60})).unwrap(); + let b = rect(&mut s, 30.0, 30.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [b.0], "swatch": "Moss", "tint": 60})).unwrap(); + let c = rect(&mut s, 60.0, 60.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [c.0], "color": "#ff0000"})).unwrap(); + let paints = |s: &Session| [a, b, c].map(|id| node(s, id).appearance.fill_paint()); + let before = paints(&s); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems; vc.log([q[0].fillColor.typename, q[0].fillColor.spot === undefined, q[2].fillColor.typename, q[3].fillColor.typename]);", + ); + // `pathItems` holds a (Leaf), the document's second rectangle, b (Moss) and c (unlinked). + assert_eq!(out, vec![json!(["SpotColor", true, "SpotColor", "RGBColor"])]); + for script in [ + "var q = app.activeDocument.pathItems; q[0].fillColor = q[0].fillColor;", + "var q = app.activeDocument.pathItems; q[2].fillColor = q[0].fillColor;", + "var q = app.activeDocument.pathItems; q[3].fillColor = q[0].fillColor;", + ] { + let e = failure(&mut s, script); + assert!(e.contains("without a spot is not available yet"), "{script}: {e}"); + assert_eq!(paints(&s), before, "{script}"); + assert_eq!(undo_steps(&s), steps, "{script}"); + } +} + +#[test] +fn a_path_painted_with_registration_reads_and_takes_its_spot() { + let (mut s, a) = doc_with_paints(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pathItems[0], c = new SpotColor(); c.spot = d.spots.getByName('[Registration]'); c.tint = 100;\ + p.strokeColor = c; vc.log([p.strokeColor.typename, p.strokeColor.spot.name, p.strokeColor.tint]);", + ); + assert_eq!(rounded(&out[0]), json!(["SpotColor", "[Registration]", 100])); + assert!(node(&s, a).appearance.stroke_paint().is_registration(), "the stroke is linked to Registration"); +} + #[test] fn a_spot_color_without_a_spot_of_the_document_is_refused() { let (mut s, _) = doc_with_paints(); @@ -369,7 +431,8 @@ fn a_spot_color_without_a_spot_of_the_document_is_refused() { let before = layers(&s); let steps = undo_steps(&s); for (source, part) in [ - ("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot"), + ("app.documents[0].pathItems[0].fillColor = new SpotColor();", "without a spot is not available yet"), + ("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"), ("var a = app.documents[0], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"), ( "var a = app.documents[0], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;", @@ -765,7 +828,7 @@ fn bad_color_components_throw_and_change_nothing() { ("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"), ("app.activeDocument.pathItems[0].fillColor = 5;", "color object"), ("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"), - ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot"), + ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "without a spot is not available yet"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); diff --git a/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs index 9defb29ff7..89cb6f7d1e 100644 --- a/crates/engine/src/tests/script_dom_resources.rs +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -221,6 +221,40 @@ fn a_spot_takes_a_cmyk_color_in_an_rgb_document() { assert_eq!(undo_steps(&s), steps, "assigning the color the spot has records no step"); } +#[test] +fn a_spot_keeps_an_rgb_color_in_a_cmyk_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 80, "m": 40, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Leaf", "color": {"c": 60, "m": 0, "y": 90, "k": 10}})).unwrap(); + let rgb = |s: &Session, name: &str| { + matches!( + s.active().unwrap().doc.swatch(name).map(|w| &w.paint), + Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }) + ) + }; + let assign = |what: &str| format!("var c = new RGBColor(); c.red = 200; c.green = 60; c.blue = 20; {what}.color = c;"); + for (what, name) in [("app.activeDocument.spots.getByName('Pea')", "Pea"), ("app.activeDocument.swatches.getByName('Ink')", "Ink")] { + if name == "Pea" { + log(&mut s, "app.activeDocument.spots.add().name = 'Pea';"); + } + let out = log(&mut s, &format!("{} var q = app.activeDocument.spots.getByName('{name}').color; vc.log([q.typename, q.red]);", assign(what))); + assert_eq!(out, vec![json!(["RGBColor", 200])], "{what}"); + assert!(rgb(&s, name), "{name} keeps its RGB color in the CMYK document"); + let kind = log(&mut s, &format!("vc.log(app.activeDocument.spots.getByName('{name}').spotKind);")); + assert_eq!(kind, vec![json!("SpotColorKind.SPOTRGB")], "{name}"); + let steps = undo_steps(&s); + log(&mut s, &assign(what)); + assert_eq!(undo_steps(&s), steps, "assigning {name} the color it has records no step"); + } + let what = "app.activeDocument.swatches.getByName('Leaf')"; + log(&mut s, &assign(what)); + assert!(!rgb(&s, "Leaf"), "a process swatch stores the RGB color as CMYK in the CMYK document"); + let steps = undo_steps(&s); + log(&mut s, &assign(what)); + assert_eq!(undo_steps(&s), steps, "assigning Leaf the RGB color it was given records no step"); +} + #[test] fn spots_list_registration_and_keep_it() { let (mut s, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 30b1ba11d4..3d62e22312 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2729,8 +2729,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a global or spot swatch reads as a `SpotColor` with its `tint`, and with its `spot` when the swatch is a spot color or Registration). Assigning a `SpotColor` (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/) links the fill or - stroke to its `spot`, a `Spot` of the path's document, at its `tint` (0 to 100, 0 when left out), with `paint.setFill` - or `paint.setStroke`; assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new + stroke to its `spot`, a `Spot` of the path's document, at its `tint` (0 to 100; VectorCraft's own defaults are 100 + for `new SpotColor()` and 0 for a color object without a `tint`), with `paint.setFill` or `paint.setStroke`. A `SpotColor` read from a color linked to a global process + swatch has no `spot` and does not name the swatch, so assigning it throws an error that says it is not available yet, + and the path keeps its paint. Assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. @@ -2776,8 +2778,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot and `removeAll()` keeps them; the Default Graphic Style cannot be renamed or removed, and `graphicStyles.removeAll()` keeps it. A color group takes solid colors only; `SwatchGroup.remove()` deletes the group with its swatches, and its `removeAll()` deletes the swatches - and keeps the group. `spots` lists Registration and the spot colors. `Spot.color` takes an `RGBColor`, a `CMYKColor` - or a `LabColor` in a document of either color space, and the spot keeps that color space. A spot's `colorType` reads + and keeps the group. `spots` lists Registration and the spot colors. A spot's color, set through `Spot.color` or + `Swatch.color`, takes an `RGBColor`, a `CMYKColor` or a `LabColor` in a document of either color space, and the spot + keeps that color space. This is VectorCraft's own rule: the Spot page says a color in another space than the + document's gives an error, and `spots.add()` follows the page by converting the fill. A process swatch's + `Swatch.color` stores an `RGBColor` in a CMYK document as CMYK. A spot's `colorType` reads and takes only `ColorModel.SPOT` (`ColorModel.REGISTRATION` for Registration), a gray spot's `spotKind` is `SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the components on the color classes' scales. `symbols.add` leaves the source art as it is, and removing a symbol turns From 6c7fd4490a958d34e1d2997db0da8fa43501bd85 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:00:55 -0800 Subject: [PATCH 005/213] Scripts: a swatch given its own color back records no step, and a SpotColor without a spot names the rule - A process swatch that holds an RGB color in a CMYK document (made with keepModel, as a color theme's swatches are) records no undo step when a script assigns it that color again. swatch.edit keeps a swatch's own color as it is, so the assignment changed nothing. - Assigning a SpotColor whose spot is unset, or one read from a global process swatch, throws "SpotColor.spot must be a Spot; a color read from a global process swatch cannot be assigned yet". The SpotColor page (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/) requires spot. The path keeps its paint. - docs/mcp.md now says that a SpotColor cannot be assigned to a swatch's or spot's color yet; a path's fillColor and strokeColor take one. --- crates/engine/src/script/dom/colors.rs | 3 ++- crates/engine/src/script/dom/paths.rs | 2 +- crates/engine/src/script/dom/resources.rs | 5 +++-- crates/engine/src/tests/script_dom_paths.rs | 6 +++--- crates/engine/src/tests/script_dom_resources.rs | 15 +++++++++++++++ docs/mcp.md | 6 +++--- 6 files changed, 27 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index f2ed0c0b24..371b72ed62 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -26,7 +26,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{Link, current, num, text}; -/// The classes whose objects can be read from a fill or stroke but not assigned yet. +/// The classes whose objects [`assigned`] refuses as not available yet. A path's `fillColor` and +/// `strokeColor` take a `SpotColor` before [`assigned`] runs; a swatch's or spot's `color` does not. const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"]; /// The components of each color class, with the value `new` gives them. diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32793a0828..59aebf5f67 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -752,7 +752,7 @@ fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer { /// process swatch reads, throws: it does not name the swatch it was read from. fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer { if matches!(spot, Data::Undefined) { - return Err(HostError::Error("assigning a SpotColor without a spot is not available yet".into())); + return Err(HostError::Error("SpotColor.spot must be a Spot; a color read from a global process swatch cannot be assigned yet".into())); } let (item, look) = this_look(h, a)?; let now = if fill { &look.fill } else { &look.stroke }; diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index dc3985f5c6..c2b5460618 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -727,9 +727,10 @@ fn set_swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { return Err(HostError::Error("a spot's color must be an RGBColor, a CMYKColor or a LabColor".into())); } // A spot keeps the color space it is given; a process swatch stores an RGB color in a CMYK - // document as CMYK, as `swatch.edit` does without `keepModel`. + // document as CMYK, as `swatch.edit` does without `keepModel`, unless the color is the + // swatch's own, which `swatch.edit` keeps as it is. let stored = if w.spot { color } else { stored_in(h, r.doc, color) }; - if now == stored { + if now == color || now == stored { return Ok(Data::Undefined); } let mut params = json!({"name": r.name, "color": colors::param(&color)}); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index db2a6223e1..7604d69601 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -404,7 +404,7 @@ fn a_global_process_link_read_as_a_spot_color_is_not_assigned() { "var q = app.activeDocument.pathItems; q[3].fillColor = q[0].fillColor;", ] { let e = failure(&mut s, script); - assert!(e.contains("without a spot is not available yet"), "{script}: {e}"); + assert!(e.contains("global process swatch cannot be assigned yet"), "{script}: {e}"); assert_eq!(paints(&s), before, "{script}"); assert_eq!(undo_steps(&s), steps, "{script}"); } @@ -431,7 +431,7 @@ fn a_spot_color_without_a_spot_of_the_document_is_refused() { let before = layers(&s); let steps = undo_steps(&s); for (source, part) in [ - ("app.documents[0].pathItems[0].fillColor = new SpotColor();", "without a spot is not available yet"), + ("app.documents[0].pathItems[0].fillColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"), ("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"), ("var a = app.documents[0], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"), ( @@ -828,7 +828,7 @@ fn bad_color_components_throw_and_change_nothing() { ("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"), ("app.activeDocument.pathItems[0].fillColor = 5;", "color object"), ("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"), - ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "without a spot is not available yet"), + ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "SpotColor.spot must be a Spot; a color read"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); diff --git a/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs index 89cb6f7d1e..c77dc3de39 100644 --- a/crates/engine/src/tests/script_dom_resources.rs +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -255,6 +255,21 @@ fn a_spot_keeps_an_rgb_color_in_a_cmyk_document() { assert_eq!(undo_steps(&s), steps, "assigning Leaf the RGB color it was given records no step"); } +#[test] +fn a_process_swatch_that_kept_an_rgb_color_takes_it_back_without_a_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Sky", "color": "#3080c0", "keepModel": true})).unwrap(); + let paint = |s: &Session| s.active().unwrap().doc.swatch("Sky").map(|w| w.paint.clone()); + let rgb = matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. })); + assert!(rgb, "the process swatch holds an RGB color in the CMYK document"); + let before = paint(&s); + let steps = undo_steps(&s); + log(&mut s, "var w = app.activeDocument.swatches.getByName('Sky'); w.color = w.color;"); + assert_eq!(paint(&s), before, "the swatch keeps its RGB color"); + assert_eq!(undo_steps(&s), steps, "assigning the swatch its own color records no step"); +} + #[test] fn spots_list_registration_and_keep_it() { let (mut s, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 3d62e22312..c9d06f8b7e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2731,8 +2731,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot Registration). Assigning a `SpotColor` (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/) links the fill or stroke to its `spot`, a `Spot` of the path's document, at its `tint` (0 to 100; VectorCraft's own defaults are 100 for `new SpotColor()` and 0 for a color object without a `tint`), with `paint.setFill` or `paint.setStroke`. A `SpotColor` read from a color linked to a global process - swatch has no `spot` and does not name the swatch, so assigning it throws an error that says it is not available yet, - and the path keeps its paint. Assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new + swatch has no `spot` and does not name the swatch, so assigning it, or a `SpotColor` whose `spot` was never set, + throws an error that says `SpotColor.spot` must be a Spot, and the path keeps its paint. Assigning a `GradientColor` or `PatternColor` throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. @@ -2793,7 +2793,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot removed, or renamed or deleted with `vc.run`, every member throws `Stale Swatch` (`Stale Spot`, `Stale SwatchGroup`, `Stale Symbol`, `Stale GraphicStyle`, `Stale Brush`). A run holds at most 100,000 of these objects. An object of another document throws `Cross-document placement is not available`. `Document.gradients`, `Document.patterns` and - assigning a `SpotColor` to art are not available yet. + assigning a `SpotColor` to a swatch's or spot's `color` are not available yet. - `$.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 From fe0c8da91908b62ed01a1c1517a638f5b08e3d91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:51:32 -0800 Subject: [PATCH 006/213] Scripts: layers and groups give their own path items Layer.pathItems and GroupItem.pathItems now return a PathItems collection for the paths directly in the layer or group, topmost first, as the Layer and GroupItem pages describe them (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). Before, both threw an error that said they were not available yet. - The collection has the members of Document.pathItems. Its parent is the layer or group, and length, [i], index and getByName read only that container's paths, so a path inside a group, a compound path or a sublayer is not listed. - add() and the shape creators put the new path on top of the layer's or group's contents and leave the current layer as it was. The path is made with the container's layer current (layer.setCurrent) and, for a group, moved into it with node.move, in the run's one undo step. - VectorCraft's own rule: a layer or group that is hidden or locked, or that is in a hidden or locked layer or group, throws "Cannot add a path to a hidden or locked layer or group" and no path is made. - The last four path lists stay cached while their documents are unchanged, so a loop over a large layer or group builds its list once. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 6 +- crates/engine/src/script/dom/layers.rs | 24 +- crates/engine/src/script/dom/paths.rs | 206 +++++++++++++----- crates/engine/src/tests/script_dom.rs | 117 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 4 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 2 +- 7 files changed, 302 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c600cc84c4..e8d0cc404a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -102,8 +102,10 @@ pub(super) struct State { coords: Cell, items: RefCell>, locked: RefCell>, - /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. - paths: RefCell>, + /// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's + /// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is + /// unchanged. + paths: RefCell>, /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..23e4d58170 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -114,7 +114,7 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { layer_of(h, arg(a, 0)) } -fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { +pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { let [high, low] = id_parts(id); host_ref("Layer", &[float(h.run), float(uid), high, low]) } @@ -845,6 +845,17 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]). +fn held_paths(h: &Host, a: &[Data]) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(super::paths::held_path_items(h, doc.uid, id)); + } + let item = this_item_of(h, a, "GroupItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -897,8 +908,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), @@ -1320,6 +1332,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ("zOrderPosition", get(l, layer_z_position)), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), ("isIsolated", get(l, layer_is_isolated)), @@ -1328,8 +1341,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order)), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32401db1d0..87287c5c27 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -13,7 +13,9 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside -//! groups and compound paths included. +//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in +//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden +//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, throws `Cannot edit` with nothing changed. //! - A path in a compound path or compound shape reads that owner's paint, which the paint @@ -23,8 +25,8 @@ //! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever -//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's +//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -56,8 +58,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, + frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -263,21 +265,48 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { r } -// ---- Document.pathItems ---- +// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ---- -/// The ids of a document's paths, in the order of its page items. -fn path_items(h: &super::Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.paths.borrow() - && *uid == st.uid - && std::sync::Arc::ptr_eq(doc, &st.doc) +/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the +/// document's), and the ids it listed then. +pub(super) type PathList = (u64, Arc, Option, Rc>); + +/// How many lists of paths [`super::State`] keeps at once. +pub(super) const PATH_LISTS: usize = 4; + +/// The ids of a document's paths, in the order of its page items, or of the paths directly in the +/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their +/// documents are unchanged, so a loop over a collection builds its list once. A new list of a +/// container is charged by the objects it looks at. +fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { { - return ids.clone(); + let mut lists = h.dom.paths.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } } - let all = super::page_items(h, st); - let ids: Rc> = - Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); - *h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); - ids + let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. }); + let ids: Rc> = match container { + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect()) + } + None => { + let all = super::page_items(h, st); + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) + } + }; + let mut lists = h.dom.paths.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= PATH_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), container, ids.clone())); + Ok(ids) } pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { @@ -285,32 +314,57 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } -fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "PathItems") +/// The `pathItems` of the layer or group `id` in the document `uid`. +pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { + let [high, low] = id_parts(id); + host_ref("PathItems", &[float(h.run), float(uid), high, low]) +} + +/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low] => { + 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 holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(HostError::Type("this is not a PathItems".into())), + } } fn items_length(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) + let (doc, c) = items_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) + let (doc, c) = items_scope(h, a)?; + Ok(match c { + None => host_ref("Document", &[float(h.run), float(doc.uid)]), + Some(c) => with_doc(h, doc, |_, st| { + if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) } + }), + }) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(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| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(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 = path_items(h, st); + let ids = path_items(h, st, c)?; 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| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -328,15 +382,15 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } } -/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or +/// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st, c)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((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 paths: {list}"))); @@ -356,19 +410,53 @@ fn made_id(r: &Data) -> std::result::Result { id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, -/// and reverses the new path's direction when `reversed`. → the new path. -fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { - let made = on_doc(h, doc.uid, true, |h| { +/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or +/// locked layer or group. +pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group"; + +/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the +/// selection and the current layer kept. With a layer or group `container`, the container's layer +/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made +/// outside the container then moves on top of its contents in the same step; a container that is +/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`] +/// before anything is made. → the new path. +fn make_in( + h: &super::Host, + doc: Doc, + container: Option, + make: impl FnOnce(&super::Host) -> std::result::Result, +) -> Answer { + if let Some(c) = container + && !with_doc(h, doc, |_, st| editable(&st.doc, c)) + { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + let made = match container { + None => on_doc(h, doc.uid, true, make)?, + Some(c) => super::atomically(h, |h| { + let id = on_doc(h, doc.uid, true, |h| { + command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; + make(h) + })?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?, + }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s +/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. +fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { + make_in(h, doc, container, |h| { let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } /// Argument `i`, or `default` when it is left out. @@ -409,13 +497,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result /// `rectangle(top, left, width, height, reversed?)`. fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); let reversed = flag(a, 5, "reversed")?; let p = corner(h, doc, left, top)?; - make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the @@ -455,7 +543,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { /// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, /// reversed = false)`: a closed path with `path.create`. fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); @@ -463,12 +551,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { let reversed = flag(a, 7, "reversed")?; let p = corner(h, doc, left, top)?; let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); - make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) + make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) } /// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); @@ -477,7 +565,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); } let p = corner(h, doc, left, top)?; - make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The center of a polygon or star, in document coordinates. @@ -489,32 +577,33 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r = size(a, 3, Some(50.0), "radius")?; let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; let reversed = flag(a, 5, "reversed")?; - make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) + make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) } /// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = /// false)`. fn items_star(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r1 = size(a, 3, Some(50.0), "radius")?; let r2 = size(a, 4, Some(20.0), "innerRadius")?; let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; let reversed = flag(a, 6, "reversed")?; - make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) + make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with -/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open -/// path is set back to none in the same step. +/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or +/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art. +/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set +/// back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - let made = on_doc(h, doc.uid, true, |h| { + let (doc, into) = items_scope(h, a)?; + make_in(h, doc, into, |h| { let unpainted = { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() @@ -524,10 +613,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } // ---- PathItem geometry ---- diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ea3e0ac497..fb7239394a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1597,6 +1597,123 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); } +#[test] +fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() { + let (mut s, _, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the + // document's list holds all three, the layer's only `a`, and a sublayer's path is its own. + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\ + vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ + vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ + var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ + vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + ); + let expected = + [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; + assert_eq!(out[..11], expected); + assert_eq!(out[11..], [json!(false), json!(true)]); +} + +#[test] +fn a_loop_over_a_groups_path_items_builds_the_list_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list + // of 1,000 paths is not built again for each read. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19))); + let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap()["log"], json!([1000])); +} + +#[test] +fn a_layers_path_items_make_their_paths_on_top_of_that_layer() { + let (mut s, ..) = doc(); + let bottom = s.active().unwrap().doc.layers[0].id; + let selected = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + // A new layer becomes the current one; each creator of the first layer's `pathItems` still + // puts its path on top of that layer. + let out = log( + &mut s, + "var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\ + var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\ + function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\ + for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\ + vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);", + ); + let mut expected = Vec::new(); + for i in 0..6 { + expected.extend([json!(true), json!(format!("m{i}"))]); + } + expected.extend([json!(true), json!(0), json!(8)]); + assert_eq!(out, expected); + assert_eq!(undo_steps(&s), steps + 1); + let st = s.active().unwrap(); + let kids = st.doc.node(bottom).unwrap().children().unwrap(); + assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5")); + assert!(st.selection == selected); +} + +#[test] +fn a_groups_path_items_add_puts_the_path_in_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\ + vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\ + var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);", + ); + assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + let top: Vec> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect(); + assert_eq!(top, [Some("R"), Some("N")]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { + const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let lid = s.active().unwrap().doc.layers[0].id; + let before = format!("{:?}", s.active().unwrap().doc.layers); + s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap(); + let locked = format!("{:?}", s.active().unwrap().doc.layers); + for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] { + assert!(failure(&mut s, src).contains(REFUSED), "{src}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); + } + s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); + let hidden = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A group's `pathItems` read after the group is gone throw. + let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;"); + assert!(msg.contains("Stale page item"), "{msg}"); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 563f23db6f..cc604a7bc4 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -108,7 +108,7 @@ const INSIDE: &[(&str, &str)] = &[ "Layer.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ - locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ textFrames= typename visible visible= zOrder zOrderPosition", ), @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ("GroupItem.", "prototype"), ( "GroupItem.prototype.", - "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \ rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", ), ("GroupItems.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 6a58f9712c..899b7f5563 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2707,12 +2707,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs `layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`, `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, - `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, - `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `pathItems`, `zOrderPosition`, `hasSelectedArtwork`, + `isIsolated`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into another layer, to the top level of the document, or directly above or below another layer. Every page item has `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has - `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` + `clipped`, `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, and a `CompoundPathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. @@ -2757,8 +2757,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot run leaves it). The report also lists a document whose active artboard has another index when the run ends because artboards were inserted, removed or reordered before it. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws - `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and - `GroupItems.createFromFile` throw an error that says they are not available yet. + `Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an + error that says they are not available yet. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and @@ -2777,7 +2777,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was. A layer's and a group's `pathItems` + (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) + have the same members, and their `parent` is that layer or group. Their `add()` and shape creators put the new path + on top of that layer's or group's contents, with the current layer left as it was: the path is made with the + container's layer as the current one (`layer.setCurrent`) and, for a group, moved into it with `node.move`, in the + run's one undo step. VectorCraft's own rules: a layer's or group's `pathItems` list the paths directly in it, + topmost first, leaving out paths in its groups, compound paths and sublayers; a layer or group that is hidden or + locked, or that is in a hidden or locked layer or group, throws `Cannot add a path to a hidden or locked layer or + group` and no path is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3796a198aa..3339695f64 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`, `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 58292d605af4e21822b7f4d0bcf7aa94a2a2838e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:23:19 -0800 Subject: [PATCH 007/213] Scripts: app.showColorPicker asks for a color app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor and returns the color picked for OK. Cancel, and OK with the color unchanged, return a new object of the color the script gave. Anything else throws a TypeError. - In the app the run waits at the picker, which previews nothing on the selection. Stop and quitting end the run as at the other script dialogs and close the picker. - A run with nobody to ask takes {kind: "colorPicker", value: color | null} from answers. The report lists the picker with the color it opened on and the answer. - script.run's params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md describe it. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 112 +++++++++++++++++---- crates/engine/src/script/dom.rs | 10 ++ crates/engine/src/script/dom/colors.rs | 14 ++- crates/engine/src/tests/script_dialogs.rs | 72 +++++++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 99 +++++++++++++----- crates/ui-egui/src/dialogs/script_run.rs | 26 ++++- crates/ui-egui/src/script_runs.rs | 17 +++- crates/ui-egui/src/tests/script_dialogs.rs | 107 +++++++++++++++++++- docs/mcp.md | 18 +++- docs/target-app-parity.md | 1 + 11 files changed, 425 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..56bf96195f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..afda864f6a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -5,12 +5,14 @@ //! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the //! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and //! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and +//! returns the color picked for OK, or a new object of the color it was given for Cancel. //! //! In the app the run waits at the call for the person's answer, and spends no fuel while it -//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with -//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no -//! answer left, or with the next answer for another kind of dialog, ends the run. The report's -//! `dialogs` lists each dialog and its answer. +//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts +//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s +//! `answers`; a call with no answer left, or with the next answer for another kind of dialog, +//! ends the run. The report's `dialogs` lists each dialog and its answer. //! //! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], //! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and @@ -21,6 +23,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; use super::{Host, console}; @@ -48,21 +51,33 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// `app.showColorPicker`. + ColorPicker, } impl DialogKind { - /// The function's name, which is also the `kind` of an answer and of a report's dialog. + /// The `kind` of an answer and of a report's dialog, which is also the function's name for + /// `alert`, `confirm` and `prompt`. pub fn id(self) -> &'static str { match self { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::ColorPicker => "colorPicker", + } + } + + /// The function's name, as its errors give it. + fn function(self) -> &'static str { + match self { + Self::ColorPicker => "showColorPicker", + k => k.id(), } } } /// A dialog a script opened, which waits for its answer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub struct ScriptDialog { pub kind: DialogKind, pub message: String, @@ -74,10 +89,12 @@ pub struct ScriptDialog { pub no_as_default: bool, /// `prompt`: the text its field starts with. pub preset: String, + /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. + pub color: Option, } /// The answer to a [`ScriptDialog`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub enum DialogAnswer { /// OK, for `alert`. Ok, @@ -85,6 +102,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// OK with the color picked, or Cancel (`None`), for `showColorPicker`. + ColorPicker(Option), } impl DialogAnswer { @@ -93,29 +112,51 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::ColorPicker(_) => DialogKind::ColorPicker, } } - /// What the function returns. - fn data(&self) -> Data { + /// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it + /// started with. + fn data(&self, d: &ScriptDialog) -> Data { match self { Self::Ok => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, + Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data), } } - /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + /// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands + /// take it, or `null`. fn json(&self) -> Value { match self { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json), } } } +/// `c` as the paint commands take it. +fn color_json(c: &Color) -> Value { + serde_json::to_value(c).unwrap_or(Value::Null) +} + +/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from +/// -128 to 128, as a script's `LabColor` takes them? +fn in_range(c: &Color) -> bool { + let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x)); + match *c { + Color::Rgb { r, g, b } => unit(&[r, g, b]), + Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]), + Color::Gray { k } => unit(&[k]), + Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)), + } +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -148,7 +189,8 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "colorPicker", value: color | +/// null}`, the color in any form the paint commands take. An empty object, which the parameter /// took before dialogs existed, is an empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { @@ -180,7 +222,12 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), + (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), + None => Err("is a color picker's answer, whose `value` must be a color or null"), + }, + _ => Err("must have `kind` alert, confirm, prompt or colorPicker"), } } @@ -245,8 +292,9 @@ impl Dialogs { let mut waiting = self.waiting.borrow_mut(); let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; self.record(d, answer.json()); + let data = answer.data(d); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true @@ -263,12 +311,15 @@ impl Dialogs { self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); - r.insert("message".into(), json!(d.message)); - r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + if d.kind != DialogKind::ColorPicker { + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + } match d.kind { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)), }; r.insert("answer".into(), answer); let r = Value::Object(r); @@ -319,7 +370,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result host.charge_call(args.iter().map(super::data_size).sum())?; let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; let (title, error_icon, no_as_default, preset) = match kind { - DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + // `showColorPicker` opens through `show_color_picker`, not here. + DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()), DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), DialogKind::Prompt => { let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; @@ -335,7 +387,29 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) +} + +/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, +/// and a new object of `color` for Cancel. +pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + let dialog = ScriptDialog { + kind: DialogKind::ColorPicker, + message: String::new(), + title: None, + error_icon: false, + no_as_default: false, + preset: String::new(), + color: Some(color), + }; + wait_or_answer(host, dialog) +} + +/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of +/// `answers`. +fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result { + let kind = dialog.kind; + let name = kind.function(); let d = &host.dialogs; if d.framed { if !d.can_wait.get() { @@ -350,11 +424,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result match next { Some(a) if a.kind() == kind => { d.record(&dialog, a.json()); - Ok(a.data()) + Ok(a.data(&dialog)) } Some(a) => { d.record(&dialog, json!("missing")); - Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id()))) } None => { d.record(&dialog, json!("missing")); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b2267a5d8..0a7eb82ef5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; mod paths; +pub(super) use colors::of_color as color_data; + /// 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. @@ -691,6 +693,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`, +/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]). +fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { + let color = colors::solid(arg(a, 1), "showColorPicker's color")?; + super::dialogs::show_color_picker(h, color) +} + /// 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 { @@ -1883,6 +1892,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)), + ("showColorPicker", method(l, app_show_color_picker)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 34c1496054..da34e8cf31 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -66,7 +66,7 @@ fn shown(v: f32, scale: f64) -> f64 { } /// The color object for a solid color. -fn of_color(c: &Color) -> Data { +pub(in crate::script) fn of_color(c: &Color) -> Data { match *c { Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), Color::Cmyk { c, m, y, k } => color_object( @@ -131,6 +131,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result std::result::Result { + let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor")); + match assigned(d, what) { + Ok(Some(c)) => Ok(c), + // A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error. + Ok(None) | Err(HostError::Error(_)) => Err(not_solid()), + Err(e) => Err(e), + } +} + /// `color` as `paint.setFill` and `paint.setStroke` take it. pub(super) fn param(color: &Color) -> Value { serde_json::to_value(color).unwrap_or(Value::Null) diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..aa373d09bb 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -177,6 +177,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); @@ -319,3 +320,74 @@ fn a_dialog_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); assert_eq!(r["dialogCount"], 0); } + +/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns. +const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() { + let mut s = one_doc(); + let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());"); + let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})])) + .unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}"); + let dialogs = r["dialogs"].as_array().unwrap(); + assert_eq!(dialogs.len(), 2); + assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}"); + assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null"); + let cmyk = headless( + &mut s, + "var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);", + answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]), + ) + .unwrap(); + assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}"); +} + +#[test] +fn the_color_picker_ends_the_run_when_no_answer_is_left() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] { + let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}"); + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains("showColorPicker") && e.contains(says), "{e}"); + assert_eq!(art(&s), before, "the run's edit goes back"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } + let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string(); + assert!(a.contains("is for colorPicker, not alert"), "{a}"); +} + +#[test] +fn the_color_picker_refuses_what_is_not_a_solid_color() { + let mut s = one_doc(); + let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\ + try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\ + try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());"; + let r = headless(&mut s, source, json!([])).unwrap(); + assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); + assert_eq!(r["dialogCount"], 0, "no picker opened"); + for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); + assert!(e.contains("color picker's answer"), "{bad}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_the_color_picker() { + let mut s = one_doc(); + framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);")); + let d = s.script_dialog().unwrap(); + assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))))); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given"); + assert!(s.script_answer(DialogAnswer::ColorPicker(None))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}"); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..4060b26d40 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -27,6 +27,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; +use vectorcraft_engine::script::DialogAnswer; use super::preview::LivePreview; use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values}; @@ -45,6 +46,8 @@ pub(crate) enum Target { Artboard(usize), /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, + /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. + Script(Color), } /// One open Color Picker: what the dialog itself does not know. @@ -152,28 +155,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let start = srgba(&color); - let mut dialog = ColorPickerDialog::new( - match (artboard, stroke) { - (Some(_), _) => "artboard", - (None, true) => "stroke", - (None, false) => "fill", - }, - tl!("Color Picker"), - start, - ) - .eyedropper(true) - .add_to_swatches(false) - .gamut(gamut(app)) - .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { - dialog = dialog.cmyk(&converter); - } - if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { - dialog = dialog.kept(model_values(&color)); - } + let key = match (artboard, stroke) { + (Some(_), _) => "artboard", + (None, true) => "stroke", + (None, false) => "fill", + }; + let mut dialog = picker(app, key, &color); // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. if let Some((i, _)) = artboard { dialog = dialog.instance(i); @@ -196,6 +183,58 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's +/// swatches and libraries, and in a CMYK document the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { + let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); + if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) + && let Some(converter) = working_cmyk() + { + dialog = dialog.cmyk(&converter); + } + if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { + dialog = dialog.kept(model_values(color)); + } + dialog +} + +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// previews nothing; its OK and Cancel answer the run ([`finish`]). +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { + let Some(dialogs) = app.dialogs() else { return }; + // The given colour's own values, so that OK can tell an untouched pick from another model's. + let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + let id = dialogs.with(|h| h.open(dialog)); + app.color_dialogs.pickers.retain(|o| o.id != id); + app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); +} + +/// The key of the Color Picker a script opens. +pub(crate) const SCRIPT_KEY: &str = "script"; + +/// The id of the Color Picker a running script waits at, while it is open or its answer is not +/// yet given. +pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) +} + +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(id) = script_picker(app) else { return }; + app.color_dialogs.pickers.retain(|o| o.id != id); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| { + h.cancel_by_id(ctx, id); + let _ = h.take_by_id::(id); + }); + } +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -259,6 +298,15 @@ fn finish( dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } } + // OK on the colour it opened with, in the model it opened with, gives that colour back. + (Some(DialogResult::Ok(r)), Target::Script(given)) => { + let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); + let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); + } + (_, Target::Script(_)) => { + app.session.script_answer(DialogAnswer::ColorPicker(None)); + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); @@ -273,7 +321,7 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -291,8 +339,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// preview. Nothing previews until the colour first changes, nor without a selection (the colour /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { - // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + // A picker over a command dialog only fills a row; the dialog previews it. A script's picker + // only answers the script. + if matches!(open.target, Target::Answer { .. } | Target::Script(_)) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..65b7c92e1a 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -29,6 +29,7 @@ use std::path::Path; +use craft::color_ui::ui::ColorPickerDialog; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; @@ -46,6 +47,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::color_picker; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -430,6 +432,22 @@ pub(crate) fn forget(app: &VectorcraftApp) { }); } +/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened. +pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if color_picker::script_picker(app).is_none() { + return; + } + let asking = with_host(app, |host, _| host.is_open::()).unwrap_or(false); + color_picker::forget_script(app, &ctx); + if asking { + with_host(app, |host, _| { + let _ = host.take::(); + host.open(close_question()); + }); + } +} + /// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { if p.get("path").is_some() || p.get("source").is_some() { @@ -514,8 +532,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let picker = color_picker::script_picker(app); with_host(app, |host, _| { - let own = host.get::().map(StackDialog::id).or_else(|| host.get::().map(StackDialog::id)); + let own = host + .get::() + .map(StackDialog::id) + .or_else(|| host.get::().map(StackDialog::id)) + .or_else(|| picker.filter(|&id| host.get_by_id::(id).is_some())); match own { Some(parent) if host.stack().is_top(parent) => { host.open_child(close_question(), parent); @@ -585,6 +608,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { crate::script_runs::failed(app, error); forget::(app); forget::(app); + forget_color_picker(app); app.sync_views(); } if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index b08a8f2e93..e4f6303fab 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,9 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, `app.showColorPicker` or a `File` or `Folder` file dialog, waits +//! for the person's answer. + +use vectorcraft_engine::script::DialogKind; use crate::VectorcraftApp; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -47,13 +51,22 @@ fn ask(app: &mut VectorcraftApp) -> bool { } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if !script_run::busy(app) { + if dialog.kind == DialogKind::ColorPicker { + // A picker that closed this frame answers the run in its own pump. + if color_picker::script_picker(app).is_none() + && !script_run::busy(app) + && let Some(color) = dialog.color + { + color_picker::open_for_script(app, color); + } + } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + script_run::forget_color_picker(app); if app.session.script_waiting() { if !script_run::busy(app) { script_run::open_growth(app); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..3417c5580b 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -1,12 +1,14 @@ //! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, //! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers -//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other -//! script tests. +//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers +//! over the dialog host are shared with the other script tests. +use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice}; use crate::{VectorcraftApp, menus, script_runs}; @@ -315,3 +317,104 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["dialogs"], headless["dialogs"]); assert_eq!(framed["log"], json!([true, "p", "done"])); } + +/// Is the Color Picker of the script's `app.showColorPicker` open? +fn picker_open(app: &VectorcraftApp) -> bool { + let id = color_picker::script_picker(app); + id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::(id).is_some()).unwrap()) +} + +/// Polls the run until it ends, or until its Color Picker is open (true). +fn until_picker(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if picker_open(app) { + return true; + } + } + panic!("the script neither ended nor opened the Color Picker"); +} + +/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump. +fn answer_picker(app: &mut VectorcraftApp, ok: bool) { + let id = color_picker::script_picker(app).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap(); + assert!(done); + color_picker::pump(app, &ctx); +} + +#[test] +fn the_color_picker_waits_and_answers_the_run() { + let mut app = app(); + let gray = "var g = new GrayColor(); g.gray = 40;"; + start( + &mut app, + &format!( + "{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \ + {gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());" + ), + ); + assert!(until_picker(&mut app)); + assert!(!is_open::(&app), "the picker opens in place of a notice"); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + color_picker::pump(&mut app, &ctx); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app), "the next call opens the picker again"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app)); + answer_picker(&mut app, false); + assert!(!until_picker(&mut app)); + assert_eq!( + log(&app), + json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]), + "OK gives the color picked, untouched its own color, Cancel the color given" + ); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing"); + let dialogs = app.session.script_report().unwrap()["dialogs"].clone(); + assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null"); +} + +#[test] +fn the_same_color_set_in_another_model_is_a_new_pick() { + let mut app = app(); + start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);"); + assert!(until_picker(&mut app)); + // The gray's own sRGB, set as a plain color, as a screen sample sets one. + let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap(); + script_run::with_host(&app, |host, _| host.get_mut_by_id::(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave"); +} + +#[test] +fn stopping_or_quitting_the_run_closes_its_color_picker() { + let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');"); + let mut app = app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert!(!picker_open(&app), "no picker is left for the stopped run"); + assert!(color_picker::script_picker(&app).is_none()); + assert_eq!(objects(&app), 0, "the run's edit goes back"); + assert_eq!(log(&app), json!([])); + let mut app = self::app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + script_run::ask_to_close(&mut app); + assert!(is_open::(&app), "quitting asks over the picker"); + cancel(&mut app, CLOSE_KIND); + assert!(picker_open(&app), "Cancel shows the picker again"); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert!(!picker_open(&app), "no picker is left for the abandoned run"); + assert_eq!(objects(&app), 0); +} diff --git a/docs/mcp.md b/docs/mcp.md index da2ab72029..5321b74f87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2667,7 +2667,8 @@ 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`, `app.getIsFileOpen(path)` and `app.showColorPicker(color)`, described + with the dialogs below. `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 @@ -3048,7 +3049,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + run ended at, or `"missing"` for a dialog `answers` had no answer for. `app.showColorPicker` is listed as `{kind: + "colorPicker", color, answer}`, with the color it opened on and the color picked, `null` for Cancel or + `"missing"`, each color as `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. ```json @@ -3096,6 +3099,17 @@ left, when the next answer is for another kind of dialog, or when the script end and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an empty object are the same. +`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at +https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, +`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK +document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting +end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its +range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. + ```sh vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2ebf0bf4..864cff266f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1036,6 +1036,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.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 80c33ec810298b6c1e65204ac378ac36b34b39ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:02:09 -0800 Subject: [PATCH 008/213] Scripts: fix review findings in the layer and path items - controlBounds takes in the paths' direction handles. A clipping group's are its clipping path's. - A compound path's pathItems is a PathItems collection: add() and the shape methods make the path inside it. - resize() scales and sets the stroke weight as one step, so a failed stroke change undoes the scale too. - A point change that adds or removes anchors deselects the path's direct-selected anchors, from a script and from path.setAnchors, so other anchors are not left selected in their place. - A script that ends past the allowance of the last answer is asked again before its changes are kept. - documents.addDocument starts from the built-in preset when a saved preset has its name, and Recent keeps the built-in preset's name. - Saved preset rows past the artboard limit read as the limit. - Host classes that do not fit the heap end with the heap limit. - Layers keep their list while the document is unchanged, and getByName charges its scan on a kept list too. - Selection ids are deduplicated with a set. - A path made on the current layer is made in one step, so a failed stroke or reversal after it undoes the path too. - Path points are found through a kept index of where each subpath's points start, rebuilt when the path's points change, so reading every point of a path with many subpaths is no longer quadratic. - A pixel-aligned compound path snaps a path moved into it. --- crates/engine/src/cmd/layer.rs | 12 +- crates/engine/src/cmd/newdoc.rs | 10 +- crates/engine/src/cmd/path.rs | 13 +- crates/engine/src/script/dom.rs | 88 +++++++++++- crates/engine/src/script/dom/layers.rs | 56 ++++++-- crates/engine/src/script/dom/paths.rs | 152 +++++++++++++++----- crates/engine/src/script/mod.rs | 10 ++ crates/engine/src/tests/newdoc.rs | 16 +++ crates/engine/src/tests/script_dom.rs | 74 +++++++++- crates/engine/src/tests/script_dom_paths.rs | 94 ++++++++++++ crates/engine/src/tests/script_run.rs | 54 +++++++ crates/js/src/host_classes.rs | 3 +- crates/js/src/host_tests.rs | 11 ++ crates/ui-egui/src/dialogs/new_document.rs | 16 +++ docs/mcp.md | 7 +- 15 files changed, 549 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9fe8d9e678..67f6cee727 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -956,7 +956,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when - // the path was, or when the compound path it leaves was. + // the path was, or when the compound path it leaves was. A compound path that is + // pixel-aligned snaps the path it takes in. if let Some(c) = into { let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { @@ -966,9 +967,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result { *live = None; } } - if aligned && let Some(cn) = d.node_mut(c) { - cn.extras_mut().pixel_aligned = true; - super::object::snap_if_aligned(cn); + if let Some(cn) = d.node_mut(c) { + aligned |= cn.extras().pixel_aligned; + if aligned { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } } } if let Some((appearance, aligned)) = out_of diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 3bec14515a..55ea019e82 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -171,8 +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")] + /// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a + /// saved or Recent preset's value past it is read as `MAX_ARTBOARDS`). + #[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")] 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). @@ -594,6 +595,11 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d747f34989..dba64bf53c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -702,9 +702,18 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>>()?, ); - s.edit("Reshape", |d, _| { - *path_mut(d, id)? = data; + s.edit("Reshape", |d, sel| { + let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>(); + let path = path_mut(d, id)?; + let reshaped = counts(path) != counts(&data); + *path = data; super::object::resnap(d, id); + // Direct-selected anchors and segments are kept by index: when anchors were added or + // removed, the path is deselected rather than left with other anchors selected. + if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { + sel.objects.retain(|o| *o != id); + sel.prune(d); + } Ok(()) })?; ok() diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e8d0cc404a..b6a1160e28 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -109,6 +109,11 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, + /// How many times [`paths`] changed the waiting point changes, which makes a + /// [`paths::PointIndex`] of them stale. + pending_changes: Cell, + /// Where the points of the path the run last read points of start, by subpath ([`paths`]). + point_index: RefCell>, /// How many times the points the run read of each path went stale, by document uid and path id /// ([`paths`]). point_cuts: RefCell>, @@ -125,6 +130,9 @@ pub(super) struct State { /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently /// used first, each kept while its document is unchanged. art: RefCell>, + /// The last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first, + /// each kept while its document is unchanged. + layer_lists: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, /// Each open document's uid and the index of its active artboard when the run started. @@ -716,11 +724,11 @@ fn on_doc_layer( keep_layer: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before, layer) = { + let (index, active, mut before, layer, old) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let st = &s.documents()[index]; - (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.doc.clone()) }; let switch = active != Some(index); if switch { @@ -737,7 +745,28 @@ fn on_doc_layer( 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()) + s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) + }; + // Anchors and segments are selected by index: a path that gained or lost anchors is not + // selected again, so that other anchors of it are not selected in their place. + if let Some(doc) = &doc { + let counts = |d: &Document, id: NodeId| { + d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) + }; + let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); + for id in partial { + if counts(&old, id) != counts(doc, id) { + before.anchors.remove(&id); + before.segments.remove(&id); + before.objects.retain(|o| *o != id); + before.key_anchor = before.key_anchor.filter(|(k, _)| *k != id); + before.key = before.key.filter(|k| *k != id); + } + } + } + let doc = { + let s = h.session.borrow(); + doc.filter(|_| s.active().is_some_and(|st| st.selection != before)) }; if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); @@ -1104,8 +1133,21 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { } // 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()); + let mut shadowed_by = None; if let Some(first) = first { - p.insert("preset".into(), json!(first.name)); + let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim())); + if shadowed { + shadowed_by = Some(first.clone()); + // `file.new` would find the saved preset of that name first: the built-in preset's + // settings go as params instead, under the ones `presetSettings` gives. + if let Value::Object(base) = first.to_json() { + for (k, v) in base.into_iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "size" | "orientation" | "profile")) { + p.entry(k).or_insert(v); + } + } + } else { + p.insert("preset".into(), json!(first.name)); + } } p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); if let Some(m) = mode { @@ -1120,6 +1162,15 @@ 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}"))); } + // The built-in preset's settings went as params: Recent keeps its name, as `file.new` + // keeps a preset's name, unless its size changed (turning it doesn't count). + if let Some(first) = &shadowed_by { + let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); + let mut s = h.session.borrow_mut(); + if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) { + r.name.clone_from(&first.name); + } + } // 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)); @@ -1346,6 +1397,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // 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(); @@ -1360,7 +1412,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { bounds(h, a, true) } +/// The box of the anchors and direction handles of the paths in `n` that its visible bounds take +/// in: a clipping group or layer gives only its clipping path's, and the source art a Shaper Group +/// or a tracing keeps is left out, as are hidden objects. +fn handles_box(n: &vectorcraft_doc::Node) -> Option { + let children = n.editing_children(); + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + _ if n.clips() => children.first().and_then(|c| handles_box(c)), + _ => children.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, handles_box(c))), + } +} + +/// The item's visible bounds grown to take in the direction handles of its paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = with_doc(h, item.doc, |_, st| { + let visible = st.doc.bounds_of(&[item.id], true); + let handles = st.doc.node(item.id).and_then(handles_box); + let r = vectorcraft_geom::union_opt(visible, handles).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok::<_, HostError>((r, frame(st)?)) + })?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -2140,7 +2216,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 23e4d58170..7a24b8fa3e 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -474,6 +474,39 @@ fn layer_list(d: &Document, parent: Option) -> Vec { list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() } +/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers. +pub(super) type LayerList = (u64, Arc, Option, Rc>); + +/// How many lists of layers [`super::State`] keeps at once. +pub(super) const LAYER_LISTS: usize = 4; + +/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a +/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at. +fn layer_ids(h: &Host, st: &DocState, parent: Option) -> Result>> { + { + let mut lists = h.dom.layer_lists.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } + } + let looked = match parent { + None => st.doc.layers.len(), + Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), + }; + h.charge_call(looked as u64)?; + let ids = Rc::new(layer_list(&st.doc, parent)); + let mut lists = h.dom.layer_lists.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= LAYER_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), parent, ids.clone())); + Ok(ids) +} + fn layers_of(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let [high, low] = id_parts(id); @@ -482,7 +515,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer { fn layers_length(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; - Ok(num(float(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -499,14 +532,14 @@ fn layers_at(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; 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| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) + with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) } fn layers_by_name(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; 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 = layer_list(&st.doc, parent); + let ids = layer_ids(h, st, parent)?; 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| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -659,6 +692,8 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { 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 = art_list(h, st, kind, c)?; + // The scan is charged by itself: a list kept from an earlier read was charged once. + 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())) }) @@ -767,10 +802,8 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - // A compound path's `pathItems` are its `PageItems`: it holds only paths. - let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); - Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -856,6 +889,13 @@ fn held_paths(h: &Host, a: &[Data]) -> Answer { Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) } +/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it +/// ([`super::paths`]). +fn compound_paths(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -913,7 +953,7 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths))]), _ => Vec::new(), } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 87287c5c27..19ad6ac4fb 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -131,20 +131,79 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path with the subpaths `subs` has. -fn point_count(subs: &[SubPath]) -> usize { - subs.iter().map(|sp| sp.anchors.len()).sum() +/// The subpaths a [`PointIndex`] was made from. +enum PointSource { + /// The path's node as its document held it, kept so that the node compared with is the same + /// one: any change to the path's points makes a new node. + Node(Arc), + /// The path's waiting point changes, after this many changes to them + /// ([`super::State`]'s `pending_changes`). + Pending(u64), } -/// The subpath and the place in it of point `i`, among the subpaths `subs`. -fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { - for (s, sp) in subs.iter().enumerate() { - if i < sp.anchors.len() { - return Some((s, i)); +/// Where the points of a path start, by subpath, so that a point is found by its index without a +/// pass over the subpaths before it. +pub(super) struct PointIndex { + /// The document uid and the id of the path. + key: (u64, u64), + source: PointSource, + /// The number of points before each subpath. + starts: Vec, + /// The number of points in all. + count: usize, +} + +impl PointIndex { + fn new(key: (u64, u64), source: PointSource, subs: &[SubPath]) -> Self { + let mut starts = Vec::with_capacity(subs.len()); + let mut count = 0; + for sp in subs { + starts.push(count); + count += sp.anchors.len(); } - i -= sp.anchors.len(); + PointIndex { key, source, starts, count } } - None + + /// The subpath and the place in it of point `i`. + fn locate(&self, i: usize) -> Option<(usize, usize)> { + if i >= self.count { + return None; + } + // The last subpath that starts at or before `i`: a subpath with no points starts where the + // next one does, so it is never the one found. + let s = self.starts.partition_point(|&start| start <= i).checked_sub(1)?; + Some((s, i - self.starts[s])) + } +} + +/// The number of points of the path of `item`, its waiting point changes included, and the subpath +/// and the place in it of point `i` when `i` is given and in the path. The index of the path's +/// subpaths is kept in [`super::State`] until the path's points change. +fn point_place(h: &super::Host, item: Item, i: Option) -> std::result::Result<(usize, Option<(usize, usize)>), HostError> { + let key = (item.doc.uid, item.id.0); + let source = match &*h.dom.pending.borrow() { + Some((waiting, _)) if same_path(*waiting, item) => PointSource::Pending(h.dom.pending_changes.get()), + _ => { + let s = h.session.borrow(); + let node = s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, item.id).cloned()); + PointSource::Node(node.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?) + } + }; + let fresh = h.dom.point_index.borrow().as_ref().is_some_and(|x| { + x.key == key + && match (&x.source, &source) { + (PointSource::Node(a), PointSource::Node(b)) => Arc::ptr_eq(a, b), + (PointSource::Pending(a), PointSource::Pending(b)) => a == b, + _ => false, + } + }); + if !fresh { + let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?; + *h.dom.point_index.borrow_mut() = Some(index); + } + let kept = h.dom.point_index.borrow(); + let Some(index) = kept.as_ref() else { return Err(HostError::Error(STALE_ITEM.into())) }; + Ok((index.count, i.and_then(|i| index.locate(i)))) } fn anchor_json(a: &Anchor) -> Value { @@ -171,6 +230,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { @@ -320,7 +380,8 @@ pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { host_ref("PathItems", &[float(h.run), float(uid), high, low]) } -/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths +/// of, if any. fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; match handle.as_slice() { @@ -328,7 +389,9 @@ fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option< [run, uid, high, low] => { 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 holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + let holds = with_doc(h, doc, |_, st| { + st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + }); if !holds { return Err(HostError::Error(STALE_ITEM.into())); } @@ -432,7 +495,9 @@ fn make_in( return Err(HostError::Error(CONTAINER_LOCKED.into())); } let made = match container { - None => on_doc(h, doc.uid, true, make)?, + // Making a path can take more than one command (a stroke, a reversal): a failure of a later + // one undoes the path too. + None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?, Some(c) => super::atomically(h, |h| { let id = on_doc(h, doc.uid, true, |h| { command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; @@ -1124,17 +1189,21 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } - if sx != 100.0 || sy != 100.0 { - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } + // The scale and the new stroke weight are one edit: a failure of either undoes both. + super::atomically(h, |h| { + if sx != 100.0 || sy != 100.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(()) + })?; Ok(Data::Undefined) } @@ -1148,7 +1217,8 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_points(h, item, |subs| num(float(point_count(subs) as u64))) + let (n, _) = point_place(h, item, None)?; + Ok(num(float(n as u64))) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -1272,7 +1342,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(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) }; - let n = read_points(h, item, point_count)?; + let (n, _) = point_place(h, item, None)?; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1290,7 +1360,8 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); - let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; + let (n, _) = point_place(h, item, None)?; + let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } @@ -1324,20 +1395,29 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It return Err(HostError::Error(STALE_POINT.into())); } let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_points(h, item, point_count)?; + let (n, _) = point_place(h, item, None)?; if i >= n { return Err(HostError::Error(STALE_POINT.into())); } Ok((item, i)) } +/// [`this_point`] with the subpath and the place in it of the point. +fn this_point_place(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize, usize), HostError> { + let (item, i) = this_point(h, a)?; + match point_place(h, item, Some(i))? { + (_, Some((s, j))) => Ok((item, s, j)), + (_, None) => Err(HostError::Error(STALE_POINT.into())), + } +} + /// Reads the anchor `this` names with `f`, given the frame and the coordinate system. fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; let c = h.dom.coords.get(); let fr = with_doc(h, item.doc, |_, st| frame(st))?; read_points(h, item, |subs| { - let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); + let anchor = subs.get(s).and_then(|sp| sp.anchors.get(j)); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1345,11 +1425,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// Changes the anchor `this` names with `f`, given the point the script assigned in document /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) - && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) - { + if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); } })?; @@ -1411,10 +1489,10 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) - && let Some(sp) = subs.get_mut(s) + if let Some(sp) = subs.get_mut(s) + && j < sp.anchors.len() { sp.anchors.remove(j); if sp.anchors.is_empty() { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ccb5b7f8d8..3a04359e7f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2227,6 +2227,16 @@ impl Session { RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } + // What the script added must fit the allowance the last answer gave: past it, the + // person is asked again, as a running script is at its next charge. + if let Err(e) = job.host.charge_growth(0, 0) { + return Some(self.script_failed(job, &end_flush_error(e))); + } + if job.host.waiting.get() { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + return None; + } return Some(self.script_ended(job)); } // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 4e99adf688..e2ac91d592 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -422,6 +422,22 @@ fn align_new_objects_to_pixel_grid_follows_the_preset() { assert!(!align(&old)); } +#[test] +fn saved_rows_past_the_limit_read_as_the_limit_and_others_stay() { + let mut s = Session::new(); + let saved = json!({"newDocPresets": [ + {"name": "Many", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 1001}, + {"name": "Four", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 4}, + ]}); + s.apply_prefs(serde_json::from_value(saved).unwrap()); + for (name, rows) in [("Many", 1000), ("Four", 4)] { + let layout = presets(&mut s, "Saved").iter().find(|p| p["name"] == name).unwrap()["artboardLayout"].clone(); + assert_eq!(layout["rows"], json!(rows), "{name}"); + // `file.new` takes the layout `file.newPresets` lists. + s.execute("file.new", &json!({"preset": name, "artboardLayout": layout})).unwrap(); + } +} + #[test] fn rearrange_keeps_its_grid() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index fb7239394a..5368a64c2f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -930,6 +930,19 @@ fn note_is_the_attributes_note() { assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } +#[test] +fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "colorMode": "rgb"})).unwrap(); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); + assert_eq!(out[0], json!([612, 792, "DocumentColorSpace.CMYK"])); + // Recent keeps the built-in preset's name, as it does when no saved preset has it. + assert_eq!(s.prefs.recent_new_docs[0].name, "Letter"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var e = app.documents.addDocument('Print', p); vc.log([e.width, e.height]);"); + assert_eq!(out[0], json!([300, 792])); + assert_eq!(s.prefs.recent_new_docs[0].name, "Custom"); +} + #[test] fn document_preset_applies_only_its_given_fields() { let mut s = Session::new(); @@ -1317,8 +1330,9 @@ 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 query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy(); + let (p, other) = (json!(p), json!(format!("{p}.other"))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({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. @@ -1612,12 +1626,12 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ - vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);", ); let expected = [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; assert_eq!(out[..11], expected); - assert_eq!(out[11..], [json!(false), json!(true)]); + assert_eq!(out[11..], [json!(true), json!(true), json!(true)]); } #[test] @@ -1917,6 +1931,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { assert!(!d.node(a).unwrap().extras().pixel_aligned); } +/// A pixel-aligned compound path snaps a path that was not aligned when it takes it in. +#[test] +fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let loose = rect(&mut s, 200.25, 20.5, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(loose).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": loose.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(loose), Some(cid)); + // Both paths have a 1 pt stroke, so the grid puts their edges where it put the aligned path's. + let (b, at) = (d.node(loose).unwrap().geometric_bounds().unwrap(), d.node(a).unwrap().geometric_bounds().unwrap()); + assert_ne!(b.x0, 200.25); + for (v, w) in [(b.x0, at.x0), (b.y0, at.y0), (b.x1, at.x1), (b.y1, at.y1)] { + assert_eq!(v.fract(), w.fract(), "{b:?} is on the pixel grid as {at:?} is"); + } +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1930,6 +1967,23 @@ fn a_compound_paths_path_items_are_path_items() { assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); } +#[test] +fn a_compound_paths_path_items_add_makes_the_path_inside_it() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.layers[0].compoundPathItems.add(); var p = c.pathItems.add(); p.setEntirePath([[0, 0], [10, 0], [10, 10]]);\ + var r = c.pathItems.rectangle(50, 20, 10, 10); vc.log(c.pathItems.length); vc.log(p.parent.typename); vc.log(r.parent.typename);\ + vc.log(c.pathItems[0].width);", + ); + assert_eq!(out, [json!(2), json!("CompoundPathItem"), json!("CompoundPathItem"), json!(10)]); + let d = &s.active().unwrap().doc; + let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(compound.children().unwrap().len(), 2); + assert!(undo_steps(&s) > steps); +} + #[test] fn art_collections_follow_edits_between_reads() { let (mut s, _, _) = doc(); @@ -1966,6 +2020,18 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); } +#[test] +fn layer_lists_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.length; for (var i = 0; i < L.length; i++) L[i];\ + var made = L.add(); made.name = 'Top'; vc.log(L.length - n); vc.log(L[0].name); vc.log(L.getByName('Top').name);\ + made.remove(); vc.log(L.length - n);", + ); + assert_eq!(out, [json!(1), json!("Top"), json!("Top"), json!(0)]); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 2dbf3263b9..99e83b4ddc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -154,6 +154,72 @@ fn shape_creators_reject_bad_sizes_without_change() { assert_eq!(undo_steps(&s), steps); } +#[test] +fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { + // `pathItems[1]` is `b`. + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + let sel = &st.selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // Moving a point keeps the anchors selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); +} + +#[test] +fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + let pt = |x: f64, y: f64| json!({"x": x, "y": y, "in": [x, y], "out": [x, y], "smooth": false}); + let three = json!([{"anchors": [pt(0.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": three})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // The same number of anchors keeps them selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap(); + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); +} + +/// Points are found by their index across subpaths, through changes that wait to be written and +/// removals that change how many points a subpath has or remove a subpath. +#[test] +fn points_are_found_across_subpaths_as_their_counts_change() { + 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 pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false}); + let subs = json!([ + {"anchors": [pt(0.0), pt(1.0)], "closed": false}, + {"anchors": [pt(2.0)], "closed": false}, + {"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false}, + ]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\ + for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\ + vc.log(q[2].anchor); vc.log(q[5].anchor);\ + q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\ + q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);", + ); + let want = + [json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)]; + assert_eq!(out, want); + let n = node(&s, a); + let counts: Vec = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect(); + assert_eq!(counts, vec![1, 3]); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); @@ -173,6 +239,34 @@ fn set_entire_path_replaces_points_and_keeps_closed() { assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); } +#[test] +fn control_bounds_take_in_direction_handles() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\ + var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\ + n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);", + ); + assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds"); + let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::>(); + let (control, visible) = (edges(&out[2]), edges(&out[3])); + assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}"); + assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}"); +} + +/// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as +/// it is from the visible bounds. +#[test] +fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);"); + assert_eq!(out[0], out[1]); +} + #[test] fn hostile_set_entire_path_input_is_bounded() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2be8a841a8..f89d15d16c 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1297,6 +1297,60 @@ fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() { assert_eq!(state(&s), before); } +/// A script that ends past the allowance the person's last answer gave is asked again before its +/// changes are kept. +#[test] +fn a_finished_run_past_its_last_allowance_asks_again() { + let draw = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('shape.rectangle', {x:2,y:1,width:1,height:1});"; + let point = "var P = app.activeDocument.pathItems, q = P[0];\ + for (var k = 1; k < P.length; k++) if (P[k].pathPoints.length > q.pathPoints.length) q = P[k];\ + var p = q.pathPoints; for (var i = 0; i < p.length; i++) p[i].anchor = [i * 3, -4 - i];"; + // The path the script moves has 600 anchors, so its point changes weigh more than the + // rectangles do. + let two_docs = || { + let mut s = two_docs(); + let id = s.documents()[1].doc.layers[0].children().unwrap()[0].id; + let anchors: Vec = (0..600) + .map(|i| json!({"x": f64::from(i), "y": f64::from(i % 7), "in": [f64::from(i), 0.0], "out": [f64::from(i), 0.0], "smooth": false})) + .collect(); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + s + }; + let added = |source: &str| { + let mut s = two_docs(); + let start = s.documents()[1].doc.clone(); + assert_eq!(run(&mut s, source).unwrap()["ok"], true); + start.retained_bytes_each(&s.documents()[1].doc).1 as u64 + }; + let whole = format!("{draw} {point}"); + let (m, p) = (added(draw), added(&whole) - added(draw)); + // The rectangles go past one object, which asks once, and stay within twice the bytes; the + // point changes, written as the script ends, then go past the second allowance and also past + // the third. + let b = (m + p - 1) / 3; + assert!(m <= 2 * b && 3 * b < m + p && m + p <= 4 * b, "m {m}, p {p}, b {b}"); + TEST_GROWTH.with(|g| g.set(Some(1))); + TEST_GROWTH_BYTES.with(|g| g.set(Some(b))); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &whole).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + TEST_GROWTH_BYTES.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance"); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..de41e7ef6f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -215,7 +215,8 @@ pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(S let global = i.global; i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; } - Ok(()) + // The prototypes, constructors and members are made without a reservation of their own. + i.reserve_heap(0) } fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..a17c420c5e 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -648,6 +648,17 @@ fn with_thing(r: &mut Realm, make: Option) { r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } +#[test] +fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() { + let mut r = realm(1_000_000); + let interp = r.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes; + let class = HostClass { name: "Empty".into(), parent: None, members: Vec::new(), index: None, construct: None }; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); +} + #[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); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 53300e92ec..77183407da 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -820,6 +820,22 @@ mod tests { assert_eq!(shown_columns(&s), 2.0); } + /// The dialog reads rows as `file.new` does: a whole number from 1 to the artboard limit, + /// `4.0` included, and a fractional, zero or larger count is refused with nothing changed. + #[test] + fn the_dialog_reads_rows_as_file_new_does() { + let mut app = app(); + open(&mut app); + set(&app, "artboards", json!(5)).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4.0})).unwrap(); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); + for rows in [json!(3.5), json!(MAX_ARTBOARDS + 1), json!(0)] { + let e = set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": rows})).unwrap_err(); + assert!(e.contains("can't take"), "{rows}: {e}"); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4), "{rows}"); + } + } + /// Press Create: the dialog files its answer and the pump runs `file.new` with it. fn create(app: &mut VectorcraftApp) { let ctx = ctx(app); diff --git a/docs/mcp.md b/docs/mcp.md index 9210de701c..9f0f89f49e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2682,7 +2682,7 @@ 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` (false for an object that is hidden or locked, in a hidden or locked layer or group, + visible bounds grown to take in the paths' direction handles), `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 @@ -2757,8 +2757,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. A layer's or group's `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any - depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound - path's `pathItems` have the typename `PathItems`. A layer's or artboard's `name` takes a number or a boolean as + depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers. A compound + path's `pathItems` are a `PathItems` collection: `add()` and its shape methods make the new path inside the + compound path. A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past From 48a09ccae35e34bd317ef0dcbd0c9cf28df0e9ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 07:05:03 -0800 Subject: [PATCH 009/213] Scripts: Document.exportForScreens writes artboards, assets or the document into a folder Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?) runs document.exportForScreens with one format row. The option classes ExportForScreensOptionsJPEG, ExportForScreensOptionsPNG24, ExportForScreensOptionsPNG8, ExportForScreensOptionsWebOptimizedSVG and ExportForScreensPDFOptions, ExportForScreensItemToExport and the enumerations they use follow the public reference pages. An omitted options object takes a new one's defaults; a bad argument, an options object of another class and an item that names nothing throw before anything is written. The folder gets the same write-access check as a File opened for writing: a folder outside the script's folders is refused, and so is an existing file. A prefix character that a file name may not hold is written as "-". A Folder object passed to a host method now carries its path, as a File does; before, it arrived as an empty object. The script checker counts exportForScreens under filesWritten. Docs: docs/mcp.md, docs/target-app-parity.md, docs/gaps.md. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/save_open.rs | 6 + .../src/script/dom/save_open/screens.rs | 491 ++++++++++++++++++ crates/engine/src/script/files.rs | 12 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_screens.rs | 351 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +- crates/js/src/file_classes.rs | 14 +- crates/js/src/host.rs | 7 +- crates/scriptcheck/src/catalog.rs | 6 +- crates/scriptcheck/src/tests.rs | 15 + docs/gaps.md | 2 +- docs/mcp.md | 40 +- docs/target-app-parity.md | 1 + 14 files changed, 954 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/script/dom/save_open/screens.rs create mode 100644 crates/engine/src/tests/script_screens.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2be7b42074..104511f055 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2077,7 +2077,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// 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.iter().chain(save_open::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(save_open::screens::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6400b32f73..c7c5eadd14 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -62,6 +62,8 @@ use std::rc::Rc; use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; +pub(super) mod screens; + use super::{ Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, property, text, this_doc, whole, @@ -955,6 +957,9 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { ("saved", property(l, doc_saved, doc_set_saved)), ("close", method(l, doc_close)), ]) + .into_iter() + .chain(screens::document_members(l)) + .collect() } /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its @@ -969,5 +974,6 @@ pub(super) fn classes(link: &Link) -> Vec { }); HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } }) + .chain(screens::classes(link)) .collect() } diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs new file mode 100644 index 0000000000..f4008be1b6 --- /dev/null +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -0,0 +1,491 @@ +//! `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)` +//! with `ExportForScreensItemToExport`, the option classes `ExportForScreensOptionsJPEG`, +//! `ExportForScreensOptionsPNG24`, `ExportForScreensOptionsPNG8`, +//! `ExportForScreensOptionsWebOptimizedSVG` and `ExportForScreensPDFOptions`, and the enumerations +//! they use, as the scripting reference pages +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! The method runs `document.exportForScreens` with one format row into the folder, which goes +//! through the script's file grants as a `File` opened for writing there would, and the command +//! writes only where the script's `File` objects may ([`super::exactly`]). +//! +//! VectorCraft's own rules, which the reference pages do not state: +//! - `exportFolder` is a `Folder`, or a `File` read as the folder at its path. The files go into +//! that folder, without sub-folders, each named `.` as +//! `document.exportForScreens` names them (`@2x` after a raster file of twice the size), with +//! the characters a file name may not hold in the prefix written as `-`. The export keeps its +//! settings in the document, as an export from the dialog does. +//! - `itemToExport` exports, in this order, the artboards of `artboards` (`all`, the default, or a +//! range of artboard numbers such as `1-3, 5`; `""` for none), the assets of `assets` (their ids) +//! and, with `document` true, the bounds of the whole document's art (a PDF of every artboard). +//! One that names nothing throws. Each of the three is its own export: when a later one throws, +//! the files of the earlier ones stay written. +//! - `ExportForScreensType.SE_JPEG100`, `SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a +//! quality of 100, 80, 50 and 20. A scale factor is from 0.01 to 64 and a resolution from 0.72 +//! to 4608 ppi. +//! - `RasterImageLocation.PRESERVE`, the default, embeds raster images as `EMBED` does, and +//! `SVGFontType.SVGFONT`, the default, writes text as SVG text elements. +//! - Options are read as `Document.exportFile` reads them: a listed option that is not mapped is +//! accepted at its default and throws at any other value, and a property the pages do not list +//! throws an error that names it, unless it is `undefined`. The options object's class must be +//! the one of `exportFormat`, and an omitted options object takes the defaults a new one holds. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; + +use super::{ + Answer, Default, Host, Link, MAX_TEXT_BYTES, OptionClass, arg, boolean, builtin_preset_name, command, current, exactly, fresh, given, member, + method, named, num, on_doc, plain, refused, text, this_doc, typename, whole, whole_in, written_as_range, +}; + +/// The enumerations these members use, as `dom`'s are made. +pub(in crate::script::dom) const ENUMS: &[(&str, &[&str])] = &[ + ("ExportForScreensType", &["SE_JPEG100", "SE_JPEG20", "SE_JPEG50", "SE_JPEG80", "SE_PDF", "SE_PNG24", "SE_PNG8", "SE_SVG"]), + ("ExportForScreensScaleType", &["SCALEBYFACTOR", "SCALEBYHEIGHT", "SCALEBYRESOLUTION", "SCALEBYWIDTH"]), + ("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), + ("JPEGCompressionMethodType", &["BASELINEOPTIMIZED", "BASELINESTANDARD", "PROGRESSIVE"]), + ("RasterImageLocation", &["EMBED", "LINK", "PRESERVE"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]), + ("SVGFontType", &["OUTLINEFONT", "SVGFONT"]), + ("SVGIdType", &["SVGIDMINIMAL", "SVGIDREGULAR", "SVGIDUNIQUE"]), +]; + +/// The members of `enumeration` in [`ENUMS`]. +fn members(enumeration: &str) -> &'static [&'static str] { + ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m) +} + +/// The member of `enumeration` that `d` names. +fn pick<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> { + member(d, enumeration, members(enumeration), what) +} + +/// The least and most pixels per point a raster file of an export has. +const SCALE_FACTORS: (f64, f64) = (0.01, 64.0); + +// ---- Raster options ---- + +/// The options JPEG, PNG24 and PNG8 share: anti-aliasing and the size, the size kept under `_scale` +/// and `_scaleValue` until [`size`] reads them together. +fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + match name { + "antiAliasing" => { + let mode = match pick(d, "AntiAliasingMethod", &what)? { + "ARTOPTIMIZED" => "art", + "TYPEOPTIMIZED" => "type", + _ => "none", + }; + p.insert("antiAlias".into(), json!(mode)); + } + "scaleType" => { + p.insert("_scale".into(), json!(pick(d, "ExportForScreensScaleType", &what)?)); + } + "scaleTypeValue" => match d { + Data::Number(n) if n.is_finite() && *n > 0.0 => { + p.insert("_scaleValue".into(), json!(n)); + } + Data::Number(_) => return Err(HostError::Range(format!("{what} must be a number above 0"))), + _ => return Err(HostError::Type(format!("{what} must be a number"))), + }, + _ => return Ok(false), + } + Ok(true) +} + +/// The format row's size from `_scale` and `_scaleValue`: a factor (`scale`), a width or a height +/// in pixels (`width`, `height`), or a resolution (`ppi`). +fn size(p: &mut Map) -> std::result::Result<(), HostError> { + let how = p.remove("_scale").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "SCALEBYFACTOR".into()); + let value = p.remove("_scaleValue").and_then(|v| v.as_f64()).unwrap_or(1.0); + let (lo, hi) = SCALE_FACTORS; + let (key, per_point) = match how.as_str() { + "SCALEBYWIDTH" => ("width", None), + "SCALEBYHEIGHT" => ("height", None), + "SCALEBYRESOLUTION" => ("ppi", Some(value / 72.0)), + _ => ("scale", Some(value)), + }; + if per_point.is_some_and(|f| !(lo..=hi).contains(&f)) { + let range = if key == "ppi" { "from 0.72 to 4608" } else { "from 0.01 to 64" }; + return Err(HostError::Range(format!("scaleTypeValue must be {range} with ExportForScreensScaleType.{how}"))); + } + p.insert(key.into(), json!(value)); + Ok(()) +} + +fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + const CLASS: &str = "ExportForScreensOptionsJPEG"; + let what = format!("{CLASS}.{name}"); + match name { + "compressionMethod" => { + let method = match pick(d, "JPEGCompressionMethodType", &what)? { + "BASELINEOPTIMIZED" => "optimized", + "PROGRESSIVE" => "progressive", + _ => "baseline", + }; + p.insert("method".into(), json!(method)); + } + "embedICCProfile" => { + p.insert("embedIcc".into(), json!(boolean(d, &what)?)); + } + "progressiveScan" => { + p.insert("scans".into(), json!(whole_in(d, &what, 3, 5)?)); + } + _ => return raster_map(CLASS, name, d, p), + } + Ok(true) +} + +fn jpeg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("compressionMethod", text("JPEGCompressionMethodType.BASELINESTANDARD")), + ("embedICCProfile", Data::Bool(false)), + ("progressiveScan", num(3.0)), + ("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")), + ("scaleTypeValue", num(1.0)), + ] +} + +/// PNG24's background, kept under `_transparent` and `_black` until [`background`] reads them +/// together. +fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + const CLASS: &str = "ExportForScreensOptionsPNG24"; + let what = format!("{CLASS}.{name}"); + match name { + "transparency" => { + p.insert("_transparent".into(), json!(boolean(d, &what)?)); + } + "backgroundBlack" => { + p.insert("_black".into(), json!(boolean(d, &what)?)); + } + "interlaced" => { + p.insert("interlaced".into(), json!(boolean(d, &what)?)); + } + _ => return raster_map(CLASS, name, d, p), + } + Ok(true) +} + +/// The PNG24 row's `background`: transparent with `transparency`, otherwise black with +/// `backgroundBlack` and white without it. +fn background(p: &mut Map) { + let transparent = p.remove("_transparent").and_then(|v| v.as_bool()).unwrap_or(true); + let black = p.remove("_black").and_then(|v| v.as_bool()).unwrap_or(false); + let background = if transparent { + "transparent" + } else if black { + "black" + } else { + "white" + }; + p.insert("background".into(), json!(background)); +} + +fn png24_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("backgroundBlack", Data::Bool(false)), + ("interlaced", Data::Bool(false)), + ("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")), + ("scaleTypeValue", num(1.0)), + ("transparency", Data::Bool(true)), + ] +} + +fn png8_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + const CLASS: &str = "ExportForScreensOptionsPNG8"; + let what = format!("{CLASS}.{name}"); + match name { + "colorCount" => { + p.insert("colors".into(), json!(whole_in(d, &what, 2, 256)?)); + } + "interlaced" => { + p.insert("interlaced".into(), json!(boolean(d, &what)?)); + } + "transparency" => { + p.insert("transparency".into(), json!(boolean(d, &what)?)); + } + // Matted on white, the default `matteColor`, or not matted. + "matte" => { + p.insert("matte".into(), if boolean(d, &what)? { json!("white") } else { Value::Null }); + } + _ => return raster_map(CLASS, name, d, p), + } + Ok(true) +} + +const PNG8_KEPT: &[(&str, Default)] = &[("matteColor", Default::Unset)]; + +fn png8_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("colorCount", num(128.0)), + ("interlaced", Data::Bool(false)), + ("matte", Data::Bool(true)), + ("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")), + ("scaleTypeValue", num(1.0)), + ("transparency", Data::Bool(true)), + ] +} + +// ---- Vector options ---- + +fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportForScreensOptionsWebOptimizedSVG.{name}"); + let (key, value) = match name { + "coordinatePrecision" => ("decimals", json!(whole_in(d, &what, 1, 7)?)), + "cssProperties" => { + let styling = match pick(d, "SVGCSSPropertyLocation", &what)? { + "ENTITIES" => "entities", + "PRESENTATIONATTRIBUTES" => "presentation", + "STYLEELEMENTS" => "css", + _ => "style", + }; + ("styling", json!(styling)) + } + "fontType" => ("outlineText", json!(pick(d, "SVGFontType", &what)? == "OUTLINEFONT")), + "rasterImageLocation" => ("images", json!(if pick(d, "RasterImageLocation", &what)? == "LINK" { "link" } else { "embed" })), + "svgId" => { + let ids = match pick(d, "SVGIdType", &what)? { + "SVGIDMINIMAL" => "minimal", + "SVGIDUNIQUE" => "unique", + _ => "layerNames", + }; + ("objectIds", json!(ids)) + } + "svgMinify" => ("minify", json!(boolean(d, &what)?)), + "svgResponsive" => ("responsive", json!(boolean(d, &what)?)), + _ => return Ok(false), + }; + p.insert(key.into(), value); + Ok(true) +} + +fn svg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("coordinatePrecision", num(3.0)), + ("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")), + ("fontType", text("SVGFontType.SVGFONT")), + ("rasterImageLocation", text("RasterImageLocation.PRESERVE")), + ("svgId", text("SVGIdType.SVGIDREGULAR")), + ("svgMinify", Data::Bool(false)), + ("svgResponsive", Data::Bool(true)), + ] +} + +/// The PDF preset's name, at most 255 bytes, as the reference page limits it. +fn pdf_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + if name != "pdfPreset" { + return Ok(false); + } + let what = "ExportForScreensPDFOptions.pdfPreset"; + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > 255 { + return Err(HostError::Range(format!("{what} is longer than 255 bytes"))); + } + if !s.is_empty() { + p.insert("preset".into(), json!(s)); + } + Ok(true) +} + +fn pdf_starts() -> Vec<(&'static str, Data)> { + Vec::new() +} + +// ---- What to export ---- + +/// `ExportForScreensItemToExport`'s properties, kept under `_artboards`, `_assets` and `_document` +/// until [`exports`] reads them. +fn item_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportForScreensItemToExport.{name}"); + match name { + "artboards" => { + let r = match d { + Data::String(s) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range(format!("{what} is too long"))), + Data::String(s) => s.clone(), + Data::Number(n) => { + whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?; + vectorcraft_js::number_to_string(*n) + } + _ => return Err(HostError::Type(format!("{what} must be a string"))), + }; + p.insert("_artboards".into(), json!(r)); + } + "assets" => { + let Data::Array(ids) = d else { return Err(HostError::Type(format!("{what} must be an array of asset ids"))) }; + let ids = ids + .iter() + .map(|id| match id { + Data::Number(n) => whole(*n).ok_or_else(|| HostError::Range(format!("{what} holds {n}, not an asset id"))), + _ => Err(HostError::Type(format!("{what} must be an array of asset ids"))), + }) + .collect::, HostError>>()?; + p.insert("_assets".into(), json!(ids)); + } + "document" => { + p.insert("_document".into(), json!(boolean(d, &what)?)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn item_starts() -> Vec<(&'static str, Data)> { + vec![("artboards", text("all")), ("assets", Data::Array(Vec::new())), ("document", Data::Bool(false))] +} + +const JPEG: OptionClass = OptionClass { name: "ExportForScreensOptionsJPEG", map: jpeg_map, kept: &[], starts: jpeg_starts }; +const PNG24: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG24", map: png24_map, kept: &[], starts: png24_starts }; +const PNG8: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG8", map: png8_map, kept: PNG8_KEPT, starts: png8_starts }; +const SVG: OptionClass = OptionClass { name: "ExportForScreensOptionsWebOptimizedSVG", map: svg_map, kept: &[], starts: svg_starts }; +const PDF: OptionClass = OptionClass { name: "ExportForScreensPDFOptions", map: pdf_map, kept: &[], starts: pdf_starts }; +const ITEM: OptionClass = OptionClass { name: "ExportForScreensItemToExport", map: item_map, kept: &[], starts: item_starts }; + +/// The params of `class` for `d` (a new object's when `d` is omitted), over a new object's, so a +/// property a record leaves out keeps its default. +fn params(class: &OptionClass, d: Option<&Data>) -> std::result::Result, HostError> { + let mut p = super::options_params(class, &fresh(class))?; + if let Some(d) = d { + p.extend(super::options_params(class, d)?); + } + Ok(p) +} + +/// The format row `exportFormat` (`d`) asks for, with its option class. +fn format(d: &Data) -> std::result::Result<(Map, &'static OptionClass), HostError> { + let (format, quality, class) = match pick(d, "ExportForScreensType", "exportFormat")? { + "SE_JPEG100" => ("jpg", Some(100), &JPEG), + "SE_JPEG80" => ("jpg", Some(80), &JPEG), + "SE_JPEG50" => ("jpg", Some(50), &JPEG), + "SE_JPEG20" => ("jpg", Some(20), &JPEG), + "SE_PNG24" => ("png", None, &PNG24), + "SE_PNG8" => ("png8", None, &PNG8), + "SE_SVG" => ("svg", None, &SVG), + _ => ("pdf", None, &PDF), + }; + let mut row = Map::new(); + row.insert("format".into(), json!(format)); + if let Some(q) = quality { + row.insert("quality".into(), json!(q)); + } + Ok((row, class)) +} + +/// The exports `itemToExport` asks for, in order: the artboards, the assets and the whole +/// document, each as the params that pick it. +fn exports(d: Option<&Data>) -> std::result::Result>, HostError> { + if let Some(d) = d + && typename(d) != Some(ITEM.name) + { + return Err(HostError::Type("itemToExport must be an ExportForScreensItemToExport object".into())); + } + let mut p = params(&ITEM, d)?; + let mut out = Vec::new(); + if let Some(Value::String(r)) = p.remove("_artboards") { + let all = r.trim().eq_ignore_ascii_case("all"); + if !r.trim().is_empty() { + if !all && !written_as_range(&r) { + return Err(HostError::Range(format!("ExportForScreensItemToExport.artboards `{r}` is not a range of artboard numbers"))); + } + out.push(Map::from_iter([("range".to_string(), json!(if all { "all" } else { r.as_str() }))])); + } + } + if let Some(ids) = p.remove("_assets").filter(|v| v.as_array().is_some_and(|a| !a.is_empty())) { + out.push(Map::from_iter([("assets".to_string(), ids)])); + } + if p.remove("_document").and_then(|v| v.as_bool()) == Some(true) { + out.push(Map::from_iter([("fullDocument".to_string(), json!(true))])); + } + if out.is_empty() { + return Err(HostError::Error( + "exportForScreens has nothing to export: itemToExport names no artboards, no assets and not the document".into(), + )); + } + Ok(out) +} + +/// The path of the `Folder` (or `File`) argument `d`, or a `TypeError`. +fn folder_path(d: &Data) -> std::result::Result<&str, HostError> { + let wrong = || HostError::Type("exportForScreens needs a Folder".into()); + if let Some(p) = vectorcraft_js::file_ref_path(d) { + return Ok(p); + } + let Data::Object(items) = d else { return Err(wrong()) }; + match items.as_slice() { + [(k, Data::String(path))] if k == vectorcraft_js::FOLDER_REF_KEY => Ok(path), + _ => Err(wrong()), + } +} + +/// `document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, +/// fileNamePrefix?)`: `document.exportForScreens` of one format row into the folder, once for each +/// of the artboards, the assets and the whole document that `itemToExport` names. +fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let folder = folder_path(arg(a, 1))?; + let (mut row, class) = format(arg(a, 2))?; + let options = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)); + let mut q = params(class, options)?; + if class.name == PNG24.name { + background(&mut q); + } + if class.name == PDF.name { + builtin_preset_name(h, &mut q); + } else if class.name != SVG.name { + size(&mut q)?; + } + row.extend(q); + let exports = exports(given(arg(a, 4)).filter(|d| !matches!(d, Data::Null)))?; + let prefix = match given(arg(a, 5)).filter(|d| !matches!(d, Data::Null)) { + None => None, + Some(Data::String(s)) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range("fileNamePrefix is too long".into())), + Some(Data::String(s)) => Some(s.clone()), + Some(_) => return Err(HostError::Type("fileNamePrefix must be a string".into())), + }; + let real = h.disk.borrow().folder_target(folder).map_err(|m| refused(m, folder))?; + let mut base = Map::new(); + base.insert("folder".into(), json!(plain(real))); + base.insert("folders".into(), json!("none")); + base.insert("formats".into(), json!([Value::Object(row)])); + if let Some(prefix) = prefix { + base.insert("prefix".into(), json!(prefix)); + } + for items in exports { + let mut p = base.clone(); + p.extend(items); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.exportForScreens", &Value::Object(p))))?; + } + Ok(Data::Undefined) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("exportForScreens", method(l, doc_export_for_screens))]) +} + +/// The classes: each `new Name()` gives a record with its `typename` and the defaults its reference +/// page gives. +pub(super) fn classes(link: &Link) -> Vec { + [&ITEM, &JPEG, &PNG24, &PNG8, &SVG, &PDF] + .into_iter() + .map(|c| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + Ok(fresh(c)) + }); + HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }) + .collect() +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 4f9358fb90..944a3dd5f6 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -127,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; pub(crate) const READ_ONLY: &str = "Script file is read-only"; pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; +pub(crate) const NOT_FOLDER: &str = "Script folder is a file"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; #[cfg(not(unix))] @@ -712,6 +713,17 @@ impl Disk { } } + /// The real path of the folder `path` that an export writes its files into, as a `File` + /// opened for writing there would reach it ([`Disk::target`]), or why it may not: a file is + /// not a folder. + pub(crate) fn folder_target(&self, path: &str) -> Result { + let real = self.target(path, true)?; + match std::fs::metadata(&real) { + Ok(m) if !m.is_dir() => Err(NOT_FOLDER), + _ => Ok(real), + } + } + /// The real path of the file `path` that opening it as a document reads, as a `File` reads it /// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or /// the script may not read it. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cad79e5046..cb2acdc530 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -181,6 +181,7 @@ mod script_include; mod script_io; mod script_run; mod script_save_open; +mod script_screens; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_screens.rs b/crates/engine/src/tests/script_screens.rs new file mode 100644 index 0000000000..c9bd000e1d --- /dev/null +++ b/crates/engine/src/tests/script_screens.rs @@ -0,0 +1,351 @@ +//! Exporting for screens from a script: `Document.exportForScreens`, `ExportForScreensItemToExport`, +//! the option classes and the file grants the folder goes through. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-screens-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn session(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +/// The script's data folder, where it may write. +fn data_folder(s: &mut Session, base: &Path) -> PathBuf { + PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +/// The names of the files in `dir`, sorted; none when it is not there. +fn names(dir: &Path) -> Vec { + let mut v: Vec = + std::fs::read_dir(dir).map(|r| r.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + v.sort(); + v +} + +/// A script that makes a document of two artboards with a rectangle on the first, in `dir`. +fn two_artboards(dir: &Path) -> String { + format!( + "Folder.userData; var dir = {}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n", + quoted(dir) + ) +} + +/// Each export type writes its format into the folder, a file per artboard of the item's range, at +/// the size the options' scale type gives. +#[test] +fn export_for_screens_writes_each_format_into_the_folder() { + let base = folder("formats"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "{}var one = new ExportForScreensItemToExport(); one.artboards = '1';\n\ + vc.log([one.typename, new ExportForScreensItemToExport().artboards, new ExportForScreensOptionsJPEG().scaleTypeValue]);\n\ + d.exportForScreens(new Folder(dir + '/jpg'), ExportForScreensType.SE_JPEG100, undefined, one);\n\ + var p = new ExportForScreensOptionsPNG24(); p.scaleType = ExportForScreensScaleType.SCALEBYFACTOR; p.scaleTypeValue = 2;\n\ + d.exportForScreens(new Folder(dir + '/png'), ExportForScreensType.SE_PNG24, p);\n\ + var w = new ExportForScreensOptionsPNG8(); w.scaleType = ExportForScreensScaleType.SCALEBYWIDTH; w.scaleTypeValue = 50;\n\ + d.exportForScreens(new Folder(dir + '/png8'), ExportForScreensType.SE_PNG8, w, one);\n\ + var r = new ExportForScreensOptionsJPEG(); r.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; r.scaleTypeValue = 144;\n\ + d.exportForScreens(new Folder(dir + '/ppi'), ExportForScreensType.SE_JPEG20, r, one);\n\ + d.exportForScreens(new Folder(dir + '/svg'), ExportForScreensType.SE_SVG);\n\ + d.exportForScreens(new Folder(dir + '/pdf'), ExportForScreensType.SE_PDF, new ExportForScreensPDFOptions(), one);", + two_artboards(&dir) + ), + ); + assert_eq!(out[0], json!(["ExportForScreensItemToExport", "all", 1])); + let size = |sub: &str| { + let files = names(&dir.join(sub)); + let image = image::open(dir.join(sub).join(&files[0])).unwrap(); + (files, image.width(), image.height()) + }; + let (jpg, w, h) = size("jpg"); + assert!(jpg.len() == 1 && jpg[0].ends_with(".jpg"), "one artboard: {jpg:?}"); + assert_eq!((w, h), (200, 100), "a pixel per point at 1x"); + let (png, w, h) = size("png"); + assert!(png.len() == 2 && png.iter().all(|n| n.ends_with("@2x.png")), "both artboards at 2x: {png:?}"); + assert_eq!((w, h), (400, 200), "{png:?}"); + let (png8, w, h) = size("png8"); + assert_eq!(png8.len(), 1, "{png8:?}"); + assert_eq!((w, h), (50, 25), "50 pixels wide, in proportion"); + let (_, w, h) = size("ppi"); + assert_eq!((w, h), (400, 200), "144 ppi is two pixels per point"); + let svg = names(&dir.join("svg")); + assert!(svg.len() == 2 && svg.iter().all(|n| n.ends_with(".svg")), "{svg:?}"); + let pdf = names(&dir.join("pdf")); + assert_eq!(pdf.len(), 1, "{pdf:?}"); + assert!(std::fs::read(dir.join("pdf").join(&pdf[0])).unwrap().starts_with(b"%PDF")); + assert_eq!(s.active().unwrap().path, None, "the export leaves the document's file as it is"); + let _ = std::fs::remove_dir_all(base); +} + +/// Without options, an export writes what an untouched new options object of its class gives. +#[test] +fn omitted_options_are_a_new_options_objects_defaults() { + let base = folder("defaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let types = [ + ("SE_JPEG80", "ExportForScreensOptionsJPEG"), + ("SE_PNG24", "ExportForScreensOptionsPNG24"), + ("SE_PNG8", "ExportForScreensOptionsPNG8"), + ("SE_SVG", "ExportForScreensOptionsWebOptimizedSVG"), + ]; + let calls: String = types + .iter() + .map(|(t, c)| { + format!( + "d.exportForScreens(new Folder(dir + '/{t}-a'), ExportForScreensType.{t});\n\ + d.exportForScreens(new Folder(dir + '/{t}-b'), ExportForScreensType.{t}, new {c}());\n" + ) + }) + .collect(); + logged(&mut s, &base, &format!("{}{calls}", two_artboards(&dir))); + for (t, _) in types { + let (a, b) = (dir.join(format!("{t}-a")), dir.join(format!("{t}-b"))); + assert!(names(&a) == names(&b) && names(&a).len() == 2, "{t}: {:?} {:?}", names(&a), names(&b)); + for n in names(&a) { + assert!(std::fs::read(a.join(&n)).unwrap() == std::fs::read(b.join(&n)).unwrap(), "{t}: {n} differs"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +/// `itemToExport` exports the artboards of its range, its assets and the whole document, each that +/// it names; one that names nothing throws and writes nothing. +#[test] +fn item_to_export_picks_artboards_assets_and_the_document() { + let base = folder("items"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "{}var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\ + var a = new ExportForScreensItemToExport(); a.artboards = ''; a.assets = ids;\n\ + d.exportForScreens(new Folder(dir + '/assets'), ExportForScreensType.SE_SVG, undefined, a);\n\ + var whole = new ExportForScreensItemToExport(); whole.artboards = ''; whole.document = true;\n\ + d.exportForScreens(new Folder(dir + '/document'), ExportForScreensType.SE_PNG24, undefined, whole);\n\ + var both = new ExportForScreensItemToExport(); both.assets = ids; both.artboards = '2';\n\ + d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);", + two_artboards(&dir) + ), + ); + assert_eq!(names(&dir.join("assets")), ["Logo.svg"]); + let whole = names(&dir.join("document")); + assert_eq!(whole.len(), 1, "{whole:?}"); + let image = image::open(dir.join("document").join(&whole[0])).unwrap(); + let (w, h) = (image.width(), image.height()); + assert!((50..60).contains(&w) && (20..30).contains(&h), "the bounds of the document's art, not an artboard: {w}x{h}"); + let both = names(&dir.join("both")); + assert!(both.len() == 2 && both.contains(&"Logo.svg".to_string()), "artboard 2 and the asset: {both:?}"); + for empty in ["''", "' '"] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var i = new ExportForScreensItemToExport(); i.artboards = {empty};\n\ + app.activeDocument.exportForScreens(new Folder({} + '/none'), ExportForScreensType.SE_PNG24, undefined, i);", + quoted(&dir) + ), + ); + assert!(e.contains("nothing to export"), "{empty}: {e}"); + } + assert!(!dir.join("none").exists(), "an empty item writes nothing"); + let _ = std::fs::remove_dir_all(base); +} + +/// The prefix comes before each file's name, and a path character in it does not make a folder or +/// reach out of the export folder. +#[test] +fn a_file_name_prefix_stays_in_the_folder() { + let base = folder("prefix"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "{}d.exportForScreens(new Folder(dir + '/out'), ExportForScreensType.SE_SVG, undefined, undefined, 'web-');\n\ + d.exportForScreens(new Folder(dir + '/up'), ExportForScreensType.SE_SVG, undefined, undefined, '../x/');", + two_artboards(&dir) + ), + ); + let out = names(&dir.join("out")); + assert!(out.len() == 2 && out.iter().all(|n| n.starts_with("web-")), "{out:?}"); + let up = names(&dir.join("up")); + assert!(up.len() == 2 && up.iter().all(|n| n.starts_with("..-x-")), "{up:?}"); + assert!(std::fs::read_dir(dir.join("up")).unwrap().all(|e| e.unwrap().file_type().unwrap().is_file()), "no folder was made"); + assert!(!dir.join("x").exists(), "nothing is written beside the folder"); + let _ = std::fs::remove_dir_all(base); +} + +/// The folder goes through the script's file grants: one outside them, and a file given as the +/// folder, throw before anything is written. +#[test] +fn an_unwritable_folder_is_refused() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("taken"), "kept").unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let outside = quoted(&base.join("outside/screens")); + let e = failure( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({outside}), ExportForScreensType.SE_PNG24);"), + ); + assert!(e.contains(DENIED), "{e}"); + assert!(!base.join("outside/screens").exists()); + let taken = quoted(&dir.join("taken")); + let e = + failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({taken}), ExportForScreensType.SE_PNG24);")); + assert!(e.contains(crate::script::files::NOT_FOLDER), "{e}"); + assert_eq!(std::fs::read_to_string(dir.join("taken")).unwrap(), "kept"); + assert_eq!(names(&base.join("outside")), Vec::::new()); + let _ = std::fs::remove_dir_all(base); +} + +/// Only a `Folder` the `Folder` class made (or a `File`) names the folder: an object made from +/// `Folder.prototype` throws a `TypeError`, and a `Folder` whose hidden path property a script set +/// keeps its own path. +#[test] +fn a_forged_folder_is_refused() { + let base = folder("forged"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let (inside, outside) = (quoted(&dir.join("in")), quoted(&base.join("outside/x"))); + let call = |f: &str| format!("Folder.userData; app.activeDocument.exportForScreens({f}, ExportForScreensType.SE_SVG);"); + let made = format!("(function () {{ var f = Object.create(Folder.prototype); f.__vcPath = {inside}; return f; }})()"); + let e = failure(&mut s, &base, &call(&made)); + assert!(e.contains("TypeError") && e.contains("needs a Folder"), "{e}"); + let moved = format!("(function () {{ var f = new Folder({outside}); f.__vcPath = {inside}; return f; }})()"); + let e = failure(&mut s, &base, &call(&moved)); + assert!(e.contains(DENIED), "{e}"); + assert!(!dir.join("in").exists() && !base.join("outside/x").exists(), "nothing is written"); + logged(&mut s, &base, &call(&format!("new File({inside})"))); + assert_eq!(names(&dir.join("in")).len(), 1, "a File names the folder at its path"); + let _ = std::fs::remove_dir_all(base); +} + +/// Bad arguments throw before anything is written. +#[test] +fn bad_arguments_are_refused_with_an_error() { + let base = folder("bad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let f = format!("new Folder({})", quoted(&dir.join("x"))); + let e = "app.activeDocument.exportForScreens"; + let long = "a".repeat(300); + let cases: Vec<(String, &str)> = vec![ + (format!("{e}('x', ExportForScreensType.SE_PNG24);"), "needs a Folder"), + (format!("{e}({f}, 'SE_PNG24');"), "ExportForScreensType"), + (format!("{e}({f}, ExportType.PNG24);"), "ExportForScreensType"), + (format!("{e}({f}, ExportForScreensType.SE_PNG24, new ExportForScreensOptionsJPEG());"), "ExportForScreensOptionsPNG24"), + ( + format!("{e}({f}, ExportForScreensType.SE_SVG, {{typename: 'ExportForScreensOptionsWebOptimizedSVG', svgMinified: true}});"), + "has no option svgMinified", + ), + (format!("var o = new ExportForScreensOptionsJPEG(); o.progressiveScan = 6; {e}({f}, ExportForScreensType.SE_JPEG50, o);"), "from 3 to 5"), + (format!("var o = new ExportForScreensOptionsPNG8(); o.colorCount = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "from 2 to 256"), + (format!("var o = new ExportForScreensOptionsPNG8(); o.matteColor = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "not available yet"), + (format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 0; {e}({f}, ExportForScreensType.SE_PNG24, o);"), "above 0"), + ( + format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 100; {e}({f}, ExportForScreensType.SE_PNG24, o);"), + "from 0.01 to 64", + ), + ( + format!( + "var o = new ExportForScreensOptionsPNG24(); o.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; o.scaleTypeValue = 5000; {e}({f}, ExportForScreensType.SE_PNG24, o);" + ), + "from 0.72 to 4608", + ), + ( + format!("var o = new ExportForScreensOptionsPNG24(); o.scaleType = 'SCALEBYWIDTH'; {e}({f}, ExportForScreensType.SE_PNG24, o);"), + "ExportForScreensScaleType", + ), + ( + format!("var o = new ExportForScreensOptionsPNG24(); o.antiAliasing = true; {e}({f}, ExportForScreensType.SE_PNG24, o);"), + "AntiAliasingMethod", + ), + ( + format!("var o = new ExportForScreensOptionsWebOptimizedSVG(); o.svgId = SVGFontType.SVGFONT; {e}({f}, ExportForScreensType.SE_SVG, o);"), + "SVGIdType", + ), + (format!("var o = new ExportForScreensPDFOptions(); o.pdfPreset = '{long}'; {e}({f}, ExportForScreensType.SE_PDF, o);"), "255 bytes"), + (format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, {{artboards: '1'}});"), "ExportForScreensItemToExport"), + (format!("var i = new ExportForScreensItemToExport(); i.artboards = '2-1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"), + ( + format!("var i = new ExportForScreensItemToExport(); i.artboards = 0; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "whole number from 1", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.assets = 3; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "array of asset ids", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.assets = [1.5]; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "not an asset id", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.document = 'yes'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "true or false", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.artboard = '1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "has no option artboard", + ), + (format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, 5);"), "fileNamePrefix must be a string"), + (format!("var i = new ExportForScreensItemToExport(); i.artboards = '3'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"), + ]; + for (case, wanted) in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(wanted), "{case}: {e}"); + } + assert!(!dir.join("x").exists(), "nothing was written"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 71a4191fae..cdf92819be 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,6 +39,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.exportForScreens", "app.activeDocument.exportForScreens(f, ExportForScreensType.SE_PNG24);", "filesWritten"), ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; @@ -155,13 +156,28 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of exporting for screens. + ( + "", + "AntiAliasingMethod ExportForScreensScaleType ExportForScreensType JPEGCompressionMethodType RasterImageLocation \ + SVGCSSPropertyLocation SVGFontType SVGIdType", + ), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("ExportForScreensScaleType.", "SCALEBYFACTOR SCALEBYHEIGHT SCALEBYRESOLUTION SCALEBYWIDTH"), + ("ExportForScreensType.", "SE_JPEG100 SE_JPEG20 SE_JPEG50 SE_JPEG80 SE_PDF SE_PNG24 SE_PNG8 SE_SVG"), + ("JPEGCompressionMethodType.", "BASELINEOPTIMIZED BASELINESTANDARD PROGRESSIVE"), + ("RasterImageLocation.", "EMBED LINK PRESERVE"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGFontType.", "OUTLINEFONT SVGFONT"), + ("SVGIdType.", "SVGIDMINIMAL SVGIDREGULAR SVGIDUNIQUE"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions ExportForScreensItemToExport ExportForScreensOptionsJPEG \ + ExportForScreensOptionsPNG24 ExportForScreensOptionsPNG8 ExportForScreensOptionsWebOptimizedSVG ExportForScreensPDFOptions"; /// 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. diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 3b5a21ca8b..3387ad1e00 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -97,15 +97,21 @@ impl Interp { /// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is /// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads - /// it; `None` for any other object, one made with `Object.create(File.prototype)` included. + /// it, or a `Folder` the `Folder` class made, as [`folder_ref`] gives one; `None` for any other + /// object, one made with `Object.create(File.prototype)` or `Object.create(Folder.prototype)` + /// included. pub(crate) fn file_ref_of(&self, id: ObjId) -> JsResult> { let Some(c) = &self.files else { return Ok(None) }; let o = self.object(id)?; - if o.proto != Some(c.file_proto) { + let key = if o.proto == Some(c.file_proto) { + FILE_REF_KEY + } else if o.proto == Some(c.folder_proto) { + FOLDER_REF_KEY + } else { return Ok(None); - } + }; Ok(match &o.class { - Class::FsEntry(s) => Some(crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(s.to_rust_string()))])), + Class::FsEntry(s) => Some(crate::Data::Object(vec![(key.to_string(), crate::Data::String(s.to_rust_string()))])), _ => None, }) } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index e31a8dff9e..60e6c28e06 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -263,11 +263,14 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } - // A `File` reads as its path ([`crate::FILE_REF_KEY`]). + // A `File` or a `Folder` reads as its path ([`crate::FILE_REF_KEY`], [`crate::FOLDER_REF_KEY`]). if r.hosted && let Some(file) = self.file_ref_of(id)? { - let len = crate::file_ref_path(&file).map_or(0, str::len); + let len = match &file { + Data::Object(items) => items.iter().map(|(_, v)| if let Data::String(p) = v { p.len() } else { 0 }).sum(), + _ => 0, + }; self.charge_reading(r, len.saturating_mul(3).saturating_add(2))?; return Ok(file); } diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 7ed0a20efd..e1d2e87c57 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -74,8 +74,10 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; -// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// Document methods that write the file they are given, or files in the folder they are given: +// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and +// https://www.indesignjs.de/indesignapi/illustrator/Document.html (exportForScreens) +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs", "exportForScreens"]; // The save option of `Document.close` that saves the document to its own file: // https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 97b36d2b2c..eedbd638c7 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -543,6 +543,21 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `exportForScreens` writes files into the folder it is given, called directly or by +/// its name in brackets; an object of the script's own that defines it writes nothing. +#[test] +fn export_for_screens_writes_files() { + let r = report(concat!( + "var dir = new Folder(p);\n", + "app.activeDocument.exportForScreens(dir, ExportForScreensType.SE_PNG24);\n", + "documents[0]['exportForScreens'](dir, ExportForScreensType.SE_SVG);\n", + "var local = {exportForScreens: function () {}};\n", + "local.exportForScreens(dir);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3][..])]); +} + /// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in /// brackets, as a string or through a variable; closing without it, and the other save options, /// write nothing. diff --git a/docs/gaps.md b/docs/gaps.md index fad8ae8dba..451bb1f782 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -814,7 +814,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **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, and save, export and open documents with - `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and + `Document.saveAs`, `Document.exportFile`, `Document.exportForScreens` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with `Document.close`. 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 diff --git a/docs/mcp.md b/docs/mcp.md index e45b156a6b..17118c0b91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2589,7 +2589,7 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File - object; a document's `saveAs` or `exportFile` counts too, and so does `SaveOptions.SAVECHANGES` wherever the script + object; a document's `saveAs`, `exportFile` or `exportForScreens` counts too, and so does `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given it saves the document to its file), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, @@ -2846,6 +2846,44 @@ app through the global object `vc`, and writes to the Script Console and runs ot and leaves the document open when the document has no file (a converted or recovered document included); and `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot show the prompt. A bad value throws an error before anything is written. +- `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)` runs + `document.exportForScreens` with one format row into `exportFolder`, a `Folder` (or a `File`, read as the folder at + its path) (https://www.indesignjs.de/indesignapi/illustrator/Document.html). `exportFormat` is an + `ExportForScreensType` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html): `SE_JPEG100`, + `SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a quality of 100, 80, 50 and 20 and take + `new ExportForScreensOptionsJPEG()`; `SE_PNG24` takes `new ExportForScreensOptionsPNG24()`; `SE_PNG8` takes + `new ExportForScreensOptionsPNG8()`; `SE_SVG` takes `new ExportForScreensOptionsWebOptimizedSVG()`; and `SE_PDF` + takes `new ExportForScreensPDFOptions()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsJPEG.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG24.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG8.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsWebOptimizedSVG.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensPDFOptions.html). The raster classes map + `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR`, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, + `SCALEBYRESOLUTION` in ppi); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); + PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`, + `matte` and `transparency`. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, + `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`, and the PDF class maps `pdfPreset` (at most 255 + bytes; a name in square brackets names a built-in preset as `PDFSaveOptions.pDFPreset` does). `itemToExport` is a + `new ExportForScreensItemToExport()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html) + with `artboards` (`all`, the default, a range of artboard numbers such as `1-3, 5`, or `""` for none), `assets` (a + list of asset ids, as `assets.list` gives them) and `document` (false by default). `fileNamePrefix` goes before each + file's name. The enumerations `ExportForScreensType`, `ExportForScreensScaleType`, `AntiAliasingMethod`, + `JPEGCompressionMethodType`, `RasterImageLocation`, `SVGCSSPropertyLocation`, `SVGFontType` and `SVGIdType` hold + strings such as `"ExportForScreensType.SE_PNG24"`. + VectorCraft's own rules: the folder is checked as a `File` opened for writing in it is checked, before the command + runs: a folder outside the script's folders throws `Script file access denied`, and a file throws `Script folder is + a file`. The command writes only where the script's folders allow. The files go into the folder without + sub-folders, each named `.` as `document.exportForScreens` names them (`@2x` + after a raster file at twice the size); a character a file name may not hold, `/` and `\` included, is written as + `-` in the prefix. The export keeps its settings in the document, as an export from the dialog does. The artboards, + the assets and, with `document` true, the bounds of the whole document's art (a PDF of every artboard) are each + their own export, in that order: when a later one throws, the files of the earlier ones stay written. An + `itemToExport` that names nothing throws `nothing to export`. A scale factor is from 0.01 to 64 and a resolution + from 0.72 to 4608 ppi. `RasterImageLocation.PRESERVE`, the default, embeds raster images as `EMBED` does, and + `SVGFontType.SVGFONT`, the default, writes text as SVG text elements. A listed option that is not mapped + (`matteColor`) is accepted at its default and throws at any other value, a property the pages do not list throws an + error that names it, an omitted options object takes the defaults a new one holds, and an options object of + another class throws. A bad value throws an error before anything is written. - `$.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 75a99d9283..b6adf11cbf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1035,6 +1035,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). 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: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_screens.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 bc99687e5e03b8447ca03d0b99593721df979036 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:09:45 -0800 Subject: [PATCH 010/213] Scripts: selection, opacity, PageItems and option checks follow review - Document.selection = undefined (an index past the end of pageItems) throws "this is not a page item" and keeps the selection; null and [] still clear it. Repeated items are found with a set instead of a scan of the list. - Assigning a page item the opacity it already has runs no command, unless a graph keeps another opacity for the item's series or kind. - PageItems.toString() on a stale collection throws as typename does. - PageItem.controlBounds throws "not available yet" instead of returning the visible bounds, which leave out the direction handles. - A host class member that is not available hides an available member of the same name in the class it descends from, for hasOwnProperty and propertyIsEnumerable. - script.check: a call of another method of an object literal with its own saveAs or exportFile (local.install()), and a property assignment that names the variable (this.local = d, $.global['local'] = d), end the exemption, so a later saveAs counts as a file write. - docs/mcp.md: SCALEBYFACTOR is a multiplier from 0.01 to 64, and SCALEBYRESOLUTION takes 0.72 to 4608 ppi. The write_encoded doc comment limits the all-or-nothing case to paths the access check refuses. - Tests: the authored error-origin case throws the Window text, the getIsFileOpen paths are JSON string literals, the folder saveAs case looks up its grant and expects "Script file is not a regular file", the selection case catches the error inside the script, and the close case checks that the file changed. --- crates/engine/src/cmd/fileio/export_names.rs | 5 ++- crates/engine/src/script/dom.rs | 25 +++++++---- crates/engine/src/tests/script_dom.rs | 45 ++++++++++++++----- crates/engine/src/tests/script_run.rs | 2 +- crates/engine/src/tests/script_save_open.rs | 14 ++++-- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/host_classes.rs | 19 ++++---- crates/js/src/host_tests.rs | 33 ++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 44 ++++++++++++++++-- crates/scriptcheck/src/tests.rs | 23 ++++++++++ docs/mcp.md | 12 ++--- 11 files changed, 178 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..dfa1479a9d 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -74,8 +74,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator, key: im /// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}` /// (`files`: every file when there are several; `linked`: the images it links to); with no path /// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is -/// checked against the file access in force before the first file is written, so a refused path -/// writes none of them. +/// checked against the file access in force before the first file is written, so a path that +/// check refuses writes none of them. A write that fails after that check leaves the files +/// written before it. pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result { let files = enc.named(doc, path.unwrap_or(name)); let (main, linked) = files.split_at(enc.files.len()); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 104511f055..337da8c093 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1298,15 +1298,17 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } /// 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. +/// `[]`. Every one must be an object of that document that can be selected; `undefined`, such as an +/// index past the end of `pageItems`, is not a page item. 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::Null => 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()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // 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(); @@ -1321,7 +1323,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { Ok(text("PageItems")) } +fn items_to_string(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)) @@ -1584,9 +1591,9 @@ 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())); } - // 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. + // A value the getter reports for the item's opacity runs no command, unless the item is a graph + // mark or label whose graph keeps another opacity for its series or kind: the opacity it has + // then replaces that one. // 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)?; @@ -1601,7 +1608,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if now.is_none() || keeps_other { refuse_in_closed_layer(h, item)?; } - set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) + set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -2154,7 +2161,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")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); @@ -2174,7 +2181,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("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)), @@ -2187,6 +2193,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), [ "artworkKnockout", "blendingMode", + "controlBounds", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..cb2cf5a63c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -266,8 +266,9 @@ 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[1]; vc.log(i.opacity); i.opacity = i.opacity;"); - assert_eq!(out, vec![json!(33.3333)]); + let r = run(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;").unwrap(); + assert_eq!(r["log"], json!([33.3333])); + assert_eq!(r["slowestCommands"], json!([]), "no command runs for the opacity the item has"); 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. @@ -282,8 +283,14 @@ fn assigning_the_reported_opacity_changes_nothing() { 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}"); + // The script catches the error and reads the selection before the run ends. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, e = '';\ + try { d.selection = [p[0], p[1]]; } catch (x) { e = String(x); } vc.log(e); vc.log(d.selection.length);", + ); + assert!(out[0].as_str().is_some_and(|e| e.contains("Cannot select PathItem")), "{out:?}"); + assert_eq!(out[1], json!(0)); assert!(s.active().unwrap().selection.objects.is_empty()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( @@ -295,6 +302,13 @@ fn selection_assignment_is_atomic_across_invalid_items() { ); assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // An index past the end gives `undefined`, which is not a page item: the selection stays. + let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];"); + assert!(e.contains("this is not a page item"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // A list with an item repeated thousands of times selects it once. + log(&mut s, "var d = app.activeDocument, p = d.pageItems, l = []; for (var i = 0; i < 5000; i++) l.push(p[0], p[1]); d.selection = l;"); + assert_eq!(s.active().unwrap().selection.objects, vec![b, 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];"); @@ -680,9 +694,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { 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")] - { + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } @@ -875,9 +893,12 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].rotate(5);", + "app.activeDocument.pageItems[0].controlBounds;", + ] { 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")); @@ -1345,8 +1366,8 @@ 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 query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let (p, other) = (json!(path.to_string_lossy()), json!(format!("{}.other", path.to_string_lossy()))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({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. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 188656a672..e311f41853 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a3f937a244..15e64aecc2 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -286,8 +286,8 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { } let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({kept}));")); assert!(e.contains("Script file is read-only"), "{e}"); - let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir))); - assert!(e.contains("Script file") && !e.contains("ran"), "a folder is not saved over: {e}"); + let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir))); + assert!(e.contains("Script file is not a regular file"), "a folder is not saved over: {e}"); assert_eq!(std::fs::read_to_string(dir.join("kept.svg")).unwrap(), "kept"); assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), "{}"); assert!(!base.join("outside/x.svg").exists() && !base.join("outside/x.svg.png").exists()); @@ -716,12 +716,18 @@ fn closing_with_save_changes_keeps_the_documents_format() { &base, &format!( "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ - vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\ - vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);" + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());" ), ); + let saved = std::fs::read(dir.join("p.svg")).unwrap_or_default(); + logged( + &mut s, + &base, + "Folder.userData; var d = app.activeDocument; vc.run('shape.rectangle', {x: 20, y: 20, width: 5, height: 5}); d.close(SaveOptions.SAVECHANGES);", + ); let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + assert_ne!(bytes, saved, "the close wrote the second rectangle to the file"); assert!(s.documents().is_empty()); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index cdf92819be..b0ba62e31a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + controlBounds 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= toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..cf26a42490 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -25,11 +25,12 @@ //! //! `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, +//! available yet ([`HostMember::Unavailable`]). A member a class declares, available or not, hides +//! the member of that name in the classes it descends from. `for`-`in` lists the properties among those members, //! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and //! `Object.getOwnPropertyDescriptor` do not report the members. -use std::collections::HashSet; +use std::collections::HashMap; use std::rc::Rc; use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; @@ -89,8 +90,9 @@ pub(crate) struct Entry { 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>, + /// The names of the members the class declares, each with whether `hasOwnProperty` reports it: + /// every member but the unavailable ones. + own: Rc>, } impl Entry { @@ -143,14 +145,15 @@ 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. + /// class, and the closest of that class and the classes it descends from that declares `k` + /// declares it as available. 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); + if let Some(available) = e.own.get(k) { + return Ok(*available); } class = e.parent; } @@ -307,7 +310,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?; - let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + let members = class.members.iter().map(|(name, m)| (key(name), !matches!(m, HostMember::Unavailable(_)))).collect(); i.host_classes.push(Entry { name: class.name.as_str().into(), proto, diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..bdcd905584 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -756,6 +756,39 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[test] +fn a_member_a_class_declares_hides_the_one_its_parent_declares() { + 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())), + ("later".to_string(), HostMember::Unavailable(missing.clone())), + ("kept".to_string(), HostMember::Get(value.clone())), + ], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("size".to_string(), HostMember::Unavailable(missing)), ("later".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 read; try { it.size; read = 'read'; } catch (e) { read = 'threw'; }\ + [it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), read, it.hasOwnProperty('later'),\ + it.propertyIsEnumerable('later'), it.hasOwnProperty('kept')].join()", + ) + .unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,threw,true,true,true".into())); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48303c173e..f6431ad2ba 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -300,8 +300,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `(` after a name: a call. - fn call(&mut self, line: Option) { + /// What the call whose `(` is the current token reaches. + fn classify_call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") @@ -373,7 +373,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or /// `exportFile` is assigned: another name may hold its object, or its methods may change, so its /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, - /// `local[k] = w`, `delete local.saveAs`). + /// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's + /// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global + /// object, so its methods are no longer known either. fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); @@ -403,6 +405,42 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if let Some(name) = escaped { self.writers.remove(name); } + if changes { + let rebound = if is(h1, ".") { + h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) + } else if is(h0, "]") && is(h2, "[") { + h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 256)) + } else { + None + }; + if let Some(name) = rebound { + self.writers.remove(&name); + } + } + } + + /// `(` after a name: a call ([`Self::classify_call`]). A call of a variable of + /// [`Analyzer::writers`]'s method other than the `saveAs` or `exportFile` its literal defines + /// (`local.install()`, `local['install']()`) may replace the object's methods through `this`, so + /// after the call they are no longer known. + fn call(&mut self, line: Option) { + let [h0, h1, h2, h3] = self.h; + let bits = self.writer_bits(h2, h3); + let receiver = if is(h1, ".") && bits != 0 && h0.is_some_and(|s| s.kind == T::Ident && !Self::defines(bits, s.text)) { + h2 + } else if is(h0, "]") + && is(h2, "[") + && self.index_receiver != 0 + && h1.is_some_and(|s| s.kind == T::Str && !Self::defines(self.index_receiver, &unquote(s.text, 32))) + { + h3 + } else { + None + }; + self.classify_call(line); + if let Some(r) = receiver { + self.writers.remove(r.text); + } } /// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called. diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index c118128eec..637d1371ce 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -650,6 +650,29 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); } +/// A call of another method of such an object may replace its `saveAs` through `this`, and a property +/// assignment that names the variable (`this.local = d`) may give it another value through the global +/// object: after either, its `saveAs` writes the file again. +#[test] +fn a_method_call_or_a_global_property_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}, install: function () { this.saveAs = app.activeDocument.saveAs; }};\n", + "var b = {saveAs: function () {}, install: function () {}};\n", + "var c = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", + "a.saveAs(f); a.install();\n", + "b['install']();\n", + "this.c = app.activeDocument;\n", + "$.global['e'] = app.activeDocument;\n", + "g.saveAs(f); g.saveAs(f);\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "e.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment diff --git a/docs/mcp.md b/docs/mcp.md index 41869aadf9..bfd486709e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2720,8 +2720,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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` (false for an object that is hidden or locked, in a hidden or locked layer or group, + 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, + `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 @@ -2788,8 +2788,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and - `app.beep`, throw an error that says they are not available yet when they are read or assigned. + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.controlBounds`, + `PageItem.rotate` and `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. `Object.keys`, `Object.getOwnPropertyNames` and @@ -2874,8 +2874,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG8.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsWebOptimizedSVG.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensPDFOptions.html). The raster classes map - `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR`, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, - `SCALEBYRESOLUTION` in ppi); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); + `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR` as a multiplier from 0.01 to 64, so 2 doubles the + size, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, `SCALEBYRESOLUTION` in ppi from 0.72 to 4608); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`, `matte` and `transparency`. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`, and the PDF class maps `pdfPreset` (at most 255 From 88fe4e979629e7aa275f3334feeaa72744976113 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:52:31 -0800 Subject: [PATCH 011/213] Tests: list app.showColorPicker in the script host inventory --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 22f0b8b0b0..af193b5d56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -84,7 +84,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection showColorPicker typename", ), ("DocumentPreset.", "prototype"), ( From 70e6f4e797632bedd375356085e8b264fc1f8a78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:20:32 -0800 Subject: [PATCH 012/213] Save: a refused file in a save of several files is not given to the writer When the file access in force refuses one of the files a save writes, the save returns the access error before calling the writer, so a writer that does not check the file access itself writes none of the files. --- crates/engine/src/cmd/fileio/save.rs | 10 ++++------ crates/engine/src/tests/script_save_open.rs | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..08138a85ca 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. When one is refused, the save returns that error and `write` is not called, so + // none of the files is written, also by a writer that does not check the file access. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(e) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(e); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 15e64aecc2..0c4efa0c58 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -208,7 +208,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// with a refused one gives none of them to the writer. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -247,7 +247,7 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { }); assert!(r.is_err(), "{r:?}"); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert!(written.is_empty(), "no file went to the writer: {written:?}"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); From 60eb7e002be84c3a00599810f7f71f02bfc7b878 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:06:16 -0800 Subject: [PATCH 013/213] Scripts: exportForScreens numbers a file that an earlier item of the same call named Document.exportForScreens exports the artboards, the assets and the document that itemToExport names one after another into the folder. A later export now names its files around the names the earlier ones took, so an asset named as an artboard writes Logo-2.svg next to Logo.svg instead of writing over it. --- crates/engine/src/cmd/fileio.rs | 4 +-- crates/engine/src/cmd/fileio/screens.rs | 34 +++++++++++++++++++ .../src/script/dom/save_open/screens.rs | 16 +++++---- crates/engine/src/tests/script_screens.rs | 22 ++++++++++++ 4 files changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 7aca68fd02..4830432047 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -112,8 +112,8 @@ pub use save::{ }; pub(crate) use screens::{ PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS, - check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings, - with_export_preset as with_screen_export_preset, + check_settings as check_screen_settings, export as export_screens, safe_file_name, sharing_names as sharing_screen_names, + store_settings as store_screen_settings, with_export_preset as with_screen_export_preset, }; pub use screens::{ PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS, diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 442f38e3cc..4ab1c492a1 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -638,6 +638,25 @@ fn fold(name: &str) -> String { .collect() } +thread_local! { + /// The [`fold`]ed names the exports run by [`sharing_names`] on this thread have taken so far. + static SHARED_NAMES: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// `f`, with every `document.exportForScreens` it runs on this thread naming its files around +/// the names the ones before it took, so a later export does not write over an earlier one's file +/// (it numbers its own: `-2`, `-3`…). +pub(crate) fn sharing_names(f: impl FnOnce() -> T) -> T { + let outer = SHARED_NAMES.with(|n| n.borrow_mut().replace(HashSet::new())); + let r = f(); + SHARED_NAMES.with(|n| *n.borrow_mut() = outer); + r +} + +/// The key the names taken by an earlier export are held under in [`Output::taken`]: no file of +/// this export has it. +const EARLIER_EXPORT: &str = "\0earlier export"; + /// The file names (and bytes) an export wrote, or the files it returns. #[derive(Default)] struct Output { @@ -1342,6 +1361,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> create_dir(dir)?; } let mut out = Output::default(); + // The names earlier exports of a [`sharing_names`] run took into the same files. + if !o.zip { + SHARED_NAMES.with(|n| { + for name in n.borrow().iter().flatten() { + out.taken.insert(name.clone(), EARLIER_EXPORT.to_string()); + } + }); + } // The notes on the options, then the encoders' notes for every file, each once. let mut notes: Vec = Vec::new(); for text in unused { @@ -1417,6 +1444,13 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> files += 1; } } + if !o.zip { + SHARED_NAMES.with(|n| { + if let Some(shared) = n.borrow_mut().as_mut() { + shared.extend(out.taken.keys().cloned()); + } + }); + } // A cancel that came while the last file was encoded returns no files. A folder export // without a ZIP has written every file by now, so it returns them. if o.zip || folder.is_none() { diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs index f4008be1b6..c4cf253ecd 100644 --- a/crates/engine/src/script/dom/save_open/screens.rs +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -461,12 +461,16 @@ fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer { if let Some(prefix) = prefix { base.insert("prefix".into(), json!(prefix)); } - for items in exports { - let mut p = base.clone(); - p.extend(items); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.exportForScreens", &Value::Object(p))))?; - } - Ok(Data::Undefined) + // The artboards, the assets and the document are exported one after another into the folder: + // a later export numbers a file whose name an earlier one took instead of writing over it. + crate::cmd::fileio::sharing_screen_names(|| { + for items in exports { + let mut p = base.clone(); + p.extend(items); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.exportForScreens", &Value::Object(p))))?; + } + Ok(Data::Undefined) + }) } /// The members these add to `Document`. diff --git a/crates/engine/src/tests/script_screens.rs b/crates/engine/src/tests/script_screens.rs index c9bd000e1d..343feff945 100644 --- a/crates/engine/src/tests/script_screens.rs +++ b/crates/engine/src/tests/script_screens.rs @@ -195,6 +195,28 @@ fn item_to_export_picks_artboards_assets_and_the_document() { let _ = std::fs::remove_dir_all(base); } +/// An asset named as an artboard of the item's range gets a file of its own: the artboard's file +/// keeps its name and the asset's is numbered, in place of writing over it. +#[test] +fn an_asset_named_as_an_artboard_does_not_overwrite_its_file() { + let base = folder("clash"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "{}vc.run('artboard.setProps', {{artboards: [{{index: 0, name: 'Logo'}}]}});\n\ + var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\ + var both = new ExportForScreensItemToExport(); both.artboards = '1'; both.assets = ids;\n\ + d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);", + two_artboards(&dir) + ), + ); + assert_eq!(names(&dir.join("both")), ["Logo-2.svg", "Logo.svg"]); + let _ = std::fs::remove_dir_all(base); +} + /// The prefix comes before each file's name, and a path character in it does not make a folder or /// reach out of the export folder. #[test] From a8cd6180cefc3a238760796dd6f4957756d4c604 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:47:22 -0800 Subject: [PATCH 014/213] Scripts: fix further review findings in the layer and path items - Point changes that add, remove or replace points deselect the path's direct-selected anchors even when the counts come out the same; path.setAnchors takes `reshaped` for this and refuses a non-boolean. - Moving points or handles, changing a point's type or setting `closed` keeps the index of where each subpath's points start. - A failed write keeps the waiting point changes. - Restoring the selection keeps a segment-only path to its segments. - getIsFileOpen folds `\` and letter case only on Windows. - Assigning `undefined` to Document.selection throws with nothing changed. - A document's path list is charged for the objects it looks at. - A made path keeps an id above 2^53. - A host object's handle is charged to the heap limit. - docs/mcp.md states that node.move into a compound path also needs its layer and groups shown and unlocked and no locked artboard. --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/path.rs | 13 +++- crates/engine/src/script/dom.rs | 37 +++++++--- crates/engine/src/script/dom/paths.rs | 81 ++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 63 +++++++++++++++- crates/engine/src/tests/script_dom_paths.rs | 34 +++++++++ crates/js/src/heap.rs | 7 ++ crates/js/src/host_classes.rs | 2 +- docs/mcp.md | 18 +++-- 9 files changed, 212 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 67f6cee727..02ed82d101 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard, and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index cc11f6f824..06d089ab08 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Set Anchors", [], None, - "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry", + "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}], reshaped?: bool (true: the anchors were added, removed or replaced, so the path's direct-selected anchors are deselected even when each subpath keeps its count)} replace a path's geometry", has_doc, set_anchors ), @@ -757,14 +757,19 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>>()?, ); + let replaced = match p.get("reshaped") { + None => false, + Some(Value::Bool(v)) => *v, + Some(_) => return Err(bad("path.setAnchors", "reshaped must be a boolean")), + }; s.edit("Reshape", |d, sel| { let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>(); let path = path_mut(d, id)?; - let reshaped = counts(path) != counts(&data); + let reshaped = replaced || counts(path) != counts(&data); *path = data; super::object::resnap(d, id); - // Direct-selected anchors and segments are kept by index: when anchors were added or - // removed, the path is deselected rather than left with other anchors selected. + // Direct-selected anchors and segments are kept by index: when anchors were added, + // removed or replaced, the path is deselected rather than left with other anchors selected. if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { sel.objects.retain(|o| *o != id); sel.prune(d); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b6a1160e28..2a716a1bb0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -44,6 +44,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; pub(super) mod layers; mod paths; +#[cfg(test)] +pub(crate) use paths::index_builds; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -112,6 +114,12 @@ pub(super) struct State { /// How many times [`paths`] changed the waiting point changes, which makes a /// [`paths::PointIndex`] of them stale. pending_changes: Cell, + /// Whether the waiting point changes added, removed or replaced points, so that writing them + /// deselects the path's direct-selected anchors even when the counts come out the same. + pending_reshaped: Cell, + /// The path [`flush`] is writing reshaped changes to, whose direct-selected anchors and + /// segments [`on_doc`] does not select again. + reshaping: Cell>, /// Where the points of the path the run last read points of start, by subpath ([`paths`]). point_index: RefCell>, /// How many times the points the run read of each path went stale, by document uid and path id @@ -626,12 +634,15 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; } else { // 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. + // its anchors, a whole path with all of them and any other object with none. A path with + // only segments selected gets no anchors here, so `select.segments` below selects it with + // just those segments. 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 if before.segments.contains_key(i) => Vec::new(), 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}) @@ -747,15 +758,16 @@ fn on_doc_layer( let s = h.session.borrow(); s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) }; - // Anchors and segments are selected by index: a path that gained or lost anchors is not - // selected again, so that other anchors of it are not selected in their place. + // Anchors and segments are selected by index: a path that gained, lost or replaced anchors + // is not selected again, so that other anchors of it are not selected in their place. if let Some(doc) = &doc { let counts = |d: &Document, id: NodeId| { d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) }; + let reshaped = h.dom.reshaping.get().filter(|it| it.doc.uid == uid).map(|it| it.id); let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); for id in partial { - if counts(&old, id) != counts(doc, id) { + if reshaped == Some(id) || counts(&old, id) != counts(doc, id) { before.anchors.remove(&id); before.segments.remove(&id); before.objects.retain(|o| *o != id); @@ -840,13 +852,15 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter -/// or a `\`) letters in one case. +/// A path as `getIsFileOpen` compares it, without a trailing `/`: on Windows, `\` and `/` alike and +/// letters in one case; elsewhere `\` is part of a name and case counts. 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 } + path_key_on(p, cfg!(windows)) +} + +/// [`path_key`] for Windows when `windows`, else for macOS and Linux. +pub(crate) fn path_key_on(p: &str, windows: bool) -> String { + if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } /// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is @@ -1391,7 +1405,8 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. 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::Null => Vec::new(), + Data::Undefined => return Err(HostError::Type("the selection takes a page item, a list of them, null or [], not undefined".into())), 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], diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 19ad6ac4fb..e6867d8b55 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, - frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, - point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, edit_item, editable, + find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, + point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -176,6 +176,18 @@ impl PointIndex { } } +#[cfg(test)] +thread_local! { + /// How many times [`point_place`] built a [`PointIndex`] on this thread. + static INDEX_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times a [`PointIndex`] was built on this thread. +#[cfg(test)] +pub(crate) fn index_builds() -> u64 { + INDEX_BUILDS.with(std::cell::Cell::get) +} + /// The number of points of the path of `item`, its waiting point changes included, and the subpath /// and the place in it of point `i` when `i` is given and in the path. The index of the path's /// subpaths is kept in [`super::State`] until the path's points change. @@ -198,6 +210,8 @@ fn point_place(h: &super::Host, item: Item, i: Option) -> std::result::Re } }); if !fresh { + #[cfg(test)] + INDEX_BUILDS.with(|n| n.set(n.get() + 1)); let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?; *h.dom.point_index.borrow_mut() = Some(index); } @@ -230,12 +244,27 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { - h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); + edit_points_keeping(h, item, false, f) +} + +/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as +/// they are, so a [`PointIndex`] of the waiting changes stays good. +fn edit_points_keeping( + h: &super::Host, + item: Item, + counts_kept: bool, + f: impl FnOnce(&mut Vec) -> T, +) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { + if !counts_kept { + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); + h.dom.pending_reshaped.set(true); + } return Ok(f(subs)); } + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); @@ -249,6 +278,7 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) return Err(cannot_edit(item.id)); } *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.pending_reshaped.set(!counts_kept); if aligned { flush(h)?; } @@ -262,9 +292,13 @@ fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::R } /// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless -/// the path has those points already. +/// the path has those points already. Changes that added, removed or replaced points are written +/// with `reshaped`, so the path's direct-selected anchors are deselected even when the counts come +/// out the same, and the selection the run puts back leaves them out. When the write fails, the +/// changes stay waiting. pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) }; + let reshaped = h.dom.pending_reshaped.replace(false); let same = { let s = h.session.borrow(); let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id)); @@ -277,7 +311,18 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + let mut params = json!({"id": item.id.0, "subpaths": subpaths}); + if reshaped { + params["reshaped"] = json!(true); + } + let kept = h.dom.reshaping.replace(reshaped.then_some(item)); + let r = edit_item(h, item, "path.setAnchors", ¶ms); + h.dom.reshaping.set(kept); + if let Err(e) = r { + *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.pending_reshaped.set(reshaped); + return Err(e); + } Ok(()) } @@ -336,8 +381,8 @@ pub(super) const PATH_LISTS: usize = 4; /// The ids of a document's paths, in the order of its page items, or of the paths directly in the /// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their -/// documents are unchanged, so a loop over a collection builds its list once. A new list of a -/// container is charged by the objects it looks at. +/// documents are unchanged, so a loop over a collection builds its list once. A new list is +/// charged by the objects it looks at. fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { { let mut lists = h.dom.paths.borrow_mut(); @@ -357,6 +402,7 @@ fn path_items(h: &super::Host, st: &DocState, container: Option) -> std: } None => { let all = super::page_items(h, st); + h.charge_call(all.len() as u64)?; Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) } }; @@ -464,13 +510,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the result of a command that made an object, read from the command's own result (not +/// the script's copy, whose numbers are exact only up to 2^53). +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or @@ -516,7 +559,7 @@ fn make_in( /// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { make_in(h, doc, container, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = made_id(&drawing_normally(h, || command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -673,7 +716,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -697,7 +740,7 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -1426,7 +1469,7 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, s, j) = this_point_place(h, a)?; - edit_points(h, item, |subs| { + edit_points_keeping(h, item, true, |subs| { if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5368a64c2f..06bf3e83b0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -855,6 +855,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() { assert!(s.active().unwrap().doc.node(a).is_none()); } +/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round. +#[test] +fn a_path_made_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 out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);"); + assert_eq!(out, vec![json!("big")]); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big")); +} + +/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and +/// leaves the selection as it was; `null` still clears it. +#[test] +fn assigning_undefined_to_the_selection_throws() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];"); + assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn only_class_constructors_construct() { let (mut s, _, _) = doc(); @@ -1349,6 +1375,18 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let _ = std::fs::remove_file(path); } +/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a +/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`. +#[test] +fn get_is_file_open_compares_paths_by_the_platform_s_rules() { + use crate::script::dom::path_key_on; + assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false)); + assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false)); + assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false)); + assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true)); + assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true)); +} + #[test] fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let (mut s, _, _) = doc(); @@ -1626,12 +1664,15 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ - G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);", + sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\ + vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); vc.log(P[1] === undefined);", ); let expected = [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; assert_eq!(out[..11], expected); - assert_eq!(out[11..], [json!(true), json!(true), json!(true)]); + // With the sublayer's path above the group, the layer's own path and both of the group's paths + // named `B`, each collection's named lookups give its own topmost path. + assert_eq!(out[11..], [json!(true), json!(true), json!(true), json!(true)]); } #[test] @@ -1716,6 +1757,22 @@ fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { assert!(failure(&mut s, src).contains(REFUSED), "{src}"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); } + // Caught inside the script, each refusal leaves both collections as they were, and the group, + // shown and unlocked itself, is refused for its locked layer. + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\ + var n = [L.pathItems.length, g.pathItems.length];\ + try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 3, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(out[1], out[2], "the collections are unchanged inside the script"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); let hidden = format!("{:?}", s.active().unwrap().doc.layers); @@ -1981,7 +2038,7 @@ fn a_compound_paths_path_items_add_makes_the_path_inside_it() { let d = &s.active().unwrap().doc; let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); assert_eq!(compound.children().unwrap().len(), 2); - assert!(undo_steps(&s) > steps); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); } #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 99e83b4ddc..0ac6a14eff 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -170,6 +170,12 @@ fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + // Removing a point and adding one in a single write ends with as many points, but the + // selected anchor's index now names another point, so the path is deselected. + log(&mut s, "var pp = app.activeDocument.pathItems[1].pathPoints; pp[0].remove(); pp.add();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + assert!(!st.selection.anchors.contains_key(&b), "{:?}", st.selection); } #[test] @@ -188,6 +194,14 @@ fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap(); assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + // `reshaped` deselects them at the same count; a value that is not a boolean is refused. + for bad in [json!(null), json!(1), json!("yes")] { + assert!(s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": bad})).is_err(), "{bad}"); + } + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": true})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); } /// Points are found by their index across subpaths, through changes that wait to be written and @@ -220,6 +234,26 @@ fn points_are_found_across_subpaths_as_their_counts_change() { assert_eq!(counts, vec![1, 3]); } +/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points +/// start: the index is built again only when a change adds or removes points. +#[test] +fn moving_each_point_keeps_the_index_of_the_subpaths() { + 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 subs: Vec = + (0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect(); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let before = crate::script::dom::index_builds(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);", + ); + assert_eq!(out, vec![json!([49, 7])]); + let built = crate::script::dom::index_builds() - before; + assert!(built <= 3, "the index was built {built} times"); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index bddab84fd6..f541c221e6 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -779,11 +779,18 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, + Class::Host(h) => extra = host_handle_bytes(h.handle.len()), _ => {} } OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra } +/// The bytes an object of a host class keeps for a handle of `numbers` numbers: the handle itself +/// and its copy in the realm's map of host objects. +pub(crate) fn host_handle_bytes(numbers: usize) -> usize { + numbers.saturating_mul(16) +} + fn add_name(name: &XmlName, strings: &mut StringSizes) { strings.add_key(&name.local); name.uri.iter().chain(&name.prefix).for_each(|k| strings.add_key(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index de41e7ef6f..0d0b7ec69c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -155,7 +155,7 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES)?; + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(crate::heap::host_handle_bytes(handle.len())))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); diff --git a/docs/mcp.md b/docs/mcp.md index 72d0c0f0f1..7ba136cb52 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,11 +2749,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or + a list of at most 10,000, `null` or `[]`; `undefined` (such as a page item looked up past the end of a list) + throws a `TypeError`, and an object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other - selected objects 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 + selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (on Windows, + letter case is ignored and `\` matches `/`; on macOS and Linux, `\` is part of a file name) 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.views`, `PageItem.blendingMode`, `PageItem.rotate` and @@ -2825,7 +2826,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. - The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path (its layer and + groups shown and unlocked too, and not on a locked artboard), where the path gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment. @@ -2859,6 +2861,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. + Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the + path ends with as many points as before; changes that only move points or handles, change a point's type or set + `closed` keep them selected. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, @@ -6744,7 +6749,8 @@ and `layerRows`, the rows highlighted in the panel. that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts - a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that + a path into a shown, unlocked compound path whose layer and groups are also shown and unlocked and that is not on + a locked artboard (see `object.newGroup` for the paint the path keeps or takes). A row that either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join, From bee68ccd13acf2d747e0cd8a5e1f78ddf3e5502e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:01:18 -0800 Subject: [PATCH 015/213] Scripts: a saveAs that can replace itself, or a computed global key, ends the own-method exemption - A saveAs or exportFile in an object literal whose body uses `this` or the variable's own name may replace the object's methods when it runs, so the script check no longer counts it as the script's own method and reports its calls as file writes. - An assignment to a property of the global object under a key that is not one string literal (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may rebind any variable, so the check forgets every own saveAs after it. - A save without a path that writes several files and is refused by the file access names the refused file by its file name, as the single-file save does, instead of its full path. --- crates/engine/src/cmd/fileio/save.rs | 23 +++++++++--- crates/scriptcheck/src/analyze.rs | 20 ++++++++++- crates/scriptcheck/src/analyze/features.rs | 19 +++++++++- crates/scriptcheck/src/tests.rs | 42 ++++++++++++++++++++++ 4 files changed, 97 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 08138a85ca..9fba907289 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,10 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// Does a refusal by the file access name the refused file by its file name + /// ([`SaveJob::naming_refused_file`])? + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + names_refused_file: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +967,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.names_refused_file = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1075,9 +1087,9 @@ impl SaveJob { // none of the files is written, also by a writer that does not check the file access. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(e) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some((p, e)) = files.iter().find_map(|(p, _)| super::may_write(p).err().map(|e| (p, e))) { - return Err(e); + return Err(if self.names_refused_file { super::access::naming_in_error(e, p) } else { e }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1239,9 +1251,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refused_file() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 4eaebc96ca..dda0f3c1c5 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -646,6 +646,11 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The depths of the open `[` that index the global object (`$.global[`, `this[`, + /// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them. + global_indexes: Vec, + /// The last token was the `]` that closes an index of the global object. + global_index_closed: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -726,6 +731,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + global_indexes: vec![], + global_index_closed: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1447,8 +1454,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing /// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the /// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on - /// (`{…} && d`), see the variable as it was. + /// (`{…} && d`), see the variable as it was. A `this` or the variable's own name inside the body + /// of such a function expression takes the method out as well: running it may replace the + /// object's methods (`{saveAs: function () { this.saveAs = d.saveAs; }}`). fn object_key(&mut self, t: &Sig<'s>, before: usize) { + if t.kind == T::Ident { + for o in self.objects.iter_mut().filter(|o| o.depth < before) { + if let Some((bit, Value::Body)) = o.value + && (t.text == "this" || t.text == o.name) + { + o.value = Some((bit, Value::Other)); + } + } + } if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) { o.step(t); } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index f6431ad2ba..70942a0986 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -375,9 +375,23 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, /// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's /// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global - /// object, so its methods are no longer known either. + /// object, so its methods are no longer known either. An assignment to a property of the global + /// object under any other key (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may give any such + /// variable a new value: no variable's methods are known after it. fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; + let global_index_closed = std::mem::take(&mut self.global_index_closed); + if t.is("[") { + let global = (word(h0, "global") && is(h1, ".") && word(h2, "$") && !member_mark(h3)) + || ((word(h0, "this") || word(h0, "globalThis")) && !member_mark(h1)); + if global && self.global_indexes.len() < self.acc.limits.nesting { + self.global_indexes.push(self.depth()); + } + } else if t.is("]") { + let depth = self.depth(); + self.global_index_closed = self.global_indexes.last() == Some(&(depth + 1)); + self.global_indexes.retain(|d| *d <= depth); + } let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); @@ -415,6 +429,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { }; if let Some(name) = rebound { self.writers.remove(&name); + } else if global_index_closed { + // `$.global[key] = …`: the key may name any of them. + self.writers.clear(); } } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0adc738db2..28aec12789 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -673,6 +673,48 @@ fn a_method_call_or_a_global_property_ends_the_own_save_as() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..])); } +/// An assignment to a property of the global object under a key that is not one string literal may +/// give any such variable another value: after it, their `saveAs` writes the file again. One under a +/// string literal ends only the variable it names, and an index of another object ends none. +#[test] +fn a_computed_global_property_ends_every_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "var rows = [];\n", + "rows[k] = 1; $.global['b'] = app.activeDocument;\n", + "a.saveAs(f);\n", + "$.global[key] = app.activeDocument;\n", + "a.saveAs(f);\n", + "var c = {saveAs: function () {}};\n", + "this['lo' + 'cal'] = app.activeDocument;\n", + "c.saveAs(f);\n", + "var h = {saveAs: function () {}};\n", + "globalThis[names[0]] = app.activeDocument;\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 10, 13][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[7, 10, 13][..])]); +} + +/// A `saveAs` whose body uses `this` or the variable's own name may replace the object's methods +/// when it runs, so it is not the script's own and its calls write the file. A `this` in another +/// method's body leaves `saveAs` the script's own. +#[test] +fn an_own_save_as_that_may_replace_itself_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var doc = app.activeDocument;\n", + "var a = {saveAs: function () { this.saveAs = function (g) { doc.saveAs(g); }; }};\n", + "var b = {saveAs: function () { b.saveAs = w; }};\n", + "var c = {saveAs: function (g) { return g; }, install: function () { this.n = 1; }};\n", + "a.saveAs(f); a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment From 210ba07347b0daa9204b4b5fe1559513fa336f2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:58:37 -0800 Subject: [PATCH 016/213] Scripts: a hoisted function that changes or shares a variable, a captured variable and a labelled var end the own-method exemption A function declared before the literal that assigns the variable's saveAs or hands the variable on, a function that calls the method on a variable it reads from outside, and a var statement after a label keep reporting the file write. --- crates/scriptcheck/src/analyze.rs | 13 +++- crates/scriptcheck/src/analyze/features.rs | 79 ++++++++++++++++------ crates/scriptcheck/src/tests.rs | 45 ++++++++++++ 3 files changed, 115 insertions(+), 22 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index dda0f3c1c5..bed249d6eb 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -637,6 +637,12 @@ struct Analyzer<'s, 'a, 'l> { /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. writers: HashMap, + /// The variables a function body read before any literal gave them methods, in a way that + /// changes or shares them ([`Analyzer::writer_use`]): the body may run after the literal (a + /// hoisted declaration), so the literal's methods are not the script's own. Each name has the + /// most function bodies that were open where it was read; a literal in a body with that many + /// open or more is unaffected, since it gives a variable of its own. + shared_early: HashMap, /// The object literals being assigned to a variable, the innermost last, up to /// [`crate::Limits::nesting`] of them. objects: Vec, @@ -646,6 +652,8 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// Whether that receiver's own methods hold at this place ([`Analyzer::stable`]). + index_stable: bool, /// The depths of the open `[` that index the global object (`$.global[`, `this[`, /// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them. global_indexes: Vec, @@ -728,9 +736,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(), maybe_files_full: false, writers: HashMap::new(), + shared_early: HashMap::new(), objects: vec![], closed: None, index_receiver: 0, + index_stable: false, global_indexes: vec![], global_index_closed: false, unsure: known.unsure || declared.unsure, @@ -1392,7 +1402,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let body = self.scopes.last().map_or(0, |s| s.depth); let starts = before.is_none() || [";", "{", "}"].iter().any(|p| is(before, p)) - || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); @@ -1441,6 +1451,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 70942a0986..839476d420 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -285,7 +285,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.setter(&name, h2, h3, line); } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. - "[" => self.index_receiver = self.writer_bits(h0, h1), + "[" => { + self.index_receiver = self.writer_bits(h0, h1); + self.index_stable = h0.is_some_and(|r| self.stable(r.text)); + } "(" => self.call(line), // `Name.prototype["+"] = …` defines an operator. "=" => { @@ -308,7 +311,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && is(h2, "[") && let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) && catalog::DOM_FILE_WRITES.contains(&method.as_str()) - && !Self::defines(self.index_receiver, &method) + && !(self.index_stable && Self::defines(self.index_receiver, &method)) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -335,7 +338,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); } else if (file && catalog::FILE_WRITES.contains(&n)) - || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3), n))) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -362,6 +365,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; /// 0 for anything else. A receiver the check does not follow may be a document. + /// Whether a call of `name`'s own method may be left out: the call is in the global code, or in a + /// function body that declares `name` itself. A body that reads `name` from outside may run + /// after the variable was given another value, so its calls are not known. + fn stable(&self, name: &str) -> bool { + self.scopes.last().is_none_or(|s| s.saved.contains_key(name)) + } + fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { match receiver { Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), @@ -395,30 +405,57 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); - let escaped = if word(h0, "delete") { - // `delete local…` - writer(Some(*t), h0) - } else if let Some(name) = writer(h0, h1) { - // `local` followed by anything but a member, its own assignment or an object key's `:`. - (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) - } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { - // `local.saveAs = …` - writer(h2, h3) - } else if is(h0, "[") { - // `local[k]` with a key that is not a string literal. - writer(h1, h2).filter(|_| t.kind != T::Str) - } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { - // `local['name' + k]`. - writer(h2, h3).filter(|_| !t.is("]")) - } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { - // `local['saveAs'] = …` - writer(h3, None) + let escape = |writer: &dyn Fn(Option>, Option>) -> Option<&'s str>| -> Option<&'s str> { + if word(h0, "delete") { + // `delete local…` + writer(Some(*t), h0) + } else if let Some(name) = writer(h0, h1) { + // `local` followed by anything but a member, its own assignment or an object key's `:`. + (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) + } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { + // `local.saveAs = …` + writer(h2, h3) + } else if is(h0, "[") { + // `local[k]` with a key that is not a string literal. + writer(h1, h2).filter(|_| t.kind != T::Str) + } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { + // `local['name' + k]`. + writer(h2, h3).filter(|_| !t.is("]")) + } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { + // `local['saveAs'] = …` + writer(h3, None) + } else { + None + } + }; + let escaped = escape(&writer); + // A function body reads a variable of the enclosing code that no literal has given methods yet + // in a way that changes or shares it: the body may run after the literal, as a hoisted + // declaration does. + let early = if escaped.is_none() && !self.scopes.is_empty() { + let captured = |s: Option>, before: Option>| { + s.filter(|s| { + s.kind == T::Ident + && !member_mark(before) + && !self.writers.contains_key(s.text) + && self.scopes.last().is_some_and(|b| !b.saved.contains_key(s.text)) + }) + .map(|s| s.text) + }; + escape(&captured) } else { None }; if let Some(name) = escaped { self.writers.remove(name); } + if let Some(name) = early + && (self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len())) + { + let open = self.scopes.len(); + let seen = self.shared_early.entry(name.to_string()).or_insert(open); + *seen = (*seen).max(open); + } if changes { let rebound = if is(h1, ".") { h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 28aec12789..938981691e 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -715,6 +715,51 @@ fn an_own_save_as_that_may_replace_itself_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7][..])); } +/// A function declared before the literal is hoisted, so it may change or share the variable before +/// the literal's later calls run: its calls then keep reporting the write. A function with a +/// variable of its own of the same name, and one that only calls the method, leave the method the +/// script's own. +#[test] +fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "function a(w) { local.saveAs = w; }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + "function b() { use(other); }\n", + "var other = {saveAs: function () {}};\n", + "other.saveAs(f);\n", + "function c() { var calm = app.activeDocument; use(calm); }\n", + "var calm = {saveAs: function () {}};\n", + "calm.saveAs(f);\n", + "function d() { quiet.saveAs(f); }\n", + "var quiet = {saveAs: function () {}};\n", + "quiet.saveAs(f);\n", + "function g1() { use(mine); }\n", + "function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11][..])); +} + +/// A function that reads the variable from outside runs after whatever the script gave it since, so +/// its calls keep reporting the write. A `var` after a label or a `case` is in a branch as well. +#[test] +fn a_captured_or_labelled_own_save_as_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var local = {saveAs: function () {}};\n", + "function run() { local.saveAs(f); }\n", + "function run2() { local['saveAs'](f); }\n", + "local = app.activeDocument;\n", + "run();\n", + "function own() { var inner = {saveAs: function () {}}; inner.saveAs(f); inner['saveAs'](f); }\n", + "if (flag) skip:\n", + "var lab = {saveAs: function () {}};\n", + "lab.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4, 10][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment From 4e43269851df94e759b8a275c8a2cec3cee45025 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:33:33 -0800 Subject: [PATCH 017/213] Scripts: a full table of shared names, an assignment and a member call in a hoisted function end the own-method exemption The script check kept a literal's own saveAs when the table of shared names was full, when a function assigned the variable with =, a compound operator, ++ or --, and when a function called a member of it or read it. Each case now keeps reporting the write. --- crates/scriptcheck/src/analyze.rs | 14 ++++- crates/scriptcheck/src/analyze/features.rs | 35 +++++++++--- crates/scriptcheck/src/tests.rs | 63 +++++++++++++++++++++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index bed249d6eb..0c9012c6ac 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -643,6 +643,9 @@ struct Analyzer<'s, 'a, 'l> { /// most function bodies that were open where it was read; a literal in a body with that many /// open or more is unaffected, since it gives a variable of its own. shared_early: HashMap, + /// [`Analyzer::shared_early`] had no room for a name: no literal gives methods that are the + /// script's own from then on. + shared_full: bool, /// The object literals being assigned to a variable, the innermost last, up to /// [`crate::Limits::nesting`] of them. objects: Vec, @@ -737,6 +740,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { maybe_files_full: false, writers: HashMap::new(), shared_early: HashMap::new(), + shared_full: false, objects: vec![], closed: None, index_receiver: 0, @@ -1423,6 +1427,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { { let h1 = self.h[1]; let declared = word(h1, "var") || (is(h1, ",") && self.var_depth.is_some()); + if !declared && !member_mark(h1) && !is(h1, "@") { + self.share_early(name.text); + } if declared { if self.in_catch(name.text) { self.declare_in_catch(name.text); @@ -1436,7 +1443,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.assign = Some(Assign { name: name.text.to_string(), after_new: false }); } } - match self.updated(t) { + let updated = self.updated(t); + if let Some((name, _)) = updated { + self.share_early(name); + } + match updated { // The value on the right is read at this depth, and the name holds nothing the check // follows once that value ends ([`Analyzer::settle_groups`]). Some((name, true)) => self.start_value(name.to_string(), Operand::Other), @@ -1451,6 +1462,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.shared_full && self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 839476d420..d77b17a20c 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -2,6 +2,12 @@ use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word}; +/// Words that start or continue a statement or an expression, never a variable's name. +const RESERVED: [&str; 24] = [ + "var", "function", "if", "else", "for", "while", "do", "return", "new", "typeof", "delete", "in", "instanceof", "this", "with", "switch", "case", + "try", "catch", "finally", "throw", "break", "continue", "void", +]; + /// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…). pub(super) fn platform_name(n: &str) -> bool { matches!( @@ -372,6 +378,23 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.scopes.last().is_none_or(|s| s.saved.contains_key(name)) } + /// A function body uses `name`, which no literal has given methods and the body does not declare, + /// in a way that may change or share it ([`Analyzer::shared_early`]). With no room left for the + /// name, no literal's methods are the script's own from then on. + pub(super) fn share_early(&mut self, name: &str) { + let Some(body) = self.scopes.last() else { return }; + if body.saved.contains_key(name) || self.writers.contains_key(name) { + return; + } + if self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()) { + let open = self.scopes.len(); + let seen = self.shared_early.entry(name.to_string()).or_insert(open); + *seen = (*seen).max(open); + } else { + self.shared_full = true; + } + } + fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { match receiver { Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), @@ -449,12 +472,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if let Some(name) = escaped { self.writers.remove(name); } - if let Some(name) = early - && (self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len())) - { - let open = self.scopes.len(); - let seen = self.shared_early.entry(name.to_string()).or_insert(open); - *seen = (*seen).max(open); + if let Some(name) = early { + self.share_early(name); + } + // A name read in a function body that the body does not declare, as a receiver or otherwise. + if let Some(r) = h0.filter(|r| r.kind == T::Ident && !member_mark(h1) && !RESERVED.contains(&r.text)) { + self.share_early(r.text); } if changes { let rebound = if is(h1, ".") { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 938981691e..c0e86dc0f1 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -738,7 +738,68 @@ fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() "function g1() { use(mine); }\n", "function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11, 13][..])); +} + +/// A table of shared names with no room left for one more means a function may share any name: no +/// literal after it gives methods that are the script's own. +#[test] +fn a_full_table_of_shared_names_keeps_reporting_the_write() { + let src = concat!( + "var f = new File(p);\n", + "function a(w) { p1.saveAs = w; p2.saveAs = w; p3.saveAs = w; }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + ); + let r = check("test.jsx", src.as_bytes(), None, &Limits { entries: 2, ..Limits::default() }); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); +} + +/// A function body that assigns a variable it does not declare (`=`, a compound operator, `++` or +/// `--`) may run after the literal and give the variable another value. +#[test] +fn an_assignment_in_a_hoisted_function_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "function a(w) { local = w; }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + "function b() { other += 1; }\n", + "var other = {saveAs: function () {}};\n", + "other.saveAs(f);\n", + "function c() { third++; }\n", + "var third = {saveAs: function () {}};\n", + "third.saveAs(f);\n", + "function e() { --fourth; }\n", + "var fourth = {saveAs: function () {}};\n", + "fourth.saveAs(f);\n", + "function d() { var mine = 1; mine = 2; }\n", + "var mine = {saveAs: function () {}};\n", + "mine.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10, 13][..])); +} + +/// A function body that calls a method of, or reads, a variable it does not declare may run before +/// the literal as well, so a later literal's calls keep reporting the write. +#[test] +fn a_member_call_or_read_in_a_hoisted_function_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "function a() { local.run(); }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + "function b() { other['m'](); }\n", + "var other = {saveAs: function () {}};\n", + "other.saveAs(f);\n", + "function c() { return third.name; }\n", + "var third = {saveAs: function () {}};\n", + "third.saveAs(f);\n", + "function d() { var calm = 1; return calm.name; }\n", + "var calm = {saveAs: function () {}};\n", + "calm.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..])); } /// A function that reads the variable from outside runs after whatever the script gave it since, so From 9a2b6499ca19a4857dcffa5c51ec9cfa0c3a51a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:46:31 -0800 Subject: [PATCH 018/213] Scripts: format the reserved word list --- crates/scriptcheck/src/analyze/features.rs | 26 ++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index d77b17a20c..0ddeb99cb0 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -4,8 +4,30 @@ use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, ca /// Words that start or continue a statement or an expression, never a variable's name. const RESERVED: [&str; 24] = [ - "var", "function", "if", "else", "for", "while", "do", "return", "new", "typeof", "delete", "in", "instanceof", "this", "with", "switch", "case", - "try", "catch", "finally", "throw", "break", "continue", "void", + "var", + "function", + "if", + "else", + "for", + "while", + "do", + "return", + "new", + "typeof", + "delete", + "in", + "instanceof", + "this", + "with", + "switch", + "case", + "try", + "catch", + "finally", + "throw", + "break", + "continue", + "void", ]; /// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…). From 637facb057236984dfb89bfe8707fdbf200bb639 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:27:19 -0800 Subject: [PATCH 019/213] Scripts: empty objects read zero control bounds and turn or scale as no-ops - controlBounds of an object with nothing in it reads zeros, like its geometric and visible bounds. - path.rotate and path.resize of a path with no anchors change nothing. - The path tests make the first rectangle last, so pathItems[0] is the topmost path as pageItems lists it. --- crates/engine/src/script/dom.rs | 9 ++++++--- crates/engine/src/script/dom/paths.rs | 17 ++++++++++------- crates/engine/src/tests/script_dom.rs | 8 ++++---- crates/engine/src/tests/script_dom_paths.rs | 13 +++++++++++-- .../tests/it/script_host_vs_scriptcheck.rs | 5 ++++- 5 files changed, 35 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4a40865c1f..2ef5503fb0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1851,10 +1851,13 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { let (r, f) = with_doc(h, item.doc, |_, st| { let visible = st.doc.bounds_of(&[item.id], true); let handles = st.doc.node(item.id).and_then(handles_box); - let r = vectorcraft_geom::union_opt(visible, handles).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; - Ok::<_, HostError>((r, frame(st)?)) + Ok::<_, HostError>((vectorcraft_geom::union_opt(visible, handles), frame(st)?)) })?; - Ok(f.bounds(h.dom.coords.get(), r)) + // An object with nothing in it has no bounds, and they read as zeros like its other bounds. + match r { + Some(r) => 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_position(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e735b8f153..ffe1a23264 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, class_text, colors, command, command_value, coordinate, edit_item, editable, - find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, - point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, class_text, colors, command, command_value, coordinate, edit_item, + editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -1202,8 +1202,10 @@ fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { let place = about_name(arg(a, 6))?; let mut params = json!({"angle": angle}); transform_options(a, 2, &mut params)?; - if angle.rem_euclid(360.0) != 0.0 { - let (r, _) = item_rect(h, item, false)?; + // A path with no anchors has no bounds to turn about, and turning it changes nothing. + if angle.rem_euclid(360.0) != 0.0 + && let (Some(r), _) = item_rect(h, item, false)? + { let origin = about(h, item, place, r)?; params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.rotate", params)?; @@ -1234,8 +1236,9 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { } // The scale and the new stroke weight are one edit: a failure of either undoes both. super::atomically(h, |h| { - if sx != 100.0 || sy != 100.0 { - let (r, _) = item_rect(h, item, false)?; + if (sx != 100.0 || sy != 100.0) + && let (Some(r), _) = item_rect(h, item, false)? + { let origin = about(h, item, place, r)?; params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.scale", params)?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0be17f5d71..09c856dbcf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -717,10 +717,10 @@ fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); let anchors = s.active().unwrap().selection.anchors.clone(); assert!(anchors.contains_key(&a)); - log(&mut s, "app.activeDocument.pageItems[1].selected = false;"); + log(&mut s, "app.activeDocument.pageItems[0].selected = false;"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone())); - log(&mut s, "app.activeDocument.pageItems[1].selected = true;"); + log(&mut s, "app.activeDocument.pageItems[0].selected = true;"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a))); } @@ -2428,7 +2428,7 @@ fn every_page_item_has_its_layer_and_members_check_this() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ - vc.log(p.layer.name); vc.log(d.pageItems[0].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(p.layer.name); vc.log(d.pageItems[1].layer.name); vc.log(p.layer.layers.typename);\ vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", ); assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); @@ -2542,7 +2542,7 @@ fn page_items_report_their_available_members_as_their_own() { ); 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])); + assert_eq!(out[1], json!([false, true, true, 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])); } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 0ac6a14eff..94b638ccc7 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -30,8 +30,9 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { 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); + // `pathItems[0]` is the topmost path, so `a` is made last. let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); s.execute("select.none", &json!({})).unwrap(); (s, a, b) } @@ -564,6 +565,14 @@ fn identity_transforms_of_an_empty_path_do_nothing() { } } +#[test] +fn turning_or_scaling_an_empty_path_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);"); + assert_eq!(undo_steps(&s), 1, "only the path is added"); +} + /// The paint of the fill (`fill`) or stroke of `id`. fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { let n = node(s, id); @@ -935,7 +944,7 @@ fn locked_paths_and_wrong_objects_are_refused() { } assert_eq!(art(&s), before); s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); - let e = failure(&mut s, "var t = app.activeDocument.pageItems[2]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); assert!(e.contains("not a PathItem"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(PathPoint.prototype, 'anchor').get.call({});"); assert!(e.contains("not a PathPoint"), "{e}"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f5a2e83aed..24722a3adc 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -153,7 +153,10 @@ const INSIDE: &[(&str, &str)] = &[ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", From 66cbebac3aa3646a1a1034e92d2d11518870b3db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:48:51 -0800 Subject: [PATCH 020/213] Preserve PNG8 transparency and reject unsupported SVG links --- .../src/script/dom/save_open/screens.rs | 11 ++++- crates/engine/src/tests/script_screens.rs | 48 +++++++++++++++++++ crates/js/src/host.rs | 2 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs index c4cf253ecd..07ef0aa324 100644 --- a/crates/engine/src/script/dom/save_open/screens.rs +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -15,6 +15,8 @@ //! The method runs `document.exportForScreens` with one format row into the folder, which goes //! through the script's file grants as a `File` opened for writing there would, and the command //! writes only where the script's `File` objects may ([`super::exactly`]). +//! With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. SVG raster images are +//! embedded; `RasterImageLocation.LINK` returns an error. //! //! VectorCraft's own rules, which the reference pages do not state: //! - `exportFolder` is a `Folder`, or a `File` read as the folder at its path. The files go into @@ -217,7 +219,7 @@ fn png8_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } // Matted on white, the default `matteColor`, or not matted. "matte" => { - p.insert("matte".into(), if boolean(d, &what)? { json!("white") } else { Value::Null }); + p.insert("matte".into(), json!(if boolean(d, &what)? { "white" } else { "none" })); } _ => return raster_map(CLASS, name, d, p), } @@ -254,7 +256,12 @@ fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Res ("styling", json!(styling)) } "fontType" => ("outlineText", json!(pick(d, "SVGFontType", &what)? == "OUTLINEFONT")), - "rasterImageLocation" => ("images", json!(if pick(d, "RasterImageLocation", &what)? == "LINK" { "link" } else { "embed" })), + "rasterImageLocation" => { + if pick(d, "RasterImageLocation", &what)? == "LINK" { + return Err(HostError::Error(format!("{what}: RasterImageLocation.LINK is not available yet"))); + } + ("images", json!("embed")) + } "svgId" => { let ids = match pick(d, "SVGIdType", &what)? { "SVGIDMINIMAL" => "minimal", diff --git a/crates/engine/src/tests/script_screens.rs b/crates/engine/src/tests/script_screens.rs index 343feff945..691fd5a107 100644 --- a/crates/engine/src/tests/script_screens.rs +++ b/crates/engine/src/tests/script_screens.rs @@ -9,6 +9,54 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[test] +fn screen_png8_without_matting_keeps_transparent_edge_colors() { + let base = vectorcraft_testkit::TempDir::new("screen-png8-unmatted"); + std::fs::create_dir_all(base.join("main")).unwrap(); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 20, 20); \ + vc.run('shape.rectangle', {{x: 0, y: 0, width: 20, height: 20}}); \ + vc.run('paint.setFill', {{color: '#ff0000'}}); d.pageItems[0].opacity = 50; \ + var o = new ExportForScreensOptionsPNG8(); o.matte = false; \ + d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG8, o);", + quoted(&dir.join("png8")) + ), + ); + let output = dir.join("png8"); + let files = names(&output); + assert_eq!(files.len(), 1); + let rgba = image::open(output.join(&files[0])).unwrap().to_rgba8(); + let pixel = rgba.get_pixel(5, 5).0; + assert!(pixel[0] > 200 && pixel[1] < 20 && pixel[2] < 20, "{pixel:?}"); +} + +#[test] +fn linked_screen_svg_images_are_rejected_before_output_is_created() { + let base = vectorcraft_testkit::TempDir::new("screen-svg-linked"); + std::fs::create_dir_all(base.join("main")).unwrap(); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + let output = dir.join("svg"); + let error = failure( + &mut s, + &base, + &format!( + "Folder.userData; var o = new ExportForScreensOptionsWebOptimizedSVG(); \ + o.rasterImageLocation = RasterImageLocation.LINK; \ + app.activeDocument.exportForScreens(new Folder({}), ExportForScreensType.SE_SVG, o);", + quoted(&output) + ), + ); + assert!(error.contains("not available yet"), "{error}"); + assert!(!output.exists()); +} + /// A fresh folder for test `name`, by its real path, with `main` for the script. fn folder(name: &str) -> PathBuf { let base = std::env::temp_dir().join(format!("vc-script-screens-{name}-{}", std::process::id())); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index bbb1be9d47..564cce2efd 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -268,7 +268,7 @@ impl Interp { if r.hosted && let Some(file) = self.file_ref_of(id)? { - let len = match &file { + let len: usize = match &file { Data::Object(items) => items.iter().map(|(_, v)| if let Data::String(p) = v { p.len() } else { 0 }).sum(), _ => 0, }; diff --git a/docs/mcp.md b/docs/mcp.md index 60044f85b2..72ec7c7532 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2941,8 +2941,8 @@ other files through `$`: `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR` as a multiplier from 0.01 to 64, so 2 doubles the size, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, `SCALEBYRESOLUTION` in ppi from 0.72 to 4608); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`, - `matte` and `transparency`. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, - `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`, and the PDF class maps `pdfPreset` (at most 255 + `matte` and `transparency`. With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, + `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`. SVG `RasterImageLocation.LINK` throws; `EMBED` and `PRESERVE` embed raster images. The PDF class maps `pdfPreset` (at most 255 bytes; a name in square brackets names a built-in preset as `PDFSaveOptions.pDFPreset` does). `itemToExport` is a `new ExportForScreensItemToExport()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html) with `artboards` (`all`, the default, a range of artboard numbers such as `1-3, 5`, or `""` for none), `assets` (a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3578b81e5f..0ba5bf7e8b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1049,7 +1049,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_screens.rs`. + - Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. SVG embeds raster images and rejects `RasterImageLocation.LINK`. `crates/engine/src/tests/script_screens.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/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, 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`. From e3b74e2fdad5fbfdba640c7a3659c4c327fccf9d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:05:12 -0800 Subject: [PATCH 021/213] Validate screen export sizes before creating output --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/screens.rs | 11 ++++++++++- crates/engine/src/tests/script_screens.rs | 23 ++++++++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/tests.rs | 14 +++++++++++++ docs/mcp.md | 5 ++++- docs/target-app-parity.md | 2 +- 7 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5e756623f0..48c584d7ad 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,