From 4ac416d7d011bf6f26c2fc83d0f6bfc64352190d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:21:26 -0800 Subject: [PATCH 01/61] 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 02/61] 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 03/61] 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 04/61] 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 05/61] 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 48a09ccae35e34bd317ef0dcbd0c9cf28df0e9ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 07:05:03 -0800 Subject: [PATCH 06/61] 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 07/61] 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 70e6f4e797632bedd375356085e8b264fc1f8a78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:20:32 -0800 Subject: [PATCH 08/61] 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 09/61] 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 bee68ccd13acf2d747e0cd8a5e1f78ddf3e5502e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:01:18 -0800 Subject: [PATCH 10/61] 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 11/61] 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 12/61] 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 13/61] 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 66cbebac3aa3646a1a1034e92d2d11518870b3db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:48:51 -0800 Subject: [PATCH 14/61] 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 15/61] 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, ,