From 4ac416d7d011bf6f26c2fc83d0f6bfc64352190d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:21:26 -0800 Subject: [PATCH] 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`.