diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 24c274846b..064fb3b5cf 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -6,7 +6,7 @@ //! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also //! take the comma-separated legacy form (). //! Hues take the angle units of CSS Values 4 (). A hex -//! color may leave out its `#`. +//! color may leave out its `#`. [`format`] writes a color in these forms. //! //! The module reads a subset of CSS. A function's arguments are literal numbers, percentages, //! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`, @@ -89,6 +89,126 @@ fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } +/// The forms [`format`] writes a color in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Notation { + /// `#rrggbb`. + Hex, + /// `#rrggbbaa`, `ff` for a color without an alpha. + HexAlpha, + /// `rgb(51 102 153)`. + Rgb, + /// `hsl(210 50% 40%)`. + Hsl, + /// `oklch(49.93% 0.0987 250.43)`. + Oklch, +} + +/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation` +/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of +/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form +/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and +/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and +/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a +/// gray is 0. [`Notation::Hex`] leaves the alpha out. +pub fn format(rgb: [f32; 3], alpha: Option, notation: Notation) -> String { + // A NaN alpha reads as none. + let alpha = alpha.filter(|a| !a.is_nan()); + let bytes = rgb.map(byte); + let units = bytes.map(|v| f64::from(v) / 255.0); + let [r, g, b] = bytes; + match notation { + Notation::Hex => hex_of(rgb), + Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))), + Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)), + Notation::Hsl => { + let [h, s, l] = rgb_to_hsl(units); + format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha)) + } + Notation::Oklch => { + let lch = oklab::to_oklch(units.map(|v| v as f32)); + // The fewest places that read back to the same bytes, from two (four for chroma). + let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes); + let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch))); + let places = |base: i32| usize::try_from(base + p).unwrap_or(2); + let c = number(c, places(4)); + // A chroma that rounds to 0 is a gray, whose hue is 0. + let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) }; + format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha)) + } + } +} + +/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the +/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under +/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of +/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at +/// the rounded lightness and hue; the chroma is lowered a step at a time instead. +fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> { + let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra)); + let step = 10f64.powi(-(4 + extra)); + let mut c = rounded(c, 4 + extra); + for _ in 0..OKLCH_CHROMA_STEPS { + if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) { + return Some([l, c.max(0.0), h]); + } + c = rounded(c - step, 4 + extra); + } + None +} + +/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB. +const OKLCH_CHROMA_STEPS: usize = 50; + +/// `v` rounded to `places` decimal places. +fn rounded(v: f64, places: i32) -> f64 { + let f = 10f64.powi(places); + (v * f).round() / f +} + +/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing. +fn alpha_part(alpha: Option) -> String { + let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2); + if percent == "100" { String::new() } else { format!(" / {percent}%") } +} + +/// A hue in degrees to two places, 360 written as 0. +fn hue_text(h: f64) -> String { + hue_text_to(h, 2) +} + +/// A hue in degrees to `places` places, 360 written as 0. +fn hue_text_to(h: f64, places: usize) -> String { + let text = number(h, places); + if text == "360" { "0".to_string() } else { text } +} + +/// `v` to `places` decimal places, without trailing zeros or a sign on zero. +fn number(v: f64, places: usize) -> String { + let text = format!("{v:.places$}"); + let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() }; + if text == "-0" { "0".to_string() } else { text.to_string() } +} + +/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's +/// rgbToHsl (); the hue of a gray is 0. +fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] { + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let (d, l) = (max - min, (max + min) / 2.0); + if d == 0.0 { + return [0.0, 0.0, l]; + } + let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h * 60.0, s, l] +} + /// A hex color of 3, 4, 6 or 8 digits, with or without `#`. fn hex(text: &str) -> Option { let digits = text.strip_prefix('#').unwrap_or(text); @@ -412,6 +532,26 @@ mod tests { assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); } + #[test] + fn format_writes_each_notation_with_the_alpha_where_it_belongs() { + let rgb = [0.2, 0.4, 0.6]; + let half = Some(0.5); + assert_eq!(format(rgb, half, Notation::Hex), "#336699"); + assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980"); + assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)"); + assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)"); + assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out"); + assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)"); + assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)"); + assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)"); + assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)"); + assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)"); + assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)"); + assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)"); + } + proptest! { #[test] fn random_text_never_panics(text in "\\PC{0,60}") { @@ -439,5 +579,23 @@ mod tests { prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a)); prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}")); } + + #[test] + fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let alpha = f32::from(a) / 255.0; + for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] { + let text = format(rgb, Some(alpha), notation); + let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse")); + prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text); + let read = c.alpha.unwrap_or(1.0); + match notation { + Notation::Hex => prop_assert_eq!(c.alpha, None), + Notation::HexAlpha => prop_assert_eq!(byte(read), a), + // A percentage to two places, left out when it rounds to 100. + _ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read), + } + } + } } } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index dd18bcadcb..4a4b998782 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -146,6 +146,15 @@ pub fn specs() -> Vec { always, parse_color ), + cmd!( + query "color.format", + "Format Color", + [], + None, + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + always, + format_color + ), cmd!( query "color.contrast", "Contrast", @@ -158,6 +167,31 @@ pub fn specs() -> Vec { ] } +fn format_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.format"; + let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?; + let opacity = super::paint::opacity_param(p, C)?; + let notation = match text_param(p, "notation", C)? { + Some("hex") => Some(css::Notation::Hex), + Some("hexAlpha") => Some(css::Notation::HexAlpha), + Some("rgb") => Some(css::Notation::Rgb), + Some("hsl") => Some(css::Notation::Hsl), + Some("oklch") => Some(css::Notation::Oklch), + Some("cmyk") => None, + _ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")), + }; + let cms = vectorcraft_color::cms::active(); + let intent = cms.settings().intent; + let text = match notation { + None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)), + Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")), + // The working RGB numbers, as the Color panel's hex field and color.parse read them; for + // oklch() the working RGB space is sRGB. + Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n), + }; + Ok(json!({ "text": text })) +} + fn parse_color(_: &mut Session, p: &Value) -> Result { const C: &str = "color.parse"; let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?; diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 660df05f71..4f498e972a 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -91,6 +91,8 @@ //! deselects it as before), Global Edit ends when fewer than two members are left, and leaving //! one out is not an undo step. +use std::sync::Arc; + use serde::Serialize; use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Scaling, Shared, StrokeLayer}; @@ -214,8 +216,18 @@ struct Form { frame: Affine, } +#[cfg(test)] +thread_local! { + /// Tests: how many times [`Form::of`] reduced an object to its form on this thread. + pub(crate) static FORMS_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many times [`outlines`] made the outline of a highlighted object on this thread. + pub(crate) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl Form { fn of(n: &Node) -> Option { + #[cfg(test)] + FORMS_MADE.with(|c| c.set(c.get() + 1)); let mut f = Self { tag: vec![], symbols: vec![], points: vec![], frame: Affine::IDENTITY }; f.add(n, 0)?; let first = *f.points.first()?; @@ -450,8 +462,8 @@ fn matches(s: &Session, o: &Options) -> Result> { ), }; let on = |r: Rect, b: Rect| b.intersect(r).area() > 0.0 || vectorcraft_doc::artboard_holds(r, b.center()); - let in_scope = |n: &Node| { - let Some(b) = n.geometric_bounds_with(&symbols) else { return false }; + let in_scope = |b: Option| { + let Some(b) = b else { return false }; if !d.artboards.iter().any(|a| on(a.rect, b)) { return o.include_canvas; } @@ -459,14 +471,16 @@ fn matches(s: &Session, o: &Options) -> Result> { }; // A copy that lies the same way has the size of the selected object when their boxes are as // wide and as high; a turned copy, when the transform that lays the object on it doesn't scale. - let same_size = |n: &Node, xf: Affine, turned: bool| { + let same_size = |b: Option, xf: Affine, turned: bool| { if turned { close(xf.determinant().abs().sqrt(), 1.0) } else { - matches!((key_size, size(n)), (Some((w, h)), Some((w2, h2))) if close(w, w2) && close(h, h2)) + matches!((key_size, b), (Some((w, h)), Some(b)) if close(w, b.width()) && close(h, b.height())) } }; let mut out = vec![(*id, Affine::IDENTITY)]; + let mut cache = st.global_edit_forms.0.borrow_mut(); + let mut pass = cache.forms.pass(); super::select::walk_selectable(d, st.isolation, |n| { if n.id == *id || out.len() >= MAX_MEMBERS { return false; @@ -482,21 +496,134 @@ fn matches(s: &Session, o: &Options) -> Result> { _ => false, }; // The object count first: it turns most objects down before their form is made. - if n.children().map(Vec::len) == count - && let Some((xf, turned)) = Form::of(n).and_then(|f| form.onto(&f)).filter(|_| supported(n)) - && (!o.size || same_size(n, xf, turned)) - && (!o.appearance || same_look(key, n)) - && in_scope(n) - { - out.push((n.id, xf)); - // A group taken is taken whole, as compound paths, symbol instances and the others are. - return false; + if n.children().map(Vec::len) != count { + return look_in; + } + let seen = pass.get(n, || Seen { form: Form::of(n).filter(|_| supported(n)), bounds: None }); + if let Some((xf, turned)) = seen.form.as_ref().and_then(|f| form.onto(f)) { + let b = seen.bounds(n, &symbols); + if (!o.size || same_size(b, xf, turned)) && (!o.appearance || same_look(key, n)) && in_scope(b) { + out.push((n.id, xf)); + // A group taken is taken whole, as compound paths, symbol instances and the others are. + return false; + } } look_in }); + cache.forms.end(pass, d); Ok(out) } +/// What [`matches`] and [`outlines`] found for each object they looked at, kept from one call to +/// the next so that after an edit only the objects the edit replaced are measured again. A clone +/// starts empty. +#[derive(Default)] +pub struct FormCache(std::cell::RefCell); + +#[derive(Default)] +struct FormCacheInner { + forms: ByNode, + /// The outline of each highlighted object, or `None` when it has none and its box is shown. + outlines: ByNode>, +} + +/// An object as [`matches`] found it. +struct Seen { + /// Its form, or `None` when Global Edit doesn't support it. + form: Option
, + /// Its geometric bounds, once measured; not kept for an object with symbol instances, whose + /// bounds follow the symbols' art. + bounds: Option>, +} + +impl Seen { + fn bounds(&mut self, n: &Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> Option { + if self.form.as_ref().is_some_and(|f| !f.symbols.is_empty()) { + return n.geometric_bounds_with(symbols); + } + *self.bounds.get_or_insert_with(|| n.geometric_bounds_with(symbols)) + } +} + +/// Values found for nodes of a document, by node address. The layers they were found in are held, +/// which keeps every node in them alive and unchanged (an edit replaces each node it changes), so +/// no other node can have that address while its entry is here. +struct ByNode { + layers: Vec>, + values: ByAddress, +} + +impl Default for ByNode { + fn default() -> Self { + Self { layers: vec![], values: ByAddress::default() } + } +} + +/// Values by node address. +type ByAddress = std::collections::HashMap>; + +/// Hashes a node address: a multiply that spreads its bits, with the high half folded into the low +/// half (addresses are aligned, so their low bits are always the same). +#[derive(Default)] +struct AddressHasher(u64); + +impl std::hash::Hasher for AddressHasher { + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3); + } + } + + fn write_usize(&mut self, n: usize) { + let x = (n as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15); + self.0 = x ^ (x >> 32); + } + + fn finish(&self) -> u64 { + self.0 + } +} + +/// One walk of a document: the values it asks for, taken from the ones kept or found anew. +struct Pass { + old: ByAddress, + new: ByAddress, +} + +impl Pass { + fn get(&mut self, n: &Node, find: impl FnOnce() -> T) -> &mut T { + let at = std::ptr::from_ref(n) as usize; + let old = &mut self.old; + self.new.entry(at).or_insert_with(|| old.remove(&at).unwrap_or_else(find)) + } +} + +impl ByNode { + fn pass(&mut self) -> Pass { + let old = std::mem::take(&mut self.values); + Pass { new: ByAddress::with_capacity_and_hasher(old.len(), Default::default()), old } + } + + /// Keep the values `pass` asked for, found in `d`. + fn end(&mut self, pass: Pass, d: &Document) { + self.values = pass.new; + self.layers.clone_from(&d.layers); + } +} + +impl Clone for FormCache { + fn clone(&self) -> Self { + Self::default() + } +} + +impl std::fmt::Debug for FormCache { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let c = self.0.borrow(); + f.debug_struct("FormCache").field("forms", &c.forms.values.len()).field("outlines", &c.outlines.values.len()).finish() + } +} + fn can_toggle(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.global_edit.is_some() { @@ -935,20 +1062,45 @@ pub fn similar(s: &Session) -> Outlines { /// selected object, in their layer's color. fn outlines(st: &crate::DocState, members: &[(NodeId, Affine)]) -> Outlines { let symbols = st.doc.symbol_boxes(); - members + let mut cache = st.global_edit_forms.0.borrow_mut(); + let mut pass = cache.outlines.pass(); + let out = members .iter() .filter_map(|(id, _)| { - let n = st.doc.node(*id).filter(|n| !holds(n, &st.selection.objects))?; - if st.doc.ancestry(*id).is_some_and(|a| a.iter().any(|p| st.selection.objects.contains(p))) { - return None; + // One look-up of the object's place, then down through its layers and groups: none of + // them may be selected, and the innermost layer gives the color. + let (mut nodes, mut found, mut layer) = (&st.doc.layers, None, None); + for i in st.doc.index_path(*id)? { + let c: &Node = nodes.get(i)?; + if st.selection.objects.contains(&c.id) { + return None; + } + if c.is_layer() { + layer = Some(c); + } + if let Some(ch) = c.children() { + nodes = ch; + } + found = Some(c); } - let path = match n.stroke_path() { - Some(p) => p, + let n = found.filter(|n| n.id == *id && !holds(n, &st.selection.objects))?; + let color = match layer.map(|l| &l.kind) { + Some(NodeKind::Layer { color, .. }) => color.rgb(), + _ => vectorcraft_doc::LAYER_COLORS[0].1, + }; + let path = match pass.get(n, || { + #[cfg(test)] + OUTLINES_MADE.with(|c| c.set(c.get() + 1)); + n.stroke_path() + }) { + Some(p) => p.clone(), None => n.geometric_bounds_with(&symbols)?.to_path(0.1), }; - Some((path, st.doc.layer_color(*id))) + Some((path, color)) }) - .collect() + .collect(); + cache.outlines.end(pass, &st.doc); + out } #[cfg(test)] diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 88ee200c2c..c722e2a58b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -913,9 +913,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { apply_paint_opacity(s, p, paint, opacity, fill) } -/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None` -/// when it is left out or null. -fn opacity_param(p: &Value, cmd: &str) -> Result> { +/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as +/// 0..1; `None` when it is left out or null. +pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result> { match p.get("opacity") { None | Some(Value::Null) => Ok(None), Some(v) => match v.as_f64() { diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 99d6cc60b9..61406fdc61 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; -use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject}; +use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject}; use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} remove them, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers, objects at 0% opacity and their members, and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step, except the clipping paths of groups and layers and what a group or compound path used as one holds → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}", has_doc, clean_up ), @@ -1715,12 +1715,152 @@ fn is_painted(a: &Appearance) -> bool { }) } +/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value. +pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4; +/// The widths Hairline Slivers takes, in points. +pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive = 0.001..=3.0; + +/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string +/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`]. +pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result { + let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH); + if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) { + let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end()); + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt"))); + } + Ok(w) +} + +/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths +/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke), +/// whose fill no circle `width` across fits inside? A compound path is measured as one fill. +/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]). +/// A hidden member of a compound path is measured too, since the compound path paints it. +fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option { + // A shape with no fill that paints is left to Unpainted Objects. + if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) { + return Some(false); + } + let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule), + NodeKind::Compound { children, rule } => { + let mut all = vec![]; + for c in children { + let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) }; + all.extend(path.subpaths.iter()); + } + (all, *rule) + } + _ => return Some(false), + }; + // Paths of one anchor are stray points, and open paths are lines. + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) { + return Some(false); + } + po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget) +} + +/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an +/// effect on the object or on one of its fills and strokes? +fn draws_beyond_its_fill(a: &Appearance) -> bool { + a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty()) +} + +/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a +/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping +/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers +/// leaves its members alone. +fn holds_generated_art(n: &Node) -> bool { + let e = n.extras(); + vectorcraft_tools::builder::is_live_paint(n) + || e.type_outlines + || e.clip_pieces + || e.graph.is_some() + || e.shaper.is_some() + || e.dimension.is_some() + || e.flare.is_some() + || e.trace.is_some() + || e.objects_on_path.is_some() + || e.live_paint_gaps.is_some() + || e.compound_shape +} + +/// The objects Hairline Slivers finds in `d` for `width`. +pub(crate) struct Slivers { + pub ids: Vec, + /// Closed paths and compound paths whose fill couldn't be measured, which are left as they are. + pub unmeasured: Vec, +} + +/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any. +pub(crate) fn unmeasured_warning(count: usize) -> Option { + (count > 0).then(|| { + format!( + "Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are" + ) + }) +} + +/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not +/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and +/// groups of the whole document. A compound path counts as one object. The clipping paths of groups +/// and layers (and all of a clipping group used as one), the members of live and generated art, +/// objects at 0 % opacity and everything in a group or layer at 0 %, and the members of groups and +/// layers whose own stroke or effect paints them are left out. +pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers { + struct Walk<'a> { + width: f64, + locks: LockedArtboards<'a>, + within: &'a dyn Fn(NodeId) -> bool, + // One budget for the whole document, so that thousands of shapes that need a search take + // a bounded time; the shapes after it runs out count as unmeasured. + budget: po::ThicknessBudget, + out: Vec<(NodeId, Option)>, + } + fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) { + // An object at 0 % opacity, or anything in a group or layer at 0 %, paints nothing. + if !n.visible || n.locked || n.is_template() || clip_path || n.opacity <= 0.0 { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) { + return; + } + let clips = n.clips(); + for (i, c) in children.iter().enumerate() { + visit(c, clips && i == 0, w); + } + } + // Art on a locked artboard, or outside `within`, is left out before it is measured. + NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => { + match is_hairline_sliver(n, w.width, &mut w.budget) { + Some(false) => {} + found => w.out.push((n.id, found)), + } + } + _ => {} + } + } + let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] }; + for l in &d.layers { + visit(l, false, &mut w); + } + let mut found = w.out; + let editable = d.editable(); + found.retain(|(id, _)| editable(*id)); + let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some()); + Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() } +} + fn clean_up(s: &mut Session, p: &Value) -> Result { const C: &str = "object.path.cleanUp"; let stray = switch_or(p, "strayPoints", true, C)?; let unpainted = switch_or(p, "unpaintedObjects", true, C)?; let empty_text = switch_or(p, "emptyTextPaths", true, C)?; - let found = { + let slivers = switch_or(p, "hairlineSlivers", false, C)?; + let width = sliver_width(p, "sliverWidth", C)?; + let (found, warning) = { let d = &s.doc()?.doc; let mut v = vec![]; fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec, opts: (bool, bool, bool)) { @@ -1763,10 +1903,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } let editable = d.editable(); v.retain(|id| editable(*id)); - v + let mut warning = None; + if slivers { + let found = hairline_slivers(d, width, &|_| true); + let listed: BTreeSet = v.iter().copied().collect(); + // A shape another option removes isn't left as it is. + warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count()); + v.extend(found.ids.into_iter().filter(|id| !listed.contains(id))); + } + (v, warning) + }; + let reply = |removed: usize| match &warning { + Some(w) => json!({ "removed": removed, "warning": w }), + None => json!({ "removed": removed }), }; if found.is_empty() { - return Ok(json!({ "removed": 0 })); + return Ok(reply(0)); } s.edit("Clean Up", |d, _| { let mut gone = Beside::replacing(d, &found); @@ -1777,7 +1929,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } gone.finish(d) })?; - Ok(json!({ "removed": found.len() })) + Ok(reply(found.len())) } // ---------- Divide Objects Below ---------- diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index e890c2b65f..10899074d9 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1468,11 +1468,11 @@ fn install(s: &mut Session, p: &Value) -> Result { // A heavy plug-in is installed once a person agrees. if plugin.manifest().budget == Budget::Heavy && !allow_heavy { let (minutes, times) = vectorcraft_plugins::heavy_terms(); + let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME); return Err(bad( C, format!( - "“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants", - plugin.manifest().name + "“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants" ), )); } @@ -1615,6 +1615,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result { if !refused.is_empty() { v["refusedCommands"] = json!(refused); } + let translations = &plugin.manifest().translations; + if !translations.is_empty() { + v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null); + } v }) } @@ -2447,7 +2451,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file or a .vcplugin manifest (desktop) | dataBase64: the module or a JavaScript plug-in's JSON, name?: the file name shown as its source (with dataBase64)} validate a plug-in without installing it, running none of its code → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)", always, inspect ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 612cf436b7..c2699f219c 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -152,6 +152,7 @@ pub(super) const ALLOWED: &[&str] = &[ "charStyle.setAttrs", "charStyle.unused", "color.convert", + "color.format", "color.gamutCheck", "color.harmony", "color.parse", @@ -541,6 +542,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.object.brushStrokes", "select.object.clippingMasks", "select.object.directionHandles", + "select.object.hairlineSlivers", "select.object.notAlignedToPixelGrid", "select.object.pointText", "select.object.slices", diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 194df59e51..6ad6c51d8f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -18,7 +18,7 @@ use crate::script; pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"]; /// The extensions of the scripts `script.run` takes as a file, in any case. -pub const RUN_EXTS: &[&str] = &["js", "jsx"]; +pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"]; /// Does `path` name a file `script.run` takes? pub fn runs(path: &str) -> bool { @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "List Installed Scripts", [], None, - "{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", + "{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", always, list_installed ), @@ -198,6 +198,7 @@ fn prepare(s: &Session, p: &Value) -> Result { let actions = script::actions::parse(p.get("actions")).map_err(param)?; let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; + let module = switch_or(p, "module", script::include::module_script(path), "script.run")?; let mut checked_real = None; let text = match (path, source) { (Some(""), None) => return Err(param("`path` is empty")), @@ -213,7 +214,7 @@ fn prepare(s: &Session, p: &Value) -> Result { return Err(EngineError::Other(COMPILED.to_string())); } if !runs(path) { - return Err(param("`path` must name a .js or .jsx file")); + return Err(param("`path` must name a .js, .mjs or .jsx file")); } // One byte more than a script may have shows that the file is too large. let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?; @@ -242,6 +243,7 @@ fn prepare(s: &Session, p: &Value) -> Result { fuel, locale, answers, + module, actions, }) } @@ -444,6 +446,7 @@ impl Session { fuel, locale, answers: vec![], + module: script::include::module_script(path.to_str()), actions: vec![], }; let runs = self.script_runs; diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index eb504b6074..931504dedb 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; use super::panelcmds::artboard_at; +use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning}; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param, @@ -205,6 +206,15 @@ pub fn specs() -> Vec { cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| p.anchor_count() == 1))), + cmd!( + "select.object.hairlineSlivers", + "Hairline Slivers…", + ["Select", "Object"], + None, + "{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, objects at 0% opacity and their members, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}", + has_doc, + select_hairline_slivers + ), cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| !p.is_closed()))), @@ -1459,6 +1469,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result { Ok(json!({ "count": s.doc()?.selection.objects.len() })) } +/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes +/// ([`hairline_slivers`]), inside the isolated group while one is isolated. +fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.object.hairlineSlivers"; + let width = sliver_width(p, "width", C)?; + let st = s.doc()?; + let (d, iso) = (&st.doc, st.isolation); + let locks = d.locked_artboards(); + let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id)); + let warning = unmeasured_warning(found.unmeasured.len()); + s.select(|_, sel| sel.set(found.ids))?; + let count = s.doc()?.selection.objects.len(); + Ok(match warning { + Some(w) => json!({ "count": count, "warning": w }), + None => json!({ "count": count }), + }) +} + /// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned /// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk /// does not look at the paths inside it. diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 4f05e615af..e1bb6df83a 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -86,6 +86,9 @@ pub struct DocState { /// Whether Start Global Edit supports the one selected object /// ([`cmd::globaledit::SupportCache`]), as of a revision. Not saved, not undoable. pub(crate) global_edit_support: cmd::globaledit::SupportCache, + /// The forms Start Global Edit compared the selected object with + /// ([`cmd::globaledit::FormCache`]). Not saved, not undoable. + pub(crate) global_edit_forms: cmd::globaledit::FormCache, /// What leaving symbol editing mode goes back to ([`cmd::symboledit`]). pub(crate) symbol_edit_return: cmd::symboledit::Return, pub interaction: Option, @@ -481,6 +484,7 @@ impl DocState { global_edit: None, similar_outlines: Default::default(), global_edit_support: Default::default(), + global_edit_forms: Default::default(), symbol_edit_return: Default::default(), interaction: None, undo_group: None, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index abff443d46..d5641d9606 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -715,6 +715,15 @@ impl ScriptScope { /// The real path of the file at `path` and its first `max` bytes, at most. pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { + match self.read_unless(path, max, |_| false)? { + (real, Some(bytes)) => Ok((real, bytes)), + (_, None) => Err(ScriptRead::Failed("the file was not read".to_string())), + } + } + + /// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened: + /// → its real path and no bytes. + pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option>), ScriptRead> { use std::io::Read; if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { return Err(ScriptRead::Refused); @@ -730,6 +739,9 @@ impl ScriptScope { if !self.allows(&real) { return Err(ScriptRead::Refused); } + if known(&real) { + return Ok((real, None)); + } let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?; if !meta.is_file() { @@ -747,7 +759,7 @@ impl ScriptScope { if std::fs::canonicalize(path).ok().as_ref() != Some(&real) { return Err(ScriptRead::Refused); } - Ok((real, bytes)) + Ok((real, Some(bytes))) } /// The first granted folder, as people read it (`None` for a script given as text). @@ -966,6 +978,21 @@ mod tests { p.to_string_lossy().into_owned() } + /// A file the caller already has is not opened: its size is not checked and no byte is read. + #[test] + fn a_known_script_file_is_not_read_again() { + let (base, _) = folders("known"); + std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap(); + let scope = ScriptScope::of_folder(&base.join("in")); + let path = base.join("in/big.js"); + assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge)); + let real = std::fs::canonicalize(&path).unwrap(); + assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None))); + assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64))); + assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused)); + let _ = std::fs::remove_dir_all(base); + } + /// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind /// only one grants is not granted. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2cdb0f6239..48964aad0c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -33,7 +33,7 @@ pub use cmd::flare::flare_settings; pub use cmd::gradient::{GradientEditPaints, StopOwner}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::{auto_simplify_level, can_outline_stroke}; +pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level, can_outline_stroke}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7c50925bf0..a5bcbe015f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -44,6 +44,9 @@ //! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. //! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. //! - `app.activeDocument` with no document open throws `No active document`. +//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run +//! made; with no such step they change nothing, and with no document open they throw +//! `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. `undefined` throws. //! - `controlBounds` is the visible bounds, widened to take in the direction points of every path @@ -827,6 +830,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach +/// only the steps the run made. With no step to undo or redo they change nothing. +fn app_history(h: &Host, id: &str, redo: bool) -> Answer { + let has_step = { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() } + }; + if has_step { + command(h, id, &json!({}))?; + } + Ok(Data::Undefined) +} + +fn app_undo(h: &Host, _: &[Data]) -> Answer { + app_history(h, "edit.undo", false) +} + +fn app_redo(h: &Host, _: &[Data]) -> Answer { + app_history(h, "edit.redo", true) +} + fn app_selection(h: &Host, _: &[Data]) -> Answer { let uid = h.session.borrow().active().map(|st| st.uid); match uid { @@ -1746,6 +1771,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + // The ids listed so far; `ids` keeps them in the order they were first listed. let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); @@ -2677,6 +2703,8 @@ fn classes(link: &Link) -> Vec { ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ("redraw", method(l, app_redraw), returns("undefined", &[])), + ("undo", method(l, app_undo), returns("undefined", &[])), + ("redo", method(l, app_redo), returns("undefined", &[])), ("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])), ("toString", class_text("Application"), returns("string", &[])), ]); diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index f9e6c49be5..1b2212c44d 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -1,4 +1,4 @@ -//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a +//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a //! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]). //! //! A listing reads names and file types only, never a script's text. It follows no link: a symbolic @@ -279,7 +279,7 @@ pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool { .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } -/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most +/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most /// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there /// and none is a link, and neither the file nor a folder below `root` is marked hidden or system? pub fn holds(root: &Path, path: &Path) -> bool { diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index ae6b41b1a1..acaee51910 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -37,11 +37,21 @@ //! //! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of //! the file it is in. +//! +//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules +//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing +//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL +//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would +//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`], +//! so a link that leads out of the script's folder is refused as well. Module files count against +//! the same limits as included files, and the paths of one file (two spellings, a link, or names +//! that differ only in letter case on Windows) give one module. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; -use vectorcraft_js::{DirectiveName, Options}; +use vectorcraft_js::{DirectiveName, LoadError, Options}; use crate::file_access::{ScriptRead, ScriptScope}; @@ -219,13 +229,65 @@ pub(crate) struct Files { frames: Vec, /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. es2015: bool, + /// The modules a module run has read, by key ([`module_key`]): the names of the folders each + /// is in, below the script's folder. + module_dirs: HashMap>, + /// The key of each module path read, below the script's folder. + module_paths: HashMap, + /// The key [`Files::module_entry`] gave the script, in a module run. + entry_key: Option, } /// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in -/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as -/// ECMAScript 5.1 with the ExtendScript extensions. +/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text +/// run as ECMAScript 5.1 with the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { - path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs")) +} + +/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case). +pub(crate) fn module_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs")) +} + +/// What names the file at the real path `real` among a run's modules: on Unix its device and file +/// number, so two paths to one file give one module; elsewhere its real path, which on Windows +/// spells each name in the letter case the folder stores it in, so two spellings of one file in a +/// folder that ignores case give one module and two files in a folder that does not stay two. +fn module_key(real: &Path) -> String { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let Ok(m) = std::fs::metadata(real) { + return format!("{}:{}", m.dev(), m.ino()); + } + } + display(real).to_string() +} + +/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is +/// not `root` or below it, or has a name that is not Unicode. +fn names_below(root: &Path, dir: &Path) -> Option> { + dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect() +} + +/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between +/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error. +fn specifier_names(specifier: &str) -> Result, LoadError> { + let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}"))); + if !(specifier.starts_with("./") || specifier.starts_with("../")) { + return wrong("must start with './' or '../'"); + } + if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) { + return wrong("must not contain \\, : or control characters"); + } + let names: Vec<&str> = specifier.split('/').collect(); + let file = names.last().copied().unwrap_or_default(); + let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default(); + if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) { + return wrong("must name a .mjs or .js file"); + } + Ok(names) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -321,9 +383,91 @@ impl Files { levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], es2015: es2015_script(path), + module_dirs: HashMap::new(), + module_paths: HashMap::new(), + entry_key: None, } } + /// Makes the run's files read ECMAScript 2015, as a module run given as text does. + pub(crate) fn read_es2015(&mut self) { + self.es2015 = true; + } + + /// The module `text`, the script's own, as a source of one file. → its key and the source. + pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> { + self.bytes = self.bytes.saturating_add(text.len()); + let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); + let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default(); + self.module_dirs.insert(key.clone(), Vec::new()); + self.entry_key = Some(key.clone()); + let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; + Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None })) + } + + /// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or + /// this function gave). → the module's key, with its text and source map the first time the + /// run reads it. + pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> { + let names = specifier_names(specifier)?; + let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?; + for name in names { + match name { + "" | "." => {} + ".." => { + if path.pop().is_none() { + return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'"))); + } + } + name => path.push(name.to_string()), + } + } + let relative = path.join("/"); + if let Some(key) = self.module_paths.get(&relative) { + return Ok((key.clone(), None)); + } + let root = + self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?; + self.probes += 1; + if self.probes > MAX_PROBES { + return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached"))); + } + let candidate = path.iter().fold(root.clone(), |p, name| p.join(name)); + // Another path to a module already read gives that module: the file is not read again, and + // its text is not counted again. + let loaded = &self.module_dirs; + let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real))); + let (real, bytes) = match read { + Ok(found) => found, + Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))), + Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))), + Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))), + Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))), + }; + let key = module_key(&real); + let Some(bytes) = bytes else { + self.module_paths.insert(relative, key.clone()); + return Ok((key, None)); + }; + if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { + return Err(LoadError::Range("script source limit reached (32 MiB)".to_string())); + } + if self.files >= MAX_FILES { + return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); + } + let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + self.bytes += bytes.len(); + self.files += 1; + self.module_paths.insert(relative, key.clone()); + // The module's relative imports start from the folder the file is in, whichever path to it + // was read first; the path as written stands in when that folder is not below the script's. + path.pop(); + let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path); + self.module_dirs.insert(key.clone(), dir); + let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; + Ok((key, Some((text, map)))) + } + /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() } @@ -362,12 +506,26 @@ impl Files { self.expand(shown, dir, text, true) } - /// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its - /// preprocessor lines read. It becomes the file being run until [`Files::end_eval`]. - pub(crate) fn eval_file(&mut self, path: &str) -> Result { + /// The folder of the module `key` ([`Files::module`] gave it), from the script's folder. + pub(crate) fn module_dir(&self, key: &str) -> Option { + let names = self.module_dirs.get(key)?; + let root = self.frames.first().and_then(|f| f.dir.clone())?; + Some(names.iter().fold(root, |p, name| p.join(name))) + } + + /// The script's folder when the run is a module run ([`Files::module_entry`] read the script), + /// or `None` for a script run. + pub(crate) fn entry_module_dir(&self) -> Option { + self.module_dir(self.entry_key.as_deref()?) + } + + /// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder + /// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It + /// becomes the file being run until [`Files::end_eval`]. + pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option) -> Result { let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 }; - let dir = self.frames.last().and_then(|f| f.dir.clone()); + let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone())); let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?; let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?; let shown = display(&real); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 5fd8e0b88b..615e9f2197 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -66,7 +66,8 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_js::{ - Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind, + Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, + Realm, RunError, RunErrorKind, }; use crate::{ @@ -207,6 +208,8 @@ pub(crate) struct Request { pub locale: String, /// The answers to the dialogs of a run with nobody to ask, in order. pub answers: Vec, + /// The script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]). + pub module: bool, /// The actions `app.doScript` can play. pub actions: Vec, } @@ -784,6 +787,9 @@ struct Host { script_map: RefCell, /// The same for each source `$.evalFile` gave, in order. eval_maps: RefCell>, + /// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a + /// module's, by its index there. + module_maps: RefCell>, /// The file, line and column of each error `$.evalFile` raised for a file it could not run, in /// order: the error's mark ([`HostError::Marked`]) is its index. eval_failures: RefCell, u32, u32)>>, @@ -979,6 +985,22 @@ impl Host { } } + /// The folder of the module whose source has `tag`, when it is a module of a module run: the + /// script itself or a module it imported (not a file `$.evalFile` gave, or code from another + /// run). + fn module_dir_at(&self, tag: u32) -> Option { + let script = self.script_tag.get(); + if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE { + return None; + } + let n = tag.checked_sub(script)?; + if n == 0 { + return self.files.borrow().entry_module_dir(); + } + let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?; + self.files.borrow().module_dir(&key) + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -1596,6 +1618,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc) -> std::result::Result { +/// run (for a call in a module the script imported, that module's file), with its preprocessor +/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not +/// waited on: the file is read at once. `args` starts with the call's place, as +/// [`HostItem::Evaluator`] gives it with `site`. +fn eval_file(host: &Host, mut args: Vec) -> std::result::Result { + let tag = match args.first() { + Some(Data::Number(n)) if args.len() >= 3 => *n as u32, + _ => vectorcraft_js::UNKNOWN_SOURCE, + }; + args.drain(..3.min(args.len())); + let module_dir = host.module_dir_at(tag); let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else { return Err(HostError::Type(EVAL_NO_PATH.to_string())); }; @@ -1626,7 +1657,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message }; let error = match f.kind { include::FailKind::Limit => HostError::Abort(message), @@ -1736,6 +1767,22 @@ fn explained(e: &RunError) -> String { } } +/// The module `specifier` names for the module `referrer` of the run of `host`, read through the +/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order +/// the modules are read, which is the order of their sources' tags. +fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result { + let (key, read) = host.files.borrow_mut().module(referrer, specifier)?; + let source = read.map(|(text, map)| { + let mut maps = host.eval_maps.borrow_mut(); + host.module_maps.borrow_mut().insert(maps.len(), key.clone()); + maps.push(map); + drop(maps); + host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::>()); + text + }); + Ok(LoadedModule { key, source }) +} + /// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own. fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { let (kind, message) = match f.kind { @@ -2153,7 +2200,19 @@ impl Session { self.script_stop.clear(); self.script_report = None; let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env()); - let expanded = files.expand_script(&request.source); + if request.module { + files.read_es2015(); + } + // A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines; + // `module_key` names it among the modules it imports. + let (expanded, module_key) = if request.module { + match files.module_entry(&request.source) { + Ok((key, expanded)) => (Ok(expanded), Some(key)), + Err(f) => (Err(f), None), + } + } else { + (files.expand_script(&request.source), None) + }; let name = match &expanded { Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(), _ => request.name, @@ -2184,9 +2243,8 @@ impl Session { // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read - // code the way the script does. Its realm has `Promise`: a kept realm gets it at the first - // `.js` run that names it, and keeps it as it keeps its globals. - let es2015 = include::es2015_script(request.file.as_deref()); + // code the way the script does. Its realm has `Promise`; a kept realm retains it. + let es2015 = request.module || include::es2015_script(request.file.as_deref()); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, e4x: true, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. @@ -2255,6 +2313,7 @@ impl Session { files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), + module_maps: RefCell::default(), eval_failures: RefCell::default(), script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE), report_name: Arc::from(name.as_str()), @@ -2319,7 +2378,13 @@ impl Session { .and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { - let r = realm.start(&expanded.source); + let r = match &module_key { + None => realm.start(&expanded.source), + Some(key) => { + let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH }; + realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier)) + } + }; // Source that does not compile defines no code, so its map is not kept. if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) { host.script_tag.set(realm.script_tag()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f51605c44d..5afe3d9b93 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -184,6 +184,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_modules; mod script_run; mod script_scriptui; mod script_styles; diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index e16542edb2..46d03c0379 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -399,6 +399,73 @@ fn parse_err(s: &mut Session, p: Value) -> String { s.execute("color.parse", &p).unwrap_err().to_string() } +/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse` +/// reads every notation but CMYK back to the same color and opacity. +#[test] +fn format_writes_each_notation_and_parse_reads_it_back() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let s = &mut s; + let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| { + let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap(); + r["text"].as_str().unwrap().to_string() + }; + let blue = json!("#336699"); + for (notation, at_half, at_full) in [ + ("hex", "#336699", "#336699"), + ("hexAlpha", "#33669980", "#336699ff"), + ("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"), + ("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"), + ] { + assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}"); + assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}"); + } + let oklch = fmt(s, blue.clone(), json!(25), "oklch"); + assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap(); + let pct: Vec = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]); + assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them"); + assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected); + assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values"); + assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40"); + for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] { + for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] { + let text = fmt(s, color.clone(), opacity.clone(), notation); + let shown = fmt(s, color.clone(), Value::Null, "hex"); + let r = s.execute("color.parse", &json!({ "text": text })).unwrap(); + assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}"); + match notation { + "hex" => assert_eq!(r["opacity"], Value::Null, "{text}"), + "hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"), + _ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"), + } + } + } +} + +/// `color.format` refuses a missing or wrong color, opacity or notation. +#[test] +fn format_refuses_bad_params() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string(); + let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk"; + assert!(err(json!({"color": "#336699"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string")); + assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`")); + assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`")); + for opacity in [json!(-1), json!(101), json!("50"), json!(true)] { + assert!( + err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"), + "{opacity}" + ); + } +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/src/tests/globaledit.rs b/crates/engine/src/tests/globaledit.rs index 3bfe6039fa..ae56fa7c5a 100644 --- a/crates/engine/src/tests/globaledit.rs +++ b/crates/engine/src/tests/globaledit.rs @@ -119,6 +119,43 @@ fn selecting_one_object_highlights_the_similar_objects_before_global_edit_starts assert!(highlights(&s).is_empty(), "two objects selected"); } +#[test] +fn after_an_edit_only_the_changed_objects_are_compared_again_from_scratch() { + use crate::cmd::globaledit::{FORMS_MADE, OUTLINES_MADE, highlights}; + let made = || (FORMS_MADE.with(std::cell::Cell::get), OUTLINES_MADE.with(std::cell::Cell::get)); + let since = |b: (usize, usize)| { + let n = made(); + (n.0 - b.0, n.1 - b.1) + }; + let mut s = session(); + let key = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let copies: Vec = (1..40).map(|i| rect(&mut s, 20.0 * f64::from(i % 20), 100.0 + 20.0 * f64::from(i / 20), 10.0, 10.0)).collect(); + sel(&mut s, &[key]); + let before = made(); + assert_eq!(highlights(&s).len(), 39); + assert_eq!(since(before), (40, 39), "the first preview measures each object"); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + let before = made(); + assert_eq!(highlights(&s).len(), 39); + assert_eq!(since(before), (1, 0), "the selected object only: the copies are unchanged"); + sel(&mut s, &[copies[0]]); + s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap(); + sel(&mut s, &[copies[1]]); + s.execute("object.move", &json!({"dx": 300, "dy": 0})).unwrap(); + sel(&mut s, &[copies[2]]); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + sel(&mut s, &[key]); + let before = made(); + let shown = highlights(&s); + assert_eq!(since(before), (4, 2), "the selected object and the three edited copies, two of them still similar"); + assert_eq!(shown.len(), 38, "the widened copy is another shape; the moved and the enlarged ones still match"); + let moved = node(&s, copies[1]).stroke_path().unwrap(); + assert!(shown.iter().any(|(p, _)| *p == moved), "the moved copy is shown where it is now"); + s.execute("select.globalEditOptions", &json!({"size": true})).unwrap(); + assert_eq!(highlights(&s).len(), 37, "with Size, the enlarged copy is left out"); + assert_eq!(crate::cmd::globaledit::match_count(&s), 38); +} + #[test] fn the_canvas_highlights_similar_objects_before_the_start_with_the_selection_tool_only() { let mut s = session(); diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 78e75dba1d..f4e251638f 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1066,6 +1066,339 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// A path drawn by `d`, filled black with no stroke. +fn filled(s: &mut Session, d: &str) -> NodeId { + let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()); + fill_only(s, id); + id +} + +fn fill_only(s: &mut Session, id: NodeId) { + s.edit("t", |d, _| { + d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into(); + Ok(()) + }) + .unwrap(); +} + +/// Hairline Slivers' test art: (the slivers, the shapes with a width). +fn sliver_art(s: &mut Session) -> (Vec, Vec) { + // A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide + // and tall. A long one across the page. A compound path of two slivers. + let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z"); + let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z"); + let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z"); + let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, two); + // Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it + // draws a line), an open path, and a compound path of a sliver and a square. + let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z"); + let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, dot); + let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into(); + Ok(()) + }) + .unwrap(); + let open = filled(s, "M500 10 L540 40 L500.001 10.0015"); + let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z"); + let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z"); + s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap(); + let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, mixed); + s.execute("select.none", &json!({})).unwrap(); + (vec![triangle, long, two], vec![strip, dot, stroked, open, mixed]) +} + +#[test] +fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() { + let mut s = session(); + let (slivers, kept) = sliver_art(&mut s); + // Off by default. + assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0); + // A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is + // at 0 % opacity paints nothing either. + let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z"); + let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0); + if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() { + f.opacity = 0.0; + } + d.node_mut(clear).unwrap().appearance = a.into(); + Ok(()) + }) + .unwrap(); + let kept = [kept, vec![unpainted, clear]].concat(); + let undo = s.doc().unwrap().history.undo.len(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left"); + for (k, id) in kept.iter().enumerate() { + assert!(d.node(*id).is_some(), "shape {k} with a width went"); + } + assert_eq!(r["removed"], slivers.len()); + // One undo step brings every sliver back. + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some())); + // A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot. + let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"}); + assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1); + assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some()); +} + +/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or +/// locked slivers. +#[test] +fn select_hairline_slivers_selects_what_clean_up_removes() { + let mut s = session(); + let (slivers, _) = sliver_art(&mut s); + let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z"); + let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + d.node_mut(locked).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], slivers.len()); + let mut selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + selected.sort_unstable(); + let mut want = slivers.clone(); + want.sort_unstable(); + assert_eq!(selected, want); + // Inside an isolated group, only the slivers in it are selected. + let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z"); + let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z"); + s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + // A sliver in a group is selected as Clean Up finds it. + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1); + assert!(s.doc().unwrap().selection.objects.contains(&inner)); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A template layer that was unlocked afterward. + let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z"); + s.edit("t", |d, _| { + let n = d.node_mut(template).unwrap(); + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = true; + } + n.locked = false; + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(template).unwrap().is_template()); + s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.objects.contains(&traced)); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some()); +} + +/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint +/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's +/// clipping path; Clean Up's other options keep the layer's clipping path too. +#[test] +fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() { + let mut s = session(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [rough.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap(); + let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z"); + let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z"); + s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + // A group's own 5 pt stroke draws along its member. + let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into(); + Ok(()) + }) + .unwrap(); + // A thin part of type's glyph outlines. + let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap(); + let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(outlines).unwrap().extras_mut().type_outlines = true; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + // A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects + // removes the clipping path. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z"); + let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z"); + let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went"); + // A clip group whose clipping path is a sliver. + let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z"); + let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + // A guide drawn as a sliver, and a sliver with an effect on its stroke. + let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z"); + let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind { + *guide = true; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(mask).is_some(), "the clip group's clipping path went"); + assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went"); + // A layer clipped by a group (as an opened file can have it): its sliver member clips too. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z"); + let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [bare.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind { + *clip = true; + let i = children.iter().position(|c| c.id == g).unwrap(); + let c = children.remove(i); + children.insert(0, c); + } + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went"); +} + +/// A sliver on a locked artboard is left alone. +#[test] +fn hairline_slivers_leave_art_on_a_locked_artboard_alone() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.edit("t", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + assert!(s.doc().unwrap().doc.node(sliver).is_some()); +} + +/// A sliver at 0 % opacity, and one in a group at 0 % opacity, paint nothing and are left alone. +#[test] +fn hairline_slivers_leave_art_at_zero_opacity_alone() { + let mut s = session(); + let clear = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + let member = filled(&mut s, "M100 10 L140 40 L100.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let seen = filled(&mut s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(clear).unwrap().opacity = 0.0; + d.node_mut(group).unwrap().opacity = 0.0; + d.node_mut(seen).unwrap().opacity = 0.5; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 1); + let d = &s.doc().unwrap().doc; + assert!(d.node(clear).is_some() && d.node(member).is_some(), "a sliver at 0 % opacity went"); + assert!(d.node(seen).is_none(), "a sliver at 50 % opacity stayed"); +} + +/// A shape too complex to measure is kept, and both commands say how many there were. +#[test] +fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + // A closed zigzag of more anchors than one shape is measured with. + let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1; + let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect(); + let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind { + *path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true)); + } + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + assert_eq!(r["removed"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(sliver).is_none() && d.node(huge).is_some()); +} + +/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the +/// document, the selection and the undo history stay as they were. +#[test] +fn hairline_slivers_refuse_a_width_out_of_range() { + let mut s = session(); + sliver_art(&mut s); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] { + for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] { + let mut p = serde_json::Map::new(); + p.insert(key.into(), w.clone()); + if cmd == "object.path.cleanUp" { + p.insert("hairlineSlivers".into(), json!(true)); + } + let r = s.execute(cmd, &Value::Object(p)); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}"); + assert!(state(&s) == before, "{cmd} {w} changed the document"); + } + } + // Both ends of the range are taken. + for w in [json!(0.001), json!(3), json!("3 pt")] { + assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}"); + let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w}); + assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}"); + } +} + /// A page-sized square under a ring (a compound path with a square hole), nothing selected. fn art_and_ring(s: &mut Session) -> (NodeId, NodeId) { let art = rect(s, 0.0, 0.0, 100.0, 100.0); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index cc04612a89..6cd51a5a1d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3195,6 +3195,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() { assert!(install(&mut s, DESATURATE).get("budget").is_none()); } +/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its +/// name is escaped, so it can't reorder the message around it. +#[test] +fn a_heavy_filter_refusal_escapes_its_name() { + let mut s = session(); + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#); + let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string(); + assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}"); +} + /// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed /// without any of its code running: its start function traps and its `vc_manifest` export loops. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 94886530c1..e87e5b5c51 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -356,6 +356,37 @@ fn page_item_properties_join_one_undo_step() { } } +/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one +/// undo step. They change nothing past the run's first edit or its last undone one. +#[test] +fn app_undo_and_redo_step_through_the_runs_edits() { + let (mut s, a, b) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\ + app.undo(); app.redo();\ + i.name = 'first'; i.opacity = 40;\ + app.undo(); vc.log([i.name, i.opacity]);\ + app.redo(); vc.log(i.opacity);\ + app.redo(); vc.log(i.opacity);\ + app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\ + vc.log(typeof app.undo());\ + d.pageItems[1].name = 'kept';", + ); + assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let st = s.active().unwrap(); + let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect(); + assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run"); + let mut s = Session::new(); + assert!(failure(&mut s, "app.undo();").contains("No active document")); + assert!(failure(&mut s, "app.redo();").contains("No active document")); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index dc9749fb6c..47eaf52e41 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() { fuel: script::DEFAULT_FUEL, locale: "en_US".into(), answers: Vec::new(), + module: false, actions: Vec::new(), }; s.script_start(request).unwrap(); diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs new file mode 100644 index 0000000000..45d5a22417 --- /dev/null +++ b/crates/engine/src/tests/script_modules.rs @@ -0,0 +1,315 @@ +//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of +//! specifiers and paths, the run's limits, and errors at the file they are in. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + base +} + +fn write(path: &Path, text: &str) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, text).unwrap(); +} + +/// Runs `main/` in `base`, with the text `text`. +fn run_file(base: &Path, file: &str, text: &str) -> (Result, Session) { + let main = base.join("main").join(file); + write(&main, text); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})); + (r, s) +} + +fn run(base: &Path, text: &str) -> Result { + run_file(base, "main.mjs", text).0 +} + +/// The report of the run of `main/main.mjs` that failed. +fn failed(base: &Path, text: &str) -> Value { + let (r, s) = run_file(base, "main.mjs", text); + assert!(r.is_err(), "the run failed: {r:?}"); + s.script_report().unwrap().clone() +} + +fn message(report: &Value) -> &str { + report["message"].as_str().unwrap_or_default() +} + +#[test] +fn script_module_imports_from_its_folder_and_below() { + let base = folder("imports"); + write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';"); + write( + &base.join("main/lib/use.mjs"), + "import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();", + ); + let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);"; + let r = run(&base, text).unwrap(); + // count.mjs ran once: use.mjs and the script share its binding. + assert_eq!(r["log"], json!([[2, "lib", true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_two_modules_import_each_other() { + let base = folder("cycle"); + write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }"); + write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();"); + let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap(); + assert_eq!(r["log"], json!([["ab", "ab"]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_path_above_the_script_folder_is_refused() { + let base = folder("above"); + write(&base.join("outside.mjs"), "export var leaked = 1;"); + let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';"); + assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}"); + assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}"); + // `..` names that stay inside are read by name. + write(&base.join("main/sub/x.mjs"), "export var x = 'x';"); + let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap(); + assert_eq!(r["log"], json!(["x"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_missing_file_is_named() { + let base = folder("missing"); + write(&base.join("main/a.mjs"), "import './nope.mjs';"); + let report = failed(&base, "import './a.mjs';"); + assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}"); + assert_eq!(report["line"], 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() { + let base = folder("specifiers"); + // The specifier as the script writes it, as the error names it, and why it is refused. + for (written, shown, why) in [ + ("lib", "lib", "must start with './' or '../'"), + ("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"), + ("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"), + ("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"), + ("./C:x.mjs", "./C:x.mjs", "must not contain"), + ("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"), + ("./x.txt", "./x.txt", "must name a .mjs or .js file"), + ("./x", "./x", "must name a .mjs or .js file"), + ] { + let report = failed(&base, &format!("import '{written}';")); + let expected = format!("SyntaxError: module specifier '{shown}' {why}"); + assert!(message(&report).starts_with(&expected), "{written}: {report}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_errors_are_at_the_file_they_are_in() { + let base = folder("errors"); + write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;"); + let report = failed(&base, "import { a } from './bad.mjs';"); + assert_eq!(report["kind"], "syntax", "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}"); + assert_eq!(report["line"], 2); + write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');"); + let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);"); + assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}"); + assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}"); + let report = failed(&base, "import { b } from './thrower.mjs';"); + assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_preprocessor_lines_and_scripts_differ_by_extension() { + let base = folder("kinds"); + write(&base.join("main/lib.jsxinc"), "var included = 1;"); + // A module has no preprocessor lines. + let report = failed(&base, "#include \"lib.jsxinc\"\n"); + assert_eq!(report["kind"], "syntax", "{report}"); + // A .js or .jsx script does not read import or export. + for file in ["main.js", "main.jsx"] { + let (r, s) = run_file(&base, file, "import { a } from './a.mjs';"); + assert!(r.is_err(), "{file}"); + assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_files_count_against_the_include_limits() { + let base = folder("limits"); + for i in 0..70 { + write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1)); + } + let report = failed(&base, "import './m0.mjs';"); + assert!(message(&report).contains("limit"), "{report}"); + assert_eq!(report["log"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_paths_of_one_file_give_one_module() { + let base = folder("same"); + write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;"); + let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string(); + // Windows file names ignore letter case. + if cfg!(windows) { + text.push_str("import { v as u } from './ONCE.mjs';\n"); + } + let r = run(&base, &text).unwrap(); + assert_eq!(r["log"], json!(["ran"])); + let _ = std::fs::remove_dir_all(base); +} + +/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere. +/// `false` when the system does not allow it here. +fn link_folder(target: &Path, link: &Path) -> bool { + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok() + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + +#[test] +fn script_module_link_out_of_the_folder_is_refused() { + let base = folder("link"); + write(&base.join("outside/x.mjs"), "export var leaked = 1;"); + if !link_folder(&base.join("outside"), &base.join("main").join("away")) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);"); + assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_is_listed_and_taken_by_path() { + assert!(cmd::scripts::runs("tool.MJS")); + let base = folder("text"); + let root = base.join("Scripts"); + write(&root.join("tool.mjs"), "export var a = 1;"); + let mut s = Session::new(); + s.attach_scripts_dir(root.clone()); + let listed = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}])); + // A script given as text is not a module, whatever its name. + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"})); + assert!(r.is_err()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_is_chosen_by_the_module_param() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap(); + assert_eq!(r["log"], json!([[1, true]])); + // A source run as a module imports no files. + let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true})); + assert!(r.is_err()); + assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report()); + let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); + // `module: false` runs a .mjs file as a script, where `export` is a syntax error. + let base = folder("param"); + let main = base.join("main").join("main.mjs"); + write(&main, "export var a = 1;"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false})); + assert!(r.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "syntax"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_read_again_through_another_path_is_not_counted_again() { + let base = folder("budget"); + // 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run. + let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024)); + write(&base.join("main/lib/big.mjs"), &big); + let mut text = String::new(); + for i in 0..5 { + if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n")); + } + text.push_str("vc.log(v0 + v4);"); + let r = run(&base, &text); + assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2]))); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_imports_are_read_from_the_folder_the_file_is_in() { + let base = folder("realdir"); + write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;"); + write(&base.join("main/real/dep.mjs"), "export const d = 'real';"); + write(&base.join("main/other/dep.mjs"), "export const d = 'other';"); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok(); + #[cfg(windows)] + let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok(); + #[cfg(not(any(unix, windows)))] + let linked = false; + if !linked { + eprintln!("skipped: a file link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap(); + assert_eq!(r["log"], json!(["real"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_eval_file_reads_beside_the_module_that_calls_it() { + let base = folder("evalfile"); + write(&base.join("main/helper.jsx"), "'top'"); + write(&base.join("main/sub/helper.jsx"), "'sub'"); + write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');"); + let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap(); + assert_eq!(r["log"], json!([["sub", "top"]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() { + let base = folder("evalfile-entry"); + write(&base.join("main/helper.jsx"), "'top'"); + write(&base.join("main/sub/helper.jsx"), "'sub'"); + // The file in `sub` calls the script's function while it is the file being run. + write(&base.join("main/sub/caller.jsx"), "$.global.load()"); + let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));"; + let r = run(&base, text).unwrap(); + assert_eq!(r["log"], json!(["top"])); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 635b5f393a..7c4196fd84 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1248,6 +1248,45 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() { assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again"); } +/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS +/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each +/// back to the hex color `color.format` gives. +#[test] +fn color_format_writes_every_css_form_through_the_intent() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + let format = |s: &mut Session, color: &serde_json::Value, notation: &str| { + s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string()) + }; + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string()); + // The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent. + let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name; + s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap(); + let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); + let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8); + let intents_differ = + absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); + // Collected as results, so that a failure still restores the process-wide settings first. + let mut read_back = vec![]; + for notation in ["hex", "rgb", "hsl", "oklch"] { + let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string()); + let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string())); + read_back.push((notation, text, hex)); + } + cms::set_active(&old).unwrap(); + cms::unregister_icc(&icc); + assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}"); + assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB"); + let hex = read_back[0].1.clone().unwrap(); + let [r, g, b] = absolute; + assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB"); + for (notation, text, back) in read_back { + assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}"); + } +} + /// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in /// `Color Settings.json`. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d7f60e5b2c..1a842e6a86 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -90,8 +90,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ - executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \ - unloadAction unloadAction=", + executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \ + undo unloadAction unloadAction=", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index c2ca9a38f6..9699944e35 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() { let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []})); assert_eq!(r["started"], false); assert_eq!(r["ok"], false); - assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}"); + assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}"); } #[test] diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c23f8c6767..a587c74fbb 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -619,6 +619,62 @@ pub struct Program { pub(crate) supers: crate::parser::SuperRules, } +/// The name an import takes from the module it names, or an export from a module it re-exports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ImportName { + /// The export of this name (`default` for a default import). + Name(String), + /// The module's namespace object (`* as ns`). + Namespace, +} + +/// A module a module imports or re-exports from: the specifier as written and where it stands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModuleRequest { + /// The specifier as text, with each unpaired surrogate written as U+FFFD. + pub specifier: String, + /// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16, + /// ModuleRequests). It may hold an unpaired surrogate, which no host path can name. + pub units: Vec, + pub span: Span, +} + +/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImportEntry { + /// The index of the module in [`ModuleInfo::requests`]. + pub request: usize, + pub import: ImportName, + /// The name bound in the importing module. + pub local: Name, +} + +/// One name a module exports (ExportEntry). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExportEntry { + /// `export_name` is the module's own binding `local` (`*default*` for a default export of an + /// expression or an anonymous function). + Local { export_name: String, local: String, span: Span }, + /// `export_name` is the export `import` of the module `request` (`export { a as b } from`, + /// `export * as ns from`, or an exported import). + Indirect { export_name: String, request: usize, import: ImportName, span: Span }, + /// Every export of the module `request` but `default` (`export * from`). + Star { request: usize, span: Span }, +} + +/// What a module imports and exports, read by [`crate::parse_module`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ModuleInfo { + /// The modules it names, each specifier once, in the order they first appear. + pub requests: Vec, + pub imports: Vec, + pub exports: Vec, +} + +/// The binding name of a default export that has no name of its own (ECMA-262 2015 section +/// 15.2.3.5); no identifier can name it. +pub const DEFAULT_BINDING: &str = "*default*"; + impl Program { /// The line and column (both from 1, the column in UTF-16 code units) of a source offset. pub fn line_column(&self, offset: u32) -> (u32, u32) { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 8bf8783adf..5fb963b34d 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -591,7 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) + Ok(Value::Bool(interp.own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -610,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) + Ok(Value::Bool(interp.own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 42947c7d7a..af377a213f 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -139,7 +139,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { let k = interp.to_prop_key(&arg(args, 1))?; - match interp.get_own_pk(o, &k)? { + match interp.own_pk(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -282,7 +282,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let o = *o; for k in own_prop_keys(interp, o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_pk(o, &k)? else { continue }; + let Some(prop) = interp.own_pk(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } @@ -311,7 +311,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { recursion: u32, /// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own. es2015: bool, + /// The code is a module's ([`compile_module`]), which has no completion value. + module: bool, scopes: Vec, templates: Vec