From 4ac416d7d011bf6f26c2fc83d0f6bfc64352190d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:21:26 -0800 Subject: [PATCH 01/12] 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/12] 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/12] 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/12] 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/12] 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 382d396eff6ad0c60ca1bb0e9f5b42f8b8dc8820 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:14:32 -0800 Subject: [PATCH 06/12] Scripts: fix review findings on path lists, resource handles and Symbol - A path list stays kept through paint, stroke and point edits that make no new object, so a loop over pathItems no longer rebuilds it per edit. - Resource handles go stale when any step of a batch or an action step removes or renames their resource, and come back when a failed dataset row restores it. The names the steps compare are charged to the run, including for a batch that fails. - Listing spots is charged for every swatch it looks at. - A path inside a group inside a compound shape reads and sets the compound shape's paint. - Assigning closed on an empty path is kept until the path has points, and is dropped once a command gives it points. - Only the host class named Symbol leaves an existing global in place. --- crates/engine/src/cmd/fileio/batch.rs | 5 + crates/engine/src/script/actions.rs | 1 + crates/engine/src/script/dom.rs | 31 +++- crates/engine/src/script/dom/paths.rs | 148 +++++++++++++++-- crates/engine/src/script/dom/resources.rs | 100 +++++++++-- crates/engine/src/script/mod.rs | 64 +++++-- crates/engine/src/tests/script_dom_paths.rs | 157 ++++++++++++++++++ .../engine/src/tests/script_dom_resources.rs | 131 ++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/host_classes.rs | 7 +- crates/js/src/host_tests.rs | 25 +++ docs/mcp.md | 9 +- 12 files changed, 629 insertions(+), 51 deletions(-) diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 93670cefd9..841d849e14 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -25,6 +25,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); let active = s.active; + let style_trail = s.script_in_run.then(|| s.script_style_trail.clone()); s.batch_stash = Some(vec![]); let mut grouped = Vec::with_capacity(cmds.len()); // The Type tool keeps what the steps' Undo and Redo change in it, to put back on a rollback. @@ -39,6 +40,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } Err(e) => { roll_back(s, start, &stash); + if let Some(mut trail) = style_trail { + trail.resources_scanned = s.script_style_trail.resources_scanned; + s.script_style_trail = trail; + } s.notify_text_tool("batch.rollBack"); s.active = active; s.sync_front_profiles(); diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 2abb290cf7..6c3cb4a611 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -258,6 +258,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); h.session.borrow_mut().set_replaying(outer); + super::dom::forget_removed(h)?; if let Err(e) = r { let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id)); return Err(match e { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d5fb10dbcf..480a97aafd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -103,13 +103,19 @@ mod text; mod variables; #[cfg(test)] -pub(crate) use paths::POINT_LOOKS; +pub(crate) use paths::{PATH_LISTS, POINT_LOOKS}; +pub(super) use resources::{Kind as ResourceKind, gone as resources_gone, held as holds_resources}; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; +/// Resources a command's steps removed or renamed (a document's uid, the kind and the name), and +/// the names the steps compared. +type GoneResources = (HashSet<(u64, ResourceKind, String)>, u64); + /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + *h.dom.resources_gone.borrow_mut() = Default::default(); variables::before_command(h, id) } @@ -183,6 +189,9 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, + /// The paths with no points, by document uid, revert count and id, that a script set `closed` + /// on: the points `setEntirePath` gives them later make a closed path. + pub(super) closed_empty: RefCell>, /// The index of the first point of each subpath of the path whose points the run read last, /// and what they were counted from ([`paths`]). point_starts: RefCell>)>>, @@ -202,6 +211,10 @@ pub(super) struct State { /// change. editing: Cell>, locked: RefCell>, + /// The resources the steps of the last kept command removed or renamed, and how many names + /// the steps compared, which the next [`forget_removed`] marks stale and charges. Each command + /// clears it first ([`before_command`]). + resources_gone: RefCell, /// The swatches, symbols, styles and brushes the run's objects name ([`resources`]). resources: RefCell, saving: Cell, @@ -906,9 +919,24 @@ fn on_doc( /// Marks stale the style objects whose styles a command the run ran removed or renamed. pub(super) fn after_kept_command(h: &Host) { + paths::forget_closed_empty(h); + let taken = { + let mut s = h.session.borrow_mut(); + let trail = &mut s.script_style_trail; + (std::mem::take(&mut trail.resources_gone), std::mem::take(&mut trail.resources_scanned)) + }; + *h.dom.resources_gone.borrow_mut() = taken; text::styles::after_command(h); } +/// After a command that is not kept: the resource names its steps compared are charged with the +/// next [`forget_removed`], and the resources they removed are not marked stale. +pub(super) fn keep_scanned(h: &Host) { + let scanned = std::mem::take(&mut h.session.borrow_mut().script_style_trail.resources_scanned); + let mut gone = h.dom.resources_gone.borrow_mut(); + gone.1 = gone.1.saturating_add(scanned); +} + /// Runs `id` with `params` on the item's document, its selection kept, as one change: when the /// selection cannot be put back, the edit is undone too. The points the run read of the item's /// paths stay valid through the change ([`paths::see_all_points`]). @@ -2926,7 +2954,6 @@ fn classes(link: &Link) -> Vec { ("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }), ("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }), ("selection", property(l, doc_selection, doc_set_selection), typed("*")), - ("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }), ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 67fd0fc6c7..1a0dc3af03 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -238,14 +238,34 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { forget_waiting_starts(h); - if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() + // A path that has or gains points keeps its own closed state from then on ([`is_closed`]). + let gained = |gained: bool| { + if gained { + let key = closed_key(h, item); + h.dom.closed_empty.borrow_mut().remove(&key); + } + }; + let mut f = Some(f); + let accepted = if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) + && let Some(f) = f.take() { - return Ok(f(subs)); + let had = !subs.is_empty(); + let r = f(subs); + Some((r, had || !subs.is_empty())) + } else { + None + }; + if let Some((r, has_points)) = accepted { + gained(has_points); + return Ok(r); } + let Some(f) = f else { return Err(HostError::Error(STALE_ITEM.into())) }; flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let had = !subs.is_empty(); let r = f(&mut subs); + let has_points = had || !subs.is_empty(); let (same, ok, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); @@ -260,9 +280,30 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) flush(h)?; } } + gained(has_points); Ok(r) } +/// The key of the path of `item` among the empty paths a script set `closed` on: its document's +/// uid and revert count, so a revert drops the setting, and its id. +fn closed_key(h: &super::Host, item: Item) -> (u64, u64, NodeId) { + (item.doc.uid, with_doc(h, item.doc, |_, st| st.reverts), item.id) +} + +/// Drops empty-path closed settings after a kept command gives a path points or removes it. +pub(super) fn forget_closed_empty(h: &super::Host) { + let s = h.session.borrow(); + h.dom.closed_empty.borrow_mut().retain(|(uid, reverts, id)| { + !s.script_style_trail.paths_with_points.contains(&(*uid, *reverts, *id)) + && s.documents() + .iter() + .find(|st| st.uid == *uid && st.reverts == *reverts) + .and_then(|st| st.doc.node(*id)) + .and_then(|n| n.path_data()) + .is_some_and(|pd| pd.subpaths.is_empty()) + }); +} + /// Drops the [`starts`] that [`super::State`] keeps of waiting point changes, which a change can /// make wrong. fn forget_waiting_starts(h: &super::Host) { @@ -315,16 +356,61 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { // Changes made before this one are looked at in full first. see_all_points(h); let kept = h.dom.one_path.replace(Some(item)); - let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})); + let r = keeping_paths(h, item, || edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))); h.dom.one_path.set(kept); r?; Ok(()) } -/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape -/// when it is a member of one, since the paint commands paint that owner in its place. +#[cfg(test)] +thread_local! { + /// How many times this thread listed a document's paths ([`path_items`]), for the tests. + pub(crate) static PATH_LISTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds, +/// removes and reorders no object of its own. When it succeeds, the document made no new object, +/// and every kept path still exists, the list of the document's paths ([`path_items`]) stays kept. +fn keeping_paths(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result) -> std::result::Result { + let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| { + let s = h.session.borrow(); + if let Some(st) = s.documents().iter().find(|d| d.uid == item.doc.uid) { + run(st); + } + }; + let mut kept = None; + doc_state(h, &mut |st| kept = super::kept_list(&h.dom.paths, st).map(|ids| (ids, st.doc.peek_next_id()))); + let r = f()?; + if let Some((ids, next)) = kept { + doc_state(h, &mut |st| { + if st.doc.peek_next_id() == next { + super::keep_list(&h.dom.paths, st, &ids); + } + }); + } + Ok(r) +} + +/// The object whose paint the path `n` with id `id` shows: the outermost compound shape it is +/// inside, at any depth, or else its compound path when it is a member of one. The paint setters +/// paint that owner ([`edit_paint`]). fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { - d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) + let ancestors = d.ancestry(id).unwrap_or_default(); + let above = ancestors.split_last().map_or(&[][..], |(_, rest)| rest); + if let Some(shape) = above.iter().filter_map(|i| d.node(*i)).find(|p| p.is_compound_shape()) { + return shape; + } + d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n) +} + +/// Runs the paint command `id` with `params` on the object whose paint the path shows +/// ([`paint_owner`]). +fn edit_paint(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { + let owner = read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).id)?; + if let Some(o) = params.as_object_mut() { + o.insert("ids".into(), json!([owner.0])); + } + edit_path(h, item, id, params) } /// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active @@ -349,9 +435,16 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } + if KEEP_PATHS.contains(&id) { + return keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, ¶ms))); + } keeping_paint(h, || edit_item(h, item, id, ¶ms)) } +/// The commands [`edit_path`] runs that change only paint, stroke or fill rule, after which the +/// document's paths are the ones listed before ([`keeping_paths`]). +const KEEP_PATHS: &[&str] = &["paint.setFill", "paint.setStroke", "stroke.set", "object.setOverprint", "path.setFillRule"]; + /// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color /// and gradient and the recent colors as they were before it. fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { @@ -372,6 +465,8 @@ fn path_items(h: &super::Host, st: &DocState) -> Rc> { if let Some(ids) = super::kept_list(&h.dom.paths, st) { return ids; } + #[cfg(test)] + PATH_LISTS.with(|n| n.set(n.get() + 1)); let all = super::page_items(h, st); let ids: Rc> = Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); @@ -650,15 +745,37 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) } +/// Whether the path of `item` is closed: every subpath is, or, for a path with no points, a script +/// set `closed` on it. +fn is_closed(h: &super::Host, item: Item) -> std::result::Result { + let (empty, closed) = read_points(h, item, |subs| (subs.is_empty(), subs.iter().all(|sp| sp.closed)))?; + Ok(if empty { h.dom.closed_empty.borrow().contains(&closed_key(h, item)) } else { closed }) +} + fn path_closed(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - read_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.iter().all(|sp| sp.closed))) + Ok(Data::Bool(is_closed(h, item)?)) } fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + let empty = edit_points(h, item, |subs| { + subs.iter_mut().for_each(|sp| sp.closed = closed); + subs.is_empty() + })?; + if empty && is_closed(h, item)? != closed { + if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + return Err(cannot_edit(item.id)); + } + let key = closed_key(h, item); + let mut held = h.dom.closed_empty.borrow_mut(); + if closed { + held.insert(key); + } else { + held.remove(&key); + } + } Ok(Data::Undefined) } @@ -762,7 +879,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { } let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::>()?; let f = with_doc(h, item.doc, |_, st| frame(st))?; - let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; + let closed = is_closed(h, item)?; let c = h.dom.coords.get(); let anchors: Vec = script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; @@ -832,7 +949,7 @@ fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option) -> s Some(c) => json!({"color": colors::param(&c)}), None => json!({"none": true}), }; - edit_path(h, item, id, params)?; + edit_paint(h, item, id, params)?; Ok(()) } @@ -895,7 +1012,7 @@ fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer { let now = if fill { !look.fill.is_none() } else { !look.stroke.is_none() }; if now != on { let params = if on { new_art_params(h, item, fill)? } else { json!({"none": true}) }; - edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?; + edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?; } Ok(Data::Undefined) } @@ -931,7 +1048,7 @@ fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f6 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}))?; + edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?; } Ok(Data::Undefined) } @@ -960,7 +1077,7 @@ fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer { /// Runs `stroke.set` with `params` on the path, unless `same`. fn set_stroke_option(h: &super::Host, item: Item, same: bool, params: Value) -> Answer { if !same { - edit_path(h, item, "stroke.set", params)?; + edit_paint(h, item, "stroke.set", params)?; } Ok(Data::Undefined) } @@ -1238,7 +1355,7 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { if let Some(w) = new_width && (w - width).abs() > 1e-9 { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; + edit_paint(h, item, "stroke.set", json!({"weight": w}))?; } Ok(Data::Undefined) } @@ -1420,11 +1537,12 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer { Some(p) => p, None => origin?, }; + let closed = last.is_none() && is_closed(h, item)?; // The kept starts are dropped, so that `counted` is their only copy and grows in place. *h.dom.point_starts.borrow_mut() = None; edit_points(h, item, |subs| match subs.last_mut() { Some(sp) => sp.anchors.push(Anchor::corner(p)), - None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), + None => subs.push(SubPath::new(vec![Anchor::corner(p)], closed)), })?; if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) { let grown = Rc::make_mut(&mut counted); diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index 406fcedeee..467509840f 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -28,8 +28,8 @@ //! 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 -//! `[]`, since a script has no Swatches panel selection. +//! unless it is Lab, or black when it is not a solid color, as a spot color. `getSelected()` throws +//! that it is not available, since the engine does not hold the Swatches panel's 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. @@ -62,6 +62,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::swatch::{self, Swatch}; use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::Shared; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref}; use super::{ @@ -78,7 +79,7 @@ pub const MAX_SLOTS: usize = 100_000; /// The kinds of resource object. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub(super) enum Kind { +pub(in crate::script) enum Kind { Swatch, Spot, Group, @@ -162,7 +163,7 @@ impl Table { } kept }); - work += present.values().map(|p| p.len() as u64).sum::(); + work += present.iter().map(|(k, p)| scanned(st.map(|st| &*st.doc), *k, p.len())).sum::(); match st { Some(st) => self.checked.insert(*uid, st.doc.clone()), None => self.checked.remove(uid), @@ -221,14 +222,63 @@ impl Table { } } } + + /// The resource `name` of `kind` is gone: for a spot, the spot objects alone, since a swatch + /// that stops being a spot is still a swatch; for any other kind its whole family. + fn remove_kind(&mut self, uid: u64, kind: Kind, name: &str) { + if kind != Kind::Spot { + return self.remove(uid, kind, name); + } + let Some(held) = self.index.get_mut(&uid) else { return }; + if let Some(i) = held.remove(&(kind, name.to_string())) { + self.slots[i].2 = None; + } + } } -/// After a `vc.run` command: the objects whose resource the command removed or renamed go stale. -/// The slots and names the check compares are charged to the run. +/// The swatches, spots, color groups, symbols, graphic styles and brushes `old` has and `new` does +/// not, each with its kind, and how many names were compared. Only the lists that changed are +/// compared. A swatch that stops being a spot is listed as a spot alone. +pub(in crate::script) fn gone(old: &Document, new: &Document) -> (Vec<(Kind, String)>, u64) { + let changed = |kind: Kind| match kind { + Kind::Swatch | Kind::Spot => !Shared::ptr_eq(&old.swatches, &new.swatches) || !Shared::ptr_eq(&old.swatch_groups, &new.swatch_groups), + Kind::Group => !Shared::ptr_eq(&old.swatch_groups, &new.swatch_groups), + Kind::Symbol => old.symbols.len() != new.symbols.len() || old.symbols.iter().zip(&new.symbols).any(|(a, b)| a.name != b.name), + Kind::Style => !Shared::ptr_eq(&old.graphic_styles, &new.graphic_styles), + Kind::Brush => { + !Shared::ptr_eq(&old.unknown, &new.unknown) && old.unknown.get(vectorcraft_brush::DOC_KEY) != new.unknown.get(vectorcraft_brush::DOC_KEY) + } + }; + let mut out = Vec::new(); + // Telling whether the symbol names changed compares them one by one. + let mut work = old.symbols.len().min(new.symbols.len()) as u64; + for kind in KINDS.into_iter().filter(|k| changed(*k)) { + let now: HashSet = names(new, kind).into_iter().collect(); + let was = names(old, kind); + work += scanned(Some(new), kind, now.len()) + scanned(Some(old), kind, was.len()); + out.extend(was.into_iter().filter(|n| !now.contains(n)).map(|n| (kind, n))); + } + (out, work) +} + +/// Whether the run holds any swatch, symbol, style or brush object, so that the steps of a batch +/// need to note what they remove ([`gone`]). +pub(in crate::script) fn held(h: &Host) -> bool { + !h.dom.resources.borrow().index.is_empty() +} + +/// After a `vc.run` command: the objects whose resource the command removed or renamed go stale, +/// including a resource a step of a batch removed or renamed and a later step made again under +/// its name. The slots and names the check compares are charged to the run. pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> { + let (gone, scanned) = std::mem::take(&mut *h.dom.resources_gone.borrow_mut()); let work = { let s = h.session.borrow(); - h.dom.resources.borrow_mut().forget(s.documents()) + let mut table = h.dom.resources.borrow_mut(); + for (uid, kind, name) in &gone { + table.remove_kind(*uid, *kind, name); + } + table.forget(s.documents()) + gone.len() as u64 + scanned }; if work > 0 { h.charge_call(work)?; @@ -279,15 +329,21 @@ fn name_arg(d: &Data, what: &str) -> std::result::Result { /// The swatches in panel order, each with its color group. fn all_swatches(d: &Document) -> Vec<(&Swatch, Option<&str>)> { + swatches_in_order(d).collect() +} + +/// [`all_swatches`], one at a time. +fn swatches_in_order(d: &Document) -> impl Iterator)> { 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() + ungrouped.chain(grouped) } +/// The swatch `name`, looked up in panel order; the lookup stops at the match. 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) + swatches_in_order(d).find(|(w, _)| w.name == name) } /// Whether `spots` lists `w`: a spot color, or Registration. @@ -371,11 +427,25 @@ fn coll_doc(h: &Host, a: &[Data], kind: Kind) -> std::result::Result 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)?; + let (list, work) = with_doc(h, doc, |_, st| { + let list = names(&st.doc, kind); + let work = scanned(Some(&st.doc), kind, list.len()); + (list, work) + }); + h.charge_call(work)?; Ok((doc, list)) } +/// How many records listing the `found` names of `kind` in `d` looked at: every swatch for the +/// spots, which are picked out of the swatches, and the names themselves otherwise. +fn scanned(d: Option<&Document>, kind: Kind, found: usize) -> u64 { + let n = match (kind, d) { + (Kind::Spot, Some(d)) => swatches_in_order(d).count().max(found), + _ => found, + }; + n as u64 +} + fn coll_length(h: &Host, kind: Kind, a: &[Data]) -> Answer { Ok(num(float(coll_names(h, a, kind)?.1.len() as u64))) } @@ -518,11 +588,6 @@ fn groups_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { 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) }; @@ -1133,7 +1198,8 @@ pub(super) fn classes(l: &Link) -> Vec { match kind { Kind::Swatch => { m.push(("add".into(), kmethod(l, kind, swatches_add), returns(one, &[]))); - m.push(("getSelected".into(), kmethod(l, kind, swatches_selected), returns("Array", &[]))); + // The engine does not hold the Swatches panel's selection. + m.push(later(l, "Swatches", "getSelected")); } Kind::Spot => m.push(("add".into(), kmethod(l, kind, spots_add), returns(one, &[]))), Kind::Group => m.push(("add".into(), kmethod(l, kind, groups_add), returns(one, &[]))), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 6f74bce6b8..6710525ba9 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1319,7 +1319,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); - s.script_style_trail = StyleTrail::start(s); + s.script_style_trail = StyleTrail::start(s, dom::holds_resources(host), host.dom.closed_empty.borrow().clone()); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1367,7 +1367,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value Ok((v, objects, bytes, save)) } Err(e) => { - s.script_style_trail = StyleTrail::default(); + s.script_style_trail = StyleTrail { resources_scanned: s.script_style_trail.resources_scanned, ..Default::default() }; if let Some(save) = save && !save.restore(s) { @@ -1393,9 +1393,8 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, id, params) }; + // The resource names a failed command's steps compared are still charged ([`dom::forget_removed`]). + if r.is_err() { + dom::keep_scanned(host); + } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { let nanos = started.elapsed().as_nanos(); @@ -1456,6 +1459,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( dom::see_points(host); dom::after_kept_command(host); } else { + dom::keep_scanned(host); session.borrow_mut().script_style_trail = StyleTrail::default(); } crossed.map(|data| (data, value)) @@ -1468,19 +1472,30 @@ pub(crate) type StyleLists = /// What the steps of a command a script runs did to the documents' style lists /// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step /// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the -/// documents a step reverted. -#[derive(Default)] +/// documents a step reverted. It also holds each open document as the last step left it, and the +/// swatches, symbols, graphic styles and brushes a step removed or renamed. +#[derive(Clone, Default)] pub(crate) struct StyleTrail { lists: Vec, pub(crate) gone: std::collections::HashSet<(u64, bool, String)>, pub(crate) reverted: Vec, + /// Whether the run holds resource objects, so that the steps note what they remove. + watch_resources: bool, + docs: Vec<(u64, Arc)>, + pub(in crate::script) resources_gone: std::collections::HashSet<(u64, dom::ResourceKind, String)>, + /// The resource names the steps compared, charged to the run with the check that follows. + pub(crate) resources_scanned: u64, + closed_empty: std::collections::HashSet<(u64, u64, NodeId)>, + pub(in crate::script) paths_with_points: std::collections::HashSet<(u64, u64, NodeId)>, } impl StyleTrail { - /// A trail that starts from the documents' style lists now. - fn start(s: &Session) -> Self { + /// A trail that starts from the documents' style lists now, and from the documents themselves + /// when `watch_resources`. + fn start(s: &Session, watch_resources: bool, closed_empty: std::collections::HashSet<(u64, u64, NodeId)>) -> Self { let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); - StyleTrail { lists, ..Default::default() } + let docs = if watch_resources { s.docs.iter().map(|st| (st.uid, st.doc.clone())).collect() } else { Vec::new() }; + StyleTrail { lists, docs, watch_resources, closed_empty, ..Default::default() } } } @@ -1490,6 +1505,17 @@ impl StyleTrail { /// document's lists, however many steps change them. pub(crate) fn note_style_lists(s: &mut Session) { let trail = &mut s.script_style_trail; + for &(uid, reverts, id) in &trail.closed_empty { + if s.docs + .iter() + .find(|st| st.uid == uid && st.reverts == reverts) + .and_then(|st| st.doc.node(id)) + .and_then(|n| n.path_data()) + .is_some_and(|pd| !pd.subpaths.is_empty()) + { + trail.paths_with_points.insert((uid, reverts, id)); + } + } trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); for st in &s.docs { let (c, p) = (&st.doc.char_styles, &st.doc.para_styles); @@ -1514,6 +1540,24 @@ pub(crate) fn note_style_lists(s: &mut Session) { } *last = (st.uid, st.reverts, c.clone(), p.clone()); } + if !trail.watch_resources { + return; + } + trail.docs.retain(|(uid, _)| s.docs.iter().any(|d| d.uid == *uid)); + for st in &s.docs { + let Some(last) = trail.docs.iter_mut().find(|(uid, _)| *uid == st.uid) else { + trail.docs.push((st.uid, st.doc.clone())); + continue; + }; + if !Arc::ptr_eq(&last.1, &st.doc) { + let (gone, scanned) = dom::resources_gone(&last.1, &st.doc); + trail.resources_scanned = trail.resources_scanned.saturating_add(scanned); + for (kind, name) in gone { + trail.resources_gone.insert((st.uid, kind, name)); + } + last.1 = st.doc.clone(); + } + } } /// How many sets of style lists the steps of a batch keep ([`note_style_lists`]). diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 03a45ce251..811a3cd374 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -428,6 +428,51 @@ fn compound_path_members_read_the_paint_they_are_given() { assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule"); } +#[test] +fn paths_in_a_group_in_a_compound_shape_read_and_set_the_compound_shapes_paint() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [group, b.0]})).unwrap(); + let shape = NodeId(s.execute("object.compoundShape.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let before = node(&s, a).appearance.clone(); + let out = log( + &mut s, + "var p = null, all = app.activeDocument.pathItems; for (var i = 0; i < all.length; i++) if (all[i].geometricBounds[0] < 50) p = all[i];\ + vc.log(p.parent.parent.typename); var c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4; vc.log([p.fillColor.red, p.strokeWidth]);", + ); + assert_ne!(out[0], json!("Layer"), "the path is inside a group inside the compound shape"); + assert_eq!(rounded(&out[1]), json!([200, 4])); + let Paint::Solid { color: Color::Rgb { r, .. }, .. } = node(&s, shape).appearance.fill_paint() else { + panic!("the compound shape has an RGB fill") + }; + assert!((r - 200.0 / 255.0).abs() < 1e-3, "the compound shape takes the fill, got {r}"); + assert_eq!(node(&s, a).appearance, before, "the nested path's own paint is left as it was"); +} + +#[test] +fn closed_set_on_an_empty_path_holds_until_it_has_points() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems.add(); vc.log(p.closed); p.closed = true; vc.log(p.closed);\ + p.setEntirePath([[0, 300], [40, 300], [40, 240]]); vc.log(p.closed);\ + var q = app.activeDocument.pathItems.add(); q.closed = true; q.closed = false; q.setEntirePath([[0, 0], [1, 1]]); vc.log(q.closed);", + ); + assert_eq!(out, vec![json!(false), json!(true), json!(true), json!(false)]); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems.add(); p.closed = true; p.pathPoints.add(); vc.log(p.closed);\ + p.closed = false; p.pathPoints.removeAll(); vc.log(p.closed);", + ); + assert_eq!(out, vec![json!(true), json!(false)], "pathPoints.add keeps the state, and an opened path does not reopen closed"); + let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.lock", &json!({"ids": [id.0]})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints.length); p.closed = false; vc.log(p.closed);"); + assert_eq!(out, vec![json!(0), json!(false)], "an unchanged assignment on a locked empty path is allowed"); +} + #[test] fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() { let (mut s, a) = doc_with_paints(); @@ -670,6 +715,118 @@ fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() { assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits"); } +#[test] +fn paint_and_point_edits_keep_the_list_of_paths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..50 { + rect(&mut s, f64::from(i % 10) * 10.0, f64::from(i / 10) * 10.0, 5.0, 5.0); + } + s.execute("select.none", &json!({})).unwrap(); + let start = crate::script::dom::PATH_LISTS.with(|n| n.get()); + log( + &mut s, + "var ps = app.activeDocument.pathItems;\ + for (var i = 0; i < ps.length; i++) { var c = new RGBColor(); c.red = i; ps[i].fillColor = c; ps[i].strokeWidth = 2;\ + ps[i].fillOverprint = true; var q = ps[i].pathPoints[0]; q.anchor = [q.anchor[0] + 1, q.anchor[1]]; }", + ); + let built = crate::script::dom::PATH_LISTS.with(|n| n.get()) - start; + assert_eq!(built, 1, "the paths are listed once for 50 paint and point edits"); + let out = log(&mut s, "var ps = app.activeDocument.pathItems; var n = ps.length; ps.rectangle(0, 0, 1, 1); vc.log([n, ps.length]);"); + assert_eq!(out, vec![json!([50, 51])], "a new path is listed"); +} + +#[test] +fn an_edit_that_regenerates_shaper_art_lists_the_paths_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap(); + for x in [0.0, 50.0] { + rect(&mut s, x, 50.0, 100.0, 100.0); + } + s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let sources = vectorcraft_doc::shaper::SOURCES; + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, n = ps.length, src = null;\ + for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src = ps[i];\ + var q = src.pathPoints[0]; q.anchor = [q.anchor[0] + 200, q.anchor[1]]; src.fillColor = new GrayColor(); vc.log(ps.length);" + ), + ); + let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);"); + assert_eq!(out, fresh, "the list after the edit matches a fresh run's"); +} + +#[test] +fn a_closed_setting_on_an_empty_path_ends_once_a_command_gives_it_points() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap()); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; p.closed = true;\ + vc.run('path.setAnchors', {{id: {}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\ + p.pathPoints.removeAll(); vc.log(p.closed);", + id.0 + ), + ); + assert_eq!(out, vec![json!(false)], "the open points the command gave end the setting"); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; p.closed = true;\ + vc.run('path.setAnchors', {{id: {0}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}});\ + vc.run('path.setAnchors', {{id: {0}, subpaths: []}}); vc.log(p.closed);", + id.0 + ), + ); + assert_eq!(out, vec![json!(false)], "clearing the points through a command does not restore the setting"); +} + +#[test] +fn a_kept_batch_ends_the_empty_path_closed_setting_even_when_it_removes_its_points() { + for fail in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap(); + let failure = if fail { ", {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}" } else { "" }; + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; p.closed = true; var failed = false;\ + try {{ vc.run('command.batch', {{commands: [\ + {{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\ + {{command: 'path.setAnchors', params: {{id: {id}, subpaths: []}}}}{failure}]}}); }} catch (e) {{ failed = true; }}\ + vc.log(failed); vc.log(p.pathPoints.length); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!(fail), json!(0), json!(fail)]); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_failed_dataset_row_keeps_the_empty_path_closed_setting() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap(); + s.execute("dataset.new", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; p.closed = true;\ + var r = vc.run('action.batch', {{source: 'datasets', commands: [\ + {{command: 'path.setAnchors', params: {{id: {id}, subpaths: [{{anchors: [{{x: 0, y: 0}}, {{x: 10, y: 0}}], closed: false}}]}}}},\ + {{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\ + vc.log(r.failed); vc.log(p.pathPoints.length); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!(1), json!(0), json!(true)]); +} + #[test] fn point_edits_are_written_before_the_next_other_member_reads() { let (mut s, a, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs index fd76ee8b45..82387ce2b8 100644 --- a/crates/engine/src/tests/script_dom_resources.rs +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -55,7 +55,7 @@ fn swatches_are_live_and_keep_reserved_entries() { &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);", + vc.log(w.getByName('Black').color.typename); try { w.getSelected(); } catch (e) { vc.log(e.message); }", ); assert_eq!( out, @@ -68,7 +68,7 @@ fn swatches_are_live_and_keep_reserved_entries() { json!("Swatch"), json!(true), json!("RGBColor"), - json!(0) + json!("Swatches.getSelected is not available yet") ] ); let out = log( @@ -123,6 +123,16 @@ fn resource_objects_go_stale_after_remove_and_follow_renames() { "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", ), + ( + "var w = app.activeDocument.swatches.getByName('Yellow'); vc.run('command.batch', {commands: [\ + {command: 'swatch.delete', params: {name: 'Yellow'}}, {command: 'swatch.new', params: {name: 'Yellow', color: '#ffff00'}}]}); w.name;", + "Stale Swatch", + ), + ( + "var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('command.batch', {commands: [\ + {command: 'graphicStyle.rename', params: {name: g.name, to: 'X'}}, {command: 'graphicStyle.rename', params: {name: 'X', to: g.name}}]}); g.name;", + "Stale GraphicStyle", + ), ]; for (script, message) in cases { let e = failure(&mut s, script); @@ -130,6 +140,114 @@ fn resource_objects_go_stale_after_remove_and_follow_renames() { } } +#[test] +fn a_spot_object_goes_stale_when_a_batch_makes_its_swatch_process_and_back() { + let (mut s, _) = doc(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap(); + let toggle = "vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'Ink', spot: false}},\ + {command: 'swatch.edit', params: {name: 'Ink', spot: true}}]});"; + let e = failure(&mut s, &format!("var p = app.activeDocument.spots.getByName('Ink'); {toggle} p.name;")); + assert!(e.contains("Stale Spot"), "{e}"); + let out = log(&mut s, &format!("var w = app.activeDocument.swatches.getByName('Ink'); {toggle} vc.log(w.name);")); + assert_eq!(out, vec![json!("Ink")], "the swatch object stays live"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn action_steps_finalize_resource_removals_before_the_next_step() { + let (mut s, _) = doc(); + s.execute("dataset.new", &json!({"name": "Row"})).unwrap(); + let actions = json!([{"set": "Set", "name": "Replace", "steps": [ + {"command": "action.batch", "params": {"source": "datasets", "commands": [ + {"command": "swatch.delete", "params": {"name": "Yellow"}}, + {"command": "swatch.new", "params": {"name": "Yellow", "color": "#ffff00"}} + ]}}, + {"command": "select.none"} + ]}]); + let source = "var w = app.activeDocument.swatches.getByName('Yellow'); app.doScript('Replace', 'Set');\ + try { vc.log(w.name); } catch (e) { vc.log(e.message); }\ + vc.log(app.activeDocument.swatches.getByName('Yellow').name);"; + let r = s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})).unwrap(); + let out = r["log"].as_array().unwrap(); + assert!(out[0].as_str().unwrap().contains("Stale Swatch"), "{r}"); + assert_eq!(out[1], json!("Yellow")); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_failed_dataset_row_keeps_restored_resource_handles_live() { + for change in ["{command: 'swatch.delete', params: {name: 'Yellow'}}", "{command: 'swatch.edit', params: {name: 'Yellow', newName: 'Ink'}}"] { + let (mut s, _) = doc(); + s.execute("dataset.new", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + &format!( + "var w = app.activeDocument.swatches.getByName('Yellow');\ + var r = vc.run('action.batch', {{source: 'datasets', commands: [{change},\ + {{command: 'swatch.edit', params: {{name: 'No such swatch', color: '#000000'}}}}]}});\ + vc.log(r.failed); vc.log(w.name);" + ), + ); + assert_eq!(out, vec![json!(1), json!("Yellow")], "{change}"); + } +} + +#[test] +fn listing_spots_is_charged_for_every_swatch_it_looks_at() { + let (mut s, _) = doc(); + for i in 0..300 { + s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap(); + } + let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.length;"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("100 listings of 300 process swatches ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); +} + +#[test] +fn a_batch_that_fails_is_charged_for_the_swatches_its_steps_compared() { + let (mut s, _) = doc(); + for i in 0..1000 { + s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap(); + } + let source = "var d = app.activeDocument, w = d.swatches.getByName('P0'); for (var i = 0; i < 30; i++) {\ + try { vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: i % 2 ? '#112233' : '#445566'}},\ + {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]}); } catch (e) {} }"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("30 failed batches over 1000 swatches ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); + let source = "var w = app.activeDocument.swatches.getByName('P0');\ + vc.run('command.batch', {commands: [{command: 'swatch.edit', params: {name: 'P1', color: '#112233'}},\ + {command: 'swatch.edit', params: {name: 'No such swatch', color: '#000000'}}]});"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("a failed batch over 1000 swatches ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "the scan budget error takes precedence over the missing swatch: {e}"); +} + +#[test] +fn the_artwork_symbol_class_leaves_the_built_in_symbol() { + let (mut s, _) = doc(); + // A `.js` file runs as ECMAScript 2015, which has the built-in `Symbol`. + let dir = std::env::temp_dir().join(format!("vc-script-symbol-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("t.js"); + std::fs::write( + &path, + "var d = app.activeDocument, m = d.symbols.add(d.pathItems[0]);\ + vc.log(typeof Symbol()); vc.log(typeof Symbol.iterator); vc.log(m.typename); vc.log(d.symbols.getByName(m.name).typename);", + ) + .unwrap(); + let r = s.execute("script.run", &json!({"path": path.to_string_lossy()})); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(r.unwrap()["log"], json!(["symbol", "symbol", "Symbol", "Symbol"])); +} + #[test] fn hostile_names_and_values_are_refused_without_change() { let (mut s, _) = doc(); @@ -248,8 +366,17 @@ fn a_spot_keeps_an_rgb_color_in_a_cmyk_document() { assert_eq!(undo_steps(&s), steps, "assigning {name} the color it has records no step"); } let what = "app.activeDocument.swatches.getByName('Leaf')"; + let paint = |s: &Session| s.active().unwrap().doc.swatch("Leaf").map(|w| w.paint.clone()); + let before = paint(&s); + let steps = undo_steps(&s); log(&mut s, &assign(what)); assert!(!rgb(&s, "Leaf"), "a process swatch stores the RGB color as CMYK in the CMYK document"); + assert_ne!(paint(&s), before, "the first assignment changes Leaf"); + assert!( + matches!(paint(&s), Some(vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. })), + "Leaf holds a CMYK color" + ); + assert_eq!(undo_steps(&s), steps + 1, "the first assignment records one step"); 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"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 16b92c1de1..3d8e328e77 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -156,7 +156,7 @@ const INSIDE: &[(&str, &str)] = &[ rightDirection= selected selected= typename", ), ("Swatches.", "prototype"), - ("Swatches.prototype.", "add constructor getByName getSelected index length parent removeAll typename"), + ("Swatches.prototype.", "add constructor getByName getSelected getSelected= index length parent removeAll typename"), ("Swatch.", "prototype"), ("Swatch.prototype.", "color color= constructor name name= parent remove typename"), ("Spots.", "prototype"), diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 7f20a30adf..9355e254fa 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -479,8 +479,13 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { unavailable: Rc::new(names(unavailable)), members, }); + // The host class named `Symbol` keeps the built-in `Symbol` global. Its objects use the host prototype. let global = i.global; - i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) + let name = key(&class.name); + if class.name == "Symbol" && i.get_own_property(global, &name)?.is_some() { + return Ok(()); + } + i.define(global, name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } /// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 727d5b22f4..04bcdf29e3 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -24,6 +24,31 @@ fn non_finite_indexer_keys_reach_the_host_unchanged() { assert_eq!(r.run(source).unwrap(), JsValue::String("true|true|true|true|true|true".into())); } +#[test] +fn a_host_class_named_like_a_built_in_global_leaves_the_built_in() { + let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() }); + let name: HostFunction = Rc::new(|_| Ok(Data::String("art".into()))); + let class = HostClass { + name: "Symbol".into(), + parent: None, + members: vec![("name".into(), HostMember::Get(name))], + info: Vec::new(), + index: None, + construct: None, + }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Symbol", &[1.0]))]).unwrap(); + let source = "[typeof Symbol(), typeof Symbol.iterator, it.name, it instanceof Symbol].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("symbol|symbol|art|false".into())); +} + +#[test] +fn a_host_class_replaces_an_existing_global_other_than_symbol() { + let mut r = realm(1_000_000); + let class = HostClass { name: "Math".into(), parent: None, members: vec![], info: Vec::new(), index: None, construct: None }; + r.define_host_classes(vec![class], vec![("it".into(), host_ref("Math", &[1.0]))]).unwrap(); + assert_eq!(r.run("it instanceof Math && it.constructor === Math").unwrap(), JsValue::Bool(true)); +} + #[test] fn host_receivers_obey_limits_lowered_after_the_object_was_created() { for limits in [DataLimits { depth: 64, bytes: 1_000, entries: 2 }, DataLimits { depth: 64, bytes: 1, entries: 100 }] { diff --git a/docs/mcp.md b/docs/mcp.md index 6e681e290e..d7004bd6c2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3118,7 +3118,8 @@ through `$`: points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points - read as the grid snaps them. + read as the grid snaps them. Assigning `closed` on an empty path records a setting instead of + writing `path.setAnchors`; the first points added by `setEntirePath` or `pathPoints.add()` use that setting. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, @@ -3202,14 +3203,16 @@ through `$`: `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/) + runs `symbol.place`. `swatches.getSelected()` throws that it is not available yet. A `Swatch` (https://ai-scripting.docsforadobe.dev/jsobjref/Swatch/) 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)` 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` + (`symbol.duplicate`) and `remove()` (`symbol.delete`); in a script engine that a `.js` or `.mjs` script starts, + the global `Symbol` stays the language's own (an engine that a `.jsx` script starts keeps the artwork `Symbol` for + the scripts that reuse it), and a script reaches artwork symbols through `symbols` and `SymbolItem.symbol`. 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`) From f3df0a647848e253869841df18907b3060688cff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:48:30 -0800 Subject: [PATCH 07/12] Scripts: resource objects go stale after undo and revert, and creation past the limit keeps nothing - A swatch, symbol, style or brush that app.undo(), app.redo() or any other command removes is noted after every command, not only after vc.run, and the note is kept until the object model next looks up an object. A later resource given the removed name no longer revives the old object. A call whose change is put back drops the removals it noted. - File > Revert leaves every resource object made before it stale, as it already does for page items and text styles. - swatches.add(), spots.add(), swatchGroups.add(), symbols.add() and Symbol.duplicate() take the object's slot in the same step as the command, so a run at its object limit throws with no new resource kept. - Reading a collection by index lists its names once while the document is unchanged, instead of once per read. - removeAll() is charged for every record it looks at and for each swatch of the color groups it deletes. - Swatch.color compares and converts an RGB color through the profiles the swatch's own document is assigned, not the front document's. - Brush.applyTo refuses a path in a compound shape, at any depth, as it refuses a path in a compound path: the shape's paint is drawn, not the path's. Docs: docs/mcp.md states when Brush.applyTo runs no command, the case where a process swatch keeps an RGB color, and when resource objects go stale. --- crates/engine/src/script/dom.rs | 36 ++-- crates/engine/src/script/dom/paths.rs | 2 +- crates/engine/src/script/dom/resources.rs | 185 +++++++++++++----- crates/engine/src/script/mod.rs | 12 ++ .../engine/src/tests/script_dom_resources.rs | 159 +++++++++++++++ docs/mcp.md | 18 +- 6 files changed, 350 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 92ed89ff49..a70db99169 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -116,9 +116,11 @@ pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; type GoneResources = (HashSet<(u64, ResourceKind, String)>, u64); /// What [`after_command`] compares with, taken before each command a script runs -/// ([`variables::before_command`]). +/// ([`variables::before_command`]). The resources earlier commands removed stay noted until the +/// run next looks up a resource object or [`forget_removed`] runs; only the count of the names +/// their steps compared starts again. pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { - *h.dom.resources_gone.borrow_mut() = Default::default(); + h.dom.resources_gone.borrow_mut().1 = 0; variables::before_command(h, id) } @@ -214,9 +216,10 @@ pub(super) struct State { /// change. editing: Cell>, locked: RefCell>, - /// The resources the steps of the last kept command removed or renamed, and how many names - /// the steps compared, which the next [`forget_removed`] marks stale and charges. Each command - /// clears it first ([`before_command`]). + /// The resources the steps of kept commands removed or renamed, which the next lookup of a + /// resource object or [`forget_removed`] marks stale, and how many names the last command's + /// steps compared, which [`forget_removed`] charges. Each command starts the count again + /// ([`before_command`]). resources_gone: RefCell, /// The swatches, symbols, styles and brushes the run's objects name ([`resources`]). resources: RefCell, @@ -255,6 +258,9 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result(h: &Host, f: impl FnOnce(&Host) -> std::result::Result std::result::Result<(), HostError> { resources::forget_removed(h) } @@ -939,15 +947,21 @@ fn on_doc_steps( Ok(v) } -/// Marks stale the style objects whose styles a command the run ran removed or renamed. +/// Marks stale the style objects whose styles a command the run ran removed or renamed, and notes +/// the swatches, symbols, styles and brushes it removed or renamed with the ones earlier commands +/// removed. pub(super) fn after_kept_command(h: &Host) { paths::forget_closed_empty(h); - let taken = { + let (taken, scanned) = { let mut s = h.session.borrow_mut(); let trail = &mut s.script_style_trail; (std::mem::take(&mut trail.resources_gone), std::mem::take(&mut trail.resources_scanned)) }; - *h.dom.resources_gone.borrow_mut() = taken; + { + let mut gone = h.dom.resources_gone.borrow_mut(); + gone.0.extend(taken); + gone.1 = gone.1.saturating_add(scanned); + } text::styles::after_command(h); } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 1f16d78358..f72baa3d77 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -394,7 +394,7 @@ fn keeping_paths(h: &super::Host, item: Item, f: impl FnOnce() -> std::result /// The object whose paint the path `n` with id `id` shows: the outermost compound shape it is /// inside, at any depth, or else its compound path when it is a member of one. The paint setters /// paint that owner ([`edit_paint`]). -fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { +pub(super) fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { let ancestors = d.ancestry(id).unwrap_or_default(); let above = ancestors.split_last().map_or(&[][..], |(_, rest)| rest); if let Some(shape) = above.iter().filter_map(|i| d.node(*i)).find(|p| p.is_compound_shape()) { diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index 467509840f..3c4bf08f33 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -20,9 +20,10 @@ //! //! 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). +//! the resource. Renaming it through the object model keeps the object; removing it, a rename or +//! deletion that `vc.run` or `app.undo()` makes, or File › Revert leaves the object stale, and +//! every member then throws `Stale Swatch` (`Stale Symbol`, and so on), also when a later +//! resource takes the name. //! - `swatches` lists the swatches in the Swatches panel's order: None, Registration, the other //! ungrouped swatches, then each color group's. `spots` lists Registration and the spot colors in //! the same order. `swatchGroups` lists the color groups only. @@ -39,7 +40,8 @@ //! 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 +//! document as CMYK, through the profiles that document is assigned; given back the RGB color it +//! already holds, the swatch stays as it is and no step is recorded. `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). @@ -52,7 +54,9 @@ //! - `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. +//! `Brush.applyTo` takes a path that is not a guide, a clipping path or a path in a compound path +//! or compound shape, and runs no command when the path already draws the brush with no brush +//! options and that brush is the current one. //! - A name is 1 to 1024 bytes, not blank, with no control characters. use std::collections::{HashMap, HashSet}; @@ -77,6 +81,15 @@ pub const MAX_NAME_BYTES: usize = 1024; /// The most resource objects one run may hold. pub const MAX_SLOTS: usize = 100_000; +/// The most resource objects one run may hold: [`MAX_SLOTS`], or a test's own limit. +fn max_slots() -> usize { + #[cfg(test)] + if let Some(n) = crate::script::TEST_MAX_SLOTS.with(std::cell::Cell::get) { + return n; + } + MAX_SLOTS +} + /// The kinds of resource object. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(in crate::script) enum Kind { @@ -138,16 +151,39 @@ pub(super) struct Table { index: HashMap>, /// Each document as [`forget_removed`] last checked it. checked: HashMap>, + /// The revert count of each document whose slots the table holds, as it was when they were + /// made: File › Revert leaves every object made before it stale. + reverts: HashMap, + /// The names a collection read by index last listed, so reading every member by index lists + /// them once ([`coll_at`]). + listed: Option, } +/// The names of a collection: the document's uid, the kind, the document they were listed from +/// and the names. +type Listed = (u64, Kind, Arc, Rc>); + 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, and its slots are not - /// visited. → how many slots and resource names it compared. + /// The document `uid` now has the revert count `reverts`: when it was reverted since its + /// slots were made, they all go stale. + fn see_reverts(&mut self, uid: u64, reverts: u64) { + if self.reverts.insert(uid, reverts).is_some_and(|r| r != reverts) { + if let Some(held) = self.index.remove(&uid) { + for i in held.into_values() { + self.slots[i].2 = None; + } + } + self.checked.remove(&uid); + } + } + + /// Marks every slot stale whose document is no longer open or was reverted since the slot + /// was made, or whose resource `docs` no 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); + let st = docs.iter().find(|d| d.uid == *uid && self.reverts.get(uid).is_none_or(|r| *r == d.reverts)); if let (Some(st), Some(seen)) = (st, self.checked.get(uid)) && Arc::ptr_eq(seen, &st.doc) { @@ -169,10 +205,11 @@ impl Table { None => self.checked.remove(uid), }; } - let checked = &mut self.checked; + let (checked, reverts) = (&mut self.checked, &mut self.reverts); self.index.retain(|uid, held| { if held.is_empty() { checked.remove(uid); + reverts.remove(uid); } !held.is_empty() }); @@ -184,8 +221,9 @@ impl Table { 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"))); + let max = max_slots(); + if self.slots.len() >= max { + return Err(HostError::Range(format!("a script may hold at most {max} swatches, symbols, styles and brushes"))); } self.slots.push((uid, kind, Some(name.to_string()))); self.index.entry(uid).or_default().insert((kind, name.to_string()), self.slots.len() - 1); @@ -267,7 +305,7 @@ pub(in crate::script) fn held(h: &Host) -> bool { !h.dom.resources.borrow().index.is_empty() } -/// After a `vc.run` command: the objects whose resource the command removed or renamed go stale, +/// After a `vc.run` command: the objects whose resource a command removed or renamed go stale, /// including a resource a step of a batch removed or renamed and a later step made again under /// its name. The slots and names the check compares are charged to the run. pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> { @@ -286,6 +324,30 @@ pub(super) fn forget_removed(h: &Host) -> std::result::Result<(), HostError> { Ok(()) } +/// The objects whose resource a kept command removed or renamed go stale: an `app.undo()` that +/// removes a swatch, for one, so that a later swatch given its name is not theirs. The object model +/// applies these before it looks up an object and before each change it makes as one step. +pub(super) fn settle_removed(h: &Host) { + let gone = std::mem::take(&mut h.dom.resources_gone.borrow_mut().0); + if gone.is_empty() { + return; + } + let mut table = h.dom.resources.borrow_mut(); + for (uid, kind, name) in &gone { + table.remove_kind(*uid, *kind, name); + } +} + +/// [`settle_removed`], and the objects of the document `uid` made before it was last reverted go +/// stale. +fn settle(h: &Host, uid: u64) { + settle_removed(h); + let reverts = h.session.borrow().documents().iter().find(|st| st.uid == uid).map(|st| st.reverts); + if let Some(reverts) = reverts { + h.dom.resources.borrow_mut().see_reverts(uid, reverts); + } +} + type Kfn = fn(&Host, Kind, &[Data]) -> Answer; fn kfunction(link: &Link, kind: Kind, f: Kfn) -> HostFunction { @@ -377,6 +439,7 @@ fn exists(d: &Document, kind: Kind, name: &str) -> bool { /// The object for the resource `name` of `kind` in the document `uid`. fn resource_ref(h: &Host, uid: u64, kind: Kind, name: &str) -> Answer { + settle(h, uid); 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)])) } @@ -392,6 +455,7 @@ fn resource_of(h: &Host, d: &Data, kind: Kind) -> std::result::Result Answer { on_doc(h, doc.uid, true, |h| command(h, id, params)) } +/// Runs `id` with `params` on the document `doc`, its selection kept, and gives the object for the +/// resource of `kind` the command made, named by the `name` of its result. The command and the +/// object succeed or fail together: when the run holds as many objects as it may, the new resource +/// is not kept. +fn create(h: &Host, doc: Doc, kind: Kind, id: &str, params: &Value) -> Answer { + on_doc(h, doc.uid, true, |h| { + let r = command(h, id, params)?; + let name = result_name(&r, "name")?; + resource_ref(h, doc.uid, kind, &name) + }) +} + /// The string `key` of a command's result. fn result_name(r: &Data, key: &str) -> std::result::Result { match r { @@ -455,8 +531,30 @@ fn coll_parent(h: &Host, kind: Kind, a: &[Data]) -> Answer { Ok(doc_ref(h, doc.uid)) } +/// The names of the collection `this`, listed again only when its document changed since the last +/// index read listed them, so that reading every member by index lists the collection once. A new +/// listing is charged to the run as [`coll_names`] charges it. +fn coll_listed(h: &Host, a: &[Data], kind: Kind) -> std::result::Result<(Doc, Rc>), HostError> { + let doc = coll_doc(h, a, kind)?; + let kept = with_doc(h, doc, |_, st| { + let t = h.dom.resources.borrow(); + t.listed.as_ref().filter(|(uid, k, d, _)| *uid == doc.uid && *k == kind && Arc::ptr_eq(d, &st.doc)).map(|l| l.3.clone()) + }); + if let Some(list) = kept { + return Ok((doc, list)); + } + let (list, work, now) = with_doc(h, doc, |_, st| { + let list = names(&st.doc, kind); + let work = scanned(Some(&st.doc), kind, list.len()); + (Rc::new(list), work, st.doc.clone()) + }); + h.charge_call(work)?; + h.dom.resources.borrow_mut().listed = Some((doc.uid, kind, now, list.clone())); + Ok((doc, list)) +} + fn coll_at(h: &Host, kind: Kind, a: &[Data]) -> Answer { - let (doc, list) = coll_names(h, a, kind)?; + let (doc, list) = coll_listed(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) { @@ -500,15 +598,23 @@ fn removable(d: &Document, kind: Kind) -> Vec { /// `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, members, visited) = 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) + // Picking out the names looks at every swatch for the swatches and spots, and at every + // style for the graphic styles. + let visited = match kind { + Kind::Swatch | Kind::Spot => swatches_in_order(&st.doc).count(), + Kind::Style => st.doc.graphic_styles.len(), + _ => list.len(), + }; + (list, members, visited) }); - h.charge_call(16 * list.len() as u64)?; + // The records looked at, and each resource the command deletes, a group's swatches included. + h.charge_call(visited as u64 + 16 * (list.len() + members.len()) as u64)?; if list.is_empty() { return Ok(Data::Undefined); } @@ -544,9 +650,7 @@ 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) + create(h, doc, Kind::Swatch, "swatch.new", ¶ms) } /// Black in the color space of `doc`. @@ -575,17 +679,13 @@ fn spots_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { 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) + create(h, doc, Kind::Spot, "swatch.new", ¶ms) } /// `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) + create(h, doc, Kind::Group, "swatch.newGroup", &json!({})) } /// The registration point index of a `SymbolRegistrationPoint` value, 4 (the center) when left out. @@ -627,9 +727,7 @@ fn symbols_add(h: &Host, kind: Kind, a: &[Data]) -> Answer { } 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) + create(h, doc, Kind::Symbol, "symbol.new", &json!({"ids": [item.id.0], "keepArt": true, "registration": reg})) } // ---- Swatch and Spot ---- @@ -808,16 +906,16 @@ fn set_swatch_color(h: &Host, kind: Kind, a: &[Data]) -> Answer { } /// `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. +/// CMYK document becomes CMYK through the color settings with the profiles `doc` is assigned, +/// whichever document is in front. 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) + with_doc(h, doc, |_, st| match color { + Color::Rgb { .. } if st.doc.color_mode != crate::doc::ColorMode::Rgb => { + let cms = crate::cmd::colormgmt::doc_cms(&st.doc); + cms.convert(&color, st.doc.color_mode.model(), cms.settings().intent) } _ => color, - } + }) } /// The `ColorModel` of the Spot `name`: Registration's own, or `SPOT`. @@ -934,9 +1032,7 @@ fn group_remove_all(h: &Host, kind: Kind, a: &[Data]) -> Answer { 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) + create(h, r.doc, Kind::Symbol, "symbol.duplicate", &json!({"name": r.name})) } /// The ids of a document's symbol instances, in the order of its page items, and how many page @@ -1100,16 +1196,17 @@ fn style_merge_to(h: &Host, kind: Kind, a: &[Data]) -> Answer { } /// `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. +/// with no brush options and the brush is the current one. A guide, a clipping path, and a path +/// that shows the paint of the compound path or compound shape it is in, at any depth, draw no +/// brush, 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 own_paint = n.is_some_and(|n| super::paths::paint_owner(&st.doc, item.id, n).id == item.id); + let brushable = n.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. })) && own_paint; 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()); @@ -1119,7 +1216,7 @@ fn brush_apply_to(h: &Host, kind: Kind, a: &[Data]) -> Answer { 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())); + return Err(HostError::Error("a brush does not apply to a guide, a clipping path or a path in a compound path or compound shape".into())); } if !same { run_on(h, r.doc, "brush.apply", &json!({"name": r.name, "ids": [item.id.0]}))?; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 73521ad6b3..5fc1a2ab1d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1349,6 +1349,8 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value match r { Ok(v) => { note_ids(s); + // A command that is not a batch, such as `edit.undo`, notes the resources it removed too. + note_resources(s); let (mut objects, mut bytes) = (0, 0); for st in &s.docs { match before.iter().find(|(uid, ..)| *uid == st.uid) { @@ -1541,6 +1543,14 @@ pub(crate) fn note_style_lists(s: &mut Session) { } *last = (st.uid, st.reverts, c.clone(), p.clone()); } + note_resources(s); +} + +/// After a step of a batch a script runs, and after each command it runs: notes the swatches, +/// symbols, styles and brushes the documents no longer have, when the run holds objects for them +/// ([`dom::after_kept_command`]). A document the trail already compared is not compared again. +fn note_resources(s: &mut Session) { + let trail = &mut s.script_style_trail; if !trail.watch_resources { return; } @@ -3013,6 +3023,8 @@ thread_local! { pub(crate) static TEST_GROWTH_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; + /// Tests: the swatch, symbol, style and brush objects a run may hold, in place of 100,000. + pub(crate) static TEST_MAX_SLOTS: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs index 82387ce2b8..256f9e2677 100644 --- a/crates/engine/src/tests/script_dom_resources.rs +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -653,3 +653,162 @@ fn several_resource_edits_are_one_undo_step_and_a_failure_puts_them_back() { assert!(e.contains("stop"), "{e}"); assert_eq!(resources(&s), before); } + +#[test] +fn a_swatch_that_undo_removed_stays_stale_when_a_new_swatch_takes_its_name() { + for make in ["vc.run('swatch.new', {name: n, color: '#ff0000'}); vc.log(true);", "vc.log(d.swatches.add().name == n);"] { + let (mut s, _) = doc(); + let out = log( + &mut s, + &format!( + "var d = app.activeDocument, k = d.swatches.length, w = d.swatches.add(), n = w.name; app.undo();\ + vc.log(d.swatches.length == k); {make}\ + try {{ vc.log(w.name); }} catch (e) {{ vc.log(e.message); }}" + ), + ); + assert_eq!(out[..2], [json!(true), json!(true)], "{make}: undo removes the swatch, and the new one takes its name"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{make}: {out:?}"); + } +} + +#[test] +fn swatch_objects_made_before_a_revert_are_stale() { + let (mut s, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-resources-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, w = d.swatches.getByName('Black');\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + try { vc.log(w.name); } catch (e) { vc.log(e.message); }\ + var again = app.activeDocument.swatches.getByName('Black'); vc.log(again.name); vc.log(again === w);", + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale Swatch")), "{out:?}"); + assert_eq!(out[1..], [json!("Black"), json!(false)], "a swatch object made after the revert names the reverted swatch"); +} + +#[test] +fn brushes_refuse_paths_in_a_compound_shape_at_any_depth() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap(); + let (m1, m2, m3) = (rect(&mut s, 10.0, 20.0, 30.0, 40.0), rect(&mut s, 30.0, 30.0, 30.0, 40.0), rect(&mut s, 50.0, 40.0, 30.0, 40.0)); + s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g, m3.0]})).unwrap(); + s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = resources(&s); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, n = d.pathItems.length, e = [];\ + for (var i = 0; i < n; i++) { try { d.brushes[0].applyTo(d.pathItems[i]); e.push('applied'); }\ + catch (x) { e.push(x.message.indexOf('compound shape') >= 0); } }\ + vc.log(n); vc.log(e);", + ); + assert_eq!(out, vec![json!(3), json!([true, true, true])], "the grouped members and the direct member are refused"); + assert_eq!((resources(&s), undo_steps(&s)), (before, steps)); +} + +#[test] +fn reading_every_swatch_by_index_lists_the_swatches_once() { + let (mut s, _) = doc(); + for i in 0..1000 { + s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap(); + } + let source = + "var w = app.activeDocument.swatches, n = w.length, read = 0; for (var i = 0; i < n; i++) if (w[i]) read++; vc.log(read == n && n > 1000);"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let r = r.unwrap_or_else(|e| panic!("reading 1000 swatches by index: {e}")); + assert_eq!(r["log"], json!([true])); + let source = "var w = app.activeDocument.swatches, n = w.length; for (var i = 0; i < n; i++) { w[i]; app.activeDocument.swatches.add(); }"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(200_000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("reading after each change listed the swatches once: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "a read after a change lists the swatches again and is charged: {e}"); +} + +#[test] +fn remove_all_is_charged_for_the_records_it_looks_at() { + let (mut s, _) = doc(); + for i in 0..1000 { + s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap(); + } + let source = "var d = app.activeDocument; for (var i = 0; i < 100; i++) d.spots.removeAll();"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("100 removeAll() calls over 1000 process swatches ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); + let colors: Vec = (0..500).map(|i| format!("#{:06x}", i * 31)).collect(); + s.execute("swatch.newGroup", &json!({"name": "Many", "colors": colors})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(3000))); + let r = run(&mut s, "app.activeDocument.swatchGroups.removeAll();"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("removing a group of 500 swatches ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "the group's swatches are charged: {e}"); +} + +#[test] +fn a_new_resource_past_the_object_limit_is_not_kept() { + let (mut s, a) = doc(); + let before = resources(&s); + let steps = undo_steps(&s); + crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1))); + let out = run( + &mut s, + "var d = app.activeDocument, p = d.pathItems[0], k = d.swatches[0], out = [];\ + var calls = [function () { d.swatches.add(); }, function () { d.spots.add(); }, function () { d.swatchGroups.add(); },\ + function () { d.symbols.add(p); }];\ + for (var i = 0; i < calls.length; i++) { try { calls[i](); out.push('made'); } catch (e) { out.push(e.message.indexOf('at most 1 ') >= 0); } }\ + vc.log(out);", + ); + crate::script::TEST_MAX_SLOTS.with(|m| m.set(None)); + assert_eq!(out.unwrap()["log"], json!([[true, true, true, true]])); + assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "no new resource is kept"); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + crate::script::TEST_MAX_SLOTS.with(|m| m.set(Some(1))); + let out = run( + &mut s, + "var d = app.activeDocument, m = d.symbols.getByName('Mark');\ + try { m.duplicate(); vc.log('made'); } catch (e) { vc.log(e.message.indexOf('at most 1 ') >= 0); } vc.log(d.symbols.length);", + ); + crate::script::TEST_MAX_SLOTS.with(|m| m.set(None)); + assert_eq!(out.unwrap()["log"], json!([true, 1]), "the duplicate is not kept"); +} + +#[test] +fn a_swatch_color_converts_through_the_profiles_of_its_own_document() { + use vectorcraft_color::{Color, cms}; + let _g = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + s.execute("edit.assignProfile", &json!({"cmyk": cms::FOGRA51_CMYK})).unwrap(); + let rgb = Color::rgb(51.0 / 255.0, 128.0 / 255.0, 204.0 / 255.0); + let own = { + let c = crate::cmd::colormgmt::doc_cms(&s.active().unwrap().doc); + c.convert(&rgb, cms::Model::Cmyk, c.settings().intent) + }; + let working = { + let c = cms::working(); + c.convert(&rgb, cms::Model::Cmyk, c.settings().intent) + }; + assert_ne!(own, working, "the assigned profile converts the color differently"); + s.execute("swatch.new", &json!({"name": "Sky", "color": serde_json::to_value(working).unwrap()})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + log( + &mut s, + "var w = null; for (var i = 0; i < app.documents.length; i++) { try { w = app.documents[i].swatches.getByName('Sky'); } catch (e) {} }\ + var c = new RGBColor(); c.red = 51; c.green = 128; c.blue = 204; w.color = c;", + ); + let sky = s.documents().iter().find_map(|st| st.doc.swatch("Sky").map(|w| w.paint.clone())); + let Some(vectorcraft_color::Paint::Solid { color, .. }) = sky else { panic!("Sky is a solid color: {sky:?}") }; + assert_ne!(color, working, "the swatch takes the color its own document's profile gives"); + assert_eq!(color, own); +} diff --git a/docs/mcp.md b/docs/mcp.md index e596a74430..bb8b7a9b8a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3240,16 +3240,22 @@ through `$`: `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 + `Swatch.color` stores a new `RGBColor` in a CMYK document as CMYK, through the profiles that document is assigned. A + process swatch that holds an RGB color in a CMYK document (one made with `keepModel: true`) and is given that same + color back stays RGB, and no undo step is recorded. 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 - 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 + and `Brush.applyTo` a path that is not a guide, a clipping path or a path in a compound path or compound shape, at + any depth. `Brush.applyTo` runs no command only when the path already draws that brush with no brush options and + that brush is the current one; with another brush current, it runs `brush.apply`, which also makes the brush current. + 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, renamed or deleted with `vc.run`, removed by `app.undo()` or `app.redo()`, or its + document is reverted, every member throws `Stale Swatch` (`Stale Spot`, `Stale SwatchGroup`, `Stale Symbol`, + `Stale GraphicStyle`, `Stale Brush`), also when a later resource takes its name. A run holds at most 100,000 of + these objects, and a call that would make one more throws with nothing changed. An object of another document throws `Cross-document placement is not available`. `Document.gradients`, `Document.patterns` and assigning a `SpotColor` to a swatch's or spot's `color` are not available yet. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type From 25d7b3d3ab2a6da404c4b57b112fc0edd44bd2f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:35:34 -0800 Subject: [PATCH 08/12] Scripts: charge resource scans after every command, and read a placed instance's id exactly - The resource names a command's steps compare are charged when the command ends, whether vc.run or the object model ran it, so repeated Swatch.color edits over many swatches use up the run's data budget. - symbolItems.add() reads the new instance's id from the command's result as an integer, so an id above 2^53 names the placed instance. --- crates/engine/src/script/dom.rs | 21 +++++++++----- crates/engine/src/script/dom/resources.rs | 15 ++++------ crates/engine/src/script/mod.rs | 6 +++- .../engine/src/tests/script_dom_resources.rs | 28 +++++++++++++++++++ 4 files changed, 53 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a70db99169..1fa2354ec8 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -117,13 +117,21 @@ type GoneResources = (HashSet<(u64, ResourceKind, String)>, u64); /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). The resources earlier commands removed stay noted until the -/// run next looks up a resource object or [`forget_removed`] runs; only the count of the names -/// their steps compared starts again. +/// run next looks up a resource object or [`forget_removed`] runs. pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { - h.dom.resources_gone.borrow_mut().1 = 0; variables::before_command(h, id) } +/// Charges the run for the resource names the last command's steps compared, whether it was kept +/// or not, and whether `vc.run` or the object model ran it. +pub(super) fn charge_scanned(h: &Host) -> std::result::Result<(), HostError> { + let scanned = std::mem::take(&mut h.dom.resources_gone.borrow_mut().1); + if scanned > 0 { + h.charge_call(scanned)?; + } + Ok(()) +} + /// After each command a script runs ([`variables::after_command`]). pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { variables::after_command(h, before); @@ -218,8 +226,7 @@ pub(super) struct State { locked: RefCell>, /// The resources the steps of kept commands removed or renamed, which the next lookup of a /// resource object or [`forget_removed`] marks stale, and how many names the last command's - /// steps compared, which [`forget_removed`] charges. Each command starts the count again - /// ([`before_command`]). + /// steps compared, which [`charge_scanned`] charges when the command ends. resources_gone: RefCell, /// The swatches, symbols, styles and brushes the run's objects name ([`resources`]). resources: RefCell, @@ -965,8 +972,8 @@ pub(super) fn after_kept_command(h: &Host) { text::styles::after_command(h); } -/// After a command that is not kept: the resource names its steps compared are charged with the -/// next [`forget_removed`], and the resources they removed are not marked stale. +/// After a command that is not kept: the resource names its steps compared are charged +/// ([`charge_scanned`]), and the resources they removed are not marked stale. pub(super) fn keep_scanned(h: &Host) { let scanned = std::mem::take(&mut h.session.borrow_mut().script_style_trail.resources_scanned); let mut gone = h.dom.resources_gone.borrow_mut(); diff --git a/crates/engine/src/script/dom/resources.rs b/crates/engine/src/script/dom/resources.rs index 3c4bf08f33..1c25652e78 100644 --- a/crates/engine/src/script/dom/resources.rs +++ b/crates/engine/src/script/dom/resources.rs @@ -70,9 +70,9 @@ use vectorcraft_doc::Shared; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref}; use super::{ - Answer, CROSS_DOCUMENT, Described, 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, returns, text, this_doc, typed, typename_of, whole, - with_doc, + Answer, CROSS_DOCUMENT, Described, Doc, Host, Item, Link, NOT_FOUND, arg, class, colors, command, command_value, 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, returns, text, this_doc, typed, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -1095,12 +1095,9 @@ fn sitems_add(h: &Host, _: Kind, a: &[Data]) -> Answer { 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()))?; + // The id is read from the command's own result, which holds every id exactly. + let (_, out) = on_doc(h, doc.uid, true, |h| command_value(h, "symbol.place", &json!({"name": sym.name})))?; + let id = out["id"].as_u64().ok_or_else(|| HostError::Error("the instance was not made".into()))?; Ok(with_doc(h, doc, |_, st| item_ref(h, st, NodeId(id)))) } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 5fc1a2ab1d..1a99399356 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1418,9 +1418,11 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, id, params) }; - // The resource names a failed command's steps compared are still charged ([`dom::forget_removed`]). + // The resource names a failed command's steps compared are still charged, before its error is + // given. if r.is_err() { dom::keep_scanned(host); + dom::charge_scanned(host)?; } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { @@ -1465,6 +1467,8 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( dom::keep_scanned(host); session.borrow_mut().script_style_trail = StyleTrail::default(); } + // The resource names the command's steps compared are charged whoever ran it. + dom::charge_scanned(host)?; crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs index 256f9e2677..2bbecf9852 100644 --- a/crates/engine/src/tests/script_dom_resources.rs +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -783,6 +783,34 @@ fn a_new_resource_past_the_object_limit_is_not_kept() { assert_eq!(out.unwrap()["log"], json!([true, 1]), "the duplicate is not kept"); } +#[test] +fn a_placed_symbol_instance_with_a_large_id_keeps_its_id() { + let (mut s, a) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "keepArt": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, "var d = app.activeDocument, i = d.symbolItems.add(d.symbols.getByName('Mark')); i.name = 'big'; vc.log(i.name);"); + assert_eq!(out, vec![json!("big")]); + assert_eq!(s.active().unwrap().doc.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big")); +} + +#[test] +fn editing_swatch_colors_is_charged_for_the_swatches_each_change_compares() { + let (mut s, _) = doc(); + for i in 0..1000 { + s.execute("swatch.new", &json!({"name": format!("P{i}"), "color": "#336699"})).unwrap(); + } + let source = "var w = app.activeDocument.swatches.getByName('P0'), a = new RGBColor(), b = new RGBColor(); b.red = 200;\ + for (var i = 0; i < 30; i++) w.color = i % 2 ? a : b;"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(20_000))); + let r = run(&mut s, source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("30 swatch color edits over 1000 swatches ran: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); +} + #[test] fn a_swatch_color_converts_through_the_profiles_of_its_own_document() { use vectorcraft_color::{Color, cms}; From 87985915720b8d150136912a5fc06499b75c31bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 12:22:18 -0800 Subject: [PATCH 09/12] Scripts: closing an empty path refuses one on a locked artboard PathItem.closed on an empty path checked only that the path was editable, so an empty path in a group on a locked artboard accepted closed = true. The setter now uses the same check as other path edits; an assignment of the value the path has still does nothing. Also splits the M14 roadmap row that a merge joined with the next row. --- crates/engine/src/script/dom/paths.rs | 4 +--- crates/engine/src/tests/script_dom_paths.rs | 17 +++++++++++++++++ docs/mcp.md | 2 ++ docs/roadmap.md | 3 ++- 4 files changed, 22 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a0302aba15..d1cc9d9be0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -783,9 +783,7 @@ fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { subs.is_empty() })?; if empty && is_closed(h, item)? != closed { - if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { - return Err(cannot_edit(item.id)); - } + with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; let key = closed_key(h, item); let mut held = h.dom.closed_empty.borrow_mut(); if closed { diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index c5b4fc94b0..2bf4419c9d 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1777,6 +1777,23 @@ fn path_changes_refuse_paths_on_a_locked_artboard() { assert_ne!(art(&s), before); } +/// An empty path in a group on a locked artboard refuses `closed = true`, and keeps allowing an +/// assignment of the value it has. +#[test] +fn closing_an_empty_path_refuses_one_on_a_locked_artboard() { + let (mut s, a, _) = doc(); + let empty = NodeId(s.execute("path.create", &json!({"d": ""})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.group", &json!({"ids": [a.0, empty.0]})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let pick = "var d = app.activeDocument, p; for (var i = 0; i < d.pathItems.length; i++) { if (d.pathItems[i].pathPoints.length == 0) p = d.pathItems[i]; }"; + log(&mut s, &format!("{pick} p.closed = false;")); + let e = failure(&mut s, &format!("{pick} p.closed = true;")); + assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", empty.0)), "{e}"); + assert_eq!(log(&mut s, &format!("{pick} vc.log(p.closed);")), vec![json!(false)]); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + assert_eq!(log(&mut s, &format!("{pick} p.closed = true; vc.log(p.closed);")), vec![json!(true)]); +} + fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } diff --git a/docs/mcp.md b/docs/mcp.md index 7a9205e782..d5f67eb979 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3234,6 +3234,8 @@ through `$`: a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. Assigning `closed` on an empty path records a setting instead of writing `path.setAnchors`; the first points added by `setEntirePath` or `pathPoints.add()` use that setting. + An assignment that changes the setting on an empty path that is hidden or locked, in a hidden or locked layer or group, or on a locked + artboard throws `Cannot edit`; an assignment of the value it already has does not. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, diff --git a/docs/roadmap.md b/docs/roadmap.md index 3f452d6364..c27206f2b8 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -210,7 +210,8 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 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, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms, each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections, and scripts save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, text lines, the selected path points, gradient stops, gradients, patterns and the other classes) and batch work remain | 18–27 | -| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; 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); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 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), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), 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 | +| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; 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); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 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), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), 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 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | | M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages remain partial and pinned fonts lack a Gujarati face | Included above | From 52ae980326cfcdd2824cea8224681448befb155c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:40:58 -0800 Subject: [PATCH 10/12] Scripts: a command no longer copies the empty-path closed settings Each command a script ran copied the set of empty paths the script had closed into the command's style trail, so a script that closed N empty paths copied up to N entries per command. The trail now shares the set through an `Arc`, and drops its share when the command's steps end, so a later change to the set does not copy it either. Settings that end after a kept command are dropped only when one actually ends. --- crates/engine/src/script/dom.rs | 5 +++-- crates/engine/src/script/dom/paths.rs | 15 ++++++++++++--- crates/engine/src/script/mod.rs | 13 +++++++++---- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8db00ef254..c825945e80 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -205,8 +205,9 @@ pub(super) struct State { /// ([`flush`]). pending: RefCell)>>, /// The paths with no points, by document uid, revert count and id, that a script set `closed` - /// on: the points `setEntirePath` gives them later make a closed path. - pub(super) closed_empty: RefCell>, + /// on: the points `setEntirePath` gives them later make a closed path. A command's steps share + /// the set without copying it ([`super::StyleTrail`]). + pub(super) closed_empty: RefCell>>, /// The index of the first point of each subpath of the path whose points the run read last, /// and what they were counted from ([`paths`]). point_starts: RefCell>)>>, diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index d1cc9d9be0..882bc4ff11 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -256,7 +256,10 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) let gained = |gained: bool| { if gained { let key = closed_key(h, item); - h.dom.closed_empty.borrow_mut().remove(&key); + let mut held = h.dom.closed_empty.borrow_mut(); + if held.contains(&key) { + Arc::make_mut(&mut held).remove(&key); + } } }; let mut f = Some(f); @@ -305,7 +308,7 @@ fn closed_key(h: &super::Host, item: Item) -> (u64, u64, NodeId) { /// Drops empty-path closed settings after a kept command gives a path points or removes it. pub(super) fn forget_closed_empty(h: &super::Host) { let s = h.session.borrow(); - h.dom.closed_empty.borrow_mut().retain(|(uid, reverts, id)| { + let keep = |(uid, reverts, id): &(u64, u64, NodeId)| { !s.script_style_trail.paths_with_points.contains(&(*uid, *reverts, *id)) && s.documents() .iter() @@ -313,7 +316,12 @@ pub(super) fn forget_closed_empty(h: &super::Host) { .and_then(|st| st.doc.node(*id)) .and_then(|n| n.path_data()) .is_some_and(|pd| pd.subpaths.is_empty()) - }); + }; + let mut held = h.dom.closed_empty.borrow_mut(); + // The set is copied only when another holder shares it and a setting ends. + if !held.iter().all(keep) { + Arc::make_mut(&mut held).retain(keep); + } } /// Drops the [`starts`] that [`super::State`] keeps of waiting point changes, which a change can @@ -786,6 +794,7 @@ fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; let key = closed_key(h, item); let mut held = h.dom.closed_empty.borrow_mut(); + let held = Arc::make_mut(&mut held); if closed { held.insert(key); } else { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 05d0cf1e9c..6b5c14b2f9 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1432,7 +1432,11 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: let before = dom::before_command(host, id); let r = { let mut s = session.borrow_mut(); - step(&mut s, host, id, params) + let r = step(&mut s, host, id, params); + // The steps are done with the empty-path closed settings, so the object model can change + // them again without copying them. + s.script_style_trail.closed_empty = Arc::default(); + r }; // The resource names a failed command's steps compared are still charged, before its error is // given. @@ -1511,14 +1515,15 @@ pub(crate) struct StyleTrail { pub(in crate::script) resources_gone: std::collections::HashSet<(u64, dom::ResourceKind, String)>, /// The resource names the steps compared, charged to the run with the check that follows. pub(crate) resources_scanned: u64, - closed_empty: std::collections::HashSet<(u64, u64, NodeId)>, + /// The object model's empty-path closed settings, shared with it while the steps run. + closed_empty: Arc>, pub(in crate::script) paths_with_points: std::collections::HashSet<(u64, u64, NodeId)>, } impl StyleTrail { /// A trail that starts from the documents' style lists now, and from the documents themselves /// when `watch_resources`. - fn start(s: &Session, watch_resources: bool, closed_empty: std::collections::HashSet<(u64, u64, NodeId)>) -> Self { + fn start(s: &Session, watch_resources: bool, closed_empty: Arc>) -> Self { let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); let docs = if watch_resources { s.docs.iter().map(|st| (st.uid, st.doc.clone())).collect() } else { Vec::new() }; StyleTrail { lists, docs, watch_resources, closed_empty, ..Default::default() } @@ -1531,7 +1536,7 @@ impl StyleTrail { /// document's lists, however many steps change them. pub(crate) fn note_style_lists(s: &mut Session) { let trail = &mut s.script_style_trail; - for &(uid, reverts, id) in &trail.closed_empty { + for &(uid, reverts, id) in trail.closed_empty.iter() { if s.docs .iter() .find(|st| st.uid == uid && st.reverts == reverts) From 1c64f808ba352a4564b16b9e9c46c5a801c68a41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:26:35 -0800 Subject: [PATCH 11/12] Scripts: list the paths again after an edit inside a Shaper group An edit to a Shaper source regenerates the group's paths. When the regeneration drops a generated path and makes none, the document's next id does not change, so the kept list of pathItems still held the removed path. Edits to a path inside a Shaper group no longer keep the list. --- crates/engine/src/script/dom/paths.rs | 11 +++++++-- crates/engine/src/tests/script_dom_paths.rs | 27 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 27c44bb202..9afb3e3fda 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -391,7 +391,9 @@ thread_local! { /// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds, /// removes and reorders no object of its own. When it succeeds, the document made no new object, -/// and every kept path still exists, the list of the document's paths ([`path_items`]) stays kept. +/// and the path is not inside a Shaper group, the list of the document's paths ([`path_items`]) +/// stays kept. An edit inside a Shaper group regenerates the group's paths, which can drop a +/// path without making a new id. fn keeping_paths(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result) -> std::result::Result { let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| { let s = h.session.borrow(); @@ -400,7 +402,12 @@ fn keeping_paths(h: &super::Host, item: Item, f: impl FnOnce() -> std::result } }; let mut kept = None; - doc_state(h, &mut |st| kept = super::kept_list(&h.dom.paths, st).map(|ids| (ids, st.doc.peek_next_id()))); + doc_state(h, &mut |st| { + let in_shaper = st.doc.ancestry(item.id).unwrap_or_default().iter().filter_map(|i| st.doc.node(*i)).any(|a| a.extras().shaper.is_some()); + if !in_shaper { + kept = super::kept_list(&h.dom.paths, st).map(|ids| (ids, st.doc.peek_next_id())); + } + }); let r = f()?; if let Some((ids, next)) = kept { doc_state(h, &mut |st| { diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 9731fc1b86..c9ddfd929d 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -817,6 +817,33 @@ fn an_edit_that_regenerates_shaper_art_lists_the_paths_again() { assert_eq!(out, fresh, "the list after the edit matches a fresh run's"); } +#[test] +fn an_edit_that_drops_a_shaper_path_lists_the_paths_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true, "ids": []})).unwrap(); + for x in [0.0, 50.0] { + rect(&mut s, x, 50.0, 100.0, 100.0); + } + s.execute("shaper.scribble", &json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let sources = vectorcraft_doc::shaper::SOURCES; + let before = log(&mut s, "vc.log(app.activeDocument.pathItems.length);"); + // The paths are listed again after the first edit. The second edit takes the generated fill + // away, and a regeneration that makes no path makes no new id. + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, n = ps.length, src = [];\ + for (var i = 0; i < n; i++) if (ps[i].parent.name == '{sources}') src.push(ps[i]);\ + for (var i = 0; i < src.length; i++) {{ src[i].fillColor = new NoColor(); var m = ps.length; }} vc.log(ps.length);" + ), + ); + let fresh = log(&mut s, "vc.log(app.activeDocument.pathItems.length);"); + assert_ne!(before, fresh, "the edit changes how many paths the document has"); + assert_eq!(out, fresh, "the list after the edit matches a fresh run's"); +} + #[test] fn a_closed_setting_on_an_empty_path_ends_once_a_command_gives_it_points() { let mut s = Session::new(); From a4b2e4fe366d0c45f97ed9e5390f02fe21a52657 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 16:52:48 -0800 Subject: [PATCH 12/12] Scripts: remove the unused empty-path closed set Setting `closed` on a path with no points gives it an empty closed subpath, so the path's own data keeps the setting. The separate set of empty paths, its key, its cleanup after commands and its copy in the command trail were no longer written to by anything. `closed` and `setEntirePath` now read the closed state from the subpaths only. --- crates/engine/src/script/dom.rs | 5 --- crates/engine/src/script/dom/paths.rs | 60 +++------------------------ crates/engine/src/script/mod.rs | 27 ++---------- 3 files changed, 9 insertions(+), 83 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 66724c0fcc..22e619a910 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -240,10 +240,6 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, - /// The paths with no points, by document uid, revert count and id, that a script set `closed` - /// on: the points `setEntirePath` gives them later make a closed path. A command's steps share - /// the set without copying it ([`super::StyleTrail`]). - pub(super) closed_empty: RefCell>>, /// The index of the first point of each subpath of the path whose points the run read last, /// and what they were counted from ([`paths`]). point_starts: RefCell>)>>, @@ -1101,7 +1097,6 @@ fn ends_run(e: &HostError) -> bool { /// the swatches, symbols, styles and brushes it removed or renamed with the ones earlier commands /// removed. pub(super) fn after_kept_command(h: &Host) { - paths::forget_closed_empty(h); let (taken, scanned) = { let mut s = h.session.borrow_mut(); let trail = &mut s.script_style_trail; diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 441611fd03..5bb5e31801 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -299,37 +299,14 @@ fn edit_points_keeping( if !counts_kept { forget_waiting_starts(h); } - // A path that has or gains points keeps its own closed state from then on ([`is_closed`]). - let gained = |gained: bool| { - if gained { - let key = closed_key(h, item); - let mut held = h.dom.closed_empty.borrow_mut(); - if held.contains(&key) { - Arc::make_mut(&mut held).remove(&key); - } - } - }; - let mut f = Some(f); - let accepted = if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() + if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) - && let Some(f) = f.take() { - let had = !subs.is_empty(); - let r = f(subs); - Some((r, had || !subs.is_empty())) - } else { - None - }; - if let Some((r, has_points)) = accepted { - gained(has_points); - return Ok(r); + return Ok(f(subs)); } - let Some(f) = f else { return Err(HostError::Error(STALE_ITEM.into())) }; flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; - let had = !subs.is_empty(); let r = f(&mut subs); - let has_points = had || !subs.is_empty(); let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); @@ -345,35 +322,9 @@ fn edit_points_keeping( flush(h)?; } } - gained(has_points); Ok(r) } -/// The key of the path of `item` among the empty paths a script set `closed` on: its document's -/// uid and revert count, so a revert drops the setting, and its id. -fn closed_key(h: &super::Host, item: Item) -> (u64, u64, NodeId) { - (item.doc.uid, with_doc(h, item.doc, |_, st| st.reverts), item.id) -} - -/// Drops empty-path closed settings after a kept command gives a path points or removes it. -pub(super) fn forget_closed_empty(h: &super::Host) { - let s = h.session.borrow(); - let keep = |(uid, reverts, id): &(u64, u64, NodeId)| { - !s.script_style_trail.paths_with_points.contains(&(*uid, *reverts, *id)) - && s.documents() - .iter() - .find(|st| st.uid == *uid && st.reverts == *reverts) - .and_then(|st| st.doc.node(*id)) - .and_then(|n| n.path_data()) - .is_some_and(|pd| pd.subpaths.is_empty()) - }; - let mut held = h.dom.closed_empty.borrow_mut(); - // The set is copied only when another holder shares it and a setting ends. - if !held.iter().all(keep) { - Arc::make_mut(&mut held).retain(keep); - } -} - /// Drops the [`starts`] that [`super::State`] keeps of waiting point changes, which a change can /// make wrong. fn forget_waiting_starts(h: &super::Host) { @@ -1116,11 +1067,10 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathPoints", &handle)) } -/// Whether the path of `item` is closed: every subpath is, or, for a path with no points, a script -/// set `closed` on it. +/// Whether the path of `item` is closed: it has a subpath and every subpath is. Setting `closed` on +/// a path with no subpath gives it an empty closed one ([`path_set_closed`]). fn is_closed(h: &super::Host, item: Item) -> std::result::Result { - let (empty, closed) = read_points(h, item, |subs| (subs.is_empty(), subs.iter().all(|sp| sp.closed)))?; - Ok(if empty { h.dom.closed_empty.borrow().contains(&closed_key(h, item)) } else { closed }) + read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed)) } fn path_closed(h: &super::Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index acf316a5a5..ce47075a39 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1406,7 +1406,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); - s.script_style_trail = StyleTrail::start(s, dom::holds_resources(host), host.dom.closed_empty.borrow().clone()); + s.script_style_trail = StyleTrail::start(s, dom::holds_resources(host)); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A // query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard. @@ -1517,12 +1517,7 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: let before = dom::before_command(host, id); let (copies, r) = { let mut s = session.borrow_mut(); - let copies = s.copies; - let r = step(&mut s, host, id, params); - // The steps are done with the empty-path closed settings, so the object model can change - // them again without copying them. - s.script_style_trail.closed_empty = Arc::default(); - (copies, r) + (s.copies, step(&mut s, host, id, params)) }; // The resource names a failed command's steps compared are still charged, before its error is // given. @@ -1608,18 +1603,15 @@ pub(crate) struct StyleTrail { pub(in crate::script) resources_gone: std::collections::HashSet<(u64, dom::ResourceKind, String)>, /// The resource names the steps compared, charged to the run with the check that follows. pub(crate) resources_scanned: u64, - /// The object model's empty-path closed settings, shared with it while the steps run. - closed_empty: Arc>, - pub(in crate::script) paths_with_points: std::collections::HashSet<(u64, u64, NodeId)>, } impl StyleTrail { /// A trail that starts from the documents' style lists now, and from the documents themselves /// when `watch_resources`. - fn start(s: &Session, watch_resources: bool, closed_empty: Arc>) -> Self { + fn start(s: &Session, watch_resources: bool) -> Self { let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); let docs = if watch_resources { s.docs.iter().map(|st| (st.uid, st.doc.clone())).collect() } else { Vec::new() }; - StyleTrail { lists, docs, watch_resources, closed_empty, ..Default::default() } + StyleTrail { lists, docs, watch_resources, ..Default::default() } } } @@ -1629,17 +1621,6 @@ impl StyleTrail { /// document's lists, however many steps change them. pub(crate) fn note_style_lists(s: &mut Session) { let trail = &mut s.script_style_trail; - for &(uid, reverts, id) in trail.closed_empty.iter() { - if s.docs - .iter() - .find(|st| st.uid == uid && st.reverts == reverts) - .and_then(|st| st.doc.node(id)) - .and_then(|n| n.path_data()) - .is_some_and(|pd| !pd.subpaths.is_empty()) - { - trail.paths_with_points.insert((uid, reverts, id)); - } - } trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); for st in &s.docs { let (c, p) = (&st.doc.char_styles, &st.doc.para_styles);