diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index dcb26b94b5..821c74acb0 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -28,6 +28,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()); // A rollback puts back the swatch renames recorded before the batch, including any its steps pushed out of the record. let swatch_renames = s.swatch_renames.clone(); let opens = s.plugin_events_mark(); @@ -46,6 +47,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { Err(e) => { s.swatch_renames = swatch_renames; 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; + } // The documents the steps opened are closed again: plug-ins are not told of them. s.forget_plugin_opens_since(opens); s.notify_text_tool("batch.rollBack"); diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 9224ab6030..c9a9c7c51e 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -274,6 +274,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 4e9611c9ae..429f43aaa5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -111,6 +111,7 @@ mod print; mod raster_capture; #[cfg(test)] pub(crate) use raster_capture::BEFORE_CAPTURE_EXPORT; +mod resources; mod save_open; mod tags; mod text; @@ -120,19 +121,35 @@ mod variables; pub(super) use colors::of_color as color_data; #[cfg(test)] -pub(crate) use paths::POINT_LOOKS; -#[cfg(test)] pub(crate) use paths::index_builds; +#[cfg(test)] +pub(crate) use paths::{PATH_LIST_BUILDS, 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`]). +/// ([`variables::before_command`]). The resources earlier commands removed stay noted until the +/// run next looks up a resource object or [`forget_removed`] runs. pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { tracing::before_command(h); 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); @@ -205,7 +222,8 @@ thread_local! { /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, the lists of paths, the point changes of a path not /// written yet, how many times each path's points went stale and each path as the run last saw its -/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each +/// points, the swatches, symbols, styles and brushes the run's objects name, whether a call's own +/// savepoint ([`atomically`]) is open, the settings of each /// `DocumentPreset` the run made, with the size of the values they hold now and the most they may /// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and /// layers its layers and groups gave, the active artboard of each document, and the tool @@ -237,6 +255,12 @@ pub(super) struct State { /// The item the object model is changing ([`edit_item`]), whose points stay valid through the /// change. editing: Cell>, + /// 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 [`charge_scanned`] charges when the command ends. + resources_gone: RefCell, + /// The swatches, symbols, styles and brushes the run's objects name ([`resources`]). + resources: RefCell, saving: Cell, /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently /// used first, each kept while its document is unchanged. @@ -308,6 +332,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) +} + /// A document's uid, the document as it was, and the ids of its page items then. type ItemList = (u64, Arc, Rc>); @@ -1057,11 +1093,31 @@ fn ends_run(e: &HostError) -> bool { } } -/// 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) { + 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)) + }; + { + 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); } +/// 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(); + 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`]). @@ -3431,6 +3487,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), realm.define_host_object("BlendModes", blend_modes)?; variables::define_enums(realm)?; paths::install_enums(realm)?; + resources::install_enums(realm)?; realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?; let l = link; // The application's members a script may name without `app.`, assigned as `app.` is. @@ -3544,9 +3601,9 @@ fn classes(link: &Link) -> Vec { ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); + document.extend(resources::document_members(l)); document.extend(defaults::document_members(l)); document.extend(text::styles::doc_members(l)); - document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m))); document.extend(layers::document_members(l)); document.extend(variables::document_members(l)); document.extend(save_open::document_members(l)); @@ -3703,13 +3760,16 @@ fn classes(link: &Link) -> Vec { classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| { let mut members = layers::members(c, l); members.extend(variables::item_members(l, c)); - if *c == "PathItem" { - members.extend(paths::path_item_members(l)); + match *c { + "PathItem" => members.extend(paths::path_item_members(l)), + "SymbolItem" => members.extend(resources::symbol_item_members(l)), + _ => {} } class(c, Some("PageItem"), members, None) })); classes.extend(paths::classes(l)); classes.extend(colors::classes(l)); + classes.extend(resources::classes(l)); classes.extend(text::classes(l)); classes.extend(variables::classes(l)); classes.extend(layers::classes(l)); diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 137902ab14..27938e00e1 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -10,14 +10,16 @@ //! 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 color read from an object gives that object the same color when it is assigned back. //! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it //! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to -//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not -//! assigned yet. +//! any other paint gives white. 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; @@ -27,7 +29,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. @@ -121,8 +124,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 cc1cbe6a62..5bb5e31801 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -405,10 +405,12 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } // The document as the edit's step keeps it, read after the switch to it, which can measure // its type again. - let doc = super::edit_item_with(h, item, |h| { - let doc = h.session.borrow().active().map(|st| st.doc.clone()); - super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; - Ok(doc) + let doc = keeping_paths(h, item, || { + super::edit_item_with(h, item, |h| { + let doc = h.session.borrow().active().map(|st| st.doc.clone()); + super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + Ok(doc) + }) })?; if let Some((doc, selection)) = doc.zip(kept) && let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) @@ -421,10 +423,67 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { 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. -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) +#[cfg(test)] +thread_local! { + /// How many times this thread listed a document's paths ([`path_items`]), for the tests. + pub(crate) static PATH_LIST_BUILDS: 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 the path is not inside a Shaper group, the lists of the document's, its layers' and its +/// groups' paths ([`path_items`]) stay 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(); + 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| { + 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 { + let listed = h.dom.paths.borrow().iter().any(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)); + if listed { + kept = Some((st.doc.clone(), st.doc.peek_next_id())); + } + } + }); + let r = f()?; + if let Some((before, next)) = kept { + doc_state(h, &mut |st| { + if st.doc.peek_next_id() == next { + for list in h.dom.paths.borrow_mut().iter_mut().filter(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &before)) { + list.1 = st.doc.clone(); + } + } + }); + } + 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`]). +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()) { + 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) } /// A script's new path goes on the active layer while it is shown and unlocked, or the topmost @@ -462,7 +521,11 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r o.insert("objectOnly".into(), json!(true)); } } - let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; + let result = if KEEP_PATHS.contains(&id) { + keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, ¶ms)))? + } else { + keeping_paint(h, || edit_item(h, item, id, ¶ms))? + }; let count = if id == "object.setOverprint" { "changed" } else { "objects" }; if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint") && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0))) @@ -472,6 +535,10 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r Ok(result) } +/// 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 { @@ -508,6 +575,8 @@ fn path_items(h: &super::Host, st: &DocState, container: Option) -> std: return Ok(ids); } } + #[cfg(test)] + PATH_LIST_BUILDS.with(|n| n.set(n.get() + 1)); let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. }); let ids: Rc> = match container { Some(c) => { @@ -998,9 +1067,15 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathPoints", &handle)) } +/// 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 { + read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.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 { @@ -1116,7 +1191,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| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; @@ -1186,7 +1261,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(()) } @@ -1249,7 +1324,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) } @@ -1263,14 +1338,37 @@ 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. 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("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 }; + 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_paint(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 }; @@ -1291,7 +1389,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) } @@ -1489,9 +1587,10 @@ pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool { with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id)) } -/// Sets the stroke weight of the path `item` to `weight` points. +/// Sets the stroke weight of the path `item` to `weight` points, on the object whose paint the +/// path shows ([`edit_paint`]). pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> { - edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ()) + edit_paint(h, item, "stroke.set", json!({"weight": weight})).map(|_| ()) } // ---- PathPoints ---- @@ -1769,11 +1868,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 new file mode 100644 index 0000000000..21ce016344 --- /dev/null +++ b/crates/engine/src/script/dom/resources.rs @@ -0,0 +1,1409 @@ +//! 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, 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. +//! - `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()` 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. +//! - `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, 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, 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). +//! - 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` (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; +//! `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}; +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_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, 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}; + +/// 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 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 { + 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)>, + /// 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>, + /// 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 { + /// 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 && 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) + { + continue; + } + work += held.len() as u64; + let mut present: HashMap> = HashMap::new(); + 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.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), + }; + } + 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() + }); + 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).and_then(|held| held.get(&(kind, name.to_string()))) { + return Ok(*i); + } + 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); + 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); + let Some(held) = self.index.get_mut(&uid) else { return }; + for k in kind.family() { + if let Some(i) = held.remove(&(*k, from.to_string())) { + self.slots[i].2 = Some(to.to_string()); + 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) = held.remove(&(*k, name.to_string())) { + self.slots[i].2 = None; + } + } + } + + /// 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; + } + } +} + +/// 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 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> { + let (gone, scanned) = std::mem::take(&mut *h.dom.resources_gone.borrow_mut()); + let work = { + let s = h.session.borrow(); + 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)?; + } + 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 { + 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>)> { + 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) +} + +/// 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>)> { + swatches_in_order(d).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, _)| 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(), + 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, _)| 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(), + 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 { + 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)])) +} + +/// 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())?; + settle(h, doc.uid); + 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)) +} + +/// 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 { + 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, 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))) +} + +fn coll_parent(h: &Host, kind: Kind, a: &[Data]) -> Answer { + let doc = coll_doc(h, a, kind)?; + 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_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) { + 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, 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(), + }; + // 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) + }); + // 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); + } + 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!({}) }; + create(h, doc, Kind::Swatch, "swatch.new", ¶ms) +} + +/// 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" }); + } + 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)?; + create(h, doc, Kind::Group, "swatch.newGroup", &json!({})) +} + +/// 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))?; + create(h, doc, Kind::Symbol, "symbol.new", &json!({"ids": [item.id.0], "keepArt": true, "registration": reg})) +} + +// ---- 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 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)?; + 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))])); + } + 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), .. } => is_spot_of(h, doc, base).then(|| base.clone()), + _ => None, + }; + match (color, base) { + (Data::Object(mut o), Some(base)) => { + o.insert(1, ("spot".into(), resource_ref(h, doc.uid, Kind::Spot, &base)?)); + Ok(Data::Object(o)) + } + (color, _) => Ok(color), + } +} + +/// 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 { + 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)?; + 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 && matches!(color, Color::Gray { .. }) { + 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`, 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 == color || now == stored { + return Ok(Data::Undefined); + } + 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 with the profiles `doc` is assigned, +/// whichever document is in front. +fn stored_in(h: &Host, doc: Doc, color: Color) -> Color { + 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`. +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 { + Ok(text(spot_model(&this_res(h, a, kind)?.name))) +} + +fn spot_set_color_type(h: &Host, kind: Kind, a: &[Data]) -> Answer { + 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 { + 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)?; + 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 +/// items it looked at. +fn instances(h: &Host, st: &DocState) -> std::result::Result<(Vec, usize), HostError> { + 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(); + Ok((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, scanned) = with_doc(h, doc, |_, st| instances(h, st))?; + h.charge_call(scanned 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())); + } + // 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)))) +} + +/// `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 +/// 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 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()); + (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 or compound shape".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 { + let mut m = named(vec![ + ("swatches", kget(l, Kind::Swatch, doc_collection), collection("Swatches")), + ("spots", kget(l, Kind::Spot, doc_collection), collection("Spots")), + ("swatchGroups", kget(l, Kind::Group, doc_collection), collection("SwatchGroups")), + ("symbols", kget(l, Kind::Symbol, doc_collection), collection("Symbols")), + ("graphicStyles", kget(l, Kind::Style, doc_collection), collection("GraphicStyles")), + ("brushes", kget(l, Kind::Brush, doc_collection), collection("Brushes")), + ("symbolItems", kget(l, Kind::Symbol, doc_symbol_items), collection("SymbolItems")), + ]); + m.extend(["gradients", "patterns"].into_iter().map(|n| later(l, "Document", n))); + m +} + +/// What `reflect` tells of a member whose value is the collection class `name`. +fn collection(name: &str) -> MemberInfo { + MemberInfo { collection: true, ..typed(name) } +} + +/// The members `SymbolItem` adds to `PageItem`'s. +pub(super) fn symbol_item_members(l: &Link) -> Vec { + named(vec![("symbol", kproperty(l, Kind::Symbol, sitem_symbol, sitem_set_symbol), typed("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 one = kind.class(); + let mut m = named(vec![ + ("typename", typename_of(kind.collection()), typed("string")), + ("length", kget(l, kind, coll_length), typed("number")), + ("parent", kget(l, kind, coll_parent), typed("Document")), + ("index", kmethod(l, kind, coll_index), returns(one, &[("itemKey", "*")])), + ("getByName", kmethod(l, kind, coll_by_name), returns(one, &[("name", "string")])), + ]); + if kind != Kind::Brush { + m.push(("removeAll".into(), kmethod(l, kind, coll_remove_all), returns("undefined", &[]))); + } + match kind { + Kind::Swatch => { + m.push(("add".into(), kmethod(l, kind, swatches_add), returns(one, &[]))); + // 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, &[]))), + Kind::Symbol => m.push(( + "add".into(), + kmethod(l, kind, symbols_add), + returns(one, &[("sourceArt", "PageItem"), ("registrationPoint", "SymbolRegistrationPoint")]), + )), + 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), typed("string")), ("parent", kget(l, kind, res_parent), typed("*"))]); + if kind == Kind::Brush { + m.push(("name".into(), kget(l, kind, res_name), typed("string"))); + } else { + m.push(("name".into(), kproperty(l, kind, res_name, res_set_name), typed("string"))); + m.push(("remove".into(), kmethod(l, kind, res_remove), returns("undefined", &[]))); + } + let extra = match kind { + Kind::Swatch => vec![("color", kproperty(l, kind, swatch_color, set_swatch_color), typed("Color"))], + Kind::Spot => vec![ + ("color", kproperty(l, kind, spot_color, set_swatch_color), typed("Color")), + ("colorType", kproperty(l, kind, spot_color_type, spot_set_color_type), typed("ColorModel")), + ("spotKind", kget(l, kind, spot_kind), typed("SpotColorKind")), + ("getInternalColor", kmethod(l, kind, spot_internal), returns("Array", &[])), + ], + Kind::Group => vec![ + ("addSwatch", kmethod(l, kind, group_add_swatch), returns("undefined", &[("swatch", "Swatch")])), + ("addSpot", kmethod(l, kind, group_add_spot), returns("undefined", &[("spot", "Spot")])), + ("getAllSwatches", kmethod(l, kind, group_all), returns("Array", &[])), + ("removeAll", kmethod(l, kind, group_remove_all), returns("undefined", &[])), + ], + Kind::Symbol => vec![("duplicate", kmethod(l, kind, symbol_duplicate), returns("Symbol", &[]))], + Kind::Style => vec![ + ("applyTo", kmethod(l, kind, style_apply_to), returns("undefined", &[("artItem", "PageItem")])), + ("mergeTo", kmethod(l, kind, style_merge_to), returns("undefined", &[("artItem", "PageItem")])), + ], + Kind::Brush => vec![("applyTo", kmethod(l, kind, brush_apply_to), returns("undefined", &[("artItem", "PageItem")]))], + }; + m.extend(named(extra)); + out.push(class(one, None, m, None)); + } + let k = Kind::Symbol; + out.push(class( + "SymbolItems", + None, + named(vec![ + ("typename", typename_of("SymbolItems"), typed("string")), + ("length", kget(l, k, sitems_length), typed("number")), + ("parent", kget(l, k, sitems_parent), typed("Document")), + ("index", kmethod(l, k, sitems_index), returns("SymbolItem", &[("itemKey", "*")])), + ("getByName", kmethod(l, k, sitems_by_name), returns("SymbolItem", &[("name", "string")])), + ("add", kmethod(l, k, sitems_add), returns("SymbolItem", &[("symbol", "Symbol")])), + ("removeAll", kmethod(l, k, sitems_remove_all), returns("undefined", &[])), + ]), + Some(kfunction(l, k, sitems_at)), + )); + out +} + +#[cfg(test)] +mod tests { + 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_eq!(slots.len(), held.len()); + 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() { + 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 b50ee6b858..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); + 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. @@ -1439,6 +1439,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) { @@ -1458,7 +1460,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) { @@ -1483,7 +1485,9 @@ fn vc_run(host: &Rc, args: Vec) -> std::result::Result std:: let mut s = session.borrow_mut(); (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. + 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)) { let nanos = started.elapsed().as_nanos(); @@ -1565,8 +1575,11 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: dom::after_kept_command(host); seen?; } else { + 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)) } @@ -1577,19 +1590,28 @@ 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, } 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) -> 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, ..Default::default() } } } @@ -1623,6 +1645,32 @@ 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; + } + 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`]). @@ -3197,6 +3245,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: how many times the object model worked out where the points of each subpath of a /// path start. pub(crate) static LAYOUTS_BUILT: Cell = const { Cell::new(0) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1dd72202f1..dbe67e702e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -189,6 +189,7 @@ mod script_dom_defaults; mod script_dom_images; mod script_dom_paths; mod script_dom_prefs; +mod script_dom_resources; mod script_dom_tracing; mod script_dom_transform; mod script_engines; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a40d6a6009..3d8716cd71 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1838,7 +1838,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } - assert!(failure(&mut s, "app.activeDocument.swatches = 1;").contains("Document.swatches is not available yet")); + assert!(failure(&mut s, "app.activeDocument.gradients = 1;").contains("Document.gradients is not available yet")); // A deleted item or an earlier run's document is stale first. let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); @@ -3218,7 +3218,7 @@ fn select_tool_makes_the_named_tool_current_when_the_run_ends() { #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); - assert!(failure(&mut s, "app.activeDocument.swatches;").contains("Document.swatches is not available yet")); + assert!(failure(&mut s, "app.activeDocument.gradients;").contains("Document.gradients is not available yet")); } fn layer_names(s: &Session) -> Vec { @@ -5398,7 +5398,7 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('gradients'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 153e348cd9..a7a49fe6c2 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1160,17 +1160,174 @@ 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(); 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_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[2].fillColor.typename, q[2].fillColor.spot === undefined, q[1].fillColor.typename, q[0].fillColor.typename]);", + ); + // `pathItems` lists c (unlinked), b (Moss), a (Leaf) and the document's first rectangle. + assert_eq!(out, vec![json!(["SpotColor", true, "SpotColor", "RGBColor"])]); + for script in [ + "var q = app.activeDocument.pathItems; q[2].fillColor = q[2].fillColor;", + "var q = app.activeDocument.pathItems; q[1].fillColor = q[2].fillColor;", + "var q = app.activeDocument.pathItems; q[0].fillColor = q[2].fillColor;", + ] { + let e = failure(&mut s, script); + 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}"); + } +} + +#[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(); + 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; a color read"), + ("var c = new SpotColor(); c.spot = 5; app.documents[0].pathItems[0].fillColor = c;", "SpotColor.spot must be a Spot"), + // `app.documents` lists the active document, the new one, first: the document with `Ink` is + // `documents[1]`. + ("var a = app.documents[1], c = new SpotColor(); c.spot = a.swatches.getByName('Ink'); a.pathItems[0].fillColor = c;", "must be a Spot"), + ( + "var a = app.documents[1], c = new SpotColor(); c.spot = a.spots.getByName('Ink'); c.tint = 101; a.pathItems[0].fillColor = c;", + "SpotColor.tint", + ), + ( + "var a = app.documents[1], b = app.documents[0], 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(); @@ -1349,6 +1506,145 @@ fn looking_for_changed_points_after_each_command_is_charged() { assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2])); } +#[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_LIST_BUILDS.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_LIST_BUILDS.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 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(); + 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(); @@ -2049,7 +2345,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; a color read"), ] { let e = failure(&mut s, source); assert!(e.contains(part), "{source}: {e}"); @@ -2500,6 +2796,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/crates/engine/src/tests/script_dom_resources.rs b/crates/engine/src/tests/script_dom_resources.rs new file mode 100644 index 0000000000..2bbecf9852 --- /dev/null +++ b/crates/engine/src/tests/script_dom_resources.rs @@ -0,0 +1,842 @@ +//! The script object model's swatches, color groups, spots, symbols, graphic styles and brushes. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt 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); try { w.getSelected(); } catch (e) { vc.log(e.message); }", + ); + assert_eq!( + out, + vec![ + json!(names.len()), + json!("Swatches"), + json!("Document"), + json!(names[0]), + json!("[Registration]"), + json!("Swatch"), + json!(true), + json!("RGBColor"), + json!("Swatches.getSelected is not available yet") + ] + ); + 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", + ), + ( + "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); + assert!(e.contains(message), "{script}: {e}"); + } +} + +#[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(); + 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_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!(2), + 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.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.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 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')"; + 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"); +} + +#[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(); + 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(); + 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.length === 0);", + ); + 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); + // `app.documents` lists the active document, the new one, first: the document with the symbol + // is `documents[1]`. + for script in [ + "var a = app.documents[1], b = app.documents[0]; b.symbolItems.add(a.symbols[0]);", + "var a = app.documents[1], b = app.documents[0]; a.graphicStyles[0].applyTo(b.pageItems[0]);", + "var a = app.documents[1], b = app.documents[0]; b.swatchGroups.add().addSwatch(a.swatches.getByName('Black'));", + "var a = app.documents[1], b = app.documents[0]; 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[0]);", + ); + 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[0]);"); + 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[0]);"); + 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); +} + +#[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_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}; + 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/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 2d83141b7b..abab545318 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -99,12 +99,14 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \ - CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ + "activeDocument activeDocument= app Application Artboard Artboards BlendModes Brush Brushes ColorModel CompoundPathItem \ + CompoundPathItems CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \ - GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \ - PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \ - selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod", + GraphicStyle GraphicStyles GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint \ + PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems \ + RulerUnits ScreenMode selection selection= Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \ + Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Tag Tags TracingObject TracingOptions Transformation \ + View Views ZOrderMethod", ), ("Application.", "prototype"), ( @@ -133,15 +135,15 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \ + "activeLayer activeLayer= artboards brushes characterStyles close compoundPathItems constructor convertCoordinate \ defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \ defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \ defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \ defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \ - defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \ - height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \ - rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \ - symbols symbols= tags textFrames toString typename views width", + defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName gradients \ + gradients= graphicStyles groupItems height layers name pageItems paragraphStyles parent path pathItems patterns \ + patterns= placedItems rasterItems rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= \ + spots stories swatchGroups swatches symbolItems symbols tags textFrames toString typename views width", ), ("Views.", "prototype"), ("Views.prototype.", "constructor index length parent toString typename"), @@ -247,6 +249,35 @@ const INSIDE: &[(&str, &str)] = &[ "anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \ rightDirection= selected selected= toString typename", ), + ("Swatches.", "prototype"), + ("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"), + ("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"), ("Tags.", "prototype"), ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), ("Tag.", "prototype"), @@ -273,8 +304,14 @@ const INSIDE: &[(&str, &str)] = &[ ("PolarityValues.", "NEGATIVE POSITIVE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"), + ("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 enumerations of saving, exporting and opening. @@ -579,7 +616,7 @@ const INSIDE: &[(&str, &str)] = &[ /// that have no members of their own, the color classes, and the save, export, rasterize and image /// capture option classes. const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \ - MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \ + MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor cmykColor \ EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \ ImageCaptureOptions RasterizeOptions \ ExportForScreensItemToExport ExportForScreensOptionsJPEG ExportForScreensOptionsPNG24 \ diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 4ab64c77e1..8cf5b64d45 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -633,6 +633,11 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und own: Rc::new(own), members, }); + // The host class named `Symbol` keeps the built-in `Symbol` global. Its objects use the host prototype. + let global = i.global; + if class.name == "Symbol" && i.get_own_property(global, &key(&class.name))?.is_some() { + return Ok(()); + } undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 56f80af28d..15d5affd66 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 10e87b2f5f..a42d856966 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3892,7 +3892,12 @@ through `$`: 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; 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, 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 copied solid new-art color keeps its color model. 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. @@ -3929,6 +3934,59 @@ through `$`: a default throws an error, since new art then takes that object's appearance. `scaleFactor` (https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts lists it as read-only) is always 1, since VectorCraft draws every document at its own size; after an assignment it still reads 1. +- 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()` 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`); 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`) + 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. `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 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 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 objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both diff --git a/docs/roadmap.md b/docs/roadmap.md index f6e6d14c9a..258135dd9c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -210,7 +210,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) 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 layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, 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, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, 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; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, gradient stops 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 | | — | 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6bc692c617..501ac14370 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,6 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.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: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.