diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 6b6099e7b6..6427f339db 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -38,27 +38,32 @@ "applicability": "required" }, { - "name": "gate / test 1/5 (ubuntu-24.04)", + "name": "gate / test 1/6 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 2/5 (ubuntu-24.04)", + "name": "gate / test 2/6 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 3/5 (ubuntu-24.04)", + "name": "gate / test 3/6 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 4/5 (ubuntu-24.04)", + "name": "gate / test 4/6 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, { - "name": "gate / test 5/5 (ubuntu-24.04)", + "name": "gate / test 5/6 (ubuntu-24.04)", + "app_id": 15368, + "applicability": "required" + }, + { + "name": "gate / test 6/6 (ubuntu-24.04)", "app_id": 15368, "applicability": "required" }, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7ae30d3ca..0954b5c35c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,11 +39,12 @@ jobs: dev-strip: true # The workspace crates also build without line tables. A panic still names its file and line. dev-debug: "0" - # Five legs instead of one: shards 1 to 4 each build and run the tests of their own crates, - # and shard 5 runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate ()` - # passes only when all five did. On pushes to main, a `cache warm` leg builds what every - # shard builds and saves the dependency cache. - test-shards: 5 + # Six legs instead of one: shards 1 and 2 each build vectorcraft-ui-egui's tests and run + # half of them, shards 3 to 5 each build and run the tests of their own crates, and shard 6 + # runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate ()` passes only + # when all six did. On pushes to main, a `cache warm` leg builds what every shard builds and + # saves the dependency cache. + test-shards: 6 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm # The dependency cache also keeps the compiled workspace crates and test executables, so a diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index 90cf166ed7..4cd4eb6387 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -1,6 +1,7 @@ name: SonarCloud on: + workflow_dispatch: push: branches: [main] pull_request: diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 78c066405d..16ceda7d38 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -920,7 +920,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/newart.rs b/crates/engine/src/cmd/newart.rs index f43221120c..f420054d11 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -6,7 +6,8 @@ //! and strokes, effects, opacity and blend mode, and the link to the style) or, with the Appearance //! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the //! option on (the default) an inherited appearance gives new art its top stroke's options only, -//! and a change of selection loads only the proxies. `paint.default` resets it. +//! and a change of selection loads only the proxies. `paint.default` resets it, and +//! `appearance.setNewArt` sets its fill, stroke and stroke options whatever is selected. //! //! A document whose Default Graphic Style no longer has the shipped look (a New Document profile //! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new` @@ -34,7 +35,7 @@ pub(crate) struct NewArtSource { use super::gradient::unplaced; use super::paint::SelectionPaints; -use super::{CommandSpec, Result, Session, always, cmd, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, cmd, switch_or}; use crate::doc_state::{SelectionRecord, objects_only}; pub fn specs() -> Vec { @@ -57,9 +58,181 @@ pub fn specs() -> Vec { always, describe ), + cmd!( + "appearance.setNewArt", + "Set New Art Appearance", + [], + None, + "{fill?: {color?, none?, swatch?, tint?, gradient?, keepModel?} (a paint as paint.setFill takes it), stroke?: (a paint, as fill), weight?: 0..1000 pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?: 1..500, dash?: [lengths, each 0..1000000 pt, at most 64, not all 0]|null (null: a solid line), dashOffset?: -1000000..1000000 pt (with a dash pattern), fillOverprint?: bool, strokeOverprint?: bool} set the fill, stroke and stroke options the next object drawn gets, whatever is selected: the selection and its art, the active proxy and the recent colors stay as they are. Without `weight` the stored stroke weight stays; a stroke painted on new art without one gets 1 pt only when that stored weight is 0. A bad value is an error with nothing changed, and so is any change while New Art Has Basic Appearance is off and an object is selected (new art takes that object's appearance then) → {changed: whether the next object drawn looks different}", + always, + set_new_art + ), ] } +/// The most dash and gap lengths `appearance.setNewArt` takes. +const MAX_DASHES: usize = 64; +/// The settings a `fill` or `stroke` paint of `appearance.setNewArt` takes. +const PAINT_KEYS: [&str; 6] = ["color", "none", "swatch", "tint", "gradient", "keepModel"]; +/// The largest dash, gap or dash offset `appearance.setNewArt` takes, in points. +const MAX_DASH_LENGTH: f64 = 1_000_000.0; + +/// What [`dash_fault`] finds wrong with a list of dash and gap lengths. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum DashFault { + /// More than [`MAX_DASHES`] lengths. + TooMany, + /// A length that is not a number from 0 to [`MAX_DASH_LENGTH`]. + OutOfRange, + /// Lengths that are all 0. + AllZero, +} + +/// What is wrong with the dash and gap lengths `lengths`, which `appearance.setNewArt` and the +/// scripts' `strokeDashes` and `defaultStrokeDashes` check the same way; `None` when they are good. +/// An empty list (a solid line) is good. +pub(crate) fn dash_fault(lengths: &[f64]) -> Option { + if lengths.len() > MAX_DASHES { + Some(DashFault::TooMany) + } else if !lengths.iter().all(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(n)) { + Some(DashFault::OutOfRange) + } else if !lengths.is_empty() && lengths.iter().all(|n| *n == 0.0) { + Some(DashFault::AllZero) + } else { + None + } +} + +/// `c` as `appearance.setNewArt` stores it without `keepModel`: an RGB color in the color mode of +/// the document in front. +pub(crate) fn stored_color(s: &Session, c: vectorcraft_color::Color) -> vectorcraft_color::Color { + super::paint::new_color(s, &json!({}), c) +} + +/// `appearance.setNewArt`: new art's fill, stroke and stroke options, every value checked before +/// anything changes. +fn set_new_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "appearance.setNewArt"; + let paint = |key: &str, fill: bool| -> Result> { + let Some(v) = p.get(key) else { return Ok(None) }; + if !v.is_object() { + return Err(bad(C, format!("{key} must be a paint object (color, none, swatch or gradient), got {v}"))); + } + if let Some(k) = v.as_object().and_then(|o| o.keys().find(|k| !PAINT_KEYS.contains(&k.as_str()))) { + return Err(bad(C, format!("{key}: unknown setting `{k}` (a paint takes {})", PAINT_KEYS.join(", ")))); + } + if v.get("swatch").is_some_and(|w| !w.is_string()) { + return Err(bad(C, format!("{key}: `swatch` must be a swatch name"))); + } + let pattern_only = |name: &str| s.doc().is_ok_and(|st| st.doc.swatch(name).is_none() && st.doc.pattern(name).is_some()); + if v.get("tint").is_some() && v.get("swatch").and_then(Value::as_str).is_none_or(pattern_only) { + return Err(bad(C, format!("{key}: `tint` goes with a global or spot `swatch`"))); + } + let given = super::paint::paint_from(s, v)?.ok_or_else(|| bad(C, format!("{key}: give color, none, swatch or gradient")))?; + if !fill && matches!(&given, Paint::Gradient(g) if g.gradient.dither) && v.get("swatch").and_then(Value::as_str).is_none() { + return Err(bad(C, "`dither` applies to gradient fills")); + } + Ok(Some(unplaced(&given))) + }; + let (fill, stroke) = (paint("fill", true)?, paint("stroke", false)?); + let number = |key: &str, min: f64, max: f64| -> Result<()> { + match p.get(key) { + None => Ok(()), + Some(v) if v.as_f64().is_some_and(|n| n.is_finite() && (min..=max).contains(&n)) => Ok(()), + Some(v) => Err(bad(C, format!("{key} must be a number from {min} to {max}, got {v}"))), + } + }; + number("weight", 0.0, 1000.0)?; + number("miterLimit", 1.0, 500.0)?; + number("dashOffset", -MAX_DASH_LENGTH, MAX_DASH_LENGTH)?; + for key in ["cap", "join"] { + if p.get(key).is_some_and(|v| !v.is_string()) { + return Err(bad(C, format!("{key} must be a name"))); + } + } + match p.get("dash") { + None | Some(Value::Null) => {} + Some(Value::Array(a)) if a.len() > MAX_DASHES => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))), + Some(Value::Array(a)) => { + let lengths: Option> = a.iter().map(Value::as_f64).collect(); + match lengths.map_or(Some(DashFault::OutOfRange), |l| dash_fault(&l)) { + None => {} + Some(DashFault::TooMany) => return Err(bad(C, format!("dash takes at most {MAX_DASHES} lengths"))), + Some(DashFault::OutOfRange) => return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))), + Some(DashFault::AllZero) => return Err(bad(C, "dash needs a length that is not 0")), + } + } + Some(v) => return Err(bad(C, format!("dash must be a list of lengths or null, got {v}"))), + } + let flag = |key: &str| -> Result> { + p.get(key).map(|v| v.as_bool().ok_or_else(|| bad(C, format!("{key} must be true or false, got {v}")))).transpose() + }; + let (fill_overprint, stroke_overprint) = (flag("fillOverprint")?, flag("strokeOverprint")?); + let options: serde_json::Map = + ["weight", "cap", "join", "miterLimit", "dash", "dashOffset"].iter().filter_map(|k| Some((k.to_string(), p.get(*k)?.clone()))).collect(); + let change = super::stroke::StrokeChange::parse(&Value::Object(options), C)?; + let dashed = match p.get("dash") { + Some(Value::Array(a)) => !a.is_empty(), + Some(_) => false, + None => s.new_art().stroke().is_some_and(|st| st.dash.is_some()), + }; + if p.get("dashOffset").and_then(Value::as_f64).is_some_and(|o| o != 0.0) && !dashed { + return Err(bad(C, "dashOffset needs a dash pattern")); + } + let nothing = fill.is_none() && stroke.is_none() && change.is_empty() && fill_overprint.is_none() && stroke_overprint.is_none(); + if !nothing + && !s.prefs.new_art_basic + && !(s.tool_paints(false) && s.tool_paints(true)) + && s.active().is_some_and(|st| !st.selection.subjects().is_empty()) + { + return Err(bad( + C, + "with New Art Has Basic Appearance off, new art takes the selected object's appearance: deselect it or turn the option on", + )); + } + let look = |s: &Session| { + let (opacity, blend, style) = s.new_art_transparency(); + (s.new_art(), opacity, blend, style.map(str::to_string)) + }; + let (before, was) = (s.paint.clone(), look(s)); + if let Some(f) = fill { + s.paint.fill = f; + } + if let Some(st) = stroke { + if !st.is_none() && s.paint.stroke.is_none() && s.paint.stroke_width == 0.0 { + s.paint.stroke_width = 1.0; + } + s.paint.stroke = st; + } + if let Some(w) = change.weight { + s.paint.stroke_width = w; + } + if !change.is_empty() + && let Some(st) = s.new_art_stroke_mut() + { + change.apply(st); + } + if let Some(on) = fill_overprint { + let t = s.new_art_template_mut(); + if t.fill().is_none() { + t.items.insert(0, AppearanceItem::Fill(FillLayer::new(Paint::None))); + } + if let Some(f) = t.fill_mut() { + f.overprint = on; + } + } + if let Some(on) = stroke_overprint + && let Some(st) = s.new_art_stroke_mut() + { + st.overprint = on; + } + let changed = look(s) != was; + if !changed { + s.paint = before; + } + Ok(json!({ "changed": changed })) +} + /// `t` reduced to a basic appearance: an empty fill under its top stroke (options kept, without /// its own transparency or effects). fn basic_of(t: &Appearance) -> Appearance { diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 0b92e37191..21f3661c89 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -180,8 +180,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, - /// Rows of a grid by column, in place of `columns` when more than 0. - #[serde(skip_serializing_if = "is_zero")] + /// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a + /// saved or Recent preset's larger value is read as `MAX_ARTBOARDS`). + #[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")] pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). @@ -380,12 +381,25 @@ impl DocSettings { return Ok(()); } let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; - let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32); for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, - "columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?, - "rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?, + "columns" => { + self.columns = v + .as_f64() + .filter(|c| c.is_finite() && *c >= 1.0) + .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? + .round() + .min(MAX_ARTBOARDS as f64) as u32 + } + "rows" => { + self.rows = v + .as_f64() + .map(f64::round) + .filter(|r| (1.0..=MAX_ARTBOARDS as f64).contains(r)) + .map(|r| r as u32) + .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be from 1 to {MAX_ARTBOARDS}")))? + } "spacing" => { self.spacing = v .as_f64() @@ -590,6 +604,12 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { + Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS)) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index bd6609e2f8..a6f85d0c46 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -77,7 +77,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/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..783f971487 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -104,6 +104,7 @@ pub(super) const ALLOWED: &[&str] = &[ "appearance.removeItem", "appearance.setActiveItem", "appearance.setItem", + "appearance.setNewArt", "appearance.showAllHidden", "appearance.targetContents", "appearance.transfer", diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a5bcbe015f..facf010415 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -111,6 +111,13 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec, items: RefCell>, + /// The last list of each document's paths ([`paths`]), kept while that document is unchanged. + paths: RefCell>, + /// A path and its subpaths with the point changes the run has made to it and not written yet + /// ([`flush`]). + pending: RefCell)>>, + /// The index of the first point of each subpath of the path whose points the run read last, + /// and what they were counted from ([`paths`]). + point_starts: RefCell>)>>, + /// How many times the points the run read of each path went stale, by document uid and path id + /// ([`paths`]). + point_cuts: RefCell>, + /// Each path whose points the run read, as the run last saw it, by document uid and then path + /// id ([`paths`]). + point_nodes: RefCell>>>, + /// The path whose points the object model is writing with `path.setAnchors`, the only path + /// that command changes ([`paths`]). + one_path: Cell>, + /// Each document, by uid, as it was when the run last looked at all the paths in it whose + /// points it read ([`paths`]). + point_docs: RefCell>>, + /// The item the object model is changing ([`edit_item`]), whose points stay valid through the + /// change. + editing: Cell>, locked: RefCell>, saving: Cell, text: text::TextState, @@ -223,6 +254,24 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); +/// The most documents whose lists [`State`] keeps at once, the least recently listed going first. +const KEPT_LISTS: usize = 8; + +/// The list kept in `lists` for the document `st`, while that document is unchanged. +fn kept_list(lists: &RefCell>, st: &DocState) -> Option>> { + lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone()) +} + +/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had. +fn keep_list(lists: &RefCell>, st: &DocState, ids: &Rc>) { + let mut l = lists.borrow_mut(); + l.retain(|(uid, ..)| *uid != st.uid); + if l.len() >= KEPT_LISTS { + l.remove(0); + } + l.push((st.uid, st.doc.clone(), ids.clone())); +} + /// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for /// each object of a layer or sublayer asked about then, whether it was on a locked artboard. type LockedList = (u64, Arc, Arc>, HashMap); @@ -279,15 +328,40 @@ type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. type Member = fn(&Host, &[Data]) -> Answer; +/// A member function that first writes the point changes waiting in [`State`] ([`flush`]). fn function(link: &Link, f: Member) -> HostFunction { + call(link, f, true) +} + +/// A member function of the points of a path, which reads and adds to the point changes waiting in +/// [`State`] instead of writing them first. +fn point_function(link: &Link, f: Member) -> HostFunction { + call(link, f, false) +} + +fn call(link: &Link, f: Member, flushing: bool) -> HostFunction { let l = link.clone(); Rc::new(move |a: Vec| { let h = current(&l)?; h.charge_call(16 + a.iter().map(data_size).sum::())?; + if flushing { + flush(&h)?; + } f(&h, &a) }) } +/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]). +pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { + paths::flush(h) +} + +/// Notes the changes a command made to the points of the paths the run has read +/// ([`paths::see_all_points`]). +pub(super) fn see_points(h: &Host) { + paths::see_all_points(h) +} + fn get(link: &Link, f: Member) -> HostMember { HostMember::Get(function(link, f)) } @@ -300,6 +374,19 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]). +fn point_get(link: &Link, f: Member) -> HostMember { + HostMember::Get(point_function(link, f)) +} + +fn point_property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: point_function(link, g), set: point_function(link, s) } +} + +fn point_method(link: &Link, f: Member) -> HostMember { + HostMember::Method(point_function(link, f)) +} + /// A member of a class with what `reflect` tells of it. pub(super) type Described = (String, HostMember, MemberInfo); @@ -315,8 +402,9 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is -/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out. +/// the check that a document, page item, path point or text range `this` is still there. +/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and +/// `reflect` leaves it out. pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -327,9 +415,12 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" | "TextFrame" => { + "PageItem" | "PathItem" | "TextFrame" => { item_of(&h, arg(&a, 0))?; } + "PathPoint" => { + paths::this_point(&h, &a)?; + } "TextRange" => { text::check_range(&h, arg(&a, 0))?; } @@ -656,6 +747,12 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - return Ok(()); } let partial = |id: &NodeId| before.anchors.contains_key(id) || before.segments.contains_key(id); + // Anchors and segments the change removed (a path opened or given fewer points) are left out. + let left = |id: &NodeId, p: usize, test: &dyn Fn(&vectorcraft_geom::path::SubPath) -> bool| { + doc.node(*id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(test)) + }; + let anchor_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| k < sp.anchors.len()); + let segment_left = |id: &NodeId, p: usize, k: usize| left(id, p, &|sp| sp.has_segment(k, true)); let kept: Vec = before.objects.iter().copied().filter(keep).collect(); if kept.is_empty() { command(h, "select.none", &json!({}))?; @@ -668,7 +765,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - .iter() .map(|i| { let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { - Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + Some(a) => a.iter().filter(|(p, k)| anchor_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(), // A path with only segments selected gets them back below, with no anchors. None if before.segments.contains_key(i) => Vec::new(), None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), @@ -679,7 +776,10 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - command(h, "select.anchorsMany", &json!({"items": items, "mode": "set"}))?; } for (i, segments) in before.segments.iter().filter(|(i, _)| keep(i)) { - let segments: Vec<[usize; 2]> = segments.iter().map(|(p, k)| [*p, *k]).collect(); + let segments: Vec<[usize; 2]> = segments.iter().filter(|(p, k)| segment_left(i, *p, *k)).map(|(p, k)| [*p, *k]).collect(); + if segments.is_empty() { + continue; + } command(h, "select.segments", &json!({"id": i.0, "segments": segments, "mode": "add"}))?; } let guides: Vec = doc.ruler_guides().into_iter().filter_map(|g| g.id).collect(); @@ -799,9 +899,15 @@ pub(super) fn after_kept_command(h: &Host) { text::styles::after_command(h); } -/// Runs `id` with `params` on the item's document, its selection kept. +/// Runs `id` with `params` on the item's document, its selection kept, as one change: when the +/// selection cannot be put back, the edit is undone too. The points the run read of the item's +/// paths stay valid through the change ([`paths::see_all_points`]). fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { - on_doc(h, item.doc.uid, true, |h| command(h, id, params)) + paths::see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params))); + h.dom.editing.set(kept); + r } /// Reads the document of `doc` with `f`. @@ -1208,6 +1314,22 @@ fn startup_preset(name: &str) -> Option<(Option<&'static str>, Option<&'static s }) } +/// The `file.newPresets` fields `addDocument` gives `file.new`: those of the profile's first +/// built-in preset with `presetSettings` over them. +const BUILT_IN_SETTINGS: &[&str] = &[ + "width", + "height", + "units", + "artboards", + "artboardLayout", + "bleed", + "backgroundContents", + "colorMode", + "rasterEffectsPpi", + "previewMode", + "alignNewObjectsToPixelGrid", +]; + /// `documents.addDocument(startupPreset, presetSettings?, showOptionsDialog?)`: a new document from /// the New Document profile `startupPreset` names, with the settings `presetSettings` gives in /// place of the profile's. @@ -1254,15 +1376,25 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { Some(Data::Bool(true)) => return Err(HostError::Error(DIALOG_UNAVAILABLE.into())), Some(_) => return Err(HostError::Type("showOptionsDialog must be true or false".into())), } - // The document starts from the first preset of the profile's category (Print: Letter). - let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); - if let Some(first) = first { - p.insert("preset".into(), json!(first.name)); - } - p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); if let Some(m) = mode { p.entry("colorMode").or_insert_with(|| json!(m)); } + // The document starts from the first built-in preset of the profile's category (Print: + // Letter) with `presetSettings` over it, given in full so that a saved preset of the same name + // does not stand in for it. Settings the built-in preset refuses are an error. + let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + if let Some(first) = first { + p.insert("preset".into(), json!(first.name)); + let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?; + if let Value::Object(settings) = full.to_json() { + for key in BUILT_IN_SETTINGS { + if let Some(v) = settings.get(*key) { + p.insert((*key).into(), v.clone()); + } + } + } + } + p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); // A profile whose file could not be read throws, and the document `file.new` made with the // defaults is put back, with the Recent sizes as they were. atomically(h, |h| { @@ -2681,6 +2813,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect(); realm.define_host_object("BlendModes", blend_modes)?; variables::define_enums(realm)?; + paths::install_enums(realm)?; realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?; let l = link; // The application's members a script may name without `app.`, assigned as `app.` is. @@ -2778,17 +2911,17 @@ fn classes(link: &Link) -> Vec { returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), ), ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("pathItems", get(l, paths::doc_path_items), MemberInfo { collection: true, ..typed("PathItems") }), ("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }), ("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }), ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); + document.extend(defaults::document_members(l)); document.extend(text::styles::doc_members(l)); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"] - .into_iter() - .map(|m| later(l, "Document", m)), + ["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)), ); document.extend(variables::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); @@ -2889,7 +3022,15 @@ fn classes(link: &Link) -> Vec { ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| { + let mut members = variables::item_members(l, c); + if *c == "PathItem" { + members.extend(paths::path_item_members(l)); + } + class(c, Some("PageItem"), members, None) + })); + classes.extend(paths::classes(l)); + classes.extend(colors::classes(l)); classes.extend(text::classes(l)); classes.extend(variables::classes(l)); classes.push(class( diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs new file mode 100644 index 0000000000..b9f0bb3a30 --- /dev/null +++ b/crates/engine/src/script/dom/colors.rs @@ -0,0 +1,189 @@ +//! 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: `exact` rounded to the fewest decimals, from 4 to 9, that +/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read +/// from an object gives that object the same color. +fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 { + let mut scale = 1e4; + for _ in 4..=9 { + let r = (exact * scale).round() / scale; + if back(r) == v { + return r; + } + scale *= 10.0; + } + exact +} + +/// A component stored as `v`, from 0 to 1, that the script sees times `scale`. +fn shown(v: f32, scale: f64) -> f64 { + shown_as(f64::from(v) * scale, v, |r| unit(r, scale)) +} + +/// 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_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 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", &[]), + } +} + +/// Whether assigning the color object `d`, read as `assigned`, leaves the paint `now` as it is: a +/// `NoColor` on no paint, or on an unlinked color either a color equal to it once `store` makes +/// it what the document stores, or the components reading `now` gives (a Gray value read back can +/// stand for an ink amount that no Gray value names exactly). +pub(super) fn unchanged(d: &Data, assigned: Option, now: &Paint, store: impl FnOnce(Color) -> Color) -> bool { + match (assigned, now) { + (None, Paint::None) => true, + (Some(c), Paint::Solid { color, swatch: None, .. }) => store(c) == *color || shows(d, &of_color(color)), + _ => false, + } +} + +/// Whether the color object `d` has the class and every component of `shown`. +fn shows(d: &Data, shown: &Data) -> bool { + let (Data::Object(a), Data::Object(b)) = (d, shown) else { return false }; + b.iter().all(|(k, v)| a.iter().any(|(n, w)| n == k && w == v)) +} + +/// 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(), + info: Vec::new(), + index: None, + construct: Some(make(name, components)), + }) + .collect(); + out.push(HostClass { + name: "cmykColor".into(), + parent: None, + members: Vec::new(), + info: Vec::new(), + index: None, + construct: Some(make("CMYKColor", CLASSES[1].1)), + }); + out +} diff --git a/crates/engine/src/script/dom/defaults.rs b/crates/engine/src/script/dom/defaults.rs new file mode 100644 index 0000000000..9080d30dd7 --- /dev/null +++ b/crates/engine/src/script/dom/defaults.rs @@ -0,0 +1,211 @@ +//! A document's default fill and stroke in the script object model, the `Document` members whose +//! names start with `default` that the help page +//! describes, and `scaleFactor`. +//! +//! The defaults are what the next object drawn gets ([`crate::Session::new_art`]), the same for +//! every open document, as the help page says of these global settings. Reading one reads new +//! art's top fill or stroke, and assigning one runs `appearance.setNewArt`, which leaves the +//! selection, its art, the active proxy and the recent colors as they were. A value that changes +//! nothing runs no command, and a bad value throws an error with nothing changed. +//! +//! VectorCraft's own rules, which the help page does not state: +//! - A color is new art's fill or stroke itself: assigning a color also makes `defaultFilled` or +//! `defaultStroked` true, and assigning a `NoColor` makes it false. `defaultFilled` or +//! `defaultStroked` set to true with no default fill or stroke gives black. +//! - An RGB color is stored in the color mode of the document in front, as `paint.setFill` stores +//! it. +//! - `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 to 1,000,000 points (at most 64 of +//! them, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which needs a +//! dash pattern unless it is 0. +//! - While New Art Has Basic Appearance is off and an object is selected, assigning a default +//! throws an error, since new art then takes that object's appearance. +//! - `scaleFactor` is 1: VectorCraft draws every document at its own size. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, LineCap, LineJoin}; +use vectorcraft_js::{Data, HostError, MemberInfo}; + +use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths}; +use super::{Answer, Described, Host, Link, arg, boolean, colors, command, get, named, num, number, property, this_doc, typed}; + +/// New art's appearance, after the check that the document `this` names is still open. +fn new_art(h: &Host, a: &[Data]) -> std::result::Result { + this_doc(h, a)?; + Ok(h.session.borrow().new_art()) +} + +/// Runs `appearance.setNewArt` with `params`, unless `same`. +fn set(h: &Host, same: bool, params: Value) -> Answer { + if !same { + command(h, "appearance.setNewArt", ¶ms)?; + } + Ok(Data::Undefined) +} + +fn top_paint(ap: &Appearance, fill: bool) -> Paint { + if fill { ap.fill_paint() } else { ap.stroke_paint() } +} + +fn default_color(h: &Host, a: &[Data], fill: bool) -> Answer { + Ok(colors::of_paint(&top_paint(&new_art(h, a)?, fill))) +} + +fn set_default_color(h: &Host, a: &[Data], fill: bool) -> Answer { + let what = if fill { "defaultFillColor" } else { "defaultStrokeColor" }; + let color = colors::assigned(arg(a, 1), what)?; + let now = top_paint(&new_art(h, a)?, fill); + let same = colors::unchanged(arg(a, 1), color, &now, |c| crate::cmd::newart::stored_color(&h.session.borrow(), c)); + let paint = match color { + Some(c) => json!({"color": colors::param(&c)}), + None => json!({"none": true}), + }; + let key = if fill { "fill" } else { "stroke" }; + set(h, same, json!({ key: paint })) +} + +fn default_painted(h: &Host, a: &[Data], fill: bool) -> Answer { + Ok(Data::Bool(!top_paint(&new_art(h, a)?, fill).is_none())) +} + +fn set_default_painted(h: &Host, a: &[Data], fill: bool) -> Answer { + let on = boolean(arg(a, 1), if fill { "defaultFilled" } else { "defaultStroked" })?; + let now = !top_paint(&new_art(h, a)?, fill).is_none(); + let paint = if on { json!({"color": colors::param(&Color::BLACK)}) } else { json!({"none": true}) }; + let key = if fill { "fill" } else { "stroke" }; + set(h, now == on, json!({ key: paint })) +} + +fn default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer { + let ap = new_art(h, a)?; + Ok(Data::Bool(if fill { ap.fill().is_some_and(|f| f.overprint) } else { ap.stroke().is_some_and(|s| s.overprint) })) +} + +fn set_default_overprint(h: &Host, a: &[Data], fill: bool) -> Answer { + let (key, what) = if fill { ("fillOverprint", "defaultFillOverprint") } else { ("strokeOverprint", "defaultStrokeOverprint") }; + let on = boolean(arg(a, 1), what)?; + let now = default_overprint(h, a, fill)? == Data::Bool(on); + set(h, now, json!({ key: on })) +} + +/// New art's top stroke option `f` reads, or `none` when new art has no stroke. +fn stroke_option(h: &Host, a: &[Data], none: T, f: impl FnOnce(&vectorcraft_doc::StrokeLayer) -> T) -> std::result::Result { + Ok(new_art(h, a)?.stroke().map_or(none, f)) +} + +fn default_stroke_width(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(num(h.session.borrow().paint.stroke_width)) +} + +fn set_default_stroke_width(h: &Host, a: &[Data]) -> Answer { + let w = number(arg(a, 1), "defaultStrokeWidth")?; + if !(0.0..=MAX_STROKE_WIDTH).contains(&w) { + return Err(HostError::Range("defaultStrokeWidth must be from 0 to 1000 points".into())); + } + this_doc(h, a)?; + let now = h.session.borrow().paint.stroke_width; + set(h, now == w, json!({"weight": w})) +} + +fn default_cap(h: &Host, a: &[Data]) -> Answer { + let cap = stroke_option(h, a, LineCap::default(), |s| s.cap)?; + Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into())) +} + +fn set_default_cap(h: &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("defaultStrokeCap must be a StrokeCap value".into())) }; + let now = stroke_option(h, a, LineCap::default(), |s| s.cap)?; + set(h, now == cap, json!({"cap": name})) +} + +fn default_join(h: &Host, a: &[Data]) -> Answer { + let join = stroke_option(h, a, LineJoin::default(), |s| s.join)?; + Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into())) +} + +fn set_default_join(h: &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("defaultStrokeJoin must be a StrokeJoin value".into())) }; + let now = stroke_option(h, a, LineJoin::default(), |s| s.join)?; + set(h, now == join, json!({"join": name})) +} + +fn default_miter(h: &Host, a: &[Data]) -> Answer { + Ok(num(stroke_option(h, a, 10.0, |s| s.miter_limit)?)) +} + +fn set_default_miter(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "defaultStrokeMiterLimit")?; + if !(1.0..=500.0).contains(&v) { + return Err(HostError::Range("defaultStrokeMiterLimit must be from 1 to 500".into())); + } + let now = stroke_option(h, a, 10.0, |s| s.miter_limit)?; + set(h, now == v, json!({"miterLimit": v})) +} + +fn dashes(h: &Host, a: &[Data]) -> std::result::Result, HostError> { + stroke_option(h, a, Vec::new(), |s| s.dash.as_ref().map_or_else(Vec::new, |d| d.pattern.clone())) +} + +fn default_dashes(h: &Host, a: &[Data]) -> Answer { + Ok(Data::Array(dashes(h, a)?.into_iter().map(num).collect())) +} + +fn set_default_dashes(h: &Host, a: &[Data]) -> Answer { + let lengths = dash_lengths(arg(a, 1), "defaultStrokeDashes")?; + let now = dashes(h, a)?; + let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) }; + set(h, now == lengths, json!({"dash": dash})) +} + +fn default_dash_offset(h: &Host, a: &[Data]) -> Answer { + Ok(num(stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?)) +} + +fn set_default_dash_offset(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "defaultStrokeDashOffset")?; + if v.abs() > MAX_STROKE_WIDTH * 1000.0 { + return Err(HostError::Range("defaultStrokeDashOffset must be from -1000000 to 1000000 points".into())); + } + if dashes(h, a)?.is_empty() && v != 0.0 { + return Err(HostError::Error("defaultStrokeDashOffset needs defaultStrokeDashes first".into())); + } + let now = stroke_option(h, a, 0.0, |s| s.dash.as_ref().map_or(0.0, |d| d.offset))?; + set(h, now == v, json!({"dashOffset": v})) +} + +fn scale_factor(h: &Host, a: &[Data]) -> Answer { + this_doc(h, a)?; + Ok(num(1.0)) +} + +/// The `Document` members of this module. +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true)), typed("Color")), + ("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true)), typed("boolean")), + ("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true)), typed("boolean")), + ("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false)), typed("Color")), + ("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false)), typed("boolean")), + ("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false)), typed("boolean")), + ( + "defaultStrokeWidth", + property(l, default_stroke_width, set_default_stroke_width), + MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") }, + ), + ("defaultStrokeCap", property(l, default_cap, set_default_cap), typed("StrokeCap")), + ("defaultStrokeJoin", property(l, default_join, set_default_join), typed("StrokeJoin")), + ("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter), typed("number")), + ("defaultStrokeDashes", property(l, default_dashes, set_default_dashes), typed("Array")), + ("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset), typed("number")), + ("scaleFactor", get(l, scale_factor), typed("number")), + ]) +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs new file mode 100644 index 0000000000..27b449a5b9 --- /dev/null +++ b/crates/engine/src/script/dom/paths.rs @@ -0,0 +1,1879 @@ +//! 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 inside the run's one undo step, and a change that changes nothing +//! runs no command. Changes to the points of one path wait in the run's [`super::State`] and are +//! written together with one `path.setAnchors` ([`flush`]) before any other member, command or +//! path's points are read or changed, and when the script ends. +//! +//! 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, and a gradient that `filled = true` gives it is placed on that +//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and +//! the recent colors as they were. `fillOverprint` and `strokeOverprint` read and change the top +//! fill or stroke only. +//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes +//! them all. +//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever +//! the drawing mode, painted as new art is; `add()` makes a path with no points. `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`, and so does a +//! point read before the run removed a point of its path or replaced its points +//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`), or before anything other +//! than the object model changed the path's points (a command run with `vc.run`, such as +//! `path.setAnchors`, `object.move` or `edit.undo`). Points stay valid through the object +//! model's other changes to the path or to an object that holds it, such as `translate()`. +//! - 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`. A transform that leaves the path where it is (`rotate(360)`, +//! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too. +//! - `PathPoint.selected` and `selectedPathPoints` count every point of a path selected as a whole +//! as a selected anchor point, and not the endpoints of selected segments; a path in a selected +//! group or compound path is selected as a whole. Direction handles are not selected on their +//! own, so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they +//! are not available yet, and so does `NOSELECTION` on a point of a path in a selected group or +//! compound path. Selecting a point of a path with selected segments replaces that path's +//! segment selection. Selecting a point of a guide while guides are locked throws an error. A +//! clipping path cannot be made a guide. Assigning `guides` a value the path does not have +//! throws an error that says it is not available yet on a path inside a compound path, throws +//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides +//! are locked; assigning the value the path has runs no command. +//! - 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 std::sync::Arc; + +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, MemberInfo, Realm, RunError, host_ref}; +use vectorcraft_tools::params::gradient_params; + +use super::{ + Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, 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, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, +}; +use crate::{DocState, NodeId, NodeKind}; + +/// The error of a point whose index is past the end of its path, or that was read before the run +/// removed or replaced points 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 s = h.session.borrow(); + match s.documents().iter().find(|d| d.uid == item.doc.uid) { + Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)), + None => Data::Null, + } +} + +/// The index of the first point of each subpath of `subs`, followed by the number of points. +fn starts(subs: &[SubPath]) -> Vec { + let mut out = Vec::with_capacity(subs.len() + 1); + let mut n = 0; + for sp in subs { + out.push(n); + n += sp.anchors.len(); + } + out.push(n); + out +} + +/// The subpath and the place in it of point `i`, given the [`starts`] of a path's subpaths. +fn locate_at(starts: &[usize], i: usize) -> Option<(usize, usize)> { + if i >= *starts.last()? { + return None; + } + let s = starts.partition_point(|first| *first <= i).checked_sub(1)?; + Some((s, i - starts.get(s)?)) +} + +/// What the [`starts`] that [`super::State`] keeps were counted from: a path's node as its document +/// holds it, by document uid, or the waiting point changes of a path ([`edit_points`]). +pub(super) enum Counted { + Node(u64, Arc), + Waiting(Item), +} + +/// The [`starts`] of the path of `item`, its waiting point changes included. They are kept while +/// the path's node is the same one, or until the waiting changes add or remove points. +fn point_starts(h: &super::Host, item: Item) -> std::result::Result>, HostError> { + let waiting = matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)); + if waiting { + if let Some((Counted::Waiting(k), kept)) = &*h.dom.point_starts.borrow() + && same_path(*k, item) + { + return Ok(kept.clone()); + } + let counted = Rc::new(read_points(h, item, starts)?); + *h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted.clone())); + return Ok(counted); + } + let node = with_doc(h, item.doc, |_, st| node_arc(&st.doc, item.id).cloned()).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if let Some((Counted::Node(uid, kept_node), kept)) = &*h.dom.point_starts.borrow() + && *uid == item.doc.uid + && Arc::ptr_eq(kept_node, &node) + { + return Ok(kept.clone()); + } + let counted = Rc::new(starts(&node.path_data().ok_or_else(|| HostError::Type("this is not a PathItem".into()))?.subpaths)); + *h.dom.point_starts.borrow_mut() = Some((Counted::Node(item.doc.uid, node), counted.clone())); + Ok(counted) +} + +/// How many points the path of `item` has, its waiting point changes included ([`point_starts`]). +fn points_of(h: &super::Host, item: Item) -> std::result::Result { + Ok(point_starts(h, item)?.last().copied().unwrap_or(0)) +} + +/// The subpath and the place in it of point `i`, among the subpaths `subs`. +fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { + for (s, sp) in subs.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}) +} + +fn same_path(a: Item, b: Item) -> bool { + a.doc.uid == b.doc.uid && a.id == b.id +} + +/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. +fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result { + if let Some((waiting, subs)) = &*h.dom.pending.borrow() + && same_path(*waiting, item) + { + return Ok(f(subs)); + } + read_path(h, item, |_, _, pd| f(&pd.subpaths)) +} + +/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with +/// the path's other point changes until [`flush`] writes them. The first change of a path writes +/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or +/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// that is, is written at once, so that its points read as the grid snaps them. +fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { + forget_waiting_starts(h); + if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() + && same_path(*waiting, item) + { + return Ok(f(subs)); + } + flush(h)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let r = f(&mut subs); + let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let d = &st.doc; + let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); + (pd.subpaths == subs, editable(d, item.id), aligned) + })?; + if !same { + if !ok { + return Err(cannot_edit(item.id)); + } + *h.dom.pending.borrow_mut() = Some((item, subs)); + if aligned { + flush(h)?; + } + } + Ok(r) +} + +/// Drops the [`starts`] that [`super::State`] keeps of waiting point changes, which a change can +/// make wrong. +fn forget_waiting_starts(h: &super::Host) { + let mut kept = h.dom.point_starts.borrow_mut(); + if matches!(&*kept, Some((Counted::Waiting(_), _))) { + *kept = None; + } +} + +/// Changes the anchor at index `i` of the path of `item` with `f` ([`edit_points`]). The change +/// adds and removes no points, so the [`starts`] of the path stay kept. +fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> { + let counted = point_starts(h, item)?; + let at = locate_at(&counted, i); + edit_points(h, item, |subs| { + if let Some((s, j)) = at + && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) + { + f(an); + } + })?; + if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) { + *h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted)); + } + Ok(()) +} + +/// Gives the path of `item` the subpaths `subs` ([`edit_points`]). +fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { + edit_points(h, item, |s| *s = subs) +} + +/// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless +/// the path has those points already. +pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { + let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) }; + forget_waiting_starts(h); + let same = { + let s = h.session.borrow(); + let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id)); + node.and_then(|n| n.path_data()).map(|pd| pd.subpaths == subs) + }; + match same { + Some(true) => return Ok(()), + Some(false) => {} + None => return Err(HostError::Error(STALE_ITEM.into())), + } + let subpaths: Vec = + subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); + // Changes made before this one are looked at in full first. + see_all_points(h); + let kept = h.dom.one_path.replace(Some(item)); + let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})); + h.dom.one_path.set(kept); + r?; + Ok(()) +} + +/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape +/// when it is a member of one, since the paint commands paint that owner in its place. +fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { + d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) +} + +/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active +/// layer, then puts the drawing mode back. +fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { + let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); + let r = f(); + h.session.borrow_mut().draw_mode = kept; + r +} + +/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) 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.entry("ids").or_insert_with(|| 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(ids) = super::kept_list(&h.dom.paths, st) { + return ids; + } + 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()); + super::keep_list(&h.dom.paths, st, &ids); + 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") +} + +/// `typename` of the paths of a document that is still open. +fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(Data::String("PathItems".into())) +} + +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, read from the command's own result so +/// that an id above 2^53 stays exact. +fn made_id(r: &Value) -> std::result::Result { + r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +} + +/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, +/// and reverses the new path's direction when `reversed`. → the new path. Selecting the new path +/// and putting the selection back load the selected objects' paint and stroke width into new art, +/// so new art's paint from before, the defaults a script set included, is put back. +fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { + let made = keeping_paint(h, || { + on_doc(h, doc.uid, true, |h| { + let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?; + 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 on top of the active layer, 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, and new art keeps the paint it had before. +fn items_add(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + // New art's paint is read with the document active, since activating a document can load its + // selection's appearance into new art. Selecting the new path loads its temporary stroke into + // new art, and putting the selection back does not undo that, so new art's paint from before + // the path is put back. + let made = keeping_paint(h, || { + 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(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?; + if unpainted { + 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_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.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)?; + edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + 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, .. }))) +} + +/// The error of assigning `guides` on a path inside a compound path. +pub const COMPOUND_MEMBER_GUIDES: &str = "Changing guides on a path inside a compound path is not available yet"; + +/// `guides = true` makes the path a guide with `view.guides.make`, and `false` makes it a path again +/// with `view.guides.release`; the selection stays as it was. A value the path has already runs no +/// command and throws no error. Otherwise a clipping path cannot be a guide, a path inside a +/// compound path throws [`COMPOUND_MEMBER_GUIDES`], and while guides are locked both values throw +/// an error. +fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "guides")?; + let item = this_path(h, a)?; + let (now, clipping) = read_path(h, item, |_, n, _| match &n.kind { + NodeKind::Path { guide, clipping, .. } => (*guide, *clipping), + _ => (false, false), + })?; + if now == on { + return Ok(Data::Undefined); + } + let (member, editable, selectable) = with_doc(h, item.doc, |_, st| { + let member = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); + (member, editable(&st.doc, item.id), selectable) + }); + if member { + return Err(HostError::Error(COMPOUND_MEMBER_GUIDES.into())); + } + if !editable || !selectable { + return Err(cannot_edit(item.id)); + } + if h.session.borrow().menu.guides_locked { + return Err(HostError::Error(format!("Cannot change guides on PathItem {}: guides are locked", item.id.0))); + } + if !on { + edit_path(h, item, "view.guides.release", json!({}))?; + return Ok(Data::Undefined); + } + if clipping { + return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0))); + } + see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + command(h, "view.guides.make", &json!({})) + }); + h.dom.editing.set(kept); + r?; + Ok(Data::Undefined) +} + +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 = with_doc(h, item.doc, |_, st| frame(st))?; + let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; + let c = h.dom.coords.get(); + let anchors: Vec = + script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; + let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + write_path(h, item, subs)?; + cut_points(h, item); + 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 ap = &paint_owner(&st.doc, item.id, n).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 bounds of the path or of the compound path or +/// compound shape whose paint it shows, 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, |st, n, _| paint_owner(&st.doc, item.id, 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 }; + if !colors::unchanged(arg(a, 1), color, now, |c| c) { + 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})) +} + +/// Each stroke cap, its `StrokeCap` value and its name in `stroke.set`. +pub(super) const CAPS: &[(LineCap, &str, &str)] = &[ + (LineCap::Butt, "StrokeCap.BUTTENDCAP", "butt"), + (LineCap::Round, "StrokeCap.ROUNDENDCAP", "round"), + (LineCap::Square, "StrokeCap.PROJECTINGENDCAP", "square"), +]; + +/// Each stroke join, its `StrokeJoin` value and its name in `stroke.set`. +pub(super) 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())) +} + +/// The dash and gap lengths a script assigned to `what`: at most [`MAX_DASHES`] finite lengths +/// that are not negative and not all 0; `[]` or `{}` gives a solid line. +pub(super) fn dash_lengths(d: &Data, what: &str) -> std::result::Result, HostError> { + let lengths: Vec = match d { + Data::Object(o) if o.is_empty() => Vec::new(), + Data::Array(list) if list.len() > MAX_DASHES => return Err(HostError::Range(format!("{what} takes at most {MAX_DASHES} lengths"))), + Data::Array(list) => list.iter().map(|d| number(d, "each dash length")).collect::>()?, + _ => return Err(HostError::Type(format!("{what} must be an array of lengths"))), + }; + use crate::cmd::newart::DashFault; + match crate::cmd::newart::dash_fault(&lengths) { + None => Ok(lengths), + Some(DashFault::TooMany) => Err(HostError::Range(format!("{what} takes at most {MAX_DASHES} lengths"))), + Some(DashFault::OutOfRange) => Err(HostError::Range("each dash length must be from 0 to 1000000 points".into())), + Some(DashFault::AllZero) => Err(HostError::Range(format!("{what} needs a length that is not 0"))), + } +} + +/// `strokeDashes = [lengths]`, as [`dash_lengths`] takes them. +fn path_set_dashes(h: &super::Host, a: &[Data]) -> Answer { + let lengths = dash_lengths(arg(a, 1), "strokeDashes")?; + 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 { + // The top fill or stroke of the object `look` reads, as `item` names it to the command. + let top = read_path(h, item, |st, n, _| { + let owner = paint_owner(&st.doc, item.id, n); + owner.appearance.items.iter().rposition(|i| i.is_fill() == fill).map(|index| (owner.id, index)) + })?; + let (Some((owner, index)), false) = (top, paint.is_none()) else { + return Err(HostError::Error(format!("the path has no {key} to overprint"))); + }; + edit_path(h, item, "object.setOverprint", json!({key: on, "item": index, "ids": [owner.0]}))?; + } + 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 member of `Transformation` that `d` names (left out: `CENTER`). +fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> { + let name = match d { + Data::Undefined => "Transformation.CENTER", + Data::String(s) => s.as_str(), + _ => return Err(HostError::Type("give a Transformation value".into())), + }; + let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m); + let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m)); + member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into())) +} + +/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation` +/// member `name` ([`about_name`]) names. +fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result { + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + Ok(match name { + "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 place = about_name(arg(a, 6))?; + let mut params = json!({"angle": angle}); + transform_options(a, 2, &mut params)?; + if angle.rem_euclid(360.0) != 0.0 + && let (Some(r), _) = item_rect(h, item, false)? + { + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + 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 place = about_name(arg(a, 8))?; + let mut params = json!({"sx": sx, "sy": sy, "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) + && let (Some(r), _) = item_rect(h, item, false)? + { + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + 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) +} + +/// `typename` of the points of a path that is still in its document. +fn points_typename(h: &super::Host, a: &[Data]) -> Answer { + points_path(h, a)?; + Ok(Data::String("PathPoints".into())) +} + +fn points_length(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + Ok(num(float(points_of(h, item)? 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), float(point_cuts(h, item))]) +} + +/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change +/// made to them since the run last saw them. +fn point_cuts(h: &super::Host, item: Item) -> u64 { + let key = (item.doc.uid, item.id.0); + see_points(h, key, || false); + h.dom.point_cuts.borrow().get(&key).copied().unwrap_or(0) +} + +/// Notes that the run removed or replaced points of `item`, which makes the points read before +/// stale. +fn cut_points(h: &super::Host, item: Item) { + cut_key(h, (item.doc.uid, item.id.0)); +} + +/// [`cut_points`] for the path of document uid and path id `key`. +fn cut_key(h: &super::Host, key: (u64, u64)) { + let mut cuts = h.dom.point_cuts.borrow_mut(); + let n = cuts.entry(key).or_insert(0); + *n = n.saturating_add(1); +} + +#[cfg(test)] +thread_local! { + /// How many times this thread looked at a path's points ([`see_points`]), for the tests. + pub(crate) static POINT_LOOKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The node of `id` in `d`, as the document holds it. +fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { + let at = d.index_path(id)?; + let (first, rest) = at.split_first()?; + let mut cur = d.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur) +} + +/// Keeps the path of document uid and path id `key` as it is now, the first time the run reads its +/// points and after each later look. When its points differ from the ones the run last saw, the +/// points read before go stale, unless `own`: the object model made the change +/// ([`see_all_points`]), which `own` is asked only after a change. The kept node is shared with +/// the document, so a node whose pointer is unchanged has unchanged points, and any change to it +/// makes a new node. +fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { + #[cfg(test)] + POINT_LOOKS.with(|n| n.set(n.get() + 1)); + let node = { + let s = h.session.borrow(); + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + }; + // A path that is gone makes its points stale, so that an undo that brings it back leaves them + // stale. + let Some(node) = node else { + if h.dom.point_nodes.borrow_mut().get_mut(&key.0).and_then(|paths| paths.remove(&key.1)).is_some() { + cut_key(h, key); + } + return; + }; + let changed = match h.dom.point_nodes.borrow_mut().entry(key.0).or_default().insert(key.1, node.clone()) { + Some(old) => !Arc::ptr_eq(&old, &node) && old.path_data().map(|pd| &pd.subpaths) != node.path_data().map(|pd| &pd.subpaths), + None => false, + }; + if changed && !own() { + cut_key(h, key); + } +} + +/// [`see_points`] for each path whose points the run has read, after each command, so that a +/// change that a later command reverses still makes the points stale. Paths under the object that +/// the object model is changing ([`super::State`]), or that object itself, take the change as the +/// object model's own, and their points stay valid. A document that is the one the run last looked +/// at is skipped, as are its paths. While the object model writes one path's points +/// ([`super::State`]'s `one_path`), only that path is looked at in its document. +pub(super) fn see_all_points(h: &super::Host) { + let keys: Vec<(u64, u64)> = { + let seen = h.dom.point_nodes.borrow(); + if seen.values().all(|paths| paths.is_empty()) { + return; + } + let s = h.session.borrow(); + let mut docs = h.dom.point_docs.borrow_mut(); + let one = h.dom.one_path.get(); + let mut keys = Vec::new(); + // The documents that changed since the last look, kept as they are now. + for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) { + match s.documents().iter().find(|d| d.uid == *uid) { + Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue, + Some(st) => { + docs.insert(*uid, st.doc.clone()); + } + None => { + docs.remove(uid); + } + } + match one { + Some(item) if item.doc.uid == *uid => keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0))), + _ => keys.extend(paths.keys().map(|id| (*uid, *id))), + } + } + keys + }; + let editing = h.dom.editing.get(); + for (uid, id) in keys { + let own = || match editing { + Some(e) if e.doc.uid == uid => { + let s = h.session.borrow(); + let id = NodeId(id); + id == e.id || s.documents().iter().find(|d| d.uid == uid).and_then(|st| st.doc.ancestry(id)).is_some_and(|a| a.contains(&e.id)) + } + _ => false, + }; + see_points(h, (uid, id), own); + } +} + +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 = points_of(h, item)?; + 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 origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); + let mut counted = point_starts(h, item)?; + let n = counted.last().copied().unwrap_or(0); + if n >= MAX_POINTS { + return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); + } + let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?; + let p = match last { + Some(p) => p, + None => origin?, + }; + // The kept starts are dropped, so that `counted` is their only copy and grows in place. + *h.dom.point_starts.borrow_mut() = None; + edit_points(h, item, |subs| match subs.last_mut() { + Some(sp) => sp.anchors.push(Anchor::corner(p)), + None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), + })?; + if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) { + let grown = Rc::make_mut(&mut counted); + if grown.len() > 1 { + if let Some(total) = grown.last_mut() { + *total += 1; + } + } else { + *grown = vec![0, 1]; + } + *h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted)); + } + 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())?; + cut_points(h, item); + Ok(Data::Undefined) +} + +// ---- PathPoint ---- + +/// The path and the index of the point `this` names, which must still be in the path, with no +/// point of the path removed or replaced since `this` was read. +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, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low)?; + if whole(*cuts) != Some(point_cuts(h, item)) { + return Err(HostError::Error(STALE_POINT.into())); + } + let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + if i >= points_of(h, item)? { + 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(); + let fr = with_doc(h, item.doc, |_, st| frame(st))?; + let at = locate_at(&point_starts(h, item)?, i); + read_points(h, item, |subs| { + let anchor = at.and_then(|(s, j)| subs.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)?; + edit_anchor(h, item, i, f)?; + 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))?; + on_canvas(fr.to_document(h.dom.coords.get(), p), what) +} + +/// `p`, a point a script gave in document coordinates, when it is on the canvas (within +/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise. +fn on_canvas(p: Point, what: &str) -> std::result::Result { + if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { + Ok(p) + } else { + Err(HostError::Range(format!("{what} is outside the canvas"))) + } +} + +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)) +} + +/// `typename` of a point that is still on its path. +fn pt_typename(h: &super::Host, a: &[Data]) -> Answer { + this_point(h, a)?; + Ok(Data::String("PathPoint".into())) +} + +/// Whether a group or compound path that holds the path `id` is selected, which selects the path +/// as a whole whatever the path's own selection is. +fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool { + d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) +} + +/// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every +/// point of a path selected as a whole is (a path is when a group or compound path that holds it +/// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The +/// endpoints of selected segments are not. +fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool { + if held { + return true; + } + if !sel.contains(id) || sel.segments.contains_key(&id) { + return false; + } + match sel.partial(id) { + None => true, + Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + } +} + +/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a +/// point index names the same anchor in both. +fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len()) +} + +/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point +/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in +/// [`super::State`] are written first only when they add or remove points of this path, since +/// the selection names anchors by their place in the document's path. +fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { + let (item, i) = this_point(h, a)?; + let moved = match &*h.dom.pending.borrow() { + Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + _ => false, + }; + if moved { + super::flush(h)?; + } + let on = + read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?; + Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into())) +} + +/// The `PathPointSelection` values that select a point's direction handles. +const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPointSelection.RIGHTDIRECTION", "PathPointSelection.LEFTRIGHTPOINT"]; + +/// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and +/// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay +/// selected, except that selecting an anchor of a path with selected segments replaces that path's +/// segment selection, as `select.anchorsMany` does. A value the point has already runs no command. +/// Direction handles cannot be selected, so `LEFTDIRECTION`, `RIGHTDIRECTION` and +/// `LEFTRIGHTPOINT` throw an error, and so does `NOSELECTION` on a path selected through a group or +/// compound path that holds it, and `ANCHORPOINT` on a guide while guides are locked. The setter +/// writes the waiting point changes first, as every member that is not a point function does. +fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { + let on = match arg(a, 1) { + Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true, + Data::String(s) if s == "PathPointSelection.NOSELECTION" => false, + Data::String(s) if HANDLE_SELECTIONS.contains(&s.as_str()) => { + return Err(HostError::Error(format!("PathPoint.selected = {s} is not available yet: only anchor points can be selected"))); + } + _ => return Err(HostError::Type("selected must be a PathPointSelection value".into())), + }; + let (item, i) = this_point(h, a)?; + let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| { + let node = st.doc.node(item.id); + let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); + let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); + let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); + let held = held_selected(&st.doc, &st.selection, item.id); + (anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide) + }); + if now == on { + return Ok(Data::Undefined); + } + let Some((s, j)) = at else { return Err(HostError::Error(STALE_POINT.into())) }; + if held { + return Err(HostError::Error(format!( + "PathPoint.selected = PathPointSelection.NOSELECTION is not available yet on PathItem {}: the group or compound path that holds it is selected", + item.id.0 + ))); + } + if on && !selectable { + return Err(HostError::Error(format!("Cannot select PathItem {}", item.id.0))); + } + if on && guide && h.session.borrow().menu.guides_locked { + return Err(HostError::Error(format!("Cannot select PathItem {}: guides are locked", item.id.0))); + } + let params = json!({"items": [{"id": item.id.0, "anchors": [[s, j]]}], "mode": if on { "add" } else { "subtract" }}); + on_doc(h, item.doc.uid, false, |h| command(h, "select.anchorsMany", ¶ms))?; + Ok(Data::Undefined) +} + +/// `selectedPathPoints`: the points that are selected anchor points ([`anchor_selected`]), in the +/// order of `pathPoints`. +fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + let picked: Vec = read_path(h, item, |st, _, pd| { + let sel = &st.selection; + let held = held_selected(&st.doc, sel, item.id); + if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { + return Vec::new(); + } + let mut out = Vec::new(); + let mut first = 0; + for (s, sp) in pd.subpaths.iter().enumerate() { + let n = sp.anchors.len(); + out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); + first += n; + } + out + })?; + h.charge_call(picked.len() as u64)?; + let [high, low] = id_parts(item.id); + let cuts = float(point_cuts(h, item)); + let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + Ok(Data::Array(points)) +} + +/// `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)?; + // A direct selection of the path's points is renumbered after the removal. + let selected = { + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + let sel = &st.selection; + (sel.anchors.contains_key(&item.id) || sel.segments.contains_key(&item.id)).then(|| sel.clone()) + }; + let removed = edit_points(h, item, |subs| { + let (s, j) = locate(subs, i)?; + let sp = subs.get_mut(s)?; + // The segment that closes a closed subpath ends at its first anchor. + let closing = (sp.closed && j == 0).then(|| sp.anchors.len() - 1); + sp.anchors.remove(j); + let gone = sp.anchors.is_empty(); + if gone { + subs.remove(s); + } + Some((s, j, gone, closing)) + })?; + if let (Some((s, j, gone, closing)), Some(mut sel)) = (removed, selected) { + // The points are written first, and the selection is then set with selection commands, + // which the journal records with the edit. + flush(h)?; + renumber_selected(&mut sel, item.id, s, j, gone, closing); + on_doc(h, item.doc.uid, false, |h| { + let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + super::restore_selection(h, &doc, &sel) + })?; + } + cut_points(h, item); + Ok(Data::Undefined) +} + +/// Updates the direct selection `sel` of the path `id` after the anchor `j` of its subpath `s` was +/// removed, and the subpath with it when `gone`: the anchor, the segments it ended and their other +/// ends leave the selection, unless a segment still selected ends there, and the anchors, segments +/// and subpaths after it keep the points they selected. `closing` is the segment that closed the +/// subpath at the removed anchor, when it did. +fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, closing: Option) { + // An anchor (or a segment, by its first anchor) after the removed one moves down one place. + let shift = |(p, k): (usize, usize), segment: bool| -> Option<(usize, usize)> { + match p.cmp(&s) { + std::cmp::Ordering::Less => Some((p, k)), + std::cmp::Ordering::Greater => Some((if gone { p - 1 } else { p }, k)), + std::cmp::Ordering::Equal if gone => None, + std::cmp::Ordering::Equal if k == j || (segment && (k + 1 == j || closing == Some(k))) => None, + std::cmp::Ordering::Equal => Some((p, if k > j { k - 1 } else { k })), + } + }; + // The other ends of the selected segments that the removal joins, in the new numbering: the + // anchor before the removed one and the one after it. + let mut ends: Vec<(usize, usize)> = Vec::new(); + if let Some(segments) = sel.segments.get_mut(&id) { + let cut: Vec<(usize, usize)> = segments.iter().copied().filter(|g| shift(*g, true).is_none() && g.0 == s && !gone).collect(); + for (p, k) in cut { + // Segment k runs from anchor k to anchor k + 1; one of the two is the removed one. + let other = if k == j { k + 1 } else { k }; + // The closing segment's other end is its first anchor, the old last one. + let other = if closing == Some(k) { k } else { other }; + ends.extend(shift((p, other), false)); + } + *segments = segments.iter().filter_map(|g| shift(*g, true)).collect(); + if segments.is_empty() { + sel.segments.remove(&id); + } + } + let kept_ends: Vec<(usize, usize)> = + sel.segments.get(&id).map(|g| g.iter().flat_map(|(p, k)| [(*p, *k), (*p, k + 1)]).collect()).unwrap_or_default(); + if let Some(anchors) = sel.anchors.get_mut(&id) { + *anchors = anchors.iter().filter_map(|a| shift(*a, false)).filter(|a| !ends.contains(a) || kept_ends.contains(a)).collect(); + } + if let Some((key, a)) = sel.key_anchor + && key == id + { + sel.key_anchor = shift(a, false).filter(|a| sel.anchors.get(&id).is_some_and(|set| set.contains(a))).map(|a| (key, a)); + } +} + +// ---- Registration ---- + +/// The members `PathItem` adds to `PageItem`'s. +pub(super) fn path_item_members(l: &Link) -> Vec { + let transform = |first: &[(&'static str, &'static str)]| { + let mut args: Vec<(&str, &str)> = first.to_vec(); + args.extend([ + ("changePositions", "boolean"), + ("changeFillPatterns", "boolean"), + ("changeFillGradients", "boolean"), + ("changeStrokePattern", "boolean"), + ]); + args + }; + let mut resize = transform(&[("scaleX", "number"), ("scaleY", "number")]); + resize.extend([("changeLineWidths", "number"), ("scaleAbout", "Transformation")]); + let mut rotate = transform(&[("angle", "number")]); + rotate.push(("rotateAbout", "Transformation")); + let translate = [ + ("deltaX", "number"), + ("deltaY", "number"), + ("transformObjects", "boolean"), + ("transformFillPatterns", "boolean"), + ("transformFillGradients", "boolean"), + ("transformStrokePattern", "boolean"), + ]; + let mut m = named(vec![ + ("pathPoints", point_get(l, path_points), MemberInfo { collection: true, ..typed("PathPoints") }), + ("closed", point_property(l, path_closed, path_set_closed), typed("boolean")), + ("evenodd", property(l, path_evenodd, path_set_evenodd), typed("boolean")), + ("area", get(l, path_area), typed("number")), + ("length", get(l, path_length), typed("number")), + ("guides", property(l, path_guides, path_set_guides), typed("boolean")), + ("clipping", get(l, path_clipping), typed("boolean")), + ("setEntirePath", point_method(l, path_set_entire), returns("undefined", &[("pathPoints", "Array")])), + ("filled", property(l, path_filled, path_set_filled), typed("boolean")), + ("fillColor", property(l, path_fill_color, path_set_fill_color), typed("Color")), + ("fillOverprint", property(l, path_fill_overprint, path_set_fill_overprint), typed("boolean")), + ("stroked", property(l, path_stroked, path_set_stroked), typed("boolean")), + ("strokeColor", property(l, path_stroke_color, path_set_stroke_color), typed("Color")), + ("strokeOverprint", property(l, path_stroke_overprint, path_set_stroke_overprint), typed("boolean")), + ( + "strokeWidth", + property(l, path_stroke_width, path_set_stroke_width), + MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") }, + ), + ("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")), + ("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")), + ("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")), + ("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")), + ("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")), + ("translate", method(l, path_translate), returns("undefined", &translate)), + ("rotate", method(l, path_rotate), returns("undefined", &rotate)), + ("resize", method(l, path_resize), returns("undefined", &resize)), + ("selectedPathPoints", get(l, path_selected_points), typed("Array")), + ]); + m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); + m +} + +/// `PathItems`, `PathPoints` and `PathPoint`. +pub(super) fn classes(l: &Link) -> Vec { + let corner = [("top", "number"), ("left", "number"), ("width", "number"), ("height", "number")]; + let center = [("centerX", "number"), ("centerY", "number"), ("radius", "number")]; + let with = |first: &[(&'static str, &'static str)], rest: &[(&'static str, &'static str)]| -> Vec<(&'static str, &'static str)> { + first.iter().chain(rest).copied().collect() + }; + vec![ + class( + "PathItems", + None, + named(vec![ + ("typename", get(l, items_typename), typed("string")), + ("length", get(l, items_length), typed("number")), + ("parent", get(l, items_parent), typed("Document")), + ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), + ("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])), + ("removeAll", method(l, items_remove_all), returns("undefined", &[])), + ("add", method(l, items_add), returns("PathItem", &[])), + ("rectangle", method(l, items_rectangle), returns("PathItem", &with(&corner, &[("reversed", "boolean")]))), + ( + "roundedRectangle", + method(l, items_rounded_rectangle), + returns("PathItem", &with(&corner, &[("horizontalRadius", "number"), ("verticalRadius", "number"), ("reversed", "boolean")])), + ), + ("ellipse", method(l, items_ellipse), returns("PathItem", &with(&corner, &[("reversed", "boolean"), ("inscribed", "boolean")]))), + ("polygon", method(l, items_polygon), returns("PathItem", &with(¢er, &[("sides", "number"), ("reversed", "boolean")]))), + ( + "star", + method(l, items_star), + returns("PathItem", &with(¢er, &[("innerRadius", "number"), ("points", "number"), ("reversed", "boolean")])), + ), + ]), + Some(super::function(l, items_at)), + ), + class( + "PathPoints", + None, + named(vec![ + ("typename", point_get(l, points_typename), typed("string")), + ("length", point_get(l, points_length), typed("number")), + ("parent", point_get(l, points_parent), typed("PathItem")), + ("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])), + ("add", point_method(l, points_add), returns("PathPoint", &[])), + ("removeAll", point_method(l, points_remove_all), returns("undefined", &[])), + ]), + Some(super::point_function(l, points_at)), + ), + class( + "PathPoint", + None, + named(vec![ + ("typename", point_get(l, pt_typename), typed("string")), + ("parent", point_get(l, pt_parent), typed("PathItem")), + ("anchor", point_property(l, pt_anchor, pt_set_anchor), typed("Array")), + ("leftDirection", point_property(l, pt_left, pt_set_left), typed("Array")), + ("rightDirection", point_property(l, pt_right, pt_set_right), typed("Array")), + ("pointType", point_property(l, pt_type, pt_set_type), typed("PointType")), + ( + "selected", + HostMember::Property { get: super::point_function(l, pt_selected), set: super::function(l, pt_set_selected) }, + typed("PathPointSelection"), + ), + ("remove", point_method(l, pt_remove), returns("undefined", &[])), + ]), + None, + ), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_made_id_above_two_to_the_53_stays_exact() { + assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993))); + assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7))); + assert!(made_id(&json!({"id": 1.5})).is_err()); + assert!(made_id(&json!({})).is_err()); + } +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 615e9f2197..2257bcc8d3 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1174,6 +1174,8 @@ struct Job { name: String, /// The file-access scope `script.run` came in, which every slice runs in. scope: crate::file_access::ScopeHandle, + /// The script has ended, and the run waits for the person's growth answer before it is kept. + finished: bool, } /// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in @@ -1402,6 +1404,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { + // Point changes that wait in the object model are written before any command runs. + dom::flush(host)?; let session = host.session.clone(); let started = clock(); let before = dom::before_command(host, id); @@ -1446,6 +1450,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( dom::after_command(host, before); // Style objects follow only a command that is kept. if crossed.is_ok() { + dom::see_points(host); dom::after_kept_command(host); } else { session.borrow_mut().script_style_trail = StyleTrail::default(); @@ -1517,6 +1522,7 @@ pub(crate) fn retained_style_lists(s: &Session) -> usize { /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { + dom::flush(host)?; let s = host.session.borrow(); let Some(st) = s.active() else { return Ok(Data::Null) }; let ids: Vec = st.selection.objects.iter().take(1_000).map(|i| i.0).collect(); @@ -2103,7 +2109,7 @@ impl Session { if h.waiting.replace(false) { h.continues.set(h.continues.get() + 1); h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects())); - h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES)); + h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(growth_bytes())); } }); } @@ -2282,7 +2288,7 @@ impl Session { bytes_kept: Cell::new(0), bridge: Cell::new(0), allowance_objects: Cell::new(growth_objects()), - allowance_bytes: Cell::new(GROWTH_BYTES), + allowance_bytes: Cell::new(growth_bytes()), continues: Cell::new(0), waiting: Cell::new(false), log: RefCell::new(Vec::new()), @@ -2407,7 +2413,7 @@ impl Session { } let scope = crate::file_access::ScopeHandle::capture(); let (run, line_name) = (host.run, host.name.clone()); - let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope }; + let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope, finished: false }; let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); self.script_key = Some(JobKey { id, run, name: line_name }); @@ -2461,6 +2467,28 @@ impl Session { self.script_key = Some(key); return None; } + // A run whose script ended past its growth allowance is kept once the person lets it go on, + // and put back when they stop it. + if job.finished { + if self.script_stop.is_set() { + let kind = LimitKind::Interrupted; + let e = + RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; + return Some(self.script_failed(job, &e)); + } + // One more allowance may still leave the growth past it: the person is asked again + // while they may be, and past that the run ends unkept. + if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) { + let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }; + return Some(self.script_failed(job, &e)); + } + if job.host.waiting.get() { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + return None; + } + return Some(self.script_ended(job)); + } // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. if job.realm.waits() { let kind = LimitKind::Interrupted; @@ -2486,24 +2514,35 @@ impl Session { self.script_key = Some(key); None } - Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => { - let n = job.host.dialogs.unused(); - let kind = LimitKind::Host; - let message = if n == 1 { - format!("`answers` has {n} answer the script did not use") - } else { - format!("`answers` has {n} answers the script did not use") - }; - Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false })) - } - Ok(Ok(Progress::Done(_))) => { - let r = self.script_commit(job); - self.trim_histories(); - Some(r) + // The point changes written as the script ended went past the growth allowance. + Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => { + job.finished = true; + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + None } + Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)), } } + /// Ends the run whose script has ended: it fails when answers it was given went unused, and is + /// kept otherwise. + fn script_ended(&mut self, job: Job) -> Result { + let n = job.host.dialogs.unused(); + if n > 0 { + let kind = LimitKind::Host; + let message = if n == 1 { + format!("`answers` has {n} answer the script did not use") + } else { + format!("`answers` has {n} answers the script did not use") + }; + return self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }); + } + let r = self.script_commit(job); + self.trim_histories(); + r + } + fn script_failed(&mut self, job: Job, e: &RunError) -> Result { job.host.dialogs.stopped(); job.host.disk.borrow_mut().picker = None; @@ -2823,6 +2862,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result std::result::Result RunError { + let message = match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m, + HostError::Marked { error, .. } => return end_flush_error(*error), + HostError::Wait => "a host function waited for its result where the run cannot pause".into(), + }; + RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false } +} + /// Tests: removes the session's running job while the session keeps its hold on it. → whether a /// job was removed. #[cfg(test)] @@ -2860,6 +2918,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The bytes of new document data a run may keep before it is asked to continue or stop. +fn growth_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_GROWTH_BYTES.with(Cell::get) { + return n; + } + GROWTH_BYTES +} + /// The data a run may pass to and from commands. fn bridge_bytes() -> u64 { #[cfg(test)] @@ -2886,6 +2953,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`]. + pub(crate) static TEST_GROWTH_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 5afe3d9b93..9e3cf2371e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -180,6 +180,8 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_defaults; +mod script_dom_paths; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 0c6cc8dfdc..6737666046 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -1,6 +1,8 @@ //! The new-art template (M3.65): Stroke panel options and graphic styles chosen with nothing //! selected, New Art Has Basic Appearance and `paint.default`. +use std::sync::Arc; + use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, Dash, LineCap, Node}; @@ -377,3 +379,98 @@ fn fill_line_gives_a_new_line_the_current_fill() { assert_ne!(s.paint.fill, Paint::None); assert!(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 1, "y2": 1, "fill": "yes"})).is_err()); } + +/// `appearance.setNewArt` sets what the next object gets while the selection keeps its own look. +#[test] +fn set_new_art_changes_the_next_object_and_not_the_selection() { + let mut s = session(); + let picked = rect(&mut s, 20.0); + run(&mut s, "select.set", json!({"ids": [picked.0]})); + let (look, undo, recent, active) = (node(&s, picked).appearance, undo_len(&s), s.recent_colors.clone(), s.fill_active); + let r = run( + &mut s, + "appearance.setNewArt", + json!({"fill": {"color": "#ff0000"}, "stroke": {"none": true}, "weight": 4, "cap": "round", "dash": [3, 1], "dashOffset": 1, "fillOverprint": true}), + ); + assert_eq!(r, json!({"changed": true})); + assert_eq!(node(&s, picked).appearance, look, "the selected art kept its look"); + assert_eq!(s.doc().unwrap().selection.objects, vec![picked]); + assert_eq!((undo_len(&s), &s.recent_colors, s.fill_active), (undo, &recent, active)); + run(&mut s, "select.none", json!({})); + let id = rect(&mut s, 200.0); + let ap = node(&s, id).appearance; + let (fill, st) = (ap.fill().unwrap(), ap.stroke().unwrap()); + assert_eq!(fill.paint, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))); + assert!(fill.overprint); + assert_eq!((st.paint.clone(), st.width, st.cap), (Paint::None, 4.0, LineCap::Round)); + assert_eq!(st.dash, Some(Dash { pattern: vec![3.0, 1.0], offset: 1.0, ..Default::default() })); + // The same values again change nothing. + assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 4, "cap": "round"})), json!({"changed": false})); +} + +#[test] +fn set_new_art_refuses_bad_values_with_nothing_changed() { + let mut s = session(); + let before = s.paint.clone(); + for params in [ + json!({"weight": -1}), + json!({"weight": 1001}), + json!({"weight": "3"}), + json!({"miterLimit": 0.5}), + json!({"cap": "flat"}), + json!({"join": 2}), + json!({"dash": [0, 0]}), + json!({"dash": [-1]}), + json!({"dash": "4 2"}), + json!({"dashOffset": 2}), + json!({"fill": "#ff0000"}), + json!({"fill": {}}), + json!({"fill": {"color": "#ff0000"}, "weight": -1}), + json!({"stroke": {"tint": 50, "color": "#000000"}}), + json!({"fillOverprint": "yes"}), + json!({"widht": 3}), + // A setting a paint does not take, here or nested in it, is refused too. + json!({"fill": {"color": "#ff0000", "opacity": 25}}), + json!({"stroke": {"none": true, "weight": 2}}), + ] { + assert!(s.execute("appearance.setNewArt", ¶ms).is_err(), "accepted {params}"); + assert_eq!(s.paint, before, "changed new art for {params}"); + } +} + +#[test] +fn set_new_art_refuses_a_tint_on_a_pattern_without_a_swatch_entry() { + let mut s = session(); + let id = rect(&mut s, 20.0); + let name = run(&mut s, "object.pattern.make", json!({"ids": [id.0], "edit": false}))["name"].as_str().unwrap().to_string(); + run(&mut s, "select.none", json!({})); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).remove_swatch(&name); + let before = s.paint.clone(); + assert!(s.execute("appearance.setNewArt", &json!({"fill": {"swatch": name, "tint": 50}})).is_err(), "accepted a tint on {name}"); + assert_eq!(s.paint, before); + assert_eq!(run(&mut s, "appearance.setNewArt", json!({"fill": {"swatch": name}})), json!({"changed": true})); +} + +#[test] +fn set_new_art_refuses_a_swatch_that_is_not_a_name() { + let mut s = session(); + let before = s.paint.clone(); + for p in [json!({"fill": {"swatch": 7, "color": "#ff0000"}}), json!({"stroke": {"swatch": null, "color": "#ff0000"}})] { + assert!(s.execute("appearance.setNewArt", &p).is_err(), "accepted {p}"); + assert_eq!(s.paint, before, "{p} changed new art"); + } +} + +#[test] +fn set_new_art_refuses_while_new_art_takes_the_selected_look() { + let mut s = session(); + let picked = rect(&mut s, 20.0); + run(&mut s, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut s, "select.set", json!({"ids": [picked.0]})); + let before = s.paint.clone(); + assert!(s.execute("appearance.setNewArt", &json!({"weight": 7})).is_err()); + assert_eq!(s.paint, before); + run(&mut s, "select.none", json!({})); + assert_eq!(run(&mut s, "appearance.setNewArt", json!({"weight": 7})), json!({"changed": true})); + assert_eq!(s.new_art().stroke().unwrap().width, 7.0); +} diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index f41253ec22..ad2711558e 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -161,6 +161,8 @@ fn ppi_overprint_preview_and_bad_params() { json!({"artboardLayout": {"layout": "spiral"}}), json!({"artboardLayout": {"columns": 0}}), json!({"artboardLayout": {"rows": 0}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0.4}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1001}}), json!({"artboardLayout": {"tiles": 2}}), json!({"units": "furlongs"}), json!({"width": 160000, "artboards": 1000}), @@ -1212,3 +1214,11 @@ fn the_new_layer_takes_an_id_no_profile_art_has() { // Ids given out later skip the symbol's art too. assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next); } + +#[test] +fn a_saved_presets_rows_are_read_within_the_artboard_limit() { + let rows = |n: u32| serde_json::from_value::(json!({"rows": n})).unwrap().rows; + assert_eq!(rows(1001), crate::cmd::newdoc::MAX_ARTBOARDS, "file.new takes the listed rows again"); + assert_eq!(rows(0), 0, "0 stays: columns in their place"); + assert_eq!(rows(12), 12, "more rows than artboards stay"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e87e5b5c51..03cab27e93 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1017,7 +1017,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); - assert!(e.contains("rows must be 1 or more"), "{e}"); + assert!(e.contains("rows must be from 1 to 1000"), "{e}"); for layout in ["gridByRow", "row", "column"] { let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); @@ -1074,6 +1074,22 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +#[test] +fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.clone(); + assert!(anchors.contains_key(&a)); + // Lists start with the topmost object, so `b` is `pageItems[0]`. + log(&mut s, "app.activeDocument.pageItems[0].selected = false;"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone())); + log(&mut s, "app.activeDocument.pageItems[0].selected = true;"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a))); +} + #[test] fn an_edit_keeps_the_order_of_a_mixed_selection() { let (mut s, a, b) = doc(); @@ -1259,9 +1275,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].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].isIsolated;", + "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")); @@ -1443,6 +1461,16 @@ fn note_is_the_attributes_note() { assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } +#[test] +fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap(); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); + assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);"); + assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset"); +} + #[test] fn document_preset_applies_only_its_given_fields() { let mut s = Session::new(); @@ -1477,6 +1505,17 @@ fn document_preset_applies_only_its_given_fields() { assert!(e.contains(part), "{source}: {e}"); } assert_eq!(s.documents().len(), 2, "a refused preset makes no document"); + // A saved preset with the built-in preset's name does not make the refused settings fit. + s.execute("file.newPresets.save", &json!({"name": "Letter", "artboardLayout": "column"})).unwrap(); + // With the layout unset, the built-in preset puts the five 1,000,000 pt artboards in one row, + // which does not fit, while the saved preset would put them in one column. + let e = failure( + &mut s, + "var p = new DocumentPreset(); p.width = 1000000; p.numArtboards = 5;\ + p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; app.documents.addDocument('Print', p);", + ); + assert!(e.contains("don't fit"), "{e}"); + assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document"); } #[test] @@ -2149,7 +2188,7 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); diff --git a/crates/engine/src/tests/script_dom_defaults.rs b/crates/engine/src/tests/script_dom_defaults.rs new file mode 100644 index 0000000000..a3bdc447e0 --- /dev/null +++ b/crates/engine/src/tests/script_dom_defaults.rs @@ -0,0 +1,169 @@ +//! The script object model's document defaults for new art and `scaleFactor`. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::LineCap; + +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() +} + +/// A 400 × 300 pt document with one rectangle, selected. +fn doc() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + (s, id) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn node(s: &Session, id: NodeId) -> crate::doc::Node { + s.active().unwrap().doc.node(id).unwrap().clone() +} + +#[test] +fn a_wider_default_stroke_goes_to_the_next_path_drawn() { + let (mut s, picked) = doc(); + let (look, steps) = (node(&s, picked).appearance, undo_steps(&s)); + let wider = s.paint.stroke_width + 1.0; + let r = run(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth);").unwrap(); + assert_eq!(r["log"][0].as_f64(), Some(wider)); + assert_eq!(undo_steps(&s), steps, "a default alone is no undo step"); + assert_eq!(node(&s, picked).appearance, look, "the selected path kept its stroke"); + assert_eq!(s.new_art().stroke().unwrap().width, wider); + let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(200, 100, 50, 50); vc.log(p.strokeWidth);"); + assert_eq!(out.iter().map(Value::as_f64).collect::>(), vec![Some(wider)]); +} + +#[test] +fn a_bad_default_throws_and_changes_nothing() { + let (mut s, _) = doc(); + let before = s.paint.clone(); + for (source, name) in [ + ("app.activeDocument.defaultStrokeWidth = -1", "RangeError"), + ("app.activeDocument.defaultStrokeWidth = 1001", "RangeError"), + ("app.activeDocument.defaultStrokeWidth = 'wide'", "TypeError"), + ("app.activeDocument.defaultStrokeMiterLimit = 0", "RangeError"), + ("app.activeDocument.defaultStrokeCap = 'round'", "TypeError"), + ("app.activeDocument.defaultStrokeJoin = 1", "TypeError"), + ("app.activeDocument.defaultStrokeDashes = [0, 0]", "RangeError"), + ("app.activeDocument.defaultStrokeDashes = '4 2'", "TypeError"), + ("app.activeDocument.defaultStrokeDashOffset = 3", "Error"), + ("app.activeDocument.defaultFillColor = 5", "TypeError"), + ("var c = new RGBColor(); c.red = 300; app.activeDocument.defaultStrokeColor = c", "RangeError"), + ("app.activeDocument.defaultFilled = 1", "TypeError"), + ("app.activeDocument.defaultStrokeOverprint = 'yes'", "TypeError"), + ] { + let out = log(&mut s, &format!("try {{ {source}; vc.log('ran'); }} catch (e) {{ vc.log(e.name); }}")); + assert_eq!(out, vec![json!(name)], "{source}"); + assert_eq!(s.paint, before, "{source} changed new art"); + } +} + +#[test] +fn default_colors_and_flags_read_back_and_paint_the_next_path() { + let (mut s, picked) = doc(); + let look = node(&s, picked).appearance; + let out = log( + &mut s, + "var d = app.activeDocument, c = new RGBColor(); c.red = 255;\ + d.defaultFillColor = c; vc.log(d.defaultFillColor.typename); vc.log(d.defaultFillColor.red); vc.log(d.defaultFilled);\ + d.defaultStroked = false; vc.log(d.defaultStroked); vc.log(d.defaultStrokeColor.typename);\ + d.defaultStrokeColor = new GrayColor(); vc.log(d.defaultStroked);\ + d.defaultFillColor = new NoColor(); vc.log(d.defaultFilled); d.defaultFilled = true; vc.log(d.defaultFilled);\ + d.defaultFillColor = c;", + ); + assert_eq!(out, vec![json!("RGBColor"), json!(255), json!(true), json!(false), json!("NoColor"), json!(true), json!(false), json!(true)]); + assert_eq!(node(&s, picked).appearance, look); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let ap = node(&s, id).appearance; + assert_eq!(ap.fill_paint(), Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert!(!ap.stroke_paint().is_none()); +} + +#[test] +fn default_stroke_options_read_back_and_a_same_value_runs_no_command() { + let (mut s, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeJoin = StrokeJoin.BEVELENDJOIN;\ + d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2]; d.defaultStrokeDashOffset = 1;\ + d.defaultStrokeOverprint = true; d.defaultFillOverprint = true;\ + vc.log([d.defaultStrokeCap, d.defaultStrokeJoin, d.defaultStrokeMiterLimit, d.defaultStrokeDashes, d.defaultStrokeDashOffset,\ + d.defaultStrokeOverprint, d.defaultFillOverprint]);", + ); + assert_eq!(out, vec![json!(["StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 2], 1, true, true])]); + let st = s.new_art().stroke().unwrap().clone(); + assert_eq!((st.cap, st.miter_limit, st.overprint), (LineCap::Round, 7.0, true)); + let r = run( + &mut s, + "var d = app.activeDocument; d.defaultStrokeCap = StrokeCap.ROUNDENDCAP; d.defaultStrokeMiterLimit = 7;\ + d.defaultStrokeDashes = [6, 2]; d.defaultStrokeOverprint = true; d.defaultStrokeWidth = d.defaultStrokeWidth;\ + d.defaultFillColor = d.defaultFillColor;", + ) + .unwrap(); + assert_eq!(r["slowestCommands"], json!([]), "the same values run no command"); + // `{}` and `[]` give a solid line. + assert_eq!(log(&mut s, "var d = app.activeDocument; d.defaultStrokeDashes = {}; vc.log(d.defaultStrokeDashes.length);"), vec![json!(0)]); +} + +#[test] +fn a_slightly_different_number_reaches_new_art() { + let (mut s, _) = doc(); + log(&mut s, "var d = app.activeDocument; d.defaultStrokeWidth = 1; d.defaultStrokeMiterLimit = 7; d.defaultStrokeDashes = [6, 2];"); + log( + &mut s, + "var d = app.activeDocument; d.defaultStrokeWidth = 1.0000000005; d.defaultStrokeMiterLimit = 7.0000000005;\ + d.defaultStrokeDashOffset = 0.0000000005;", + ); + let st = s.new_art().stroke().unwrap().clone(); + assert_eq!(st.width, 1.000_000_000_5); + assert_eq!(st.miter_limit, 7.000_000_000_5); + assert_eq!(st.dash.map(|d| d.offset), Some(0.000_000_000_5)); +} + +#[test] +fn an_rgb_default_in_a_cmyk_document_runs_no_command_the_second_time() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let set = "var d = app.activeDocument, c = new RGBColor(); c.red = 200; c.green = 40; c.blue = 90; d.defaultFillColor = c;"; + let first = run(&mut s, set).unwrap(); + assert_ne!(first["slowestCommands"], json!([]), "the first assignment changes new art"); + let again = run(&mut s, set).unwrap(); + assert_eq!(again["slowestCommands"], json!([]), "the same RGB value runs no command"); +} + +#[test] +fn scale_factor_is_one_and_read_only() { + let (mut s, _) = doc(); + let out = log(&mut s, "var d = app.activeDocument; vc.log(d.scaleFactor); d.scaleFactor = 4; vc.log(d.scaleFactor);"); + assert_eq!(out, vec![json!(1), json!(1)]); +} + +#[test] +fn defaults_refuse_while_new_art_takes_the_selected_look() { + let (mut s, _) = doc(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let before = s.paint.clone(); + let out = log( + &mut s, + "try { app.activeDocument.defaultStrokeWidth = 9; } catch (e) { vc.log(e.message.indexOf('New Art Has Basic Appearance') >= 0); }", + ); + assert_eq!(out, vec![json!(true)]); + assert_eq!(s.paint, before); +} 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..d33246aba7 --- /dev/null +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -0,0 +1,1346 @@ +//! 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, `a` above `b`. Lists start with the topmost +/// object, so `a` is `pathItems[0]` and `b` is `pathItems[1]`. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.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 points_off_the_canvas_throw_where_they_are_given() { + let (mut s, _, _) = doc(); + let before = art(&s); + for source in [ + "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [7000000, 1]]);", + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [7000000, 1];", + "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, -7000000];", + ] { + let out = log(&mut s, &format!("try {{ {source} vc.log('kept'); }} catch (e) {{ vc.log(e.name); }}")); + assert_eq!(out, vec![json!("RangeError")], "{source}"); + assert_eq!(art(&s), before, "{source}"); + } +} + +#[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 points_read_before_a_removal_or_replacement_go_stale() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ + var second = p.pathPoints[1], other = q.pathPoints[1]; p.pathPoints[0].remove();\ + try { second.anchor = [0, 0]; } catch (e) { vc.log(e.message); } try { second.anchor; } catch (e) { vc.log(e.message); }\ + vc.log(other.anchor); var first = p.pathPoints[0]; vc.log(first.anchor);\ + p.setEntirePath([[1, 1], [2, 2], [3, 3]]); try { first.anchor; } catch (e) { vc.log(e.message); }\ + var again = p.pathPoints[0]; vc.log(again.anchor); p.pathPoints.removeAll(); try { again.anchor; } catch (e) { vc.log(e.message); }", + ); + assert_eq!( + out, + vec![ + json!("Stale path point"), + json!("Stale path point"), + json!([150, 200]), + json!([40, 280]), + json!("Stale path point"), + json!([1, 1]), + json!("Stale path point") + ] + ); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[1], pt = p.pathPoints[0]; vc.log(pt.typename); pt.remove();\ + try { vc.log(pt.typename); } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point")]); + // The points of a removed path, and collections kept from an earlier run, throw on typename as on + // their other members. + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints; vc.log([pp.typename, app.activeDocument.pathItems.typename]); p.remove();\ + var a = '', b = ''; try { pp.length; } catch (e) { a = e.message; } try { pp.typename; } catch (e) { b = e.message; } vc.log(a !== '' && a === b);", + ); + assert_eq!(out, vec![json!(["PathPoints", "PathItems"]), json!(true)]); + run(&mut s, "#targetengine keep\nvar items = app.activeDocument.pathItems, pts = items[0].pathPoints;").unwrap(); + for (member, message) in [("items.typename", "Stale document"), ("pts.typename", "Stale")] { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains(message), "{member}: {e}"); + } +} + +#[test] +fn points_read_before_a_command_changes_the_path_go_stale() { + let (mut s, a, _) = doc(); + let source = format!( + "function A(x, y) {{ return {{x: x, y: y, in: [x, y], out: [x, y], smooth: false}}; }}\ + var p = app.activeDocument.pathItems[0], id = {id}, first = p.pathPoints[1];\ + vc.run('path.setAnchors', {{id: id, subpaths: [{{anchors: [A(0, 0), A(20, 0), A(20, 20), A(0, 20)], closed: true}}]}});\ + try {{ first.anchor = [1, 1]; }} catch (e) {{ vc.log(e.message); }} try {{ first.anchor; }} catch (e) {{ vc.log(e.message); }}\ + var second = p.pathPoints[1]; vc.log(second.anchor);\ + vc.run('stroke.set', {{ids: [id], weight: 3}}); vc.log(second.anchor);\ + p.translate(5, 0); vc.log(second.anchor);\ + vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); try {{ second.anchor; }} catch (e) {{ vc.log(e.message); }}\ + var third = p.pathPoints[1]; vc.log(third.anchor);\ + vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); vc.run('edit.undo');\ + try {{ third.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);\ + var fourth = p.pathPoints[1]; vc.run('edit.clear', {{ids: [id]}}); vc.run('edit.undo');\ + try {{ fourth.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);", + id = a.0 + ); + let out = log(&mut s, &source); + assert_eq!( + out, + vec![ + json!("Stale path point"), + json!("Stale path point"), + json!([20, 300]), + json!([20, 300]), + json!([25, 300]), + json!("Stale path point"), + json!([30, 300]), + json!("Stale path point"), + json!(4), + json!("Stale path point"), + json!(4) + ] + ); +} + +#[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); + let r = run( + &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);", + ) + .unwrap(); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + assert_eq!(r["slowestCommands"], json!([]), "and run no command"); +} + +#[test] +fn identity_transforms_of_an_empty_path_do_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.rotate(360); n.rotate(0, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(100, 100); n.resize(100, 100, true, true, true, true, 100, Transformation.BOTTOM); n.translate(0, 0);", + ); + for source in [ + "app.activeDocument.pathItems[0].rotate(360, true, true, true, true, 'CENTER');", + "app.activeDocument.pathItems[0].resize(100, 100, true, true, true, true, 100, 'x');", + ] { + assert!(failure(&mut s, source).contains("Transformation"), "{source}"); + } +} + +/// The paint of the fill (`fill`) or stroke of `id`. +fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { + let n = node(s, id); + if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() } +} + +#[test] +fn a_color_read_from_a_path_assigns_back_unchanged() { + let colors = [ + "var c = new RGBColor(); c.red = 0.00001; c.green = 200.123456789; c.blue = 1 / 3;", + "var c = new CMYKColor(); c.cyan = 100 / 3; c.magenta = 0.00001; c.yellow = 99.99999; c.black = 12.3456789;", + "var c = new GrayColor(); c.gray = 100 / 3;", + "var c = new GrayColor(); c.gray = 99.99999;", + "var c = new LabColor(); c.l = 12.3456789; c.a = -0.00001; c.b = 127.99999;", + ]; + for color in colors { + for prop in ["fillColor", "strokeColor"] { + let (mut s, a, _) = doc(); + log(&mut s, &format!("{color} app.activeDocument.pathItems[0].{prop} = c;")); + let (before, steps) = (paint_of(&s, a, prop == "fillColor"), undo_steps(&s)); + let r = run(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.{prop} = p.{prop};")).unwrap(); + assert_eq!(paint_of(&s, a, prop == "fillColor"), before, "{color} {prop}"); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "{color} {prop}"); + } + } + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 0.5; p.fillColor = c;\ + var g = new GrayColor(); g.gray = 25; p.strokeColor = g; vc.log([p.fillColor.red, p.fillColor.green, p.strokeColor.gray]);", + ); + assert_eq!(out, vec![json!([200, 0.5, 25])], "whole and short values read as they were given"); + // A Gray ink amount too small for its Gray value to name: assigning the color read back changes nothing. + let (mut s, a, _) = doc(); + let k = f32::from_bits(0x1f00_0000); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(a).unwrap().appearance.set_fill(Paint::solid(Color::Gray { k })); + let steps = undo_steps(&s); + let r = run(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").unwrap(); + assert_eq!(paint_of(&s, a, true), Paint::solid(Color::Gray { k })); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([]))); +} + +#[test] +fn many_point_edits_run_one_command() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let anchors: Vec = (0..2000).map(|i| json!({"x": f64::from(i) * 0.1, "y": 100})).collect(); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let r = run( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ + for (var i = 0; i < pp.length; i++) { var a = pp[i].anchor; pp[i].rightDirection = [a[0] + 1, a[1]]; pp[i].anchor = [a[0], a[1] + 5]; }\ + vc.log(pp[1999].anchor); vc.log(pp[1999].rightDirection); pp[0].remove(); vc.log(pp.length); vc.log(p.pathPoints[0].anchor);", + ) + .unwrap(); + let out: Vec = r["log"].as_array().unwrap().iter().map(rounded).collect(); + assert_eq!(out, vec![json!([199.9, 205]), json!([200.9, 200]), json!(1999), json!([0.1, 205])]); + assert_eq!( + r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), + Some(vec![(json!("path.setAnchors"), json!(1))]), + "one command writes every point" + ); + let pd = node(&s, id).path_data().unwrap().clone(); + assert_eq!(pd.subpaths[0].anchors.len(), 1999); + assert!(pd.subpaths[0].anchors.iter().all(|a| (a.h_out.x - a.p.x - 1.0).abs() < 1e-9 && (a.h_out.y - a.p.y - 5.0).abs() < 1e-9)); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..300 { + rect(&mut s, f64::from(i % 30) * 10.0, f64::from(i / 30) * 10.0, 5.0, 5.0); + } + s.execute("select.none", &json!({})).unwrap(); + let start = crate::script::dom::POINT_LOOKS.with(|n| n.get()); + log( + &mut s, + "var ps = app.activeDocument.pathItems;\ + for (var i = 0; i < ps.length; i++) { var q = ps[i].pathPoints[0]; var a = q.anchor; q.anchor = [a[0] + 1, a[1]]; }", + ); + let looks = crate::script::dom::POINT_LOOKS.with(|n| n.get()) - start; + assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits"); +} + +#[test] +fn point_edits_are_written_before_the_next_other_member_reads() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ + p.pathPoints[0].anchor = [0, 300]; vc.log(p.geometricBounds); q.pathPoints[0].anchor = [90, 210];\ + p.pathPoints[1].anchor = [50, 300]; vc.log(q.geometricBounds); vc.log(p.geometricBounds);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out, vec![json!([0, 300, 40, 240]), json!([90, 210, 150, 150]), json!([0, 300, 50, 240])]); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, vectorcraft_geom::Point::new(50.0, 0.0)); +} + +#[test] +fn closed_and_set_entire_path_join_the_point_edits_in_one_command() { + let (mut s, a, _) = doc(); + let r = run( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 300], [40, 300], [40, 240]]); p.closed = false;\ + p.pathPoints[1].anchor = [50, 300]; vc.log(p.closed); p.closed = true; p.setEntirePath([[0, 300], [60, 300], [60, 240]]); vc.log(p.closed);", + ) + .unwrap(); + assert_eq!(r["log"], json!([false, true])); + assert_eq!( + r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), + Some(vec![(json!("path.setAnchors"), json!(1))]), + "one command writes every change" + ); + let pd = node(&s, a).path_data().unwrap().clone(); + assert!(pd.subpaths[0].closed); + assert_eq!(pd.subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(), vec![(0.0, 0.0), (60.0, 0.0), (60.0, 60.0)]); +} + +#[test] +fn point_edits_of_a_pixel_aligned_path_read_as_the_grid_snaps_them() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[10.3, 280.3], [40.3, 280.3], [40.3, 240.3], [10.3, 240.3]]);\ + vc.log(p.pathPoints[0].anchor); p.pathPoints[1].anchor = [40.4, 280.3]; vc.log(p.pathPoints[1].anchor);", + ); + let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + let stored = |i: usize| rounded(&json!([anchors[i].p.x, 300.0 - anchors[i].p.y])); + assert_ne!(rounded(&out[0]), json!([10.3, 280.3]), "the grid moves the point"); + assert_eq!((rounded(&out[0]), rounded(&out[1])), (stored(0), stored(1)), "points read as the path has them"); +} + +#[test] +fn added_paths_go_on_top_of_the_layer_whatever_the_drawing_mode() { + for mode in ["behind", "inside"] { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let drawing = s.draw_mode; + log( + &mut s, + "var d = app.activeDocument; d.pathItems.add().name = 'n'; d.pathItems.rectangle(10, 10, 5, 5).name = 'r';\ + d.pathItems.roundedRectangle(10, 10, 5, 5).name = 'q';", + ); + let st = s.active().unwrap(); + let children = st.doc.layers[0].children().unwrap(); + let names: Vec> = children.iter().rev().take(3).map(|c| c.name.as_deref()).collect(); + assert_eq!(names, [Some("q"), Some("r"), Some("n")], "{mode}: the new paths are on top of the layer"); + assert_eq!(s.draw_mode, drawing, "{mode}: the drawing mode stays"); + } +} + +#[test] +fn overprint_changes_the_top_fill_or_stroke_only() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.addStroke", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.fillOverprint = true; p.strokeOverprint = true; vc.log([p.fillOverprint, p.strokeOverprint]);", + ); + assert_eq!(out, vec![json!([true, true])]); + let items = node(&s, a).appearance.items.clone(); + for fill in [true, false] { + let flags: Vec = items.iter().filter(|i| i.is_fill() == fill).map(|i| i.overprint()).collect(); + assert!(flags.len() >= 2, "{flags:?}"); + let (top, lower) = flags.split_last().unwrap(); + assert!(*top && lower.iter().all(|f| !f), "fill {fill}: only the top row overprints: {flags:?}"); + } +} + +#[test] +fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() { + for member in 0..2 { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "stops": stops}})).unwrap(); + if let Paint::Gradient(g) = &mut s.paint.fill { + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(0.0, 0.5), + end: vectorcraft_geom::Point::new(1.0, 0.5), + aspect: 1.0, + focal: None, + }); + } + log(&mut s, &format!("app.activeDocument.pathItems[{member}].filled = true;")); + let b = node(&s, compound).geometric_bounds().unwrap(); + let Paint::Gradient(g) = node(&s, compound).appearance.fill_paint() else { panic!("member {member}: the compound has a gradient") }; + let geom = g.geom.unwrap(); + assert!((geom.start.x - b.x0).abs() < 1e-6 && (geom.end.x - b.x1).abs() < 1e-6, "member {member}: {geom:?} spans {b:?}"); + } +} + +#[test] +fn set_anchors_reads_smooth_false_as_a_corner() { + let (mut s, a, _) = doc(); + let anchor = |smooth: Value| { + let mut v = json!({"x": 20, "y": 20, "in": [10, 20], "out": [30, 20]}); + if !smooth.is_null() { + v["smooth"] = smooth; + } + v + }; + for (smooth, kind, read) in [(json!(false), AnchorKind::Corner, "PointType.CORNER"), (Value::Null, AnchorKind::Smooth, "PointType.SMOOTH")] { + let subpaths = json!([{"anchors": [anchor(smooth.clone()), {"x": 60, "y": 20}], "closed": false}]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[0].kind, kind, "smooth {smooth}"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].pointType);"), vec![json!(read)], "smooth {smooth}"); + } +} + +#[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"); +} + +#[test] +fn an_added_path_leaves_new_art_unpainted_with_basic_appearance_off() { + let (mut s, _, _) = doc(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.prefs.new_art_basic = false; + let paint = s.paint.clone(); + let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.stroked);"); + assert_eq!(out, [json!(false)]); + assert!(s.active().unwrap().selection.is_empty()); + assert_eq!(s.paint, paint, "new art keeps no fill and no stroke"); +} + +/// With Basic Appearance off, a path added to a document in the back takes the appearance of that +/// document's selection, which its activation loads into new art, even when new art in the +/// document in front has no paint. +#[test] +fn a_path_added_to_a_document_in_the_back_keeps_that_documents_stroke() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.prefs.new_art_basic = false; + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.prefs.new_art_basic = true; + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.prefs.new_art_basic = false; + assert!(s.new_art().stroke_paint().is_none()); + let out = log(&mut s, "var d = app.documents[1]; var n = d.pathItems.add(); vc.log(n.stroked); vc.log(app.activeDocument == d);"); + assert_eq!(out, [json!(true), json!(false)]); +} + +/// Drawing a path and putting the selection back keep the defaults a script set, so a second +/// path gets them too. +#[test] +fn every_path_a_script_draws_gets_its_default_stroke_width() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.defaultStrokeWidth = 7;\ + var r1 = d.pathItems.rectangle(10, 10, 5, 5), r2 = d.pathItems.rectangle(20, 20, 5, 5);\ + vc.log([r1.strokeWidth, r2.strokeWidth, d.defaultStrokeWidth]);", + ); + assert_eq!(out, [json!([7, 7, 7])]); +} + +/// Removing a point renumbers the direct-selected anchors after it, and a removed selected anchor +/// leaves the selection. +#[test] +fn removing_a_point_keeps_the_direct_selection_on_the_same_anchors() { + let (mut s, a, _) = doc(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 3]]}], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[3].remove();"); + // A path left with no selected anchor leaves the selection, as `select.anchorsMany` leaves it. + assert_eq!(selected_anchors(&s, a), None, "the removed anchor is not selected"); + assert!(!s.active().unwrap().selection.objects.contains(&a)); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 2]]}], "mode": "set"})).unwrap(); + let at = node(&s, a).path_data().unwrap().subpaths[0].anchors[2].p; + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1)]), "the selected anchor moved down one place"); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, at); + // A selected segment that the removal joins leaves the selection with its other end. + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();"); + assert_eq!(selected_anchors(&s, a), None, "the segment's other end is not selected"); + assert!(!s.active().unwrap().selection.objects.contains(&a)); +} + +/// [`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(); + // The text is the topmost object, and lists start with the topmost object. + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0]; 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); + let look = |s: &Session| [a, b].map(|id| (node(s, id).appearance, node(s, id).path_data().map(|pd| pd.subpaths.clone()))); + let before = look(&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); + assert_ne!(look(&s), before); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(look(&s), before, "one Undo puts back the fill, the stroke width and the anchor of both paths"); +} + +#[test] +fn point_indexes_follow_subpaths_through_edits_adds_and_removals() { + let (mut s, a, _) = doc(); + let source = format!( + "function A(x) {{ return {{x: x, y: 5, in: [x, 5], out: [x, 5], smooth: false}}; }}\ + function xs() {{ var out = []; for (var i = 0; i < pp.length; i++) out.push(pp[i].anchor[0]); return out; }}\ + var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ + vc.run('path.setAnchors', {{id: {id}, subpaths: [{{anchors: [A(0), A(1)], closed: false}}, {{anchors: [A(10), A(11), A(12)], closed: false}},\ + {{anchors: [A(20)], closed: false}}]}});\ + vc.log(xs()); pp[3].anchor = [50, pp[3].anchor[1]]; vc.log([pp[3].anchor[0], pp[4].anchor[0], pp[5].anchor[0]]);\ + pp.add(); vc.log([pp.length, pp[6].anchor[0]]);\ + pp[0].remove(); vc.log(xs()); pp[0].remove(); vc.log(xs()); pp[4].anchor = [70, 0]; vc.log(xs());", + id = a.0 + ); + let out = log(&mut s, &source); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!( + out, + vec![ + json!([0, 1, 10, 11, 12, 20]), + json!([50, 12, 20]), + json!([7, 20]), + json!([1, 10, 50, 12, 20, 20]), + json!([10, 50, 12, 20, 20]), + json!([10, 50, 12, 20, 70]), + ] + ); + let subs = node(&s, a).path_data().unwrap().subpaths.clone(); + let xs: Vec> = subs.iter().map(|sp| sp.anchors.iter().map(|an| (an.p.x * 1000.0).round() / 1000.0).collect()).collect(); + assert_eq!(xs, vec![vec![10.0, 50.0, 12.0], vec![20.0, 70.0]]); +} + +fn selected_anchors(s: &Session, id: NodeId) -> Option> { + s.active().unwrap().selection.anchors.get(&id).map(|set| set.iter().copied().collect()) +} + +#[test] +fn path_point_selected_selects_and_deselects_anchor_points() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ + vc.log(pp[1].selected); vc.log(p.selectedPathPoints.length);\ + pp[1].selected = PathPointSelection.ANCHORPOINT; pp[2].selected = PathPointSelection.ANCHORPOINT;\ + vc.log(pp[1].selected); vc.log(pp[0].selected); vc.log(p.selected);\ + var sp = p.selectedPathPoints; vc.log(sp.length); vc.log(sp[1].anchor.join() == pp[2].anchor.join());", + ); + assert_eq!( + out, + vec![ + json!("PathPointSelection.NOSELECTION"), + json!(0), + json!("PathPointSelection.ANCHORPOINT"), + json!("PathPointSelection.NOSELECTION"), + json!(true), + json!(2), + json!(true) + ] + ); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert!(s.active().unwrap().selection.contains(b), "the other selected object stays selected"); + assert_eq!(undo_steps(&s), steps, "a selection change is not an undo step"); + let r = run( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + pp[1].selected = PathPointSelection.ANCHORPOINT; pp[0].selected = PathPointSelection.NOSELECTION;", + ) + .unwrap(); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "a value the point has runs no command"); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].selected = PathPointSelection.NOSELECTION;"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 2)])); +} + +#[test] +fn a_path_selected_as_a_whole_has_every_point_selected() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; vc.log(p.selectedPathPoints.length); vc.log(p.pathPoints[3].selected);\ + p.pathPoints[0].selected = PathPointSelection.NOSELECTION; vc.log(p.selectedPathPoints.length);\ + vc.log(app.activeDocument.pathItems[1].selectedPathPoints.length);", + ); + assert_eq!(out, vec![json!(4), json!("PathPointSelection.ANCHORPOINT"), json!(3), json!(0)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2), (0, 3)])); +} + +#[test] +fn a_path_in_a_selected_group_or_compound_path_is_selected_as_a_whole() { + for make in ["object.group", "object.compoundPath.make"] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute(make, &json!({})).unwrap(); + let sel = format!("{:?}", s.active().unwrap().selection); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);\ + vc.log(ps[0].pathPoints[2].selected); ps[0].pathPoints[2].selected = PathPointSelection.ANCHORPOINT;\ + try { ps[0].pathPoints[2].selected = PathPointSelection.NOSELECTION; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out[..2], [json!([4, 4]), json!("PathPointSelection.ANCHORPOINT")], "{make}"); + assert!(out[2].as_str().is_some_and(|m| m.contains("not available yet")), "{make}: {out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().selection), sel, "{make}: the selection stays as it was"); + assert_eq!(undo_steps(&s), steps, "{make}"); + } +} + +#[test] +fn a_path_in_a_selected_group_reads_as_a_whole_when_its_own_anchors_are_also_picked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [group.0, a.0]})).unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 1]]}], "mode": "subtract"})).unwrap(); + assert!(s.active().unwrap().selection.contains(group), "the group stays selected"); + assert!(s.active().unwrap().selection.partial(a).is_some(), "the path has its own anchor selection"); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.selectedPathPoints.length, p.pathPoints[1].selected]);"); + assert_eq!(out, vec![json!([4, "PathPointSelection.ANCHORPOINT"])]); +} + +#[test] +fn reading_selected_while_moving_points_writes_the_path_once() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = run( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + for (var i = 0; i < pp.length; i++) if (pp[i].selected == PathPointSelection.ANCHORPOINT) pp[i].anchor = [pp[i].anchor[0] + 1, pp[i].anchor[1]];", + ) + .unwrap(); + let calls: Vec = + r["slowestCommands"].as_array().unwrap().iter().filter(|c| c["id"] == "path.setAnchors").map(|c| c["calls"].as_u64().unwrap()).collect(); + assert_eq!(calls, vec![1], "{r}"); +} + +#[test] +fn selection_reads_and_writes_see_points_the_script_added() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = p.pathPoints.add(); q.selected = PathPointSelection.ANCHORPOINT;\ + vc.log(q.selected); vc.log(p.selectedPathPoints.length);", + ); + assert_eq!(out, vec![json!("PathPointSelection.ANCHORPOINT"), json!(1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 4)])); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; p.pathPoints.add(); vc.log([p.selectedPathPoints.length, p.pathPoints.length]);"); + assert_eq!(out, vec![json!([6, 6])]); +} + +#[test] +fn selecting_a_point_of_a_path_with_selected_segments_replaces_the_segments() { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; vc.log(p.selectedPathPoints.length);\ + p.pathPoints[1].selected = PathPointSelection.NOSELECTION;", + ); + assert_eq!(out, vec![json!(0)]); + assert!(s.active().unwrap().selection.segments.contains_key(&a), "a value the point has leaves the segments selected"); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + let sel = &s.active().unwrap().selection; + assert!(!sel.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); +} + +#[test] +fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { + let (mut s, a, _) = doc(); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.LEFTDIRECTION;"); + assert!(e.contains("not available yet"), "{e}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = true;"); + assert!(e.contains("PathPointSelection"), "{e}"); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("Cannot select"), "{e}"); + assert!(s.active().unwrap().selection.is_empty()); +} + +#[test] +fn opening_a_path_with_its_closing_segment_selected_keeps_the_edit() { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0], [0, 3]], "mode": "add"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems; p[0].closed = false; p[1].closed = false;"); + for id in [a, b] { + assert!(!node(&s, id).path_data().unwrap().subpaths[0].closed, "{id:?} stayed closed"); + } + let sel = &s.active().unwrap().selection; + assert_eq!(sel.segments.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0)])); + assert!(sel.segments.get(&a).is_none_or(|g| g.is_empty()), "{:?}", sel.segments); +} + +/// The ways an editable path cannot be selected: on a locked artboard, and outside the isolated +/// object. +const UNSELECTABLE: [&str; 2] = ["locked artboard", "isolation"]; + +/// Makes the paths of [`doc`] other than `b` editable but not selectable, as `case` names. +fn lock_out(s: &mut Session, case: &str, b: NodeId) { + if case == "isolation" { + s.execute("object.isolate", &json!({"id": b.0})).unwrap(); + } else { + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + } +} + +#[test] +fn path_point_selected_refuses_paths_on_locked_artboards_and_outside_isolation() { + for case in UNSELECTABLE { + let (mut s, a, b) = doc(); + lock_out(&mut s, case, b); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("Cannot select"), "{case}: {e}"); + assert!(!s.active().unwrap().selection.contains(a), "{case}"); + } +} + +#[test] +fn selecting_a_point_of_a_guide_throws_while_guides_are_locked() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("guides are locked"), "{e}"); + assert!(!s.active().unwrap().selection.contains(a)); +} + +#[test] +fn assigning_guides_refuses_paths_that_cannot_be_selected() { + for case in UNSELECTABLE { + let (mut s, a, b) = doc(); + lock_out(&mut s, case, b); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("Cannot edit"), "{case}: {e}"); + assert!(!is_guide(&s, a), "{case}"); + } + // A guide is on no locked artboard, so only isolation keeps a guide from being released. + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(is_guide(&s, a)); + lock_out(&mut s, "isolation", b); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(e.contains("Cannot edit"), "{e}"); + assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); +} + +fn is_guide(s: &Session, id: NodeId) -> bool { + matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) +} + +#[test] +fn assigning_guides_makes_and_releases_a_guide() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let steps = undo_steps(&s); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; p.guides = true; vc.log(p.guides);"); + assert_eq!(out, vec![json!(true)]); + assert!(is_guide(&s, a)); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); + assert_eq!(undo_steps(&s), steps + 1); + let r = run(&mut s, "app.activeDocument.pathItems[0].guides = true;").unwrap(); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps + 1, &json!([])), "a value the path has runs no command"); + log(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(!is_guide(&s, a)); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + let out = log(&mut s, "try { app.activeDocument.pathItems[0].guides = 1; } catch (e) { vc.log(e.name); }"); + assert_eq!(out, vec![json!("TypeError")]); + assert!(!is_guide(&s, a)); + // A path in a group becomes a guide on its own; the other path in the group stays a path. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems[1]; p.name = 'assigned'; p.guides = true;"); + let (assigned, other) = if node(&s, a).name.as_deref() == Some("assigned") { (a, b) } else { (b, a) }; + assert_eq!(node(&s, assigned).name.as_deref(), Some("assigned")); + assert_eq!((is_guide(&s, assigned), is_guide(&s, other)), (true, false), "only the assigned path in the group is a guide"); + assert!(s.active().unwrap().selection.is_empty(), "the selection stays as it was"); +} + +#[test] +fn assigning_guides_refuses_compound_members_clipping_paths_and_paths_that_cannot_be_edited() { + 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 before = art(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("compound path"), "{e}"); + assert_eq!((art(&s), is_guide(&s, a), is_guide(&s, b)), (before, false, false), "no member of the compound path changed"); + + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = art(&s); + let e = failure(&mut s, "var ps = app.activeDocument.pathItems; for (var i = 0; i < ps.length; i++) if (ps[i].clipping) ps[i].guides = true;"); + assert!(e.contains("clipping path"), "{e}"); + assert_eq!(art(&s), before); + + for cmd in ["object.lock", "object.hide"] { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute(cmd, &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("Cannot edit"), "{cmd}: {e}"); + assert!(!is_guide(&s, a), "{cmd}"); + } +} + +#[test] +fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(is_guide(&s, a)); + s.set_guides_locked(true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(e.contains("guides are locked"), "{e}"); + let e = failure(&mut s, "app.activeDocument.pathItems[1].guides = true;"); + assert!(e.contains("guides are locked"), "{e}"); + assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps)); + log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); + assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); +} diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 184f43cc4a..8fd3e8c8fe 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -5,7 +5,7 @@ use std::cell::Cell; use serde_json::{Value, json}; -use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES}; +use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_GROWTH_BYTES, TEST_RESULT_BYTES}; use crate::*; fn rect(x: i64) -> Value { @@ -1371,6 +1371,54 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() { assert_eq!(state(&s), before); } +#[test] +fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() { + // The point change waits in the object model until the script ends. + let source = "app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, -4];"; + let mut s = two_docs(); + let start = s.documents()[1].doc.clone(); + assert_eq!(run(&mut s, source).unwrap()["ok"], true); + let added = start.retained_bytes_each(&s.documents()[1].doc).1 as u64; + assert!(added >= 3, "{added}"); + // The change goes past this allowance and stays within twice it. + TEST_GROWTH_BYTES.with(|g| g.set(Some(added * 2 / 3))); + let run_to_the_question = |s: &mut Session| { + s.script_frames = true; + run(s, source).unwrap(); + for _ in 0..1_000 { + if s.script_waiting() { + break; + } + assert!(s.script_pump().is_none()); + } + assert!(s.script_waiting()); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); + }; + let mut s = two_docs(); + let before = state(&s); + let undo = s.documents()[1].history.undo.len(); + run_to_the_question(&mut s); + assert_eq!(state(&s), before); + s.script_continue(); + assert!(!s.script_waiting()); + let done = s.script_pump().expect("the run ends once it may go on"); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(s.documents()[1].history.undo.len(), undo + 1); + assert_ne!(state(&s), before); + + let mut s = two_docs(); + let before = state(&s); + run_to_the_question(&mut s); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + let ended = s.script_pump().expect("a stopped run ends"); + TEST_GROWTH_BYTES.with(|g| g.set(None)); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert!(!s.script_running()); + assert_eq!(state(&s), before); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1a842e6a86..d8b6c989d5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -83,7 +83,8 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \ + Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType \ + PolarityValues RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags Transformation View Views \ ZOrderMethod", ), ("Application.", "prototype"), @@ -107,8 +108,13 @@ const INSIDE: &[(&str, &str)] = &[ ( "Document.prototype.", "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ - documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ - pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \ + defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \ + defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \ + defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \ + defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \ + defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \ + groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \ + rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \ symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), @@ -129,6 +135,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 guides= length pathPoints polarity polarity= resize resolution resolution= rotate 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", + ), ("Tags.", "prototype"), ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), ("Tag.", "prototype"), @@ -150,8 +175,14 @@ 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"), ("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"), + ("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"), + ("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"), + ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ( "", @@ -282,9 +313,11 @@ const INSIDE: &[(&str, &str)] = &[ ("TextFrame.prototype.", "contentVariable contentVariable="), ]; -/// The classes the host adds with nothing but a prototype and its constructor: the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem"; +/// The classes the host adds with nothing but a prototype and its constructor: the page item types +/// other than `PathItem`, and the color classes. +const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ + IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ + SymbolItem 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/gaps.md b/docs/gaps.md index 1acbfa6149..1d0694fce1 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -846,11 +846,12 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes) +- **Missing:** the rest of the document object model for scripts (layers, artboards, gradient stops and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and character and paragraph attributes, their links to each other and the stories they form, its character and - paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries. + paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and + `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..7ed0eebae6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3079,7 +3079,8 @@ through `$`: a list of at most 10,000, `null` or `[]`. Any other value, `undefined` included (such as an index past the end of `pageItems`), throws a `TypeError`, and an object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or - with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other + selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined` @@ -3094,7 +3095,100 @@ through `$`: layer, a document or the application does not have does not keep the value; it does not throw, except in strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. 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 that this page does not describe 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. `add()` and the shape creators put the new path on top of the active layer whatever the drawing + mode, which stays as it was. 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`, `selectedPathPoints`, `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`. Changes to the + points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one + `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the + script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points + read as the grid snaps them. + `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`, `selected`, + `parent` and `remove()`. Assigning `guides` makes the path a guide with `view.guides.make` (`true`) or a path again + with `view.guides.release` (`false`), with the selection kept; a value that is not a boolean throws a `TypeError`. + `PathPoint.selected` reads `PathPointSelection.ANCHORPOINT` for a selected anchor point and + `PathPointSelection.NOSELECTION` otherwise; assigning `ANCHORPOINT` adds the point to the direct-selected anchors and + `NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept. + `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `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`, and so does a point read before the script removed + a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other + than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, + `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an + object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, + and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` + to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a + path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's + segment selection. Changing `selected` adds no undo step. Selecting a point of a path that cannot be selected + throws `Cannot select`, and selecting a point of a guide while guides are locked throws an error. A clipping path + cannot be made a guide, and `guides = true` on one throws an error. Assigning `guides` the value a path already + has runs no command. Assigning the other value throws an error that says it is not available yet on a path inside + a compound path, throws `Cannot edit` on a path that is hidden, locked or cannot be selected, and throws an error + while guides are locked. 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. A component reads with the fewest + decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it + was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a + global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new + art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the + stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. + `fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. 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`. A transform that leaves the path where it is, such as `rotate(360)` or + `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. 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. `transform`, `polarity` and the gradient stops + are not available yet. +- A `Document`'s default paint members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set what + the next object drawn gets, as `appearance.newArt` reports it, the same for every open document: `defaultFillColor`, + `defaultFilled`, `defaultFillOverprint`, `defaultStrokeColor`, `defaultStroked`, `defaultStrokeOverprint`, + `defaultStrokeWidth`, `defaultStrokeCap`, `defaultStrokeJoin`, `defaultStrokeMiterLimit`, `defaultStrokeDashes` + (`[]` or `{}` for a solid line) and `defaultStrokeDashOffset`. Assigning one runs `appearance.setNewArt`, which + leaves the selection, its art, the active Fill or Stroke proxy and Recent Colors as they were and adds no undo step. + A value that changes nothing runs no command, and a bad value throws an error with nothing changed. VectorCraft's + own rules: assigning a color also makes `defaultFilled` or `defaultStroked` true, and a `NoColor` makes it false; + `defaultFilled` or `defaultStroked` set to true with no fill or stroke gives black; an RGB color is stored in the + front document's color mode, as `paint.setFill` stores it; `defaultStrokeWidth` is 0 to 1000 points, a dash or gap 0 + to 1,000,000 points (at most 64, not all 0), and `defaultStrokeDashOffset` -1,000,000 to 1,000,000 points, which + needs a dash pattern unless it is 0; while New Art Has Basic Appearance is off and an object is selected, assigning + a default throws an error, since new art then takes that object's appearance. `scaleFactor` + (https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts lists it as read-only) is always 1, since + VectorCraft draws every document at its own size; after an assignment it still reads 1. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both @@ -10259,6 +10353,13 @@ colorized) changes nothing. With the option off (`appearance.setNewArtBasic {on: whole appearance of the last selected object. `appearance.newArt` reports what the next object gets; `paint.default` resets it. `appearance.setNewArtBasic` rejects an `on` value that is not a boolean. Omitting `on` toggles the current preference. +`appearance.setNewArt {fill?, stroke?, weight?, cap?, join?, miterLimit?, dash?, dashOffset?, fillOverprint?, +strokeOverprint?}` sets new art's fill, stroke and stroke options whatever is selected, and leaves the selection, its +art, the active proxy and Recent Colors as they were. `fill` and `stroke` take a paint as `paint.setFill` does, and +`tint` only with a global or spot `swatch`. Without `weight` the stored stroke weight stays; a stroke painted on new +art without one gets 1 pt only when that stored weight is 0. Every value is checked before +anything changes, and any change while New Art Has Basic Appearance is off and an object is selected is an error. It +returns `{changed}`, false when the next object would look the same. ```json {"name":"run_command","arguments":{"command":"select.none","params":{}}} @@ -10396,7 +10497,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +rows, spacing, rightToLeft}` (`rows`, 1 to 1000 and rounded to a whole number, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), @@ -10600,8 +10701,8 @@ runs, as `document.open` reads its file when it runs. A file larger than 64 MiB When the file is a link or a folder, cannot be read, is too large or is not a native document, or the request's read roots leave out the folder (whether or not the file exists), the document starts with the defaults and `file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and -a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's -file. The +a script's `app.documents.addDocument` throws it. Reading the profile's file is not limited to the script's folder (the +`File` and `Folder` rule in [Script engines](#script-engines)), but the request's automation read roots still apply. The reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the diff --git a/docs/nightly-release-preparation.md b/docs/nightly-release-preparation.md index 3d9d1fe494..c2b4917fad 100644 --- a/docs/nightly-release-preparation.md +++ b/docs/nightly-release-preparation.md @@ -78,9 +78,13 @@ Read on 2026-11-24; re-read anything that may have moved before `nightly-signer` | `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` | | `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist | | `platforms` | three rows | Learning Machines stable identities (Windows Authenticode publisher subject, Linux OpenPGP fingerprint, Apple Developer ID team `DJ6XS33FX8`) | -| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 8 jobs | Workflow list API; jobs that succeeded on recent main push runs | +| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135806`), 9 jobs | Workflow list API; jobs that succeeded on recent main push runs | | `candidate_policy.sonar` | `storytold` / `storytold_vectorcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits | +The signer reads the policy from `nightly-signer`, so a candidate whose CI ran six test shards +(`test 1/6` to `test 6/6`) is admitted only after `nightly-signer` advances to a main commit with +this policy. Candidates whose CI ran five shards should be signed before that advance. + ## Ownership and interface - `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..f2d93a4568 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1120,13 +1120,15 @@ 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: `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, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). - `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index d8c86d36a2..9738b641bd 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -110,7 +110,7 @@ def assert_caller_secrets(source, job_name, names): for value, children in (*root.values(), *job.values()): outside_map = "\n".join([value or "", *children]) # Scan all remaining text: quoted braces can appear before a secret reference. - if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map): + if re.search(r"(?im)(?:^\s*environment:)|(?:\bsecrets\b)", outside_map): raise ValueError("secret bindings belong only in the signer map") @@ -600,10 +600,13 @@ def app_workflows(): return {path.name: path.read_text() for path in sorted((ROOT / ".github/workflows").glob("*.y*ml"))} -WORKFLOW_KEY = re.compile(r'''("(?:[^"\\]|\\.)*"|'(?:[^']|'')*'|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*?|-[^\s:#][^:#,{}]*?)\s*:(?:\s+(.*))?$''') +WORKFLOW_KEY = re.compile( + r'''((?:"(?:[^"\\]|\\.)*"|'(?:[^']|'')*')[ \t]*|[^\s'"#{}\[\],:&*!|>%@`?-][^:#,{}]*|-[^\s:#][^:#,{}]*):(?:[ \t]+(.*))?$''' +) def _workflow_key(text): + text = text.rstrip() if text.startswith('"'): return None if "\\" in text else text[1:-1] if text.startswith("'"): @@ -620,7 +623,10 @@ def _workflow_value(text): if text.startswith("'"): quoted = re.match(r"'((?:[^']|'')*)'\s*(?:#.*)?$", text) return None if quoted is None else quoted.group(1).replace("''", "'") - return re.split(r"\s+#", text, maxsplit=1)[0].strip() + for idx, ch in enumerate(text): + if ch == "#" and idx > 0 and text[idx - 1].isspace(): + return text[:idx].rstrip() + return text def _strip_comment(text): diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 28f0622914..ba0ed79acf 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -23,7 +23,7 @@ mod version; mod web_fonts; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode}; +use std::process::{Command, ExitCode, Stdio}; const USAGE: &str = "\ usage: cargo xtask @@ -264,12 +264,63 @@ fn has_nextest() -> bool { /// The workspace's unit and integration tests, without examples (clippy still checks those). /// nextest runs each test in its own process, in parallel across all test binaries. fn cmd_test() -> Result<(), String> { - test_packages(&["--workspace".to_owned()], "--workspace") + test_packages(&["--workspace".to_owned()], "--workspace", None) } -/// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`. -fn test_packages(select: &[String], shown: &str) -> Result<(), String> { +/// [`cmd_test`] for the packages `select` picks (`--workspace` or `-p` ids), shown as `shown`; +/// with `part`, only that part's share of their tests (xtask/src/shards.rs), which needs nextest. +fn test_packages(select: &[String], shown: &str, part: Option) -> Result<(), String> { const TARGETS: [&str; 3] = ["--lib", "--bins", "--tests"]; + if let Some(part) = part { + if !has_nextest() { + return Err(format!("cargo nextest run {shown}: a shard that runs part of a crate's tests needs cargo-nextest")); + } + let mut c = cargo(); + c.args(["nextest", "list", "--color", "never", "--message-format", "json"]).args(select).args(TARGETS); + let out = c.stderr(Stdio::inherit()).output().map_err(|e| format!("cargo nextest list {shown}: failed to spawn: {e}"))?; + if !out.status.success() { + return Err(format!("cargo nextest list {shown}: exited with {}", out.status)); + } + let missing = part.missing_pins(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("cargo nextest list {shown}: {e}"))?; + if !missing.is_empty() { + return Err(format!( + "cargo nextest list {shown}: no test has the full name of pinned test(s) {} (update `pinned` in xtask/src/shards.rs)", + missing.join(", ") + )); + } + let command = |args: Vec| { + let mut c = cargo(); + c.args(["nextest", "run"]).args(select).args(TARGETS).args(&args); + let quoted = args.iter().map(|a| if a.contains(' ') { format!("'{a}'") } else { a.clone() }).collect::>().join(" "); + (c, format!("cargo nextest run {shown} --lib --bins --tests {quoted}")) + }; + let cpus = std::thread::available_parallelism().map_or(1, usize::from); + let pinned_threads = part.pins().max(1).min(cpus.saturating_sub(1).max(1)); + let counted_threads = if part.pins() == 0 { cpus } else { cpus.saturating_sub(pinned_threads).max(1) }; + let mut runs = part.runs().into_iter(); + let mut counted = runs.next().ok_or_else(|| format!("cargo nextest run {shown}: no counted run"))?; + counted.extend(["--test-threads".to_owned(), counted_threads.to_string()]); + let pinned = runs + .next() + .map(|mut args| { + args.extend(["--test-threads".to_owned(), pinned_threads.to_string()]); + let (mut c, what) = command(args); + eprintln!("$ {what}"); + c.spawn().map(|child| (child, what.clone())).map_err(|e| format!("{what}: failed to spawn: {e}")) + }) + .transpose()?; + let (c, what) = command(counted); + let counted_result = run(c, &what); + let pinned_result = match pinned { + None => Ok(()), + Some((mut child, what)) => match child.wait() { + Ok(status) if status.success() => Ok(()), + Ok(status) => Err(format!("{what}: exited with {status}")), + Err(e) => Err(format!("{what}: failed to wait: {e}")), + }, + }; + return counted_result.and(pinned_result); + } let mut c = cargo(); if has_nextest() { c.args(["nextest", "run"]).args(select).args(TARGETS); @@ -307,7 +358,8 @@ fn cmd_ci() -> Result<(), String> { /// `cargo xtask ci shard`: shard `GATE_SHARD` of `GATE_SHARDS` (1-based, as the shared gate /// workflow sets them). A test shard runs the shard checks, then the tests and doctests of its -/// crates, and the i18n report where it tests vectorcraft-ui-egui. The checks shard runs every +/// crates, and the i18n report where it tests vectorcraft-ui-egui; a part of a split runs its +/// share of the tests, and only part 1 the doctests and the report. The checks shard runs every /// other `ci` step and the shard checks. fn cmd_ci_shard() -> Result<(), String> { let number = |key: &str| -> Result { @@ -327,16 +379,22 @@ fn cmd_ci_shard() -> Result<(), String> { let checked = shards::run()?; let mut steps: Vec = Vec::new(); match &checked[shard - 1] { - shards::Shard::Tests(crates) => { + shards::Shard::Tests(crates, part) => { let names = shards::names(crates); - eprintln!("ci shard {shard}/{count}: the tests of {names}"); + let share = part.map(|p| format!(" (part {} of {})", p.index, p.split.parts())).unwrap_or_default(); + eprintln!("ci shard {shard}/{count}: the tests of {names}{share}"); let select = shards::select(crates); let shown = crates.iter().map(|m| format!("-p {}", m.name)).collect::>().join(" "); + let part = *part; let (s, w) = (select.clone(), shown.clone()); - steps.push(("test", Box::new(move || test_packages(&s, &w)))); + steps.push(("test", Box::new(move || test_packages(&s, &w, part)))); + // The doctests and the i18n report run once, on a split's first part. + let first = part.is_none_or(|p| p.is_first()); let (s, w) = (select.clone(), shown.clone()); - steps.push(("doctests", Box::new(move || doctest_packages(&s, &w)))); - if crates.iter().any(|m| m.name == "vectorcraft-ui-egui") { + if first { + steps.push(("doctests", Box::new(move || doctest_packages(&s, &w)))); + } + if first && crates.iter().any(|m| m.name == "vectorcraft-ui-egui") { steps.push(("i18n-report", Box::new(move || i18n_report_packages(&select, &shown)))); } } @@ -361,7 +419,11 @@ fn cmd_ci_warm() -> Result<(), String> { let checked = shards::run()?; let mut steps: Vec = Vec::new(); for shard in checked { - if let shards::Shard::Tests(crates) = shard { + // A split's later parts build the same tests as its first. + if let shards::Shard::Tests(crates, part) = shard { + if part.is_some_and(|p| !p.is_first()) { + continue; + } steps.push(( "build tests", Box::new(move || { diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index a885619b15..1baede03bd 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -10,6 +10,12 @@ //! its features in `cargo test --workspace`. Cargo resolves features over the packages a command //! selects, so a feature that only another crate's dev-dependencies turn on is off in a shard //! without that crate, and the tests behind it do not build. +//! +//! A [`Split`] runs the tests of its crates on several shards in a row ([`Group::Part`]). Each +//! part builds the same tests and runs its share of them: the tests its `pinned` list names, and +//! every other test of the crates by nextest's counted partition (`--partition count:/` +//! with the pinned tests filtered out, so each of them runs once). The doctests and the i18n +//! report run on part 1. use std::collections::{BTreeMap, BTreeSet}; @@ -20,15 +26,53 @@ use serde_json::Value; pub enum Group { /// The tests of these workspace crates (package names). Crates(&'static [&'static str]), + /// Part `k` (1-based) of a split's tests. Parts 1 to n of a split are consecutive shards. + Part(&'static Split, usize), /// The tests of every workspace member no other group names. Rest, /// The `cargo xtask ci` steps that are not tests. Checks, } +/// Crates whose tests run on several shards, one [`Group::Part`] each. +#[derive(Debug, PartialEq, Eq)] +pub struct Split { + /// The workspace crates (package names). + pub crates: &'static [&'static str], + /// For each part, the full names of the tests it runs outside the counted partition (the + /// slowest ones, spread so that no part waits on all of them). Its length is the part count. + pub pinned: &'static [&'static [&'static str]], +} + +impl Split { + /// How many shards the split runs on. + pub fn parts(&self) -> usize { + self.pinned.len() + } +} + +/// vectorcraft-ui-egui's tests, on two shards. The pinned tests took 23 to 74 s each in CI +/// (run 46256086023), and each part's pinned tests add up to about 120 to 130 s. +pub static UI_EGUI: Split = Split { + crates: &["vectorcraft-ui-egui"], + pinned: &[ + &[ + "panels::actions::tests_edits::every_listed_menu_item_runs_from_the_menu_what_its_step_holds", + "dialogs::revolve::tests::a_3d_row_sets_its_param_previews_and_applies_in_one_step", + "shortcuts::tests::alt_chords_type_special_characters_while_editing_text", + ], + &[ + "palette::tests::the_palette_leaves_out_the_commands_a_pick_cannot_run", + "chrome::tests::the_control_bar_leaves_members_out_in_its_priority_order", + "menus::tests::help_f1_opens_discover_without_a_document", + ], + ], +}; + /// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length. pub const GROUPS: &[Group] = &[ - Group::Crates(&["vectorcraft-ui-egui"]), + Group::Part(&UI_EGUI, 1), + Group::Part(&UI_EGUI, 2), Group::Crates(&["vectorcraft-engine"]), Group::Crates(&["vectorcraft", "vectorcraft-web", "vectorcraft-cli", "vectorcraft-mcp", "xtask"]), Group::Rest, @@ -45,13 +89,70 @@ pub struct Member { pub version: String, } -/// What one shard runs, with its crates resolved. +/// What one shard runs, with its crates resolved; a shard of a [`Split`] carries its part. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Shard { - Tests(Vec), + Tests(Vec, Option), Checks, } +/// Part `index` (1-based) of `split`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Part { + pub split: &'static Split, + pub index: usize, +} + +impl Part { + /// The number of tests this part pins. + pub fn pins(&self) -> usize { + self.split.pinned[self.index - 1].len() + } + + /// The arguments `cargo nextest run` takes after the package and target selection, once for + /// each run this part makes: the counted share (`--partition count:/`, with every + /// pinned test filtered out when the split pins any), then the tests this part pins. + /// The counted run passes `--no-tests=pass`. The pinned run keeps nextest's default and + /// fails when no tests match. + pub fn runs(&self) -> Vec> { + let all: Vec<&str> = self.split.pinned.iter().flat_map(|p| p.iter().copied()).collect(); + let mut counted = vec!["--partition".to_owned(), format!("count:{}/{}", self.index, self.split.parts()), "--no-tests=pass".to_owned()]; + if !all.is_empty() { + counted.extend(["-E".to_owned(), format!("not ({})", exact(&all))]); + } + let mut runs = vec![counted]; + let own = self.split.pinned[self.index - 1]; + if !own.is_empty() { + runs.push(vec!["-E".to_owned(), exact(own)]); + } + runs + } + + /// The tests this part pins whose full names are absent from + /// `cargo nextest list --message-format json` output. Invalid listings return an error. + pub fn missing_pins(&self, list: &str) -> Result, String> { + let list: Value = serde_json::from_str(list).map_err(|e| format!("invalid JSON listing: {e}"))?; + let suites = list.get("rust-suites").and_then(Value::as_object).ok_or("JSON listing has no `rust-suites` map")?; + let mut listed = BTreeSet::new(); + for (binary, suite) in suites { + let tests = + suite.get("testcases").and_then(Value::as_object).ok_or_else(|| format!("JSON listing has no `testcases` map for `{binary}`"))?; + listed.extend(tests.keys().map(String::as_str)); + } + Ok(self.split.pinned[self.index - 1].iter().copied().filter(|p| !listed.contains(p)).collect()) + } + + /// Whether this part runs the doctests and the i18n report. + pub fn is_first(&self) -> bool { + self.index == 1 + } +} + +/// A filterset that matches each of `names` exactly. +fn exact(names: &[&str]) -> String { + names.iter().map(|n| format!("test(={n})")).collect::>().join(" | ") +} + /// The workspace members of `cargo metadata --no-deps` output, in its order. pub fn members(meta: &Value) -> Result, String> { let ids: BTreeSet<&str> = meta["workspace_members"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); @@ -72,22 +173,49 @@ pub fn members(meta: &Value) -> Result, String> { } /// Each group of `groups` with its crates: a named crate must be a workspace member and named -/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. +/// once, there must be exactly one [`Group::Rest`], and no test shard may be empty. A split's +/// parts 1 to n must be consecutive shards, with at least two parts, and no test pinned twice. pub fn assign(groups: &[Group], members: &[Member]) -> Result, String> { const WHERE: &str = "xtask/src/shards.rs › GROUPS"; let mut named: BTreeMap<&str, usize> = BTreeMap::new(); for (i, g) in groups.iter().enumerate() { - if let Group::Crates(names) = g { - if names.is_empty() { - return Err(format!("shard {} names no crates ({WHERE})", i + 1)); + let names = match g { + Group::Crates(names) => *names, + Group::Part(split, k) => { + let n = split.parts(); + if n < 2 { + return Err(format!("shard {} is a part of a split with {n} part(s), not 2 or more ({WHERE})", i + 1)); + } + // Part 1 of the split is shard `first` (0-based) when this shard is part k. + let in_order = (1..=n).contains(k) + && (i + 1).checked_sub(*k).is_some_and(|first| { + (1..=n).all(|p| matches!(groups.get(first + p - 1), Some(Group::Part(s, q)) if *s == *split && *q == p)) + }); + if !in_order { + return Err(format!("shard {} is part {k} of a split whose {n} parts are not shards 1 to {n} in a row ({WHERE})", i + 1)); + } + if *k > 1 { + continue; + } + let mut pinned = BTreeSet::new(); + for name in split.pinned.iter().flat_map(|p| p.iter()) { + if !pinned.insert(*name) { + return Err(format!("`{name}` is pinned to two parts of shard {}'s split ({WHERE})", i + 1)); + } + } + split.crates } - for name in *names { - if !members.iter().any(|m| m.name == *name) { - return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); - } - if let Some(first) = named.insert(name, i) { - return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)); - } + Group::Rest | Group::Checks => continue, + }; + if names.is_empty() { + return Err(format!("shard {} names no crates ({WHERE})", i + 1)); + } + for name in names { + if !members.iter().any(|m| m.name == *name) { + return Err(format!("shard {} names `{name}`, which is not a workspace member ({WHERE})", i + 1)); + } + if let Some(first) = named.insert(name, i) { + return Err(format!("`{name}` is in shard {} and shard {} ({WHERE})", first + 1, i + 1)); } } } @@ -100,13 +228,14 @@ pub fn assign(groups: &[Group], members: &[Member]) -> Result, String .iter() .enumerate() .map(|(i, g)| match g { - Group::Crates(names) => Ok(Shard::Tests(pick(&|m| names.contains(&m.name.as_str())))), + Group::Crates(names) => Ok(Shard::Tests(pick(&|m| names.contains(&m.name.as_str())), None)), + Group::Part(split, index) => Ok(Shard::Tests(pick(&|m| split.crates.contains(&m.name.as_str())), Some(Part { split, index: *index }))), Group::Rest => { let rest = pick(&|m| !named.contains_key(m.name.as_str())); if rest.is_empty() { return Err(format!("shard {} takes the remaining crates, and there are none ({WHERE})", i + 1)); } - Ok(Shard::Tests(rest)) + Ok(Shard::Tests(rest, None)) } Group::Checks => Ok(Shard::Checks), }) @@ -184,7 +313,7 @@ pub fn check() -> Result, String> { let workspace = tree_features(&tree(&["--workspace".to_owned()])?, &members); let mut differences = Vec::new(); for (i, shard) in shards.iter().enumerate() { - if let Shard::Tests(crates) = shard { + if let Shard::Tests(crates, _) = shard { let alone = tree_features(&tree(&select(crates))?, &members); differences.extend(feature_differences(i + 1, crates, &workspace, &alone)); } @@ -206,7 +335,10 @@ pub fn run() -> Result, String> { let shards = check()?; for (i, shard) in shards.iter().enumerate() { match shard { - Shard::Tests(crates) => println!("shard {}/{}: tests of {} crate(s): {}", i + 1, shards.len(), crates.len(), names(crates)), + Shard::Tests(crates, part) => { + let share = part.map(|p| format!(", part {} of {}", p.index, p.split.parts())).unwrap_or_default(); + println!("shard {}/{}: tests of {} crate(s): {}{share}", i + 1, shards.len(), crates.len(), names(crates)) + } Shard::Checks => println!("shard {}/{}: the other ci steps", i + 1, shards.len()), } } @@ -224,11 +356,130 @@ mod tests { fn crates(shard: &Shard) -> Vec<&str> { match shard { - Shard::Tests(c) => c.iter().map(|m| m.name.as_str()).collect(), + Shard::Tests(c, _) => c.iter().map(|m| m.name.as_str()).collect(), Shard::Checks => Vec::new(), } } + /// The crates of each shard that runs a crate's tests from the start: a part after the first + /// runs a share of the same tests, so it is counted with part 1. + fn owners(shard: &Shard) -> Vec<&str> { + match shard { + Shard::Tests(_, Some(p)) if !p.is_first() => Vec::new(), + _ => crates(shard), + } + } + + /// The tests (binary ids and full names, in the order nextest lists them) that one `cargo nextest run` with + /// `args` from [`Part::runs`] runs, as nextest selects them: the `-E` filterset (`test(=…)` + /// terms joined by `|`, or `not (…)` of them) first, then `--partition count:/`, which + /// keeps the i-th (0-based) test the filter left in each binary when `i % n` is `k - 1`. + fn selected<'a>(args: &[String], tests: &[(&'a str, &'a str)]) -> Vec<(&'a str, &'a str)> { + let value = |flag: &str| args.iter().position(|a| a == flag).map(|i| args[i + 1].as_str()); + let filtered: Vec<(&str, &str)> = match value("-E") { + None => tests.to_vec(), + Some(expr) => { + let (negated, body) = expr.strip_prefix("not (").and_then(|e| e.strip_suffix(')')).map_or((false, expr), |b| (true, b)); + let names: Vec<&str> = body.split(" | ").map(|t| t.strip_prefix("test(=").and_then(|t| t.strip_suffix(')')).unwrap()).collect(); + tests.iter().copied().filter(|(_, t)| names.contains(t) != negated).collect() + } + }; + match value("--partition") { + None => filtered, + Some(p) => { + let (k, n) = p.strip_prefix("count:").and_then(|p| p.split_once('/')).unwrap(); + let (k, n): (usize, usize) = (k.parse().unwrap(), n.parse().unwrap()); + let mut counts = BTreeMap::new(); + filtered + .into_iter() + .filter(|(binary, _)| { + let count = counts.entry(*binary).or_insert(0); + let selected = *count % n == k - 1; + *count += 1; + selected + }) + .collect() + } + } + } + + /// The tests each part of `split` runs, over all of its runs. + fn share<'a>(split: &'static Split, tests: &[(&'a str, &'a str)]) -> Vec> { + (1..=split.parts()).map(|index| Part { split, index }.runs().iter().flat_map(|args| selected(args, tests)).collect()).collect() + } + + static SPLIT: Split = Split { crates: &["a"], pinned: &[&["a::slow1", "a::slow3"], &["a::slow2"]] }; + + #[test] + fn a_split_runs_on_its_parts_in_a_row() { + let ws = [m("a"), m("b")]; + let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap(); + assert_eq!(shards.iter().map(crates).collect::>(), [vec!["a"], vec!["a"], vec!["b"], vec![]]); + assert_eq!(shards[1], Shard::Tests(vec![m("a")], Some(Part { split: &SPLIT, index: 2 }))); + let apart = assign(&[Group::Part(&SPLIT, 1), Group::Rest, Group::Part(&SPLIT, 2)], &ws).unwrap_err(); + assert!(apart.contains("not shards 1 to 2 in a row"), "{apart}"); + let missing = assign(&[Group::Part(&SPLIT, 2), Group::Rest], &ws).unwrap_err(); + assert!(missing.contains("shard 1 is part 2"), "{missing}"); + let twice = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Crates(&["a"]), Group::Rest], &ws).unwrap_err(); + assert!(twice.contains("`a` is in shard 1 and shard 3"), "{twice}"); + const ONE: Split = Split { crates: &["a"], pinned: &[&[]] }; + assert!(assign(&[Group::Part(&ONE, 1), Group::Rest], &ws).unwrap_err().contains("not 2 or more")); + const DOUBLE: Split = Split { crates: &["a"], pinned: &[&["a::t"], &["a::t"]] }; + assert!(assign(&[Group::Part(&DOUBLE, 1), Group::Part(&DOUBLE, 2), Group::Rest], &ws).unwrap_err().contains("pinned to two parts")); + } + + #[test] + fn every_test_of_a_split_runs_on_exactly_one_part() { + let tests = [ + ("a::lib", "a::t1"), + ("a::lib", "a::slow1"), + ("a::lib", "a::t2"), + ("a::lib", "a::t3"), + ("a::bin/a", "a::slow2"), + ("a::bin/a", "a::t4"), + ("a::bin/a", "a::t5"), + ("a::bin/a", "a::slow3"), + ]; + let parts = share(&SPLIT, &tests); + assert_eq!( + parts, + [ + vec![("a::lib", "a::t1"), ("a::lib", "a::t3"), ("a::bin/a", "a::t4"), ("a::lib", "a::slow1"), ("a::bin/a", "a::slow3")], + vec![("a::lib", "a::t2"), ("a::bin/a", "a::t5"), ("a::bin/a", "a::slow2")], + ] + ); + let mut all = parts.concat(); + all.sort_unstable(); + let mut want = tests.to_vec(); + want.sort_unstable(); + assert_eq!(all, want); + let (one, two) = (Part { split: &SPLIT, index: 1 }, Part { split: &SPLIT, index: 2 }); + assert_eq!( + one.runs(), + [ + vec![ + "--partition".to_owned(), + "count:1/2".to_owned(), + "--no-tests=pass".to_owned(), + "-E".to_owned(), + "not (test(=a::slow1) | test(=a::slow3) | test(=a::slow2))".to_owned(), + ], + vec!["-E".to_owned(), "test(=a::slow1) | test(=a::slow3)".to_owned()], + ] + ); + assert!(one.is_first() && !two.is_first()); + let list = r#"{"rust-suites":{"a::lib":{"testcases":{"a::t1":{},"a::slow1":{}}},"a::bin/a":{"testcases":{"a::slow2":{}}}}}"#; + assert_eq!(one.missing_pins(list).unwrap(), ["a::slow3"]); + assert!(two.missing_pins(list).unwrap().is_empty()); + assert!(one.missing_pins("invalid JSON").is_err()); + assert!(one.missing_pins("{}").is_err()); + assert!(one.missing_pins(r#"{"rust-suites":{"a::lib":{}}}"#).is_err()); + // A split that pins nothing passes no filterset, which nextest would reject as `not ()`. + static BARE: Split = Split { crates: &["a"], pinned: &[&[], &[]] }; + assert_eq!(Part { split: &BARE, index: 2 }.runs(), [vec!["--partition".to_owned(), "count:2/2".to_owned(), "--no-tests=pass".to_owned()]]); + assert_eq!(share(&BARE, &tests).concat().len(), tests.len()); + } + #[test] fn the_rest_shard_takes_every_crate_no_group_names() { let ws = [m("a"), m("b"), m("c"), m("d")]; @@ -259,7 +510,7 @@ mod tests { fn every_workspace_member_is_tested_on_exactly_one_shard() { let ws = members(&crate::metadata().unwrap()).unwrap(); let shards = assign(GROUPS, &ws).unwrap(); - let mut tested: Vec<&str> = shards.iter().flat_map(crates).collect(); + let mut tested: Vec<&str> = shards.iter().flat_map(owners).collect(); tested.sort_unstable(); let mut all: Vec<&str> = ws.iter().map(|m| m.name.as_str()).collect(); all.sort_unstable();