From e97b0b49ae6d94acaad0ed4a2fe75832bf32ce13 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:31:11 -0800 Subject: [PATCH] Scripts: Document default fill and stroke members and scaleFactor A script that read or assigned a document's defaultFillColor, defaultStrokeWidth or another default paint member, or read scaleFactor, got undefined. The twelve default members now read and set the fill, stroke and stroke options of the next object drawn, and scaleFactor reads 1. - appearance.setNewArt sets new art's fill, stroke and stroke options whatever is selected, leaving the selection, its art, the active proxy and Recent Colors as they were. Every value is checked before anything changes. - The default members run it only when the value changes. A bad value throws an error with nothing changed. - paths.rs shares its dash length checks with defaultStrokeDashes. --- crates/engine/src/cmd/newart.rs | 131 ++++++++++- crates/engine/src/script/dom.rs | 2 + crates/engine/src/script/dom/defaults.rs | 212 ++++++++++++++++++ crates/engine/src/script/dom/paths.rs | 26 ++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/newart.rs | 69 ++++++ .../engine/src/tests/script_dom_defaults.rs | 144 ++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 9 +- docs/mcp.md | 23 +- docs/target-app-parity.md | 3 +- 10 files changed, 605 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/script/dom/defaults.rs create mode 100644 crates/engine/src/tests/script_dom_defaults.rs diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index a42088e7e3..56e7e4dfe8 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` @@ -20,7 +21,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STY use vectorcraft_tools::PaintDefaults; use super::gradient::unplaced; -use super::{CommandSpec, Result, Session, always, cmd, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, cmd, switch_or}; pub fn specs() -> Vec { vec![ @@ -42,9 +43,135 @@ 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. A stroke painted on new art without one gets a 1 pt weight unless `weight` is given. 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 largest dash, gap or dash offset `appearance.setNewArt` takes, in points. +const MAX_DASH_LENGTH: f64 = 1_000_000.0; + +/// `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 v.get("tint").is_some() && v.get("swatch").is_none() { + 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)) => { + if !a.iter().all(|v| v.as_f64().is_some_and(|n| n.is_finite() && (0.0..=MAX_DASH_LENGTH).contains(&n))) { + return Err(bad(C, format!("each dash length must be a number from 0 to {MAX_DASH_LENGTH}"))); + } + if !a.is_empty() && a.iter().all(|v| v.as_f64() == Some(0.0)) { + 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.bucket_paints() && 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/script/dom.rs b/crates/engine/src/script/dom.rs index 8b2267a5d8..8cc774bd92 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -39,6 +39,7 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; +mod defaults; mod paths; /// The error for a member read or called with no document open. @@ -1928,6 +1929,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, doc_selection, doc_set_selection)), ("pathItems", get(l, paths::doc_path_items)), ]); + document.extend(defaults::document_members(l)); document.extend( ["layers", "artboards", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() diff --git a/crates/engine/src/script/dom/defaults.rs b/crates/engine/src/script/dom/defaults.rs new file mode 100644 index 0000000000..fe8eb5c3f3 --- /dev/null +++ b/crates/engine/src/script/dom/defaults.rs @@ -0,0 +1,212 @@ +//! 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, HostMember}; + +use super::paths::{CAPS, JOINS, MAX_STROKE_WIDTH, dash_lengths}; +use super::{Answer, Host, Link, arg, boolean, colors, command, get, num, number, property, this_doc}; + +/// 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 = match (&color, &now) { + (None, Paint::None) => true, + (Some(c), Paint::Solid { color, swatch: None, .. }) => c == color, + _ => false, + }; + 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).abs() < 1e-9, 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).abs() < 1e-9, 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).abs() < 1e-9, 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<(String, HostMember)> { + let members: Vec<(&str, HostMember)> = vec![ + ("defaultFillColor", property(l, |h, a| default_color(h, a, true), |h, a| set_default_color(h, a, true))), + ("defaultFilled", property(l, |h, a| default_painted(h, a, true), |h, a| set_default_painted(h, a, true))), + ("defaultFillOverprint", property(l, |h, a| default_overprint(h, a, true), |h, a| set_default_overprint(h, a, true))), + ("defaultStrokeColor", property(l, |h, a| default_color(h, a, false), |h, a| set_default_color(h, a, false))), + ("defaultStroked", property(l, |h, a| default_painted(h, a, false), |h, a| set_default_painted(h, a, false))), + ("defaultStrokeOverprint", property(l, |h, a| default_overprint(h, a, false), |h, a| set_default_overprint(h, a, false))), + ("defaultStrokeWidth", property(l, default_stroke_width, set_default_stroke_width)), + ("defaultStrokeCap", property(l, default_cap, set_default_cap)), + ("defaultStrokeJoin", property(l, default_join, set_default_join)), + ("defaultStrokeMiterLimit", property(l, default_miter, set_default_miter)), + ("defaultStrokeDashes", property(l, default_dashes, set_default_dashes)), + ("defaultStrokeDashOffset", property(l, default_dash_offset, set_default_dash_offset)), + ("scaleFactor", get(l, scale_factor)), + ]; + members.into_iter().map(|(k, m)| (k.to_string(), m)).collect() +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32401db1d0..29b5e44719 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -797,13 +797,15 @@ fn path_set_stroke_width(h: &super::Host, a: &[Data]) -> Answer { set_stroke_option(h, item, (look.width - w).abs() < 1e-9, json!({"weight": w})) } -const CAPS: &[(LineCap, &str, &str)] = &[ +/// 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"), ]; -const JOINS: &[(LineJoin, &str, &str)] = &[ +/// 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"), @@ -856,21 +858,27 @@ fn path_dashes(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Array(this_look(h, a)?.1.dashes.into_iter().map(num).collect())) } -/// `strokeDashes = [lengths]`: at most [`MAX_DASHES`] finite lengths that are not negative and -/// not all 0; `[]` or `{}` gives a solid line. -fn path_set_dashes(h: &super::Host, a: &[Data]) -> Answer { - let lengths: Vec = match arg(a, 1) { +/// 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!("strokeDashes takes at most {MAX_DASHES} lengths"))), + 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("strokeDashes must be an array of lengths".into())), + _ => return Err(HostError::Type(format!("{what} must be an array of lengths"))), }; if lengths.iter().any(|l| !(0.0..=MAX_STROKE_WIDTH * 1000.0).contains(l)) { return Err(HostError::Range("each dash length must be from 0 to 1000000 points".into())); } if !lengths.is_empty() && lengths.iter().all(|l| *l == 0.0) { - return Err(HostError::Range("strokeDashes needs a length that is not 0".into())); + return Err(HostError::Range(format!("{what} needs a length that is not 0"))); } + Ok(lengths) +} + +/// `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})) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a611da1857..6826625700 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_defaults; mod script_dom_paths; mod script_engines; mod script_folder; diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 583a5f43d8..ef0f0c8b50 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -299,3 +299,72 @@ 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}), + ] { + 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_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/script_dom_defaults.rs b/crates/engine/src/tests/script_dom_defaults.rs new file mode 100644 index 0000000000..cc6c53eb4e --- /dev/null +++ b/crates/engine/src/tests/script_dom_defaults.rs @@ -0,0 +1,144 @@ +//! 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 r = run(&mut s, "var d = app.activeDocument; var w = d.defaultStrokeWidth; d.defaultStrokeWidth += 1; vc.log(d.defaultStrokeWidth > w);") + .unwrap(); + assert_eq!(r["log"], json!([true])); + 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"); + let wider = s.new_art().stroke().unwrap().width; + 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)]); + assert!(wider > 1.0); +} + +#[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 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/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 24417b2c21..3c67918b7e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -97,9 +97,14 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ + "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate defaultFillColor \ + defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= defaultStrokeCap \ + defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset defaultStrokeDashOffset= \ + defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= defaultStrokeMiterLimit \ + defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= defaultStrokeWidth defaultStrokeWidth= \ + defaultStroked defaultStroked= documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + rulerUnits saveAs saveAs= scaleFactor selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index e3d4e634ed..ee0e5b2372 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,7 +2749,22 @@ app through the global object `vc`, and writes to the Script Console and runs ot changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `selectedPathPoints`, `PathPoint.selected`, - `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. + `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. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -8810,6 +8825,12 @@ 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; a +stroke painted on new art without one gets a 1 pt weight unless `weight` is given. 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":{}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 72ed713051..56b8b1d8fd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops 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: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.