From 43813db855a6be9ff0bede754595cd181d24c0cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:46:44 -0800 Subject: [PATCH] Scripts: paths, path points and colors for scripts Document.pathItems lists a document's paths and makes empty paths, rectangles, rounded rectangles, ellipses, polygons and stars with the parameter order and defaults of the PathItems help page. A PathItem reads and changes its points, closed state, fill rule, area, length, fill and stroke colors, stroke options and overprint, and translates, rotates and resizes. PathPoints and PathPoint read and set each point's anchor, handles and type. RGBColor, CMYKColor, GrayColor, LabColor and NoColor make colors; a gradient, spot or pattern paint reads as GradientColor, SpotColor or PatternColor. Each change runs an existing command (path.create, the shape.* commands, path.setAnchors, path.close, path.setFillRule, paint.setFill, paint.setStroke, stroke.set, object.setOverprint, object.move, object.rotate, object.scale) inside the run's one undo step, and puts back the selection and the paint for new art. A value that changes nothing runs no command; a bad value throws and changes nothing. path.setAnchors now makes an anchor a corner when it is given `smooth: false`; before, the key was ignored and handles in line made it smooth. --- crates/engine/src/cmd/create.rs | 3 +- crates/engine/src/cmd/path.rs | 2 +- crates/engine/src/script/dom.rs | 22 +- crates/engine/src/script/dom/colors.rs | 154 +++ crates/engine/src/script/dom/paths.rs | 1223 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom.rs | 8 +- crates/engine/src/tests/script_dom_paths.rs | 602 ++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 39 +- docs/mcp.md | 50 +- docs/target-app-parity.md | 3 +- 11 files changed, 2090 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/script/dom/colors.rs create mode 100644 crates/engine/src/script/dom/paths.rs create mode 100644 crates/engine/src/tests/script_dom_paths.rs diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..103eb44f8d 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -850,7 +850,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result { }; let mut anchor = Anchor::with_handles(p, handle("in")?, handle("out")?); match v.get("smooth").filter(|b| !b.is_null()) { - None | Some(Value::Bool(false)) => {} + None => {} + Some(Value::Bool(false)) => anchor.kind = AnchorKind::Corner, Some(Value::Bool(true)) => anchor.kind = AnchorKind::Smooth, Some(_) => return Err(bad(cmd, "anchor `smooth` must be true or false")), } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d32594d92d..d747f34989 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Set Anchors", [], None, - "{id, subpaths: [{anchors: [{x,y,in?,out?}], closed}]} replace a path's geometry", + "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry", has_doc, set_anchors ), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b986dfcf2d..03b236c0e1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod colors; +mod paths; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -91,6 +94,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; pub(super) struct State { coords: Cell, items: RefCell>, + /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. + paths: RefCell>, saving: Cell, } @@ -151,7 +156,7 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. +/// the check that a document, page item or path point `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -162,9 +167,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "PathItem" => { item_of(&h, arg(&a, 0))?; } + "PathPoint" => { + paths::this_point(&h, &a)?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -1740,9 +1748,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("selection", property(l, doc_selection, doc_set_selection)), + ("pathItems", get(l, paths::doc_path_items)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); @@ -1809,7 +1818,12 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend( + ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), if *c == "PathItem" { paths::path_item_members(l) } else { Vec::new() }, None)), + ); + classes.extend(paths::classes(l)); + classes.extend(colors::classes(l)); + paths::install_enums(realm)?; classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs new file mode 100644 index 0000000000..40421c5d38 --- /dev/null +++ b/crates/engine/src/script/dom/colors.rs @@ -0,0 +1,154 @@ +//! The color classes of the script object model, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components, +//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time. +//! 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; +//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` +//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page +//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! assigned yet. + +use std::rc::Rc; + +use serde_json::Value; +use vectorcraft_color::{Color, Paint}; +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. +const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"]; + +/// The components of each color class, with the value `new` gives them. +const CLASSES: &[(&str, &[&str])] = &[ + ("RGBColor", &["red", "green", "blue"]), + ("CMYKColor", &["cyan", "magenta", "yellow", "black"]), + ("GrayColor", &["gray"]), + ("LabColor", &["l", "a", "b"]), + ("NoColor", &[]), + ("GradientColor", &[]), + ("SpotColor", &["tint"]), + ("PatternColor", &[]), +]; + +fn color_object(class: &str, values: &[(&str, f64)]) -> Data { + let mut items = vec![("typename".to_string(), text(class))]; + items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v)))); + Data::Object(items) +} + +/// A component as the script sees it: `v` times `scale`, rounded to 4 decimals. +fn shown(v: f32, scale: f64) -> f64 { + (f64::from(v) * scale * 1e4).round() / 1e4 +} + +/// The color object for a solid color. +fn of_color(c: &Color) -> Data { + match *c { + Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), + Color::Cmyk { c, m, y, k } => color_object( + "CMYKColor", + &[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))], + ), + Color::Gray { k } => color_object("GrayColor", &[("gray", shown(1.0 - k, 100.0))]), + Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]), + } +} + +/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor` +/// with its `tint` for a color linked to a global or spot swatch. +pub(super) fn of_paint(paint: &Paint) -> Data { + match paint { + Paint::None => color_object("NoColor", &[]), + Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]), + Paint::Solid { color, .. } => of_color(color), + Paint::Gradient(_) => color_object("GradientColor", &[]), + Paint::Pattern { .. } => color_object("PatternColor", &[]), + } +} + +/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out). +fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result { + match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { + None | Some(Data::Undefined) => Ok(0.0), + Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n), + Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))), + Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))), + } +} + +#[allow(clippy::cast_possible_truncation)] +fn unit(v: f64, scale: f64) -> f32 { + (v / scale) as f32 +} + +/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property. +pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result, HostError> { + let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) }; + let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) { + Some(Data::String(s)) => s.as_str(), + _ => return Err(HostError::Type(format!("{what} must be a color object"))), + }; + let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max); + Ok(Some(match class { + "NoColor" => return Ok(None), + "RGBColor" => { + Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) } + } + "CMYKColor" => Color::Cmyk { + c: unit(c("cyan", 0.0, 100.0)?, 100.0), + m: unit(c("magenta", 0.0, 100.0)?, 100.0), + y: unit(c("yellow", 0.0, 100.0)?, 100.0), + k: unit(c("black", 0.0, 100.0)?, 100.0), + }, + "GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) }, + "LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) }, + l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))), + _ => return Err(HostError::Type(format!("{what} must be a color object"))), + })) +} + +/// `color` as `paint.setFill` and `paint.setStroke` take it. +pub(super) fn param(color: &Color) -> Value { + serde_json::to_value(color).unwrap_or(Value::Null) +} + +/// The constructors of the color classes, and `cmykColor`. +pub(super) fn classes(link: &Link) -> Vec { + let make = |name: &str, components: &'static [&'static str]| { + let l = link.clone(); + let class = name.to_string(); + let f: HostFunction = Rc::new(move |_| { + current(&l)?.charge_call(64)?; + let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect(); + Ok(color_object(&class, &zeros)) + }); + f + }; + let mut out: Vec = CLASSES + .iter() + .map(|(name, components)| HostClass { + name: (*name).into(), + parent: None, + members: Vec::new(), + index: None, + construct: Some(make(name, components)), + }) + .collect(); + out.push(HostClass { + name: "cmykColor".into(), + parent: None, + members: Vec::new(), + index: None, + construct: Some(make("CMYKColor", CLASSES[1].1)), + }); + out +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs new file mode 100644 index 0000000000..ac643ce370 --- /dev/null +++ b/crates/engine/src/script/dom/paths.rs @@ -0,0 +1,1223 @@ +//! Paths and their points in the script object model, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! A `PathPoints` object holds its path's handle, and a `PathPoint` the path's handle and the +//! point's index, counted across the path's subpaths in order. Each read looks the path up again. +//! Every change runs one command (`path.setAnchors` for the geometry), inside the run's one undo +//! step, and a change that changes nothing runs no command. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside +//! groups and compound paths included. +//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden +//! or locked layer or group, throws `Cannot edit` with nothing changed. +//! - A path in a compound path or compound shape reads that owner's paint, which the paint +//! commands change in its place. A paint or stroke change leaves the paint for new art, the +//! active proxy and the recent colors as they were. +//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes +//! them all. +//! - `pathItems.add()` makes a path with no points on top of the active layer, painted as new art +//! is. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds +//! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. +//! Removing the last points leaves the path, with no points. +//! - A point whose index is past the end of its path throws `Stale path point`. +//! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole +//! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that +//! says it is not available yet. `rotateAbout` and `scaleAbout` default to +//! `Transformation.CENTER`. +//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and +//! `changeStrokePattern` given as different values throw an error; gradients move with the art, +//! so `changeFillGradients` false throws an error that says it is not available yet. + +use std::rc::Rc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::pattern::pattern_paint; +use vectorcraft_doc::{GraphicStyle, LineCap, LineJoin}; +use vectorcraft_geom::path::{Anchor, AnchorKind, FillRule, PathData, SubPath}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, host_ref}; +use vectorcraft_tools::params::gradient_params; + +use super::{ + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, + float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, property, + this_doc, typename_of, whole, with_doc, +}; +use crate::{DocState, NodeId, NodeKind}; + +/// The error of a point whose index is past the end of its path. +pub const STALE_POINT: &str = "Stale path point"; +/// The most points `setEntirePath` takes. +pub const MAX_POINTS: usize = 100_000; +/// The most lengths `strokeDashes` takes. +pub const MAX_DASHES: usize = 64; +/// The largest stroke weight a script may set, in points. +pub const MAX_STROKE_WIDTH: f64 = 1000.0; + +/// The enumerations of paths, as frozen objects whose members are `"Name.MEMBER"` strings. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("PointType", &["CORNER", "SMOOTH"]), + ("PathPointSelection", &["ANCHORPOINT", "LEFTDIRECTION", "LEFTRIGHTPOINT", "NOSELECTION", "RIGHTDIRECTION"]), + ("StrokeCap", &["BUTTENDCAP", "PROJECTINGENDCAP", "ROUNDENDCAP"]), + ("StrokeJoin", &["BEVELENDJOIN", "MITERENDJOIN", "ROUNDENDJOIN"]), + ("PolarityValues", &["NEGATIVE", "POSITIVE"]), + ("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]), +]; + +/// Adds the enumerations of [`ENUMS`] to `realm`. +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 cannot_edit(id: NodeId) -> HostError { + HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) +} + +/// The path `d` names, which must still be in its document. +fn path_of(h: &super::Host, d: &Data) -> std::result::Result { + let item = item_of(h, d)?; + let is_path = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); + if is_path { Ok(item) } else { Err(HostError::Type("this is not a PathItem".into())) } +} + +fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result { + path_of(h, arg(a, 0)) +} + +/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + path_of(h, &path_ref(h, Item { doc, id })) +} + +/// Reads the path of `item` with `f`. +fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::doc::Node, &PathData) -> T) -> std::result::Result { + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => match n.path_data() { + Some(pd) => Ok(f(st, n, pd)), + None => Err(HostError::Type("this is not a PathItem".into())), + }, + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn path_ref(h: &super::Host, item: Item) -> Data { + let [high, low] = id_parts(item.id); + host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) +} + +/// How many points a path has, across its subpaths. +fn point_count(pd: &PathData) -> usize { + pd.subpaths.iter().map(|sp| sp.anchors.len()).sum() +} + +/// The subpath and the place in it of point `i`. +fn locate(pd: &PathData, mut i: usize) -> Option<(usize, usize)> { + for (s, sp) in pd.subpaths.iter().enumerate() { + if i < sp.anchors.len() { + return Some((s, i)); + } + i -= sp.anchors.len(); + } + None +} + +fn anchor_json(a: &Anchor) -> Value { + json!({"x": a.p.x, "y": a.p.y, "in": [a.h_in.x, a.h_in.y], "out": [a.h_out.x, a.h_out.y], "smooth": a.kind == AnchorKind::Smooth}) +} + +/// Gives the path of `item` the subpaths `subs` with `path.setAnchors`, unless it has them. +fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { + let (same, ok) = read_path(h, item, |st, _, pd| (pd.subpaths == subs, editable(&st.doc, item.id)))?; + if same { + return Ok(()); + } + if !ok { + return Err(cannot_edit(item.id)); + } + let subpaths: Vec = + subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + Ok(()) +} + +/// Runs `id` with `params` and `ids: [item]` on the item, which must be one the user could edit. +/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the +/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put +/// back afterwards, so the edit changes only the path. +fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { + let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); + if !ok { + return Err(cannot_edit(item.id)); + } + if let Some(o) = params.as_object_mut() { + o.insert("ids".into(), json!([item.id.0])); + } + keeping_paint(h, || edit_item(h, item, id, ¶ms)) +} + +/// 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 { + let kept = { + let s = h.session.borrow(); + (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()) + }; + let r = f(); + let mut s = h.session.borrow_mut(); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + r +} + +// ---- Document.pathItems ---- + +/// The ids of a document's paths, in the order of its page items. +fn path_items(h: &super::Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.paths.borrow() + && *uid == st.uid + && std::sync::Arc::ptr_eq(doc, &st.doc) + { + return ids.clone(); + } + let all = super::page_items(h, st); + let ids: Rc> = + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); + *h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + ids +} + +pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) +} + +fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "PathItems") +} + +fn items_length(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) +} + +fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) +} + +fn items_at(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) +} + +fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = path_items(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn items_index(h: &super::Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => items_by_name(h, a), + Data::Number(_) => match items_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked +/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = path_items(h, st); + let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +/// The id in the result of a command that made an object. +fn made_id(r: &Data) -> std::result::Result { + let id = match r { + Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), + _ => None, + }; + id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +} + +/// Runs the command `id` that makes a path in `doc`, the selection kept, and reverses the new +/// path's direction when `reversed`. → the new path. +fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { + let made = on_doc(h, doc.uid, true, |h| { + let id = made_id(&command(h, id, params)?)?; + if reversed { + command(h, "path.reverse", &json!({"ids": [id.0]}))?; + } + Ok(id) + })?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +/// Argument `i`, or `default` when it is left out. +fn number_or(a: &[Data], i: usize, default: f64, what: &str) -> std::result::Result { + given(arg(a, i)).map_or(Ok(default), |d| number(d, what)) +} + +/// A size or radius: finite and not negative. +fn size(a: &[Data], i: usize, default: Option, what: &str) -> std::result::Result { + let v = match (given(arg(a, i)), default) { + (Some(d), _) => number(d, what)?, + (None, Some(v)) => v, + (None, None) => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if !(0.0..=super::MAX_SIZE).contains(&v) { + return Err(HostError::Range(format!("{what} must be from 0 to 3999856 points"))); + } + Ok(v) +} + +/// A whole number argument from `min` to `max`. +fn count(a: &[Data], i: usize, default: f64, min: f64, max: f64, what: &str) -> std::result::Result { + let v = number_or(a, i, default, what)?; + if v.fract() != 0.0 || !(min..=max).contains(&v) { + return Err(HostError::Range(format!("{what} must be a whole number from {min} to {max}"))); + } + Ok(v) +} + +fn flag(a: &[Data], i: usize, what: &str) -> std::result::Result { + given(arg(a, i)).map_or(Ok(false), |d| boolean(d, what)) +} + +/// The top-left corner, in document coordinates, of a box whose top-left corner the script gives. +fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result { + with_doc(h, doc, |_, st| Ok(frame(st)?.to_document(h.dom.coords.get(), [left, top]))) +} + +/// `rectangle(top, left, width, height, reversed?)`. +fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let top = coordinate(arg(a, 1), "top")?; + let left = coordinate(arg(a, 2), "left")?; + let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); + let reversed = flag(a, 5, "reversed")?; + let p = corner(h, doc, left, top)?; + make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) +} + +/// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the +/// page from the top of the left side. +fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { + const K: f64 = 0.552_284_749_830_793_4; + let (rx, ry) = (rx.min(r.width() / 2.0), ry.min(r.height() / 2.0)); + let (kx, ky) = (rx * K, ry * K); + let a = |p: Point, h_in: Point, h_out: Point| Anchor { p, h_in, h_out, kind: AnchorKind::Corner }; + let (x0, y0, x1, y1) = (r.x0, r.y0, r.x1, r.y1); + let mut out = vec![ + a(Point::new(x0, y0 + ry), Point::new(x0, y0 + ry), Point::new(x0, y0 + ry - ky)), + a(Point::new(x0 + rx, y0), Point::new(x0 + rx - kx, y0), Point::new(x0 + rx, y0)), + a(Point::new(x1 - rx, y0), Point::new(x1 - rx, y0), Point::new(x1 - rx + kx, y0)), + a(Point::new(x1, y0 + ry), Point::new(x1, y0 + ry - ky), Point::new(x1, y0 + ry)), + a(Point::new(x1, y1 - ry), Point::new(x1, y1 - ry), Point::new(x1, y1 - ry + ky)), + a(Point::new(x1 - rx, y1), Point::new(x1 - rx + kx, y1), Point::new(x1 - rx, y1)), + a(Point::new(x0 + rx, y1), Point::new(x0 + rx, y1), Point::new(x0 + rx - kx, y1)), + a(Point::new(x0, y1 - ry), Point::new(x0, y1 - ry + ky), Point::new(x0, y1 - ry)), + ]; + out.dedup_by(|b, a| { + b.p.distance(a.p) < 1e-9 && { + a.h_out = b.h_out; + true + } + }); + if out.len() > 1 + && out.first().zip(out.last()).is_some_and(|(f, l)| f.p.distance(l.p) < 1e-9) + && let Some(l) = out.pop() + && let Some(f) = out.first_mut() + { + f.h_in = l.h_in; + } + out +} + +/// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, +/// reversed = false)`: a closed path with `path.create`. +fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let top = coordinate(arg(a, 1), "top")?; + let left = coordinate(arg(a, 2), "left")?; + let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); + let (rx, ry) = (size(a, 5, Some(15.0), "horizontalRadius")?, size(a, 6, Some(20.0), "verticalRadius")?); + let reversed = flag(a, 7, "reversed")?; + let p = corner(h, doc, left, top)?; + let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); + make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) +} + +/// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. +fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; + let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; + let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); + let reversed = flag(a, 5, "reversed")?; + if flag(a, 6, "inscribed")? { + return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); + } + let p = corner(h, doc, left, top)?; + make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) +} + +/// The center of a polygon or star, in document coordinates. +fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result { + let x = given(arg(a, 1)).map_or(Ok(200.0), |d| coordinate(d, "centerX"))?; + let y = given(arg(a, 2)).map_or(Ok(300.0), |d| coordinate(d, "centerY"))?; + corner(h, doc, x, y) +} + +/// `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed = false)`. +fn items_polygon(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let c = center(h, doc, a)?; + let r = size(a, 3, Some(50.0), "radius")?; + let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; + let reversed = flag(a, 5, "reversed")?; + make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) +} + +/// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = +/// false)`. +fn items_star(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let c = center(h, doc, a)?; + let r1 = size(a, 3, Some(50.0), "radius")?; + let r2 = size(a, 4, Some(20.0), "innerRadius")?; + let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; + let reversed = flag(a, 6, "reversed")?; + make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) +} + +/// `pathItems.add()`: a path with no points, from `path.create` with empty path data, painted as +/// new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open +/// path is set back to none in the same step. +fn items_add(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let made = on_doc(h, doc.uid, true, |h| { + let unpainted = { + let ap = h.session.borrow().new_art(); + ap.fill_paint().is_none() && ap.stroke_paint().is_none() + }; + let id = made_id(&command(h, "path.create", &json!({"d": ""}))?)?; + if unpainted { + keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; + } + Ok(id) + })?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +// ---- PathItem geometry ---- + +fn path_points(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + let [high, low] = id_parts(item.id); + Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) +} + +fn path_closed(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, _, pd| Data::Bool(!pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed))) +} + +fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { + let closed = boolean(arg(a, 1), "closed")?; + let item = this_path(h, a)?; + let subs = read_path(h, item, |_, _, pd| pd.subpaths.iter().map(|sp| SubPath { anchors: sp.anchors.clone(), closed }).collect())?; + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +/// Whether the path fills by the even-odd rule: its compound path's rule when it is a member of one, +/// as `path.setFillRule` sets it there. +fn path_evenodd(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |st, n, _| { + let owner = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n); + Data::Bool(matches!(owner.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. } | NodeKind::Compound { rule: FillRule::EvenOdd, .. })) + }) +} + +fn path_set_evenodd(h: &super::Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "evenodd")?; + let item = this_path(h, a)?; + if path_evenodd(h, a)? != Data::Bool(on) { + edit_path(h, item, "path.setFillRule", json!({"rule": if on { "evenOdd" } else { "nonZero" }}))?; + } + Ok(Data::Undefined) +} + +/// The area in square points: negative when the path runs counterclockwise on the page. +fn path_area(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, _, pd| num(pd.subpaths.iter().map(SubPath::signed_area).sum())) +} + +fn path_length(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, _, pd| num(pd.length())) +} + +fn path_guides(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { guide: true, .. }))) +} + +fn path_clipping(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { clipping: true, .. }))) +} + +/// `setEntirePath([[x, y], ...])`: corner points with no handles in place of every point, in one +/// subpath that stays closed when the path was. +fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + let Data::Array(list) = arg(a, 1) else { return Err(HostError::Type("setEntirePath needs an array of [x, y] points".into())) }; + if list.len() > MAX_POINTS { + return Err(HostError::Range(format!("setEntirePath takes at most {MAX_POINTS} points"))); + } + let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::>()?; + let (f, closed) = read_path(h, item, |st, _, pd| (frame(st), !pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed)))?; + let (f, c) = (f?, h.dom.coords.get()); + let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); + let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +// ---- PathItem paint ---- + +/// The top fill's paint and the top stroke's paint, width, cap, join, miter limit, dashes and +/// offset, and the overprint flags of both. +struct Look { + fill: Paint, + fill_overprint: bool, + stroke: Paint, + width: f64, + cap: LineCap, + join: LineJoin, + miter: f64, + dashes: Vec, + offset: f64, + stroke_overprint: bool, +} + +/// The look of `item`, read from its compound path or compound shape when it is a member of one, +/// since the paint commands paint that owner in its place. +fn look(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |st, n, _| { + let d = &st.doc; + let owner = d + .parent_of(item.id) + .and_then(|p| d.node(p)) + .filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()) + .unwrap_or(n); + let ap = &owner.appearance; + let fill = ap.fill(); + let stroke = ap.stroke(); + Look { + fill: fill.map_or(Paint::None, |f| f.paint.clone()), + fill_overprint: fill.is_some_and(|f| f.overprint), + stroke: stroke.map_or(Paint::None, |s| s.paint.clone()), + width: stroke.map_or(0.0, |s| s.width), + cap: stroke.map_or(LineCap::default(), |s| s.cap), + join: stroke.map_or(LineJoin::default(), |s| s.join), + miter: stroke.map_or(10.0, |s| s.miter_limit), + dashes: stroke.and_then(|s| s.dash.as_ref()).map_or_else(Vec::new, |d| d.pattern.clone()), + offset: stroke.and_then(|s| s.dash.as_ref()).map_or(0.0, |d| d.offset), + stroke_overprint: stroke.is_some_and(|s| s.overprint), + } + }) +} + +fn this_look(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, Look), HostError> { + let item = this_path(h, a)?; + Ok((item, look(h, item)?)) +} + +fn path_filled(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(!this_look(h, a)?.1.fill.is_none())) +} + +fn path_stroked(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(!this_look(h, a)?.1.stroke.is_none())) +} + +/// Sets the fill (`fill`) or the stroke to `color`, or to none, with `paint.setFill` or +/// `paint.setStroke`. +fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option) -> std::result::Result<(), HostError> { + let id = if fill { "paint.setFill" } else { "paint.setStroke" }; + let params = match color { + Some(c) => json!({"color": colors::param(&c)}), + None => json!({"none": true}), + }; + edit_path(h, item, id, params)?; + Ok(()) +} + +/// The paint new art gets for its fill or stroke, as `paint.setFill` or `paint.setStroke` params for +/// the path `item`: a solid color, linked to its global or spot swatch while the document has that +/// swatch; a gradient, a placed one moved onto the path's bounds as new art takes it; or a pattern. +/// A fill or stroke of none gives black. A pattern that its swatch does not give as new art has it +/// (its own placement, or a pattern the document does not have) throws an error. +fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Result { + let mut ap = h.session.borrow().new_art(); + let top = |ap: &vectorcraft_doc::Appearance| if fill { ap.fill_paint() } else { ap.stroke_paint() }; + let what = if fill { "filled" } else { "stroked" }; + let paint = top(&ap); + match &paint { + Paint::None => Ok(json!({"color": colors::param(&Color::BLACK)})), + Paint::Solid { color, swatch: Some(name), tint } => { + let linked = read_path(h, item, |st, _, _| st.doc.swatch(name).is_some())?; + Ok(match linked { + true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), + true => json!({"swatch": name}), + false => json!({"color": colors::param(color)}), + }) + } + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Gradient(g) => { + let mut g = g.clone(); + if g.geom.is_some() || g.freeform.is_some() { + match read_path(h, item, |_, n, _| n.geometric_bounds())? { + Some(b) => { + ap.rebase_gradients(GraphicStyle::UNIT_BOX, b); + if let Paint::Gradient(placed) = top(&ap) { + g = placed; + } + } + None => (g.geom, g.freeform) = (None, None), + } + } + Ok(json!({"gradient": gradient_params(&g), "keepModel": true})) + } + Paint::Pattern { pattern, .. } => { + let given = read_path(h, item, |st, _, _| { + let d = &st.doc; + d.swatch(pattern).map(|sw| sw.paint.clone()).or_else(|| d.pattern(pattern).map(|_| pattern_paint(pattern))) + })?; + match given { + Some(p) if p == paint => Ok(json!({"swatch": pattern})), + Some(_) => Err(HostError::Error(format!( + "Cannot set {what}: new art's pattern `{pattern}` has a placement of its own, which is not available yet" + ))), + None => Err(HostError::Error(format!("Cannot set {what}: new art's pattern `{pattern}` is not in this document"))), + } + } + } +} + +fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer { + let on = boolean(arg(a, 1), if fill { "filled" } else { "stroked" })?; + let (item, look) = this_look(h, a)?; + 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)?; + } + Ok(Data::Undefined) +} + +fn path_set_filled(h: &super::Host, a: &[Data]) -> Answer { + set_painted(h, a, true) +} + +fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer { + set_painted(h, a, false) +} + +fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer { + Ok(colors::of_paint(&this_look(h, a)?.1.fill)) +} + +fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer { + Ok(colors::of_paint(&this_look(h, a)?.1.stroke)) +} + +fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer { + 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 }; + let same = match (&color, now) { + (None, Paint::None) => true, + (Some(c), Paint::Solid { color, swatch: None, .. }) => c == color, + _ => false, + }; + if !same { + set_paint(h, item, fill, color)?; + } + Ok(Data::Undefined) +} + +fn path_set_fill_color(h: &super::Host, a: &[Data]) -> Answer { + set_color(h, a, true) +} + +fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer { + set_color(h, a, false) +} + +/// 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)?; + } + Ok(Data::Undefined) +} + +fn path_stroke_width(h: &super::Host, a: &[Data]) -> Answer { + Ok(num(this_look(h, a)?.1.width)) +} + +fn path_set_stroke_width(h: &super::Host, a: &[Data]) -> Answer { + let w = number(arg(a, 1), "strokeWidth")?; + if !(0.0..=MAX_STROKE_WIDTH).contains(&w) { + return Err(HostError::Range("strokeWidth must be from 0 to 1000 points".into())); + } + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, (look.width - w).abs() < 1e-9, json!({"weight": w})) +} + +const CAPS: &[(LineCap, &str, &str)] = &[ + (LineCap::Butt, "StrokeCap.BUTTENDCAP", "butt"), + (LineCap::Round, "StrokeCap.ROUNDENDCAP", "round"), + (LineCap::Square, "StrokeCap.PROJECTINGENDCAP", "square"), +]; + +const JOINS: &[(LineJoin, &str, &str)] = &[ + (LineJoin::Bevel, "StrokeJoin.BEVELENDJOIN", "bevel"), + (LineJoin::Round, "StrokeJoin.ROUNDENDJOIN", "round"), + (LineJoin::Miter, "StrokeJoin.MITERENDJOIN", "miter"), +]; + +fn path_stroke_cap(h: &super::Host, a: &[Data]) -> Answer { + let cap = this_look(h, a)?.1.cap; + Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into())) +} + +fn path_set_stroke_cap(h: &super::Host, a: &[Data]) -> Answer { + let found = match arg(a, 1) { + Data::String(s) => CAPS.iter().find(|c| c.1 == s), + _ => None, + }; + let Some(&(cap, _, name)) = found else { return Err(HostError::Type("strokeCap must be a StrokeCap value".into())) }; + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, look.cap == cap, json!({"cap": name})) +} + +fn path_stroke_join(h: &super::Host, a: &[Data]) -> Answer { + let join = this_look(h, a)?.1.join; + Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into())) +} + +fn path_set_stroke_join(h: &super::Host, a: &[Data]) -> Answer { + let found = match arg(a, 1) { + Data::String(s) => JOINS.iter().find(|j| j.1 == s), + _ => None, + }; + let Some(&(join, _, name)) = found else { return Err(HostError::Type("strokeJoin must be a StrokeJoin value".into())) }; + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, look.join == join, json!({"join": name})) +} + +fn path_miter(h: &super::Host, a: &[Data]) -> Answer { + Ok(num(this_look(h, a)?.1.miter)) +} + +fn path_set_miter(h: &super::Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "strokeMiterLimit")?; + if !(1.0..=500.0).contains(&v) { + return Err(HostError::Range("strokeMiterLimit must be from 1 to 500".into())); + } + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, (look.miter - v).abs() < 1e-9, json!({"miterLimit": v})) +} + +fn path_dashes(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Array(this_look(h, a)?.1.dashes.into_iter().map(num).collect())) +} + +/// `strokeDashes = [lengths]`: at most [`MAX_DASHES`] finite lengths that are not negative and +/// not all 0; `[]` or `{}` gives a solid line. +fn path_set_dashes(h: &super::Host, a: &[Data]) -> Answer { + let lengths: Vec = match arg(a, 1) { + Data::Object(o) if o.is_empty() => Vec::new(), + Data::Array(list) if list.len() > MAX_DASHES => return Err(HostError::Range(format!("strokeDashes takes at most {MAX_DASHES} lengths"))), + Data::Array(list) => list.iter().map(|d| number(d, "each dash length")).collect::>()?, + _ => return Err(HostError::Type("strokeDashes must be an array of lengths".into())), + }; + if lengths.iter().any(|l| !(0.0..=MAX_STROKE_WIDTH * 1000.0).contains(l)) { + return Err(HostError::Range("each dash length must be from 0 to 1000000 points".into())); + } + if !lengths.is_empty() && lengths.iter().all(|l| *l == 0.0) { + return Err(HostError::Range("strokeDashes needs a length that is not 0".into())); + } + let (item, look) = this_look(h, a)?; + let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) }; + set_stroke_option(h, item, look.dashes == lengths, json!({"dash": dash})) +} + +fn path_dash_offset(h: &super::Host, a: &[Data]) -> Answer { + Ok(num(this_look(h, a)?.1.offset)) +} + +fn path_set_dash_offset(h: &super::Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "strokeDashOffset")?; + if v.abs() > MAX_STROKE_WIDTH * 1000.0 { + return Err(HostError::Range("strokeDashOffset must be from -1000000 to 1000000 points".into())); + } + let (item, look) = this_look(h, a)?; + if look.dashes.is_empty() && v != 0.0 { + return Err(HostError::Error("strokeDashOffset needs strokeDashes first".into())); + } + set_stroke_option(h, item, (look.offset - v).abs() < 1e-9, json!({"dashOffset": v})) +} + +fn path_fill_overprint(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(this_look(h, a)?.1.fill_overprint)) +} + +fn path_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(this_look(h, a)?.1.stroke_overprint)) +} + +fn set_overprint(h: &super::Host, a: &[Data], fill: bool) -> Answer { + let key = if fill { "fill" } else { "stroke" }; + let on = boolean(arg(a, 1), if fill { "fillOverprint" } else { "strokeOverprint" })?; + let (item, look) = this_look(h, a)?; + let (now, paint) = if fill { (look.fill_overprint, &look.fill) } else { (look.stroke_overprint, &look.stroke) }; + if now != on { + if paint.is_none() { + return Err(HostError::Error(format!("the path has no {key} to overprint"))); + } + edit_path(h, item, "object.setOverprint", json!({key: on}))?; + } + Ok(Data::Undefined) +} + +fn path_set_fill_overprint(h: &super::Host, a: &[Data]) -> Answer { + set_overprint(h, a, true) +} + +fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { + set_overprint(h, a, false) +} + +// ---- PathItem transforms ---- + +/// The point of the path's geometric bounds `r`, in document coordinates, that a `Transformation` +/// value names (left out: the center). +fn about(h: &super::Host, item: Item, d: &Data, r: Rect) -> std::result::Result { + let name = match d { + Data::Undefined => "Transformation.CENTER", + Data::String(s) => s.as_str(), + _ => return Err(HostError::Type("give a Transformation value".into())), + }; + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + Ok(match name.strip_prefix("Transformation.").unwrap_or("") { + "CENTER" => Point::new(cx, cy), + "TOP" => Point::new(cx, r.y0), + "BOTTOM" => Point::new(cx, r.y1), + "LEFT" => Point::new(r.x0, cy), + "RIGHT" => Point::new(r.x1, cy), + "TOPLEFT" => Point::new(r.x0, r.y0), + "TOPRIGHT" => Point::new(r.x1, r.y0), + "BOTTOMLEFT" => Point::new(r.x0, r.y1), + "BOTTOMRIGHT" => Point::new(r.x1, r.y1), + "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(Coords::Document, [0.0, 0.0])))?, + _ => return Err(HostError::Type("give a Transformation value".into())), + }) +} + +/// The `objects` and `patterns` options of a transform command from the four flags from `i`: +/// objects, fill patterns, fill gradients and stroke patterns, each left out or true or false. +fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::Result<(), HostError> { + let names = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; + let mut flags = [None; 4]; + for (k, name) in names.iter().enumerate() { + flags[k] = given(arg(a, i + k)).map(|d| boolean(d, name)).transpose()?; + } + if flags[2] == Some(false) { + return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); + } + if let (Some(f), Some(s)) = (flags[1], flags[3]) + && f != s + { + return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); + } + if let Some(o) = params.as_object_mut() { + if let Some(b) = flags[0] { + o.insert("objects".into(), json!(b)); + } + if let Some(b) = flags[1].or(flags[3]) { + o.insert("patterns".into(), json!(b)); + } + } + Ok(()) +} + +/// `translate(deltaX = 0, deltaY = 0, transformObjects?, transformFillPatterns?, ...)`. +fn path_translate(h: &super::Host, a: &[Data]) -> Answer { + let dx = given(arg(a, 1)).map_or(Ok(0.0), |d| coordinate(d, "deltaX"))?; + let dy = given(arg(a, 2)).map_or(Ok(0.0), |d| coordinate(d, "deltaY"))?; + let item = this_path(h, a)?; + let mut params = json!({"dx": dx, "dy": if h.dom.coords.get() == Coords::Document { -dy } else { dy }}); + transform_options(a, 3, &mut params)?; + if dx != 0.0 || dy != 0.0 { + edit_path(h, item, "object.move", params)?; + } + Ok(Data::Undefined) +} + +/// `rotate(angle, changePositions?, ..., rotateAbout?)`: counterclockwise on the page for a +/// positive angle. +fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { + let angle = number(arg(a, 1), "angle")?; + let item = this_path(h, a)?; + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, arg(a, 6), r)?; + let mut params = json!({"angle": angle, "origin": [origin.x, origin.y]}); + transform_options(a, 2, &mut params)?; + if angle.rem_euclid(360.0) != 0.0 { + edit_path(h, item, "object.rotate", params)?; + } + Ok(Data::Undefined) +} + +/// `resize(scaleX, scaleY, changePositions?, ..., changeLineWidths?, scaleAbout?)`: 100 is 100%; +/// `changeLineWidths` scales the stroke weight by that percent. +fn path_resize(h: &super::Host, a: &[Data]) -> Answer { + let sx = number(arg(a, 1), "scaleX")?; + let sy = number(arg(a, 2), "scaleY")?; + if sx == 0.0 || sy == 0.0 || sx.abs() > 100_000.0 || sy.abs() > 100_000.0 { + return Err(HostError::Range("scaleX and scaleY must not be 0 and at most 100000 percent".into())); + } + let widths = given(arg(a, 7)).map(|d| number(d, "changeLineWidths")).transpose()?; + if widths.is_some_and(|w| !(0.0..=100_000.0).contains(&w)) { + return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); + } + let item = this_path(h, a)?; + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, arg(a, 8), r)?; + let mut params = json!({"sx": sx, "sy": sy, "origin": [origin.x, origin.y], "basis": "page", "strokes": false}); + transform_options(a, 3, &mut params)?; + let width = look(h, item)?.width; + let new_width = widths.map(|w| width * w / 100.0); + if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } + if sx != 100.0 || sy != 100.0 { + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(Data::Undefined) +} + +// ---- PathPoints ---- + +fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { + let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + path_at(h, *run, *uid, *high, *low) +} + +fn points_length(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + read_path(h, item, |_, _, pd| num(float(point_count(pd) as u64))) +} + +fn points_parent(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + Ok(path_ref(h, item)) +} + +fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { + let [high, low] = id_parts(item.id); + host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64)]) +} + +fn points_at(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; + let n = read_path(h, item, |_, _, pd| point_count(pd))?; + Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) +} + +/// `index(key)`: the points are not named, so a key that is not a number throws `Not found`. +fn points_index(h: &super::Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::Number(_) => match points_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn points_add(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + let (mut subs, n, origin) = read_path(h, item, |st, _, pd| { + let origin = frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0])); + (pd.subpaths.clone(), point_count(pd), origin) + })?; + if n >= MAX_POINTS { + return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); + } + let p = match subs.iter().rev().find_map(|sp| sp.anchors.last()) { + Some(last) => last.p, + None => origin?, + }; + match subs.last_mut() { + Some(sp) => sp.anchors.push(Anchor::corner(p)), + None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), + } + write_path(h, item, subs)?; + Ok(point_ref(h, item, n)) +} + +fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + write_path(h, item, Vec::new())?; + Ok(Data::Undefined) +} + +// ---- PathPoint ---- + +/// The path and the index of the point `this` names, which must still be in the path. +pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let [run, uid, high, low, i] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low)?; + let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + let n = read_path(h, item, |_, _, pd| point_count(pd))?; + if i >= n { + return Err(HostError::Error(STALE_POINT.into())); + } + Ok((item, i)) +} + +/// Reads the anchor `this` names with `f`, given the frame and the coordinate system. +fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { + let (item, i) = this_point(h, a)?; + let c = h.dom.coords.get(); + read_path(h, item, |st, _, pd| { + let fr = frame(st)?; + let anchor = locate(pd, i).and_then(|(s, j)| pd.subpaths.get(s).and_then(|sp| sp.anchors.get(j))); + anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) + })? +} + +/// Changes the anchor `this` names with `f`, given the point the script assigned in document +/// coordinates (for a point property) or the value itself. +fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { + let (item, i) = this_point(h, a)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { + f(an); + } + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +/// The point the script assigned to a point property, in document coordinates. +fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Result { + let p = point(arg(a, 1), what)?; + let (item, _) = this_point(h, a)?; + let fr = with_doc(h, item.doc, |_, st| frame(st))?; + Ok(fr.to_document(h.dom.coords.get(), p)) +} + +fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |f, c, an| pair(f.to_script(c, an.p))) +} + +fn pt_set_anchor(h: &super::Host, a: &[Data]) -> Answer { + let p = assigned_point(h, a, "anchor")?; + edit_point(h, a, |an| an.p = p) +} + +fn pt_left(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |f, c, an| pair(f.to_script(c, an.h_in))) +} + +fn pt_set_left(h: &super::Host, a: &[Data]) -> Answer { + let p = assigned_point(h, a, "leftDirection")?; + edit_point(h, a, |an| an.h_in = p) +} + +fn pt_right(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |f, c, an| pair(f.to_script(c, an.h_out))) +} + +fn pt_set_right(h: &super::Host, a: &[Data]) -> Answer { + let p = assigned_point(h, a, "rightDirection")?; + edit_point(h, a, |an| an.h_out = p) +} + +fn pt_type(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |_, _, an| Data::String(if an.kind == AnchorKind::Smooth { "PointType.SMOOTH" } else { "PointType.CORNER" }.into())) +} + +fn pt_set_type(h: &super::Host, a: &[Data]) -> Answer { + let kind = match arg(a, 1) { + Data::String(s) if s == "PointType.CORNER" => AnchorKind::Corner, + Data::String(s) if s == "PointType.SMOOTH" => AnchorKind::Smooth, + _ => return Err(HostError::Type("pointType must be a PointType value".into())), + }; + edit_point(h, a, |an| an.kind = kind) +} + +fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { + let (item, _) = this_point(h, a)?; + Ok(path_ref(h, item)) +} + +/// `remove()`: deletes the point; a subpath left with no points goes too. +fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { + let (item, i) = this_point(h, a)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + if let Some(sp) = subs.get_mut(s) { + sp.anchors.remove(j); + if sp.anchors.is_empty() { + subs.remove(s); + } + } + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +// ---- Registration ---- + +/// The members `PathItem` adds to `PageItem`'s. +pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![ + ("pathPoints", get(l, path_points)), + ("closed", property(l, path_closed, path_set_closed)), + ("evenodd", property(l, path_evenodd, path_set_evenodd)), + ("area", get(l, path_area)), + ("length", get(l, path_length)), + ("guides", get(l, path_guides)), + ("clipping", get(l, path_clipping)), + ("setEntirePath", method(l, path_set_entire)), + ("filled", property(l, path_filled, path_set_filled)), + ("fillColor", property(l, path_fill_color, path_set_fill_color)), + ("fillOverprint", property(l, path_fill_overprint, path_set_fill_overprint)), + ("stroked", property(l, path_stroked, path_set_stroked)), + ("strokeColor", property(l, path_stroke_color, path_set_stroke_color)), + ("strokeOverprint", property(l, path_stroke_overprint, path_set_stroke_overprint)), + ("strokeWidth", property(l, path_stroke_width, path_set_stroke_width)), + ("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap)), + ("strokeJoin", property(l, path_stroke_join, path_set_stroke_join)), + ("strokeMiterLimit", property(l, path_miter, path_set_miter)), + ("strokeDashes", property(l, path_dashes, path_set_dashes)), + ("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset)), + ("translate", method(l, path_translate)), + ("rotate", method(l, path_rotate)), + ("resize", method(l, path_resize)), + ]); + m.extend(["selectedPathPoints", "polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); + m +} + +/// `PathItems`, `PathPoints` and `PathPoint`. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "PathItems", + None, + named(vec![ + ("typename", typename_of("PathItems")), + ("length", get(l, items_length)), + ("parent", get(l, items_parent)), + ("index", method(l, items_index)), + ("getByName", method(l, items_by_name)), + ("removeAll", method(l, items_remove_all)), + ("add", method(l, items_add)), + ("rectangle", method(l, items_rectangle)), + ("roundedRectangle", method(l, items_rounded_rectangle)), + ("ellipse", method(l, items_ellipse)), + ("polygon", method(l, items_polygon)), + ("star", method(l, items_star)), + ]), + Some(super::function(l, items_at)), + ), + class( + "PathPoints", + None, + named(vec![ + ("typename", typename_of("PathPoints")), + ("length", get(l, points_length)), + ("parent", get(l, points_parent)), + ("index", method(l, points_index)), + ("add", method(l, points_add)), + ("removeAll", method(l, points_remove_all)), + ]), + Some(super::function(l, points_at)), + ), + class( + "PathPoint", + None, + { + let mut m = named(vec![ + ("typename", typename_of("PathPoint")), + ("parent", get(l, pt_parent)), + ("anchor", property(l, pt_anchor, pt_set_anchor)), + ("leftDirection", property(l, pt_left, pt_set_left)), + ("rightDirection", property(l, pt_right, pt_set_right)), + ("pointType", property(l, pt_type, pt_set_type)), + ("remove", method(l, pt_remove)), + ]); + m.push(later(l, "PathPoint", "selected")); + m + }, + None, + ), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..a611da1857 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_paths; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 67bd373e2d..fc2cd6ce67 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -646,9 +646,11 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].transform(5);", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs new file mode 100644 index 0000000000..9d9c0c5f7a --- /dev/null +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -0,0 +1,602 @@ +//! The script object model's paths, path points and colors. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::path::AnchorKind; + +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 document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("select.none", &json!({})).unwrap(); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The layers of the active document, to show that a failed run changed nothing. +fn art(s: &Session) -> String { + format!("{:?}", s.active().unwrap().doc.layers) +} + +fn node(s: &Session, id: NodeId) -> crate::doc::Node { + s.active().unwrap().doc.node(id).unwrap().clone() +} + +/// Each number of `v` rounded to 3 decimals, in place. +fn rounded(v: &Value) -> Value { + match v { + Value::Number(n) => { + let r = (n.as_f64().unwrap() * 1000.0).round() / 1000.0; + if r.fract() == 0.0 { json!(r as i64) } else { json!(r) } + } + Value::Array(a) => Value::Array(a.iter().map(rounded).collect()), + v => v.clone(), + } +} + +#[test] +fn path_items_are_live_and_list_only_paths() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "first"})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pathItems;\ + vc.log(p.length); vc.log(d.pageItems.length); vc.log(p.typename); vc.log(p.parent.typename);\ + vc.log(p[0].typename); vc.log(p[1].parent.typename); vc.log(p.getByName('first').name);\ + vc.log(p[2] === undefined && p[-1] === undefined);\ + var r = p.rectangle(100, 10, 5, 5); vc.log(p.length); vc.log(p[2].typename);", + ); + let expected = [json!(2), json!(4), json!("PathItems"), json!("Document"), json!("PathItem"), json!("GroupItem"), json!("first"), json!(true)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!(3), json!("PathItem")]); + assert!(failure(&mut s, "app.activeDocument.pathItems.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pathItems.index('none');").contains("Not found")); +} + +#[test] +fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let before = art(&s); + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("hidden or locked paths"), "{e}"); + assert_eq!(art(&s), before); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); +} + +#[test] +fn shape_creators_use_documented_defaults_and_y_up() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems;\ + vc.log(p.rectangle(250, 10, 30, 40).geometricBounds);\ + vc.log(p.ellipse().geometricBounds);\ + var g = p.polygon(); vc.log(g.pathPoints.length); var b = g.geometricBounds; vc.log([(b[0] + b[2]) / 2, b[1]]);\ + vc.log(p.star().pathPoints.length); vc.log(p.star(0, 0, 10, 5, 7).pathPoints.length);\ + var r = p.roundedRectangle(250, 10, 100, 60); vc.log(r.pathPoints.length); vc.log(r.geometricBounds); vc.log(r.closed);\ + vc.log(p.roundedRectangle(250, 10, 100, 60, 0, 0).pathPoints.length);\ + vc.log(p.length);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out[0], json!([10, 250, 40, 210])); + assert_eq!(out[1], json!([100, 100, 150, 0])); + assert_eq!(out[2], json!(8)); + assert_eq!(out[3], json!([200, 350]), "the polygon is centered on (200, 300) and reaches 50 pt up"); + assert_eq!(out[4], json!(10)); + assert_eq!(out[5], json!(14)); + assert_eq!(out[6], json!(8)); + assert_eq!(out[7], json!([10, 250, 110, 190])); + assert_eq!(out[8], json!(true)); + assert_eq!(out[9], json!(4), "corners of radius 0 leave four points"); + assert_eq!(out[10], json!(7)); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + assert!(s.active().unwrap().selection.objects.is_empty(), "the selection stays as it was"); +} + +#[test] +fn shape_creators_reject_bad_sizes_without_change() { + let (mut s, _, _) = doc(); + let before = art(&s); + let steps = undo_steps(&s); + for (source, part) in [ + ("app.activeDocument.pathItems.rectangle(10, 10, -5, 10);", "width"), + ("app.activeDocument.pathItems.rectangle(10, 10, 5);", "height"), + ("app.activeDocument.pathItems.rectangle();", "top"), + ("app.activeDocument.pathItems.ellipse(0, 0, NaN);", "finite"), + ("app.activeDocument.pathItems.polygon(0, 0, 10, 2);", "sides"), + ("app.activeDocument.pathItems.polygon(0, 0, 10, 5.5);", "sides"), + ("app.activeDocument.pathItems.star(0, 0, 10, 5, 1001);", "points"), + ("app.activeDocument.pathItems.star(0, 0, 10, -5);", "innerRadius"), + ("app.activeDocument.pathItems.roundedRectangle(0, 0, 10, 10, -1);", "horizontalRadius"), + ("app.activeDocument.pathItems.rectangle(0, 0, 10, 10, 'yes');", "reversed"), + ("app.activeDocument.pathItems.rectangle(1e12, 0, 10, 10);", "outside the canvas"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn set_entire_path_replaces_points_and_keeps_closed() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0];\ + p.setEntirePath([[0, 0], [10, 0], [10, 10]]); vc.log(p.pathPoints.length); vc.log(p.closed); vc.log(p.pathPoints[2].anchor);\ + var n = app.activeDocument.pathItems.add(); vc.log(n.pathPoints.length); vc.log(n.closed);\ + n.setEntirePath([[50, 50], [60, 50]]); vc.log(n.pathPoints.length); vc.log(n.closed); vc.log(n.length);\ + n.closed = true; vc.log(n.closed);", + ); + assert_eq!(out, vec![json!(3), json!(true), json!([10, 10]), json!(0), json!(false), json!(2), json!(false), json!(10), json!(true)]); + let n = node(&s, a); + let pd = n.path_data().unwrap(); + assert_eq!(pd.subpaths.len(), 1); + assert!(pd.subpaths[0].closed); + assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); +} + +#[test] +fn hostile_set_entire_path_input_is_bounded() { + let (mut s, _, _) = doc(); + let before = art(&s); + for (source, part) in [ + ("var a = []; for (var i = 0; i < 100001; i++) a.push([i % 100, 1]); app.activeDocument.pathItems[0].setEntirePath(a);", "at most"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [NaN, 1]]);", "finite"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1]]);", "two numbers"), + ("app.activeDocument.pathItems[0].setEntirePath('0,0');", "array"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 1e13]]);", "outside the canvas"), + ( + "var o = {}; Object.defineProperty(o, 0, {get: function () { return 1; }}); app.activeDocument.pathItems[0].setEntirePath([o]);", + "two numbers", + ), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); +} + +#[test] +fn path_point_setters_edit_one_anchor() { + let (mut s, a, _) = doc(); + let anchors_before = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[1];\ + vc.log(pp.length); vc.log(pp.typename); vc.log(q.typename); vc.log(q.parent.typename); vc.log(q.anchor);\ + q.anchor = [45, 285]; vc.log(q.anchor); vc.log(q.leftDirection); vc.log(q.rightDirection);\ + q.rightDirection = [55, 285]; q.leftDirection = [35, 285]; vc.log(q.pointType);\ + q.pointType = PointType.SMOOTH; vc.log(q.pointType); q.pointType = PointType.CORNER; vc.log(q.pointType);\ + vc.log(pp.index(1).anchor);", + ); + assert_eq!(out[0], json!(4)); + assert_eq!(out[1], json!("PathPoints")); + assert_eq!(out[2], json!("PathPoint")); + assert_eq!(out[3], json!("PathItem")); + assert_eq!(out[5], json!([45, 285])); + assert_eq!(out[6], json!([40, 280]), "moving the anchor leaves its handles"); + assert_eq!(out[8], json!("PointType.CORNER"), "moving handles leaves the point type"); + assert_eq!(out[9], json!("PointType.SMOOTH")); + assert_eq!(out[10], json!("PointType.CORNER"), "a corner with handles in line stays a corner"); + assert_eq!(out[11], json!([45, 285])); + let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + for i in [0, 2, 3] { + assert_eq!(anchors[i], anchors_before[i], "point {i} did not change"); + } + assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite")); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints.getByName === undefined);"), vec![json!(true)]); +} + +#[test] +fn path_point_wrapper_goes_stale_after_remove() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, last = pp[3];\ + pp[0].remove(); vc.log(pp.length); vc.log(pp[0].anchor);\ + try { last.anchor; } catch (e) { vc.log(e.message); } try { last.selected; } catch (e) { vc.log(e.message); }\ + var n = pp.add(); vc.log(pp.length); vc.log(n.anchor);\ + pp.removeAll(); vc.log(pp.length); vc.log(app.activeDocument.pathItems.length);\ + p.remove(); try { pp.length; } catch (e) { vc.log(e.message); } try { p.closed; } catch (e) { vc.log(e.message); }\ + try { p.polarity; } catch (e) { vc.log(e.message); }", + ); + assert_eq!( + out, + vec![ + json!(3), + json!([40, 280]), + json!("Stale path point"), + json!("Stale path point"), + json!(4), + json!([10, 240]), + json!(0), + json!(2), + json!("Stale page item"), + json!("Stale page item"), + json!("Stale page item") + ] + ); +} + +#[test] +fn fill_color_round_trips_rgb_cmyk_gray_lab() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); vc.log(c.typename); vc.log([c.red, c.green, c.blue]);\ + c.red = 255; c.blue = 128; p.fillColor = c; var f = p.fillColor; vc.log([f.typename, f.red, f.green, f.blue]);\ + var k = new cmykColor(); k.cyan = 10; k.black = 50; p.strokeColor = k; var t = p.strokeColor; vc.log([t.typename, t.cyan, t.black]);\ + var g = new GrayColor(); g.gray = 25; p.fillColor = g; vc.log([p.fillColor.typename, p.fillColor.gray]);\ + var l = new LabColor(); l.l = 50; l.a = -20; l.b = 30; p.strokeColor = l; vc.log([p.strokeColor.l, p.strokeColor.a, p.strokeColor.b]);", + ); + assert_eq!(out[0], json!("RGBColor")); + assert_eq!(out[1], json!([0, 0, 0])); + assert_eq!(rounded(&out[2]), json!(["RGBColor", 255, 0, 128])); + assert_eq!(rounded(&out[3]), json!(["CMYKColor", 10, 50])); + assert_eq!(rounded(&out[4]), json!(["GrayColor", 25])); + assert_eq!(rounded(&out[5]), json!([50, -20, 30])); + let n = node(&s, a); + match n.appearance.fill_paint() { + Paint::Solid { color: Color::Gray { k }, .. } => assert!((k - 0.75).abs() < 1e-6, "gray 25 is 75% black ink, got {k}"), + p => panic!("fill is {p:?}"), + } +} + +#[test] +fn no_color_unfills_and_unstrokes() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; vc.log([p.filled, p.stroked]);\ + p.fillColor = new NoColor(); p.stroked = false; vc.log([p.filled, p.stroked, p.fillColor.typename]);\ + p.filled = true; vc.log(p.filled);", + ); + assert_eq!(out, vec![json!([true, true]), json!([false, false, "NoColor"]), json!(true)]); + let n = node(&s, a); + assert!(n.appearance.stroke_paint().is_none()); + assert!(!n.appearance.fill_paint().is_none()); +} + +#[test] +fn path_paint_edits_leave_new_art_and_recent_colors() { + let (mut s, _, _) = doc(); + let (paint, active, last, recent) = (s.paint.clone(), s.fill_active, s.last_solid, s.recent_colors.clone()); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7; p.strokeCap = StrokeCap.ROUNDENDCAP; p.filled = false;", + ); + assert_eq!(s.paint, paint, "the paint for new art"); + assert_eq!(s.fill_active, active); + assert_eq!(s.last_solid, last); + assert_eq!(s.recent_colors, recent); +} + +#[test] +fn compound_path_members_read_the_paint_they_are_given() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4;\ + vc.log([p.fillColor.red, p.fillColor.green, p.strokeWidth]); vc.log(app.activeDocument.pathItems[1].fillColor.red);\ + p.evenodd = true; vc.log([p.evenodd, app.activeDocument.pathItems[1].evenodd]);", + ); + assert_eq!(rounded(&out[0]), json!([200, 0, 4])); + assert_eq!(rounded(&out[1]), json!(200), "the compound path paints every member"); + assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule"); +} + +#[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")); + assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch"); +} + +#[test] +fn filled_true_on_a_filled_path_runs_no_command() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.filled = true; p.stroked = true; p.fillColor = p.fillColor;\ + p.strokeWidth = p.strokeWidth; p.strokeCap = p.strokeCap; p.closed = true; p.evenodd = false; p.strokeDashes = [];\ + p.pathPoints[0].anchor = p.pathPoints[0].anchor; p.translate(0, 0); p.rotate(360); p.resize(100, 100);", + ); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); +} + +#[test] +fn an_added_point_follows_the_last_point_before_an_empty_subpath() { + let (mut s, a, _) = doc(); + let subpaths = json!([{"anchors": [{"x": 10, "y": 20}, {"x": 40, "y": 20}], "closed": false}, {"anchors": [], "closed": false}]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); + assert!(node(&s, a).path_data().is_some_and(|pd| pd.subpaths.len() == 2), "the empty subpath is kept"); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints; var n = pp.add(); vc.log(pp.length); vc.log(n.anchor); vc.log(pp[1].anchor);", + ); + assert_eq!(out[0], json!(3)); + assert_eq!(out[1], out[2], "the new point is at the last point"); +} + +#[test] +fn transforms_change_the_path_and_not_the_selected_one() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let (before_a, before_b) = (node(&s, a).geometric_bounds(), node(&s, b).geometric_bounds()); + log(&mut s, "var p = app.activeDocument.pathItems[0]; p.translate(5, 0); p.rotate(90); p.resize(50, 50);"); + assert_ne!(node(&s, a).geometric_bounds(), before_a, "the path the script named changes"); + assert_eq!(node(&s, b).geometric_bounds(), before_b, "the selected path stays"); + assert_eq!(s.active().unwrap().selection.objects, [b], "the selection stays"); +} + +#[test] +fn an_added_path_takes_new_art_without_a_fill_or_stroke() { + let (mut s, _, _) = doc(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let unpainted = |s: &Session| { + let ap = s.new_art(); + matches!(ap.fill_paint(), Paint::None) && matches!(ap.stroke_paint(), Paint::None) + }; + assert!(unpainted(&s)); + let (steps, recent) = (undo_steps(&s), s.recent_colors.clone()); + let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.filled); vc.log(n.stroked); vc.log(n.pathPoints.length);"); + assert_eq!(out, [json!(false), json!(false), json!(0)]); + assert_eq!(undo_steps(&s), steps + 1, "one step for the run"); + assert!(unpainted(&s), "new art keeps no fill and no stroke"); + assert_eq!(s.recent_colors, recent); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.filled); vc.log(n.stroked); vc.log(n.strokeColor.red);"); + assert_eq!(out, [json!(false), json!(true), json!(255)], "a new-art stroke stays"); +} + +/// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. +fn doc_with_paints() -> (Session, NodeId) { + let (mut s, a, _) = doc(); + let dot = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("object.pattern.make", &json!({"ids": [dot.0], "name": "Dots", "width": 20, "height": 20, "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [dot.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#2a6fb0", "spot": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + (s, a) +} + +#[test] +fn filled_and_stroked_true_give_the_new_art_paint() { + let kinds = [ + json!({"color": "#00ff00"}), + json!({"swatch": "Ink", "tint": 40}), + json!({"gradient": {"kind": "radial", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + json!({"swatch": "Dots"}), + ]; + for fill in [true, false] { + for params in &kinds { + let (mut s, a) = doc_with_paints(); + s.execute(if fill { "paint.setFill" } else { "paint.setStroke" }, params).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + assert!(!matches!(want, Paint::None), "{params}: new art takes the paint"); + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + let got = if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }; + assert_eq!(crate::cmd::gradient::unplaced(&got), want, "fill {fill}, {params}"); + } + } +} + +#[test] +fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() { + let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) }; + for (paint, says) in [(placed, "placement of its own"), (vectorcraft_doc::pattern::pattern_paint("Gone"), "not in this document")] { + for fill in [true, false] { + let (mut s, _) = doc_with_paints(); + if fill { + s.paint.fill = paint.clone(); + } else { + (s.paint.stroke, s.paint.stroke_width) = (paint.clone(), 1.0); + } + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure( + &mut s, + if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }, + ); + assert!(e.contains(says), "{e}"); + assert_eq!((art(&s), undo_steps(&s)), (before, steps), "nothing changes"); + } + } +} + +#[test] +fn stroke_options_map_to_stroke_set() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0];\ + p.strokeWidth = 4; p.strokeCap = StrokeCap.ROUNDENDCAP; p.strokeJoin = StrokeJoin.BEVELENDJOIN; p.strokeMiterLimit = 7;\ + p.strokeDashes = [6, 3]; p.strokeDashOffset = 2; p.evenodd = true; p.fillOverprint = true;\ + vc.log([p.strokeWidth, p.strokeCap, p.strokeJoin, p.strokeMiterLimit, p.strokeDashes, p.strokeDashOffset, p.evenodd, p.fillOverprint]);\ + p.strokeDashes = {}; vc.log(p.strokeDashes);", + ); + assert_eq!(out[0], json!([4, "StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 3], 2, true, true])); + assert_eq!(out[1], json!([])); + let n = node(&s, a); + let st = n.appearance.stroke().unwrap(); + assert_eq!((st.width, st.cap, st.join, st.miter_limit, st.dash.is_none()), (4.0, LineCap::Round, LineJoin::Bevel, 7.0, true)); + for (source, part) in [ + ("app.activeDocument.pathItems[0].strokeMiterLimit = 600;", "strokeMiterLimit"), + ("app.activeDocument.pathItems[0].strokeCap = 'round';", "StrokeCap"), + ("app.activeDocument.pathItems[0].strokeJoin = StrokeCap.ROUNDENDCAP;", "StrokeJoin"), + ("app.activeDocument.pathItems[0].strokeWidth = -1;", "strokeWidth"), + ("app.activeDocument.pathItems[0].strokeDashes = [0, 0];", "not 0"), + ("app.activeDocument.pathItems[0].strokeDashes = [1, -2];", "dash length"), + ("var d = []; for (var i = 0; i < 65; i++) d.push(1); app.activeDocument.pathItems[0].strokeDashes = d;", "at most 64"), + ("app.activeDocument.pathItems[0].strokeDashOffset = 3;", "strokeDashes first"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } +} + +#[test] +fn bad_color_components_throw_and_change_nothing() { + let (mut s, _, _) = doc(); + let before = art(&s); + for (source, part) in [ + ("var c = new RGBColor(); c.red = 300; app.activeDocument.pathItems[0].fillColor = c;", "RGBColor.red"), + ("var c = new CMYKColor(); c.cyan = NaN; app.activeDocument.pathItems[0].fillColor = c;", "finite"), + ("var c = new CMYKColor(); c.cyan = -1; app.activeDocument.pathItems[0].fillColor = c;", "CMYKColor.cyan"), + ("var c = new GrayColor(); c.gray = '5'; app.activeDocument.pathItems[0].fillColor = c;", "GrayColor.gray"), + ("var c = new LabColor(); c.a = 200; app.activeDocument.pathItems[0].strokeColor = c;", "LabColor.a"), + ("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"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); +} + +#[test] +fn locked_paths_and_wrong_objects_are_refused() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let before = art(&s); + for (source, part) in [ + ("app.activeDocument.pathItems[0].fillColor = new NoColor();", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].translate(5, 5);", "Cannot edit PathItem"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[2]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); + assert!(e.contains("not a PathItem"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(PathPoint.prototype, 'anchor').get.call({});"); + assert!(e.contains("not a PathPoint"), "{e}"); +} + +#[test] +fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.setEntirePath([[100, 100], [110, 100]]);\ + n.rotate(90, true, true, true, true, Transformation.LEFT); vc.log(n.pathPoints[1].anchor);\ + n.translate(5, 10); vc.log(n.pathPoints[0].anchor);\ + var r = app.activeDocument.pathItems.rectangle(250, 10, 30, 40); r.strokeWidth = 2;\ + r.resize(200, 50, true, true, true, true, 300, Transformation.TOPLEFT); vc.log(r.geometricBounds); vc.log(r.strokeWidth);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out[0], json!([100, 110]), "a positive angle turns counterclockwise"); + assert_eq!(out[1], json!([105, 110]), "translate moves up for a positive deltaY"); + assert_eq!(out[2], json!([10, 250, 70, 230])); + assert_eq!(out[3], json!(6)); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("changePositions")); + let before = art(&s); + for (source, part) in [ + ("app.activeDocument.pathItems[0].translate(1, 2, true, true, false);", "changeFillGradients false"), + ("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"), + ("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"), + ( + "var ps = app.activeDocument.pathItems;\ + for (var i = 0; i < ps.length; i++) { if (ps[i].strokeWidth == 6) ps[i].resize(150, 100, true, true, true, true, 20000); }", + "more than 1000 points", + ), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); +} + +#[test] +fn area_sign_follows_direction() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [10, 0], [10, 10], [0, 10]]); n.closed = true;\ + vc.log(n.area); vc.log(n.length);\ + var r = app.activeDocument.pathItems.rectangle(100, 0, 10, 10), q = app.activeDocument.pathItems.rectangle(100, 0, 10, 10, true);\ + vc.log(r.area + q.area); vc.log(Math.abs(r.area));", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out, vec![json!(-100), json!(40), json!(0), json!(100)]); +} + +#[test] +fn many_path_edits_are_one_undo_step() { + let (mut s, a, b) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var p = app.activeDocument.pathItems, c = new RGBColor(); c.green = 200;\ + for (var i = 0; i < p.length; i++) { p[i].fillColor = c; p[i].strokeWidth = 3; p[i].pathPoints[0].anchor = [0, 0]; }", + ); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + for id in [a, b] { + assert!((node(&s, id).appearance.stroke_width() - 1.0).abs() < 1e-9); + } +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..828a97f585 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,7 +75,8 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType PolarityValues RulerUnits StrokeCap \ + StrokeJoin Transformation ZOrderMethod", ), ("Application.", "prototype"), ( @@ -89,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ + groupItems groupItems= height layers layers= name pageItems parent pathItems rulerOrigin rulerOrigin= \ rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), @@ -107,6 +108,25 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("PathItems.", "prototype"), + ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"), + ("PathItem.", "prototype"), + ( + "PathItem.prototype.", + "area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \ + filled= guides length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \ + selectedPathPoints= setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \ + strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \ + strokeWidth strokeWidth= stroked stroked= translate", + ), + ("PathPoints.", "prototype"), + ("PathPoints.prototype.", "add constructor index length parent removeAll typename"), + ("PathPoint.", "prototype"), + ( + "PathPoint.prototype.", + "anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \ + rightDirection= selected selected= typename", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), @@ -119,14 +139,21 @@ const INSIDE: &[(&str, &str)] = &[ TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"), + ("PointType.", "CORNER SMOOTH"), + ("PolarityValues.", "NEGATIVE POSITIVE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"), + ("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"), + ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; +/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, +/// the page item types other than `PathItem`, and the color classes. +const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem DocumentPreset EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ + IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ + SymbolItem TextFrame cmykColor"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..44d375ae2c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,7 +2675,55 @@ app through the global object `vc`, and writes to the Script Console and runs ot Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds - themselves, such as a path's fill, are not defined yet and read as `undefined`. + themselves, such as a text frame's `contents`, are not defined yet and read as `undefined`. +- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the + order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, + `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new + art has no fill and no stroke, the path has neither), and the shape creators + `rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15, + verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`, + `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed?)` and `star(centerX = 200, centerY = 300, + radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, + `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new + art is painted. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, + `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, + `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, + `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)` (counterclockwise for a + positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through + `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through + `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms + through `object.move`, `object.rotate` and `object.scale`. `pathPoints` + (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and + `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, + `leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `parent` and + `remove()`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 + white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes + the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` + and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. + VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is + closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner + points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and + `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point + whose index is past the end of its path throws `Stale path point`. Color components left out count as 0, `new + cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of + range throws a `RangeError` when the color is assigned, with nothing changed. 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 + art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the + stroke; a new-art pattern with a placement of its own, or one missing from the document, throws an error. Sizes and + radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, + `strokeWidth` 0 to 1000 points (a `changeLineWidths` that would scale it past 1000 throws), `strokeDashes` at most + 64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to + `Transformation.CENTER`. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and + `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with + `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path + that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing + changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new + art, the active Fill or Stroke proxy and Recent Colors as they were. `selectedPathPoints`, `PathPoint.selected`, + `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..81abb83e94 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.