diff --git a/Cargo.lock b/Cargo.lock index d7dd0d4ec7..75c87011b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10437,7 +10437,9 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" name = "xtask" version = "0.25.1" dependencies = [ + "craft-fonts-build", "serde_json", + "tempfile", ] [[package]] diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 4eb39067a0..651be6f6a3 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -177,9 +177,10 @@ mod system { return Vec::new(); } let named = cups_server(); + let sockets = local_sockets(); // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, // so its sizes come from the server. - if scheduler_is_local(named.as_deref()) { + if scheduler_is_local(named.as_deref(), &sockets, real_path) { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); @@ -199,7 +200,7 @@ mod system { } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); - let server = ipp_server(named, |s| std::path::Path::new(s).exists()); + let server = ipp_server(named, |s| std::path::Path::new(s).exists(), real_path); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; @@ -234,17 +235,52 @@ mod system { /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. #[cfg(not(windows))] const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; - /// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server - /// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default - /// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local - /// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job - /// does not go to. + /// The real path of a socket path, through symbolic links (`/var/run/cupsd` is `/private/var/run/cupsd` on macOS). + #[cfg(not(windows))] + pub(super) fn real_path(path: &str) -> Option { + std::fs::canonicalize(path).ok().map(|p| p.to_string_lossy().into_owned()) + } + /// The domain sockets of the local scheduler: CUPS's own, and those the `Listen` lines of `/etc/cups/cupsd.conf` add. + #[cfg(not(windows))] + pub(super) fn local_sockets() -> Vec { + use std::io::Read as _; + let mut text = String::new(); + let read = std::fs::File::open("/etc/cups/cupsd.conf").and_then(|f| f.take(1 << 20).read_to_string(&mut text)); + cupsd_listen_sockets(if read.is_ok() { &text } else { "" }) + } + /// CUPS's own domain sockets and the socket paths of the `Listen` lines of a `cupsd.conf`. + #[cfg(not(windows))] + pub(super) fn cupsd_listen_sockets(text: &str) -> Vec { + let listed = text.lines().filter_map(|line| { + let line = cups_conf_line(line); + let (key, value) = line.trim().split_once(char::is_whitespace)?; + let value = value.trim(); + (key.eq_ignore_ascii_case("Listen") && value.starts_with('/')).then(|| value.to_string()) + }); + CUPS_SOCKETS.iter().map(|s| (*s).to_string()).chain(listed).collect() + } + /// Whether the socket path `path` is one of the local scheduler's `sockets`, as written or as `resolve` gives the + /// real paths of both. + #[cfg(not(windows))] + fn is_local_socket(path: &str, sockets: &[impl AsRef], resolve: impl Fn(&str) -> Option) -> bool { + let path = path.trim(); + let real = resolve(path); + sockets.iter().any(|s| { + let s = s.as_ref(); + s == path || real.as_ref().is_some_and(|real| real == s || resolve(s).as_ref() == Some(real)) + }) + } + /// The server for the IPP lookup, given the one `cups_server` names, whether a path exists and a socket path's real path. + /// With no server named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` + /// on the IPP default port), and `localhost` on `IPP_PORT` otherwise. A + /// named socket in `CUPS_SOCKETS`, or a link to one, also returns `None`. Any other socket path stays as named, + /// and the lookup is skipped. /// /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri #[cfg(not(windows))] - pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool) -> Option { + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool, resolve: impl Fn(&str) -> Option) -> Option { match named { - Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None, + Some(server) if server.trim().starts_with('/') && is_local_socket(&server, &CUPS_SOCKETS, resolve) => None, Some(server) => Some(server), None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), } @@ -268,14 +304,15 @@ mod system { client_conf_server_name(&text) }) } - /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, - /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback - /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. + /// Whether a scheduler named by `cups_server` runs on this machine: none named, one of the local scheduler's domain + /// `sockets`, or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. + /// A loopback name on another port, or another socket path, is a second scheduler, whose queues the local PPD folder + /// does not describe. `resolve` gives a socket path's real path, so a link to one of `sockets` counts as that socket. #[cfg(not(windows))] - pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { + pub(super) fn scheduler_is_local(server: Option<&str>, sockets: &[String], resolve: impl Fn(&str) -> Option) -> bool { let Some(server) = server.map(str::trim) else { return true }; if server.starts_with('/') { - return true; + return is_local_socket(server, sockets, resolve); } // A network name may end in `/version=1.1`. let server = server.split_once('/').map_or(server, |(server, _)| server); @@ -289,17 +326,22 @@ mod system { let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; loopback && port.is_none_or(|port| port.trim() == "631") } - /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a + /// A line of a CUPS configuration file without its comment. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is /// dropped and the rest of the line is kept as written. #[cfg(not(windows))] + fn cups_conf_line(line: &str) -> String { + match line.find('#') { + Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), + Some(at) => line[..at].to_string(), + None => line.to_string(), + } + } + /// The last `ServerName` in a `client.conf`. + #[cfg(not(windows))] pub(super) fn client_conf_server_name(text: &str) -> Option { text.lines().rev().find_map(|line| { - let kept = match line.find('#') { - Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), - Some(at) => line[..at].to_string(), - None => line.to_string(), - }; + let kept = cups_conf_line(line); let (key, value) = kept.trim().split_once(char::is_whitespace)?; (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) }) @@ -604,18 +646,47 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + use super::system::{client_conf_server_name, cupsd_listen_sockets, ipp_server, scheduler_is_local}; #[test] fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { let none = |_: &str| false; let socket = |s: &str| s == "/run/cups/cups.sock"; - assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631"); - assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None); - assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); - assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631")); - assert_eq!(ipp_server(None, socket), None); - assert_eq!(ipp_server(None, none).as_deref(), Some("localhost")); + let real = |_: &str| None; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none, real), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none, real), None); + assert_eq!(ipp_server(Some("/var/run/cupsd".into()), none, linked), None, "a link to CUPS's socket is that socket"); + let other = ipp_server(Some("/tmp/other.sock".into()), socket, linked); + assert_eq!(other.as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket, real).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket, real), None); + assert_eq!(ipp_server(None, none, real).as_deref(), Some("localhost")); + } + + #[test] + fn a_socket_the_local_cupsd_listens_on_counts_as_local() { + let real = |_: &str| None; + let sockets = cupsd_listen_sockets( + "Listen localhost:631\nListen /srv/cups/print.sock # office\n# Listen /tmp/off.sock\nListen /run/cups/office\\#2.sock\n", + ); + assert!(scheduler_is_local(Some("/srv/cups/print.sock"), &sockets, real), "its PPD folder describes the queue"); + assert!(!scheduler_is_local(Some("/tmp/off.sock"), &sockets, real), "a commented-out Listen line adds nothing"); + assert!(sockets.iter().any(|s| s == "/run/cups/office#2.sock")); + assert_eq!(ipp_server(Some("/srv/cups/print.sock".into()), |_| false, real).as_deref(), Some("/srv/cups/print.sock")); + } + + /// The real path of a socket path on a macOS-like system, where `/var` is a link to `/private/var`. + fn linked(path: &str) -> Option { + path.strip_prefix("/var/").map(|rest| format!("/private/var/{rest}")) + } + + #[test] + fn a_socket_path_counts_as_local_only_when_it_is_cups_own() { + let real = |_: &str| None; + let own = cupsd_listen_sockets(""); + assert!(scheduler_is_local(Some("/var/run/cupsd"), &own, linked), "a link to CUPS's socket reads the local PPD folder"); + assert!(!scheduler_is_local(Some("/var/run/cupsd"), &own, real), "an unresolved unknown path is another scheduler"); + assert!(!scheduler_is_local(Some("/var/run/other.sock"), &own, linked)); } #[test] @@ -623,6 +694,8 @@ mod client_conf_tests { for local in [ None, Some("/run/cups/cups.sock"), + Some(" /var/run/cups/cups.sock "), + Some("/private/var/run/cupsd"), Some("localhost"), Some("LocalHost:631"), Some("localhost:631"), @@ -633,7 +706,7 @@ mod client_conf_tests { Some("localhost/version=1.1"), Some("localhost:631/version=1.1"), ] { - assert!(scheduler_is_local(local), "{local:?}"); + assert!(scheduler_is_local(local, &cupsd_listen_sockets(""), |_| None), "{local:?}"); } for remote in [ "print.example.com", @@ -647,8 +720,10 @@ mod client_conf_tests { "127.0.0.1:8631", "[::1]:8631", "localhost:8631/version=1.1", + "/tmp/other.sock", + "/home/me/.cups/second.sock", ] { - assert!(!scheduler_is_local(Some(remote)), "{remote}"); + assert!(!scheduler_is_local(Some(remote), &cupsd_listen_sockets(""), linked), "{remote}"); } } diff --git a/crates/doc/src/decode.rs b/crates/doc/src/decode.rs index 11d1b2d72b..f06ea81b00 100644 --- a/crates/doc/src/decode.rs +++ b/crates/doc/src/decode.rs @@ -2,6 +2,17 @@ //! File › Open and Place, SVG import, and embedded and linked images read their pixels with //! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`]. +thread_local! { + /// Images [`decode_image`] has decoded, or tried, on this thread ([`decodes`]). + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many images [`decode_image`] has decoded on this thread so far, failed decodes included. +/// Images other threads decode are not counted. +pub fn decodes() -> u64 { + DECODES.with(std::cell::Cell::get) +} + /// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds. pub type DecodedImage = (image::DynamicImage, Option>); @@ -10,6 +21,7 @@ pub type DecodedImage = (image::DynamicImage, Option>); /// The renderer, File › Open and Place, SVG import, and embedded and linked images read images /// with it. pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result { + DECODES.with(|n| n.set(n.get() + 1)); let opts = craft_image_codecs::DecodeOptions { limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance }, keep_orientation: true, diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 4f19f09a5a..73321a7e09 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -43,8 +43,8 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", - defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; a named style sets the shape and angle over the stored ones: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°; effect.apply and effect.setParams refuse an unknown style), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + defaults: json!({"shape": "circle", "style": "custom", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), }] @@ -71,6 +71,23 @@ pub enum DotShape { Elliptical, } +/// The named styles: each sets a dot shape and a screen angle. +pub const STYLES: [(&str, DotShape, f64); 4] = [ + ("grid", DotShape::Euclidean, 0.0), + ("gridAngle", DotShape::Euclidean, 45.0), + ("gridDots", DotShape::Circle, 0.0), + ("gridDotsAngle", DotShape::Circle, 45.0), +]; + +/// The shape and angle of style `s`: `Some(None)` for `custom` (the shape and angle as given), +/// `None` for an unknown style. +pub fn style(s: &str) -> Option> { + if s.eq_ignore_ascii_case("custom") { + return Some(None); + } + STYLES.iter().find(|(name, ..)| name.eq_ignore_ascii_case(s)).map(|&(_, shape, angle)| Some((shape, angle))) +} + impl DotShape { pub fn parse(s: &str) -> Option { Some(match s.to_ascii_lowercase().as_str() { @@ -89,6 +106,10 @@ impl DotShape { /// running along x. fn path(self, t: f64, s: f64) -> PathData { let square = |side: f64| shapes::rectangle(Rect::from_center_size(Point::ZERO, (side, side))); + // A full-tone dot is the cell itself; Line keeps its overlap along the row. + if t >= 1.0 && self != DotShape::Line { + return square(s); + } match self { DotShape::Circle => cell_dot(t, s / 2.0, CellKind::Circle), DotShape::Ellipse => cell_dot(t, s / 2.0, CellKind::Ellipse), @@ -413,6 +434,12 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { let i = (x.floor() as usize).min(SIZE_STEPS - 1); let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); let r = lo + (hi - lo) * (x - i as f64); + if matches!(kind, CellKind::Circle | CellKind::Ellipse) { + let (a, b) = if matches!(kind, CellKind::Circle) { (r, r) } else { (1.3 * r, r / 1.3) }; + if t > 0.0 && a <= 1.0 && b <= 1.0 { + return shapes::ellipse(Rect::new(-a * h, -b * h, a * h, b * h)); + } + } let q1 = mapped(&kind.quadrant(r), |p| Point::new(p.x * h, p.y * h)); PathData::from_bezpath(&four_quadrants(&q1)) } @@ -423,8 +450,13 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData { fn four_quadrants(q1: &[CubicBez]) -> BezPath { let mut bp = BezPath::new(); let mut end: Option = None; + // A piece lying on an axis would be drawn back over by its mirror image, so it is left out. + let on_axis = |c: &CubicBez| { + let pts = [c.p0, c.p1, c.p2, c.p3]; + pts.iter().all(|p| p.x.abs() < 1e-9) || pts.iter().all(|p| p.y.abs() < 1e-9) + }; let mut add = |curves: Vec| { - for (k, c) in curves.iter().enumerate() { + for (k, c) in curves.iter().filter(|c| !on_axis(c)).enumerate() { if k == 0 { match end { None => bp.move_to(c.p0), @@ -440,7 +472,9 @@ fn four_quadrants(q1: &[CubicBez]) -> BezPath { add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y)))); add(mapped(q1, |p| Point::new(-p.x, -p.y))); add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y)))); - bp.close_path(); + if end.is_some() { + bp.close_path(); + } bp } @@ -540,10 +574,12 @@ impl Halftone { } fn from_params(p: &Value) -> Self { + // A named style sets the shape and angle over the stored ones (which hold the defaults). + let styled = style(text(p, "style", "custom")).flatten(); Self { - shape: DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), + shape: styled.map_or_else(|| DotShape::parse(text(p, "shape", "circle")).unwrap_or(DotShape::Circle), |s| s.0), frequency: num(p, "frequency", 20.0).clamp(1.0, 300.0), - angle: num(p, "angle", 45.0), + angle: styled.map_or_else(|| num(p, "angle", 45.0), |s| s.1), mono: !text(p, "mode", "mono").eq_ignore_ascii_case("cmyk"), color: crate::raster::color_param(p, Color::BLACK), from_art: flag(p, "fromArt", false), @@ -781,6 +817,46 @@ mod tests { assert_eq!(h.color, Color::BLACK); } + #[test] + fn round_dots_inside_the_cell_have_four_anchors() { + for (shape, tone) in [(DotShape::Circle, 0.5), (DotShape::Ellipse, 0.3)] { + let dot = shape.path(tone, 10.0); + assert_eq!(dot.subpaths.len(), 1, "{shape:?}"); + let sp = &dot.subpaths[0]; + assert!(sp.closed, "{shape:?}"); + assert_eq!(sp.anchors.len(), 4, "{shape:?}: {:?}", sp.anchors); + } + } + + /// Dots whose quadrants meet on the axes have no extra anchors at the joins: a Circle dot small + /// enough to stay inside its cell has the anchors of its arcs only, all distinct. + #[test] + fn dot_quadrants_join_without_extra_anchors() { + let dot = DotShape::Circle.path(0.2, 10.0); + let anchors: Vec = dot.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(); + for (i, a) in anchors.iter().enumerate() { + assert!(anchors[i + 1..].iter().all(|b| a.distance(*b) > 1e-6), "{anchors:?}"); + } + for shape in [DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + for t in [0.2, 0.6, 0.9] { + for sp in &shape.path(t, 10.0).subpaths { + let n = sp.anchors.len(); + for i in 0..n { + let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p); + assert!(n < 2 || a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors); + } + } + } + } + } + + #[test] + fn zero_tone_quadrant_dots_have_empty_paths() { + for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + assert!(shape.path(0.0, 10.0).is_empty(), "{shape:?}"); + } + } + #[test] fn values_out_of_range_are_brought_in() { let h = Halftone::of(&effect(json!({"frequency": 1e308, "angle": "NaN", "shape": 7, "mode": "CMYK", "color": "nope"}))).unwrap(); @@ -817,6 +893,51 @@ mod tests { fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) } + #[test] + fn grid_dots_fill_the_cell_at_full_tone() { + for name in ["gridDots", "gridDotsAngle"] { + let Some(Some((shape, _))) = style(name) else { panic!("{name} is not a style") }; + // At 100% the cell's corners are covered, so neighboring cells leave no holes. + assert!(covers(shape, 1.0, (0.49, 0.49)) && covers(shape, 1.0, (-0.49, 0.49)), "{name}"); + // Below it the corners stay light. + assert!(!covers(shape, 0.9, (0.49, 0.49)), "{name}"); + } + } + + #[test] + fn full_tone_dots_have_exactly_the_cell_corners() { + let Some(Some((grid_dots, _))) = style("gridDots") else { panic!("gridDots is not a style") }; + let corners = [Point::new(-5.0, -5.0), Point::new(5.0, -5.0), Point::new(5.0, 5.0), Point::new(-5.0, 5.0)]; + for shape in [grid_dots, DotShape::Ellipse, DotShape::Square, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] { + let dot = shape.path(1.0, 10.0); + assert_eq!(dot.subpaths.len(), 1, "{shape:?}"); + let sp = &dot.subpaths[0]; + assert!(sp.closed, "{shape:?}"); + let anchors: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{shape:?}: {anchors:?}"); + for corner in corners { + assert!(anchors.contains(&corner), "{shape:?}: {anchors:?}"); + } + } + } + + #[test] + fn styles_set_the_shape_and_angle() { + let defaults = crate::effect_info(HALFTONE).unwrap().defaults; + let with = |style: &str| { + let mut p = defaults.clone(); + p["style"] = json!(style); + let h = Halftone::of(&effect(p)).unwrap(); + (h.shape, h.angle) + }; + assert_eq!(with("grid"), (DotShape::Euclidean, 0.0)); + assert_eq!(with("gridAngle"), (DotShape::Euclidean, 45.0)); + assert_eq!(with("gridDots"), (DotShape::Circle, 0.0)); + assert_eq!(with("custom"), (DotShape::Circle, 45.0)); + assert_eq!(with("checker"), (DotShape::Circle, 45.0)); + assert_eq!((style("GRIDDOTS"), style("custom"), style("checker")), (Some(Some((DotShape::Circle, 0.0))), Some(None), None)); + } + #[test] fn spot_dots_cover_the_tone() { for shape in [DotShape::Euclidean, DotShape::Elliptical] { diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index f9bfa01329..894b6138cd 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -6,12 +6,12 @@ #[cfg(test)] mod tests; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; use vectorcraft_render::drawn_bounds_with; @@ -36,7 +36,22 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \ + \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \ + \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 \ + (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), \ + color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object \ + (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, \ + stacked directly above its object (above the outermost clip group, clipping sublayer or live object that holds it: \ + a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, \ + mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or \ + clipping pieces group, so the clip does not hide them and the live object does not take them in; in isolation mode, \ + marks that would go outside the isolated art are an error). Selected parts of compound paths, envelopes, meshes, repeats, \ + Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost \ + such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. \ + A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds \ + such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; \ + one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] @@ -81,13 +96,18 @@ fn corner_paths(r: Rect, length: f64) -> Vec { .collect() } -/// Where the marks of object `id` go: directly above it, or above the outermost clip group or -/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer -/// with a clipping mask holds its marks too, since nothing lies outside it. -fn anchor(d: &Document, id: NodeId) -> NodeId { +/// Where the marks of object `id` go: directly above it, or above the outermost clip group, +/// clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, +/// Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, +/// graph series, graph design copy or clipping pieces group) that holds it at any +/// depth, which would otherwise clip them or take them in as one of its parts. A top-level layer +/// with a clipping mask holds its marks too, since nothing lies outside it. `held` keeps each +/// container's answer, so that siblings selected together look each container up once. +fn anchor(d: &Document, id: NodeId, held: &mut HashMap) -> NodeId { let (mut at, mut outermost) = (id, id); while let Some(up) = d.parent_of(at) { - if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() { + let holds = *held.entry(up).or_insert_with(|| d.node(up).is_some_and(|n| n.clips() || !plain(n)) && d.parent_of(up).is_some()); + if holds { outermost = up; } at = up; @@ -95,6 +115,51 @@ fn anchor(d: &Document, id: NodeId) -> NodeId { outermost } +/// Whether `n` is a layer or a group with no live role, which keeps new art as an ordinary member. +fn plain(n: &Node) -> bool { + let e = n.extras(); + matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) + && !n.is_compound_shape() + && e.shaper.is_none() + && e.objects_on_path.is_none() + && e.dimension.is_none() + && e.graph.is_none() + && e.flare.is_none() + && e.trace.is_none() + && e.generated.is_none() + && e.series_index.is_none() + && !e.graph_design_art + && !e.clip_pieces + && e.live_paint_gaps.is_none() + && !vectorcraft_tools::builder::is_live_paint(n) +} + +/// The outermost live object that draws a selected part with different geometry or placement. +fn measured_object(d: &Document, id: NodeId) -> NodeId { + let (mut at, mut measured) = (id, id); + while let Some(up) = d.parent_of(at) { + if let Some(n) = d.node(up) { + let redraws = match &n.kind { + NodeKind::Compound { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => true, + NodeKind::Blend { spec, .. } => { + (spec.spine.is_some() && !spec.no_spine) || spec.orientation == vectorcraft_doc::BlendOrientation::AlignToPath + } + _ => { + n.extras().shaper.is_some() + || (n.extras().trace.is_some() + && n.children() + .is_some_and(|children| children.first().is_some_and(|c| c.id == at) && n.editing_children().len() < children.len())) + } + }; + if redraws { + measured = up; + } + } + at = up; + } + measured +} + fn mark_bounds(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle"); @@ -106,18 +171,39 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result { if roots.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); } - let d = &s.doc()?.doc; + let st = s.doc()?; + let (d, isolation) = (&st.doc, st.isolation); let symbols = d.symbol_boxes(); let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + let mut held: HashMap = HashMap::new(); + let mut measured = HashSet::new(); let mut too_small = false; for id in roots { + if d.node(id).is_none_or(|n| n.is_guide()) { + continue; + } + let id = measured_object(d, id); + if !measured.insert(id) { + continue; + } let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; + let placed = matches!(n.kind, NodeKind::Blend { .. }).then(|| { + let mut art = vectorcraft_render::effects::expand_live_deep(Some(d), n); + art.appearance = n.appearance.clone(); + art + }); + let n = placed.as_ref().unwrap_or(n); let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue }; // Corner legs are at most half a side, so an object too small for any leg gets no marks. let (lx, ly) = legs(r, length); if rectangle || lx > FLAT || ly > FLAT { - marked.push((anchor(d, id), r)); + let at = anchor(d, id, &mut held); + // Marks placed outside the isolated art could not be selected or edited there. + if isolation.is_some_and(|iso| iso == at || !d.ancestry(at).is_some_and(|a| a.contains(&iso))) { + return Err(bad(C, "the marks would go outside the isolated art: exit isolation mode first")); + } + marked.push((at, r)); } else { too_small = true; } diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index 13c9401464..186c433505 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -288,6 +288,228 @@ fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() { assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}"); } +#[test] +fn marks_on_envelope_sources_follow_the_drawn_bounds_once_per_live_object() { + for nested in [false, true] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 20.0, 0.0, 20.0, 20.0); + let top = rect(&mut s, 180.0, 120.0, 100.0, 60.0); + select(&mut s, &[a, b, top]); + let r = s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap(); + let envelope = NodeId(r["id"].as_u64().unwrap()); + let outermost = if nested { + let r = s.execute("object.repeat.grid", &json!({"ids": [envelope.0], "rows": 2, "cols": 2})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + } else { + envelope + }; + let layer = parent(&s, outermost); + let before = node(&s, outermost); + let d = &s.doc().unwrap().doc; + let drawn = vectorcraft_render::drawn_bounds(d, d.node(outermost).unwrap()).unwrap(); + assert!(drawn.x0 > marks_bounds(&s, b).x1, "the visible art is away from its sources"); + for selected in [vec![a], vec![a, b], vec![a, envelope]] { + for style in ["corners", "rectangle"] { + for bounds in ["geometric", "visual"] { + select(&mut s, &selected); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1, "one set of marks for the live object"); + assert_eq!(marks.len(), 1); + assert_eq!(children(&s, layer), vec![outermost, marks[0]]); + assert_eq!(node(&s, outermost), before); + assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "{nested}, {style}, {bounds}"); + assert_eq!(steps(&s), n + 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![outermost]); + assert_eq!(node(&s, outermost), before); + } + } + } + } +} + +#[test] +fn marks_on_a_blend_key_or_compound_shape_operand_go_above_the_live_object() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let layer = parent(&s, blend); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, blend), vec![a, b], "the blend keeps its keys"); + assert_eq!(children(&s, layer), vec![blend, mark]); + assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 20.0, 20.0)), "the key's own bounds"); + s.execute("edit.undo", &json!({})).unwrap(); + + for stored_spine in [false, true] { + s.execute("object.blend.options", &json!({"id": blend.0, "orientation": if stored_spine { "page" } else { "path" }})).unwrap(); + if stored_spine { + s.execute("object.blend.spine.reshapeSegment", &json!({"id": blend.0, "segment": 0, "t": 0.5, "dx": 0, "dy": 60})).unwrap(); + } + let before = node(&s, blend); + let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") }; + let drawn = vectorcraft_doc::live::blend_expand(keys, spec).iter().filter_map(Node::visual_bounds).reduce(|a, b| a.union(b)).unwrap(); + select(&mut s, &[a, b]); + let r = s.execute(COMMAND, &json!({"bounds": "visual"})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1, "repositioned keys are measured as one live object"); + assert_eq!(marks.len(), 1); + assert_eq!(children(&s, layer), vec![blend, marks[0]]); + assert_eq!(node(&s, blend), before); + assert!(near(marks_bounds(&s, marks[0]), (drawn.x0, drawn.y0, drawn.x1, drawn.y1))); + s.execute("edit.undo", &json!({})).unwrap(); + } + + let c = rect(&mut s, 100.0, 100.0, 30.0, 30.0); + let d = rect(&mut s, 110.0, 100.0, 30.0, 30.0); + select(&mut s, &[c, d]); + s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap(); + let shape = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[d]); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, shape), vec![c, d], "the compound shape keeps its operands"); + assert!(near(marks_bounds(&s, mark), (110.0, 100.0, 140.0, 130.0)), "the operand's own bounds"); + let stack = children(&s, parent(&s, shape)); + assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == shape).map(|i| i + 1), "{stack:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + + // With the compound shape isolated, the marks could only go outside the isolated art: refused. + s.execute("object.isolate", &json!({"id": shape.0})).unwrap(); + select(&mut s, &[d]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("outside the isolated art"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); +} + +#[test] +fn marks_on_an_outlined_glyph_stay_directly_above_it_inside_the_outlines_group() { + for isolated in [false, true] { + let mut s = session(); + let text = + s.execute("text.create", &json!({"x": 20, "y": 60, "text": "AB", "size": 24, "font": "Source Sans 3", "style": "Regular"})).unwrap(); + select(&mut s, &[NodeId(text["id"].as_u64().unwrap())]); + let outlines = ids_of(&s.execute("type.createOutlines", &json!({})).unwrap())[0]; + let glyphs = children(&s, outlines); + if isolated { + s.execute("object.isolate", &json!({"id": outlines.0})).unwrap(); + } + select(&mut s, &[glyphs[0]]); + let bounds = marks_bounds(&s, glyphs[0]); + let mark = ids_of(&s.execute(COMMAND, &json!({})).unwrap())[0]; + assert_eq!(parent(&s, mark), outlines); + let mut expected = glyphs; + expected.insert(1, mark); + assert_eq!(children(&s, outlines), expected); + assert!(near(marks_bounds(&s, mark), (bounds.x0, bounds.y0, bounds.x1, bounds.y1))); + } +} + +#[test] +fn marks_measure_blend_keys_and_steps_placed_on_a_diagonal_spine() { + let mut s = session(); + let a = rect(&mut s, 20.0, 30.0, 40.0, 10.0); + let b = rect(&mut s, 120.0, 130.0, 20.0, 40.0); + select(&mut s, &[a, b]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 8})).unwrap(); + s.execute("object.blend.make", &json!({"spacing": "steps", "steps": 3, "orientation": "path"})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let before = node(&s, blend); + let vectorcraft_doc::NodeKind::Blend { children: keys, spec } = &before.kind else { panic!("a blend") }; + let placed = vectorcraft_doc::live::blend_expand(keys, spec); + assert!(placed.len() > keys.len()); + let geometry = placed.iter().map(|n| n.path_data().unwrap().bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let visual = placed.iter().map(|n| n.visual_bounds().unwrap()).reduce(|a, b| a.union(b)).unwrap(); + let stored = before.geometric_bounds().unwrap(); + assert!(geometry.y0 < stored.y0 || geometry.y1 > stored.y1); + assert!(visual.x0 < geometry.x0 && visual.y0 < geometry.y0 && visual.x1 > geometry.x1 && visual.y1 > geometry.y1); + + for selected in [vec![a], vec![a, b], vec![blend]] { + for style in ["corners", "rectangle"] { + for (bounds, expected) in [("geometric", geometry), ("visual", visual)] { + select(&mut s, &selected); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"style": style, "bounds": bounds})).unwrap(); + let marks = ids_of(&r); + assert_eq!(r["count"], 1); + assert_eq!(marks.len(), 1); + let actual = marks_bounds(&s, marks[0]); + assert!( + near(actual, (expected.x0, expected.y0, expected.x1, expected.y1)), + "{selected:?}, {style}, {bounds}: {actual:?}, {expected:?}" + ); + for shape in &placed { + let r = if bounds == "visual" { shape.visual_bounds().unwrap() } else { shape.path_data().unwrap().bounds().unwrap() }; + assert!(actual.x0 <= r.x0 + 1e-6 && actual.y0 <= r.y0 + 1e-6 && actual.x1 >= r.x1 - 1e-6 && actual.y1 >= r.y1 - 1e-6); + } + assert_eq!(node(&s, blend), before); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(node(&s, blend), before); + } + } + } +} + +#[test] +fn marks_on_a_dimension_part_go_above_the_live_object() { + let mut s = session(); + let r = s.execute("dimension.create", &json!({"a": [0, 0], "b": [100, 0]})).unwrap(); + let dimension = NodeId(r["id"].as_u64().unwrap()); + let layer = parent(&s, dimension); + let parts = children(&s, dimension); + let before = node(&s, dimension); + select(&mut s, &[parts[0]]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, dimension), parts, "the dimension keeps its generated parts"); + assert_eq!(node(&s, dimension), before); + assert_eq!(children(&s, layer), vec![dimension, mark]); + + let before = node(&s, mark); + s.execute("dimension.update", &json!({"ids": [dimension.0], "offset": 40})).unwrap(); + assert_eq!(children(&s, layer), vec![dimension, mark]); + assert_eq!(node(&s, mark), before, "updating the dimension preserves the mark"); +} + +#[test] +fn marks_on_an_image_trace_part_go_above_the_live_object() { + let mut s = session(); + let art = rect(&mut s, 20.0, 30.0, 60.0, 40.0); + select(&mut s, &[art]); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let r = s.execute("imageTrace.make", &json!({"params": {"ignoreWhite": true}})).unwrap(); + let trace = NodeId(r["id"].as_u64().unwrap()); + let layer = parent(&s, trace); + let parts = children(&s, trace); + let before = node(&s, trace); + let part = before.children().unwrap().iter().find(|n| n.path_data().is_some()).unwrap().id; + select(&mut s, &[part]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, trace), parts, "the trace keeps its generated parts"); + assert_eq!(node(&s, trace), before); + assert_eq!(children(&s, layer), vec![trace, mark]); + + let before = node(&s, mark); + let r = s.execute("imageTrace.make", &json!({"id": trace.0, "params": {"ignoreWhite": true, "threshold": 100}})).unwrap(); + let retraced = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(children(&s, layer), vec![retraced, mark]); + assert_eq!(node(&s, mark), before, "retracing preserves the mark"); +} + #[test] fn flat_objects_get_lines_and_guides_and_empty_groups_none() { let mut s = session(); diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index a9f1b48166..8dff9593e9 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Randomize Fill Colors", ["Object", "Plug-ins", "Color Effects"], None, - "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", + "{scheme?: \"color\" (any color: red, green and blue each at random, in the document's color mode) | \"tint\" (a tint of `swatch`, linked to it) | \"gray\" (a gray) (\"color\"), swatch?: a global or spot color swatch's name (tint only, and needed there; a tint swatch gives tints of its base, which must still support tints), min?: % 0..100 (0), max?: % 0..100 (100; not less than min) (tint and gray only: the tint, or the gray's black, ranges from min to max), seed?: whole number (0; the same seed, objects and settings give the same colors; colors are drawn in the order of ids, a repeated id counting once and an id inside a listed group taking its color with that group's objects, so another order can give each object a different color), ids?: [id…] (default: the selection)} give each selected filled path, compound path and live compound shape, and each one inside the selected groups, its own top fill color, picked at random and evenly within the scheme, as one undo step (none when no fill changes). Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths, hidden and locked objects (and objects in hidden or locked groups and layers, or on a locked artboard, also when given in ids, except new art made there while it is still selected), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill becomes the color. A user compound path or live compound shape directly inside a graph series group takes a color unless that series is set to draw a compound design: a marker design while it draws markers, or a column design while it draws columns. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, which gives every mark of the series that one color (docs/mcp.md) → {count: objects whose fill changed}", has_selection, random_fill::run ), diff --git a/crates/engine/src/cmd/addons/color/random_fill.rs b/crates/engine/src/cmd/addons/color/random_fill.rs index eaf78e5660..799da3c423 100644 --- a/crates/engine/src/cmd/addons/color/random_fill.rs +++ b/crates/engine/src/cmd/addons/color/random_fill.rs @@ -6,7 +6,7 @@ #[cfg(test)] mod tests; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; @@ -16,7 +16,7 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use super::super::super::colorcmds::{edit_if_changed, keeping_series_paint}; #[cfg(test)] use super::super::super::graph::is_design_art; -use super::super::super::graph::{is_series_group, paint_targets}; +use super::super::super::graph::{is_series_group, paint_targets, series_drawn_designs}; use super::super::super::menucmds::whole_or; use super::super::super::paint::swatch_solid; use super::super::super::{bad, checked_ids_or_selection, number_or, text_param}; @@ -210,6 +210,39 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { } let series_groups = cached_series_groups(before, &targets); let mut seen = std::collections::HashSet::new(); + let compound_groups: HashSet = targets + .iter() + .filter_map(|id| { + let n = before.node(*id)?; + if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { + return None; + } + before.parent_of(*id).filter(|p| series_groups.contains(p)) + }) + .collect(); + let mut drawn_designs = HashMap::new(); + // The series groups whose compounds are marks: the series draws no compound design, so the graph made none of + // them from one. Only a design the series draws can have made a compound. Each series is checked once. + let compound_marks: HashSet = compound_groups + .iter() + .copied() + .filter(|group| { + let Some(index) = before.node(*group).and_then(|g| g.extras().series_index).and_then(|i| usize::try_from(i).ok()) else { + return false; + }; + let graph = before.parent_of(*group).and_then(|p| before.node(p)); + graph.is_some_and(|graph| { + let Some(spec) = graph.extras().graph.as_deref() else { return false }; + let drawn = drawn_designs.entry(graph.id).or_insert_with(|| series_drawn_designs(spec)); + let (marker, column) = drawn(index); + ![column, marker].into_iter().flatten().any(|name| { + before.graph_designs.iter().any(|design| { + design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape()) + }) + }) + }) + }) + .collect(); // A compound directly in a series group is one of the series' marks unless the graph drew it from a design; // the rest of the series' art below its top level is design art. let series_compound = |id: NodeId| { @@ -217,19 +250,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { if !(matches!(n.kind, NodeKind::Compound { .. }) || n.is_compound_shape()) || n.extras().graph_design_art { return false; } - let Some(group) = before.parent_of(id).filter(|p| series_groups.contains(p)).and_then(|p| before.node(p)) else { return false }; - let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false }; - let graph = before.parent_of(group.id).and_then(|p| before.node(p)).and_then(|p| p.extras().graph.as_deref()); - graph.is_some_and(|spec| { - let column = spec.series_columns.get(index).and_then(Option::as_ref).map(|c| c.design.as_str()); - let marker = spec.series_markers.get(index).and_then(Option::as_deref); - ![column, marker].into_iter().flatten().any(|name| { - before - .graph_designs - .iter() - .any(|design| design.name == name && (matches!(design.art.kind, NodeKind::Compound { .. }) || design.art.is_compound_shape())) - }) - }) + before.parent_of(id).is_some_and(|p| compound_marks.contains(&p)) }; targets.retain(|id| seen.insert(*id) && !locks.holds_id(*id) && (series_compound(*id) || !cached_is_design_art(before, *id, &series_groups))); let count = keeping_series_paint(d, &roots, |d| { diff --git a/crates/engine/src/cmd/addons/color/random_fill/tests.rs b/crates/engine/src/cmd/addons/color/random_fill/tests.rs index 11b4f989be..61655534d7 100644 --- a/crates/engine/src/cmd/addons/color/random_fill/tests.rs +++ b/crates/engine/src/cmd/addons/color/random_fill/tests.rs @@ -398,6 +398,54 @@ fn a_user_compound_in_a_series_with_a_plain_path_design_takes_a_color() { } } +#[test] +fn a_user_compound_in_a_column_series_naming_an_undrawn_compound_marker_takes_a_color() { + let mut s = session(); + let tile = rects(&mut s, 2); + select(&mut s, &tile); + let design = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[design]); + s.execute("graph.design", &json!({"new": "Tile"})).unwrap(); + assert!(matches!(s.doc().unwrap().doc.graph_designs[0].art.kind, NodeKind::Compound { .. })); + let graph = NodeId( + s.execute( + "graph.create", + &json!({"type": "column", "x": 100, "y": 100, "width": 200, "height": 150, "series": ["X", "A"], "rows": [[10, 20], [20, 30]]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + // A column series keeps a marker design it was given as a line series, and does not draw it. + s.edit("Name a marker design on a column series", |d, _| { + let mut extras = d.node_mut(graph).unwrap().extras_mut(); + let spec = extras.graph.as_deref_mut().unwrap(); + spec.series_markers = vec![Some("Tile".into()), Some("Tile".into())]; + Ok(()) + }) + .unwrap(); + let d = &s.doc().unwrap().doc; + let series = d.node(graph).unwrap().children().into_iter().flatten().find(|n| n.extras().series_index.is_some()).unwrap(); + let group = series.id; + let marks: Vec = series + .children() + .into_iter() + .flatten() + .filter(|m| matches!(m.kind, NodeKind::Path { .. }) && !m.appearance.fill_paint().is_none()) + .map(|m| m.id) + .collect(); + assert!(marks.len() >= 2); + let marks = &marks[..2]; + select(&mut s, marks); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(compound), Some(group)); + for ids in [vec![compound], vec![group], vec![graph]] { + s.execute(C, &json!({"scheme": "gray", "min": 40, "max": 40, "ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + assert_eq!(fill(&s, compound), Paint::solid(Color::gray(0.4)), "{ids:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + #[test] fn grouped_paths_in_a_graph_series_keep_their_fills_as_for_paint_set_fill() { for kind in ["column", "line", "scatter"] { diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index e8e512a448..ef010d7f32 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -71,7 +71,7 @@ pub fn specs() -> Vec { "Make Numbers Sequence…", ["Object", "Plug-ins", "Type Tools"], None, - "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", + "{start?: number (1), step?: number (1; its sign is set to run toward `end`; 0: every object gets `start`), end?: number (omitted: the numbers run to the last type object; given: they stop past `end`, and the objects after the last number keep their text), order?: \"stacking\" (stacking order, from the back) | \"rows\" (top to bottom, each row left to right) | \"columns\" (left to right, each column top to bottom) (\"stacking\"; rows and columns group objects whose centers are within half the median height or width), replace?: \"all\" (the whole text) | \"numbers\" (every number in the text: digits, with any `.` or `,` between digits and a `-` before them that does not follow a letter or digit) | \"placeholder\" (every {%n}, in any case) (\"all\"; with numbers or placeholder, objects that hold none are skipped, get no number and order leaves them out; the remaining objects are ordered before end limits the sequence, so objects past end still count for rows and columns; at most 10000 numbers or placeholders are replaced in one run (matches that already read their number do not count); more is an error), shuffle?: false (true: the numbers go to the objects in random order, and order is not used), seed?: whole number (0; the same seed gives the same order; checked even with shuffle off), leadingZeros?: true (non-negative numbers are padded with zeros to the whole digits of the widest of start and end, or of the last number), digits?: 1..30 (with leadingZeros, at least this many whole digits), trailingZeros?: false (true: every number gets as many decimal places as the one with the most), removeUnused?: false (true, with end: the objects left without a number are deleted, except a clipping mask), ids?: [id…], id? (instead of ids; neither: the selection)} number the type objects among the objects (inside groups too), as one undo step. Locked or hidden type is left alone. A frame of threaded type among them is an error, unless replace skips it because its story holds no number or placeholder. Values are -1e12..1e12, rounded to the most decimal places among start, step and end (at most 6). Replaced text takes the style of the text it replaces, and a match that already reads its number keeps its style. Objects that already read so are left as they are, and when nothing changes no undo step is made → {count (objects changed), ids (numbered, in order), removed}", has_selection, numbers::make_numbers ), diff --git a/crates/engine/src/cmd/addons/typetools/numbers.rs b/crates/engine/src/cmd/addons/typetools/numbers.rs index c83c306496..f8064b9ded 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers.rs @@ -9,7 +9,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{CharStyle, NodeId, NodeKind, TextObject, TextRun}; use vectorcraft_geom::Rect; use vectorcraft_render::effects; use vectorcraft_text::edit; @@ -273,6 +273,109 @@ pub(crate) fn edits(text: &str, spans: Vec<(usize, usize)>, number: &str) -> Vec spans.into_iter().rev().filter(|(a, b)| text.get(*a..*b) != Some(number)).map(|(a, b)| (a, b, number.to_string())).collect() } +thread_local! { + /// [`text_passes`] of this thread. + static TEXT_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times Make Numbers Sequence has gone over a type object's text or style runs on this +/// thread: once to build the text an object would read, and once for each part of the object it +/// changes, however many numbers the text holds. +#[cfg(test)] +pub(crate) fn text_passes() -> u64 { + TEXT_PASSES.get() +} + +/// Adds one to [`text_passes`]. +fn note_text_pass() { + TEXT_PASSES.set(TEXT_PASSES.get().saturating_add(1)); +} + +/// `text` with `changes` (from the last to the first, as [`edits`] gives them) made. +pub(crate) fn replaced(text: &str, changes: &[Edit]) -> String { + note_text_pass(); + let mut out = String::with_capacity(text.len()); + let mut at = 0; + for (a, b, n) in changes.iter().rev() { + out.push_str(text.get(at..*a).unwrap_or_default()); + out.push_str(n); + at = *b; + } + out.push_str(text.get(at..).unwrap_or_default()); + out +} + +/// Makes `changes` (from the last to the first, as [`edits`] gives them) in `t`, with the +/// paragraphs, style runs and ruby that replacing each range by itself with +/// [`edit::replace_range`] would give, in one pass over each. +pub(crate) fn apply(t: &mut TextObject, changes: &[Edit]) { + if changes.len() < 2 || !t.ruby.is_empty() || t.runs.iter().any(|r| r.inline.is_some()) || { + let text = t.plain_text(); + changes.iter().any(|(a, b, n)| n.contains('\n') || text.get(*a..*b).is_none_or(|s| s.contains('\n'))) + } { + // One change (a whole text), one that adds or removes paragraphs, or text with ruby or + // inline art, whose spans each replacement moves or drops in turn. + for (a, b, n) in changes { + note_text_pass(); + t.splice_paras(*a, *b, n); + edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + return; + } + // Changes inside paragraphs leave every paragraph's style where it is: one splice sets the + // paragraph list as each of them would. + if let Some((a, b, n)) = changes.first() { + t.splice_paras(*a, *b, n); + } + replace_runs(&mut t.runs, changes); +} + +/// The runs with each range of `changes` replaced by its number in the style of the range's first +/// character, without a glyph choice, as [`edit::replace_range`] gives it. +fn replace_runs(runs: &mut Vec, changes: &[Edit]) { + note_text_pass(); + let old = std::mem::take(runs); + let mut out: Vec = Vec::with_capacity(old.len()); + let mut pending = changes.iter().rev().peekable(); + // Where the run starts and where the last replaced range ends. + let (mut off, mut cut) = (0, 0); + for r in old { + let (start, end) = (off, off + r.text.len()); + off = end; + // The run's style without a glyph choice, for pieces that start inside it and numbers. + let plain = CharStyle { glyph_alternate: None, ..r.style.clone() }; + // A piece of the run from `a` to `b`: one that starts inside it has no glyph choice. + let piece = |out: &mut Vec, a: usize, b: usize| { + let style = if a == start { &r.style } else { &plain }; + push(out, r.text.get(a - start..b - start).unwrap_or_default(), style); + }; + let mut pos = start.max(cut).min(end); + while let Some((a, b, n)) = pending.next_if(|(a, _, _)| *a < end) { + if pos < *a { + piece(&mut out, pos, *a); + } + push(&mut out, n, &plain); + cut = *b; + pos = cut.min(end); + } + if pos < end { + piece(&mut out, pos, end); + } + } + edit::normalize(&mut out); + *runs = out; +} + +/// Adds `text` in `style` to the end of `out`, onto the last run when it has the same style, so a +/// style is copied once for each change of style rather than once for each number. +fn push(out: &mut Vec, text: &str, style: &CharStyle) { + match out.last_mut() { + Some(last) if last.style == *style && last.inline.is_none() && style.glyph_alternate.is_none() => last.text.push_str(text), + _ => out.push(TextRun { text: text.to_string(), style: style.clone(), inline: None }), + } +} + pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let o = Options::parse(p)?; @@ -292,24 +395,43 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { if texts.len() > MAX_TEXTS { return Err(bad(C, format!("too many type objects: at most {MAX_TEXTS}"))); } - let threads = threads::ThreadIndex::of(d); - if texts.iter().any(|id| threads.threaded(*id)) { - return Err(bad(C, "threaded type can't be numbered: its frames share one story")); - } let plain = |id: NodeId| match d.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.plain_text(), _ => String::new(), }; - // Only objects that hold a number or the placeholder count, for the order too. - let mut texts: Vec<(NodeId, String)> = texts - .into_iter() - .map(|id| (id, plain(id))) - .filter(|(_, t)| match o.replace { - "numbers" => t.bytes().any(|b| b.is_ascii_digit()), - "placeholder" => !placeholder_spans(t).is_empty(), - _ => true, - }) - .collect(); + let threads = threads::ThreadIndex::of(d); + let threaded = || bad(C, "threaded type can't be numbered: its frames share one story"); + if o.replace == "all" && texts.iter().any(|id| threads.threaded(*id)) { + return Err(threaded()); + } + let holds = |t: &str| match o.replace { + "numbers" => t.bytes().any(|b| b.is_ascii_digit()), + "placeholder" => !placeholder_spans(t).is_empty(), + _ => true, + }; + // Only objects that hold a number or the placeholder count, for the order too. Threaded type + // is skipped like other type when its whole story holds none, so a placeholder split across + // two frames is still refused. + let mut kept: Vec<(NodeId, String)> = Vec::with_capacity(texts.len()); + let mut checked_threads = std::collections::HashSet::::new(); + for id in texts { + if threads.threaded(id) { + if threads.first_thread_index(id).is_some_and(|index| !checked_threads.insert(index)) { + continue; + } + let frames = threads.story(id); + let story: String = frames.iter().copied().map(plain).collect(); + if holds(&story) { + return Err(threaded()); + } + continue; + } + let t = plain(id); + if holds(&t) { + kept.push((id, t)); + } + } + let mut texts = kept; if o.order != "stacking" && o.shuffle.is_none() { let placed: Vec<(NodeId, Rect)> = texts .iter() @@ -345,11 +467,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { _ => vec![(0, text.len(), number.clone())], }; // The text it would have, to leave out objects that already read so. - let mut after = text.clone(); - for (a, b, n) in &changes { - after.replace_range(*a..*b, n); - } - if after != *text { + if replaced(text, &changes) != *text { plans.push((*id, changes)); } } @@ -367,11 +485,7 @@ pub(crate) fn make_numbers(s: &mut Session, p: &Value) -> Result { s.edit("Make Numbers Sequence", |d, sel| { for (id, changes) in &plans { let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?; - for (a, b, n) in changes { - t.splice_paras(*a, *b, n); - edit::replace_range(&mut t.runs, *a, *b, n); - t.ruby_after_replace(*a, *b, n.len()); - } + apply(t, changes); refresh_bounds(t); } d.remove_many(&removed)?; diff --git a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs index e7d51d47b4..d472268049 100644 --- a/crates/engine/src/cmd/addons/typetools/numbers/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/numbers/tests.rs @@ -2,9 +2,9 @@ //! orders, removed objects, one undo step, and bad params refused without a change. use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{NodeId, NodeKind, TextObject, TextRun}; -use super::{COMMAND as C, Options, number_spans, placeholder_spans, sequence}; +use super::{COMMAND as C, Options, apply, edits, number_spans, placeholder_spans, sequence, text_passes}; use crate::Session; fn session() -> Session { @@ -93,6 +93,51 @@ fn threaded_type_is_refused() { assert_eq!((plain(&s, NodeId(a)), steps(&s)), ("1 2 3".to_string(), n)); } +/// Replacing numbers or placeholders skips threaded type that holds none, as it skips other type. +#[test] +fn threaded_type_with_nothing_to_replace_is_skipped() { + let mut s = session(); + let a = + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a b c", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let seat = text_at(&mut s, 40.0, 300.0, "Seat 0"); + let scans = super::threads::thread_scans(); + let builds = super::threads::story_builds(); + let out = s.execute(C, &json!({"ids": [a, b, seat.0], "replace": "numbers", "start": 4})).unwrap(); + assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index"); + assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check"); + assert_eq!(out["count"], json!(1)); + assert_eq!((plain(&s, NodeId(a)), plain(&s, seat)), ("a b c".to_string(), "Seat 4".to_string())); + let n = steps(&s); + let scans = super::threads::thread_scans(); + let builds = super::threads::story_builds(); + assert!(s.execute(C, &json!({"ids": [a, b], "replace": "placeholder"})).is_ok(), "no placeholder in the story"); + assert_eq!(super::threads::thread_scans() - scans, 1, "one thread index"); + assert_eq!(super::threads::story_builds() - builds, 1, "selected frames of one story share its match check"); + assert!(s.execute(C, &json!({"ids": [a, b]})).is_err(), "the whole text of threaded type is still refused"); + assert_eq!(steps(&s), n); +} + +/// A placeholder in a threaded story is refused even when no one frame holds all of it. +#[test] +fn threaded_type_whose_story_holds_a_placeholder_is_refused() { + let mut s = session(); + let words = format!("{} {{%n}}", "word ".repeat(40)); + let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": words, "area": {"width": 60, "height": 30}})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 300, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + let first = plain(&s, NodeId(a)); + let second = plain(&s, NodeId(b)); + assert!(!first.contains("{%n}"), "the selected frame alone has no placeholder"); + assert!((first + &second).contains("{%n}"), "the story contains the placeholder in thread order"); + let n = steps(&s); + assert!(s.execute(C, &json!({"ids": [a], "replace": "placeholder"})).is_err()); + assert_eq!(steps(&s), n); +} + #[test] fn the_spans_find_numbers_and_placeholders() { assert_eq!(number_spans("No. 12, page 3.5 of 1,000."), [(4, 6), (13, 16), (20, 25)]); @@ -335,3 +380,65 @@ fn a_run_that_changes_nothing_makes_no_step_and_bad_params_fail() { } assert_eq!((plain(&s, a), steps(&s)), ("1".to_string(), n)); } + +#[test] +fn a_long_text_is_numbered_in_a_few_passes() { + let mut s = session(); + let a = text_at(&mut s, 40.0, 100.0, &"9 ".repeat(2_000)); + let before = text_passes(); + s.execute(C, &json!({"ids": [a.0], "replace": "numbers", "start": 1})).unwrap(); + let passes = text_passes() - before; + assert_eq!(plain(&s, a), "1 ".repeat(2_000)); + assert!(passes <= 4, "2,000 numbers in one object took {passes} passes over its text"); +} + +/// `t` with `changes` made one at a time, as the command made them before it made them in one pass. +fn one_at_a_time(t: &TextObject, changes: &[(usize, usize, String)]) -> TextObject { + let mut t = t.clone(); + for (a, b, n) in changes { + t.splice_paras(*a, *b, n); + vectorcraft_text::edit::replace_range(&mut t.runs, *a, *b, n); + t.ruby_after_replace(*a, *b, n.len()); + } + t +} + +#[test] +fn numbers_made_in_one_pass_keep_the_styles_and_ruby_of_one_at_a_time() { + let mut s = session(); + let id = text_at(&mut s, 40.0, 100.0, "x"); + let NodeKind::Text(base) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("not text") }; + let base = base.clone(); + let style = |size: f64, glyph: Option| { + let mut st = base.first_style(); + st.size = size; + st.glyph_alternate = glyph.map(|ch| serde_json::from_value(json!({"ch": ch.to_string(), "gid": 7, "font": "F"})).unwrap()); + st + }; + let ruby = |start: usize, end: usize| serde_json::from_value(json!({"start": start, "end": end, "text": "r"})).unwrap(); + // Runs that split numbers, start at them and end inside them, with glyph choices and ruby + // over, across and between the numbers. + type Case<'a> = (Vec<(&'a str, f64, Option)>, Vec<(usize, usize)>); + let cases: Vec = vec![ + (vec![("a12 b", 10.0, None), ("34 c5", 12.0, Some('3')), ("6 -7.8 9", 14.0, None)], vec![(1, 3), (0, 6), (7, 12), (12, 14), (16, 18)]), + (vec![("1", 10.0, Some('1')), ("2", 11.0, Some('2')), (" x ", 12.0, None), ("333", 13.0, None)], vec![(0, 2), (2, 4), (5, 8)]), + (vec![("no 1, 2 or 3", 10.0, None), ("", 11.0, None), ("44", 12.0, Some('4'))], vec![(3, 4), (4, 9), (13, 14)]), + (vec![("a", 10.0, Some('a')), ("a", 10.0, Some('a')), (" 12 34", 10.0, None)], vec![(3, 5), (6, 8)]), + ]; + for (runs, spans) in cases { + let mut t = base.clone(); + t.runs = runs.iter().map(|(text, size, glyph)| TextRun { text: text.to_string(), style: style(*size, *glyph), inline: None }).collect(); + let text = t.plain_text(); + // Without ruby the runs are rebuilt in one pass; with it each change is made in turn. + for with_ruby in [false, true] { + t.ruby = if with_ruby { spans.iter().map(|(a, b)| ruby(*a, *b)).collect() } else { Vec::new() }; + for number in ["0", "123456", "5", "123"] { + let changes = edits(&text, number_spans(&text), number); + let mut fast = t.clone(); + apply(&mut fast, &changes); + let slow = one_at_a_time(&t, &changes); + assert_eq!((&fast.runs, &fast.ruby, &fast.paras), (&slow.runs, &slow.ruby, &slow.paras), "{text:?} numbered {number}"); + } + } + } +} diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 9bdddebbdc..28a9fbaaa9 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -23,7 +23,7 @@ use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, Node use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; -pub use flavours::{ImageRead, read_image}; +pub use flavours::{ImageRead, read_image, read_pixels}; pub(crate) use resources::SwatchChoices; pub use resources::{ArtResources, SymbolOptions, art_resources}; diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index bf900adcf1..80e31e849e 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -461,6 +461,20 @@ pub fn read_image(bytes: &[u8]) -> Result { Ok(ImageRead(img)) } +/// [`read_image`] for a bitmap another app put on the clipboard as decoded pixels, on any thread: +/// the pixels are encoded once as the PNG the document keeps, and kept as the decoded image the +/// renderers share, so neither this read nor the first frame that draws the image decodes them. +/// When the renderers' store refuses the pixels (over its budget, or no room beside the images +/// being drawn), they are dropped, and the renderers decode the PNG as they decode any other image, +/// under the same memory limits. An error when the image is empty or too large to draw. +pub fn read_pixels(img: image::RgbaImage) -> Result { + let img = image::DynamicImage::ImageRgba8(img); + let read = fileio::pixels_png(&img).map_err(|e| bad("clipboard.importImage", e.to_string()))?; + // Refused pixels are not held anywhere else, so the store's budget stays the only one. + let _kept = vectorcraft_render::keep_decoded_image(&read.blob, img); + Ok(ImageRead(read)) +} + impl Session { /// `clipboard.importImage` with `p` (its `mime` and `center`) for an image [`read_image`] read /// (off the UI thread in the desktop app), which it loads instead of reading `dataBase64`. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ac500697be..55726c31c9 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones; an unknown category, or one without preset, is an error), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index e5463f6c44..5d849cfed2 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -481,6 +481,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, id, ¶ms)?; super::params::check_effect_channel(C, id, ¶ms)?; super::params::check_effect_center(C, id, ¶ms)?; + super::params::check_effect_halftone_style(C, id, ¶ms)?; super::params::check_effect_pathfinder(C, id, ¶ms)?; // Crop Marks take their style from the preferences when applied. if id == effects::CROP_MARKS && params.get("style").is_none() { @@ -826,6 +827,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; super::params::check_effect_center(C, effect, ¶ms)?; + super::params::check_effect_halftone_style(C, effect, ¶ms)?; super::params::check_effect_pathfinder(C, effect, ¶ms)?; } if edited.iter().any(|e| texture_load_effect(e)) { diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 38654bb8ba..52871e23fa 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -44,7 +44,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, pixels_png, preview_with_clip, size_note}; mod heifread; pub mod hpgl; mod jp2read; @@ -87,6 +87,7 @@ pub(crate) use load::decode_native_file; use load::err; pub(crate) use load::import_svg; pub(crate) use load::is_placeholder; +pub(crate) use load::is_raster_image; pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ @@ -146,6 +147,8 @@ mod commands; mod export_names; mod formats; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::FILES_READ; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 649e8944f8..0a4cf89b18 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -283,10 +283,18 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX #[cfg(not(target_arch = "wasm32"))] pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + /// The paths [`read_file`] has read on this thread, in order. + pub(crate) static FILES_READ: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { use std::io::Read; may_read(path)?; + #[cfg(test)] + FILES_READ.with(|r| r.borrow_mut().push(path.to_string())); // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index b0a6aab5fc..53cac16bee 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1160,6 +1160,20 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { (drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size")) } +/// Whether `bytes` start as a file in a format [`raster_image`] reads, whether or not the rest of +/// it can be decoded. +pub(crate) fn is_raster_image(bytes: &[u8]) -> bool { + super::pcraftread::is_pcraft(bytes) + || psdread::is_psd(bytes) + || jxlread::is_jxl(bytes) + || super::jp2read::is_jpeg2000(bytes) + || super::heifread::is_heif(bytes) + || super::pxrread::is_pxr(bytes) + || craft_image_codecs::detect(bytes).is_some() + || super::tgaread::is_targa(bytes) + || super::pcxread::is_pcx(bytes) +} + /// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as /// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); @@ -1338,6 +1352,18 @@ pub(super) fn as_png(img: impl Into, icc: Option>, stored(png, "image/png", size, ppi) } +/// Decoded pixels `img` stored as a PNG, without a resolution or an ICC profile. An image whose +/// pixels as RGBA need more than [`MAX_RASTER_ALLOC`] is refused as too large to draw. +pub(crate) fn pixels_png(img: &image::DynamicImage) -> Result { + let (w, h) = (img.width(), img.height()); + if u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC { + return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); + } + let mut png = Vec::new(); + img.write_with_encoder(image::codecs::png::PngEncoder::new(&mut png)).map_err(err)?; + stored(png, "image/png", (w, h), None) +} + /// Effect › Distort › Glass › Load Texture…: encoded image `bytes`, in any format [`raster_image`] /// reads, as the `textureImage` Glass stores ([`LoadedTexture::to_stored`]). The pixels are decoded /// within [`MAX_RASTER_ALLOC`], counted as RGBA, as the renderer decodes them (#1717); a CMYK image diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 7a6547890f..5369b34398 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -47,7 +47,12 @@ pub const OPTIONS: &[FormatOption] = &[ default: "\"layerNames\"", description: "layerNames (readable ids from names) | minimal (only referenced ids) | unique (content-hashed prefix on every id and class)", }, - FormatOption { name: "decimals", ty: "integer", default: "3", description: "coordinate precision, 1–7 decimal places" }, + FormatOption { + name: "decimals", + ty: "integer", + default: "3", + description: "coordinate precision, 1–7 decimal places; positive root width/height and viewBox size stay positive", + }, FormatOption { name: "minify", ty: "boolean", default: "false", description: "no XML declaration, indentation or line breaks" }, FormatOption { name: "responsive", ty: "boolean", default: "false", description: "no width/height: the SVG scales to its container" }, FormatOption { diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f348a97f3c..cb70427ef0 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,7 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; -pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; +pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs, series_drawn_designs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index f0d42808ab..6b7ac1e9ec 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -88,22 +88,36 @@ pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: sup /// on or the legend has an entry for the series, or as the columns of a series drawn as columns or /// bars. fn draws_with(g: &GraphSpec, name: &str) -> bool { + let count = g.series_markers.len().max(g.series_columns.len()); + let drawn = series_drawn_designs(g); + (0..count).any(|s| { + let (marker, column) = drawn(s); + marker == Some(name) || column == Some(name) + }) +} + +/// For each series `s` of graph `g`, the designs it draws with, as [`draws_with`] counts them: its +/// marker design and its column design, each only when the series draws it. +pub(crate) fn series_drawn_designs<'a>(g: &'a GraphSpec) -> impl Fn(usize) -> (Option<&'a str>, Option<&'a str>) + 'a { let scatter = g.kind == GraphKind::Scatter; let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); // The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank // (a scatter graph's entries are its pairs of series, labeled by the first of each pair). - let in_legend = |s: usize| { + let in_legend = move |s: usize| { let entries = if scatter { nser.div_ceil(2) } else { nser }; let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str); g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label) }; // Point markers use the same range of designs: a scatter graph plots a pair of series for each. let plotted = if scatter { nser.div_ceil(2) } else { nser }; - let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s)); - let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); - let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); - g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s)) - || g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s)) + let shown = move |s: usize| s < plotted && (g.mark_points || in_legend(s)); + let marked = move |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); + let columnar = move |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); + move |s: usize| { + let marker = g.series_markers.get(s).and_then(Option::as_deref).filter(|_| marked(s)); + let column = g.series_columns.get(s).and_then(Option::as_ref).map(|c| c.design.as_str()).filter(|_| columnar(s)); + (marker, column) + } } /// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index 9677f23ad6..70a5b11b9f 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_color::Color; use vectorcraft_doc::Node; -use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes}; +use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes, style}; use super::edit::selected_roots; use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param}; @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; at partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes; at full tone every shape but line is the cell's square), style?: \"custom\"|\"grid\"|\"gridAngle\"|\"gridDots\"|\"gridDotsAngle\" (custom; sets shape and angle unless they are given: grid euclidean at 0°, gridAngle euclidean at 45°, gridDots circle at 0°, gridDotsAngle circle at 45°), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -27,17 +27,24 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; + let styled = match p.get("style") { + Some(v) => { + let v = v.as_str().ok_or_else(|| bad(C, "style must be a string"))?; + style(v).ok_or_else(|| bad(C, format!("unknown style `{v}` (custom|grid|gridAngle|gridDots|gridDotsAngle)")))? + } + None => None, + }; let shape = match text_param(p, "shape", C)? { Some(v) => { DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? } - None => DotShape::Circle, + None => styled.map_or(DotShape::Circle, |s| s.0), }; let frequency = number_or(p, "frequency", 20.0, C)?; if !(1.0..=300.0).contains(&frequency) { return Err(bad(C, "frequency must be between 1 and 300 lines per inch")); } - let angle = number_or(p, "angle", 45.0, C)?; + let angle = number_or(p, "angle", styled.map_or(45.0, |s| s.1), C)?; if !angle.is_finite() { return Err(bad(C, "invalid angle")); } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 6a88bf74ef..a5e00eab67 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2392,7 +2392,17 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } // Read before it is copied: a file that can't be shown isn't copied. - let img = if images.is_empty() { None } else { Some(linked_image(&bytes, Some(&path)).map_err(|e| bad(C, format!("{path}: {e}")))?) }; + let img = if images.is_empty() { + None + } else { + Some(linked_image(&bytes, Some(&path)).map_err(|e| { + // A file in no image format; a damaged image keeps its own error. + if s.image_only.get().is_some() && !fileio::is_raster_image(&bytes) && !super::place::dcs::is_dcs(&bytes) { + s.image_only.set(Some(false)); + } + bad(C, format!("{path}: {e}")) + })?) + }; // A copy beside the document would point at plate files it can't find there. if copy_to.is_some() && img.as_ref().is_some_and(|img| !img.blob.plate_files().is_empty()) { return Err(bad(C, format!("{path}: copy takes a DCS file only when its plates are inside it; relink to it where its plate files are"))); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 3dc7f579d8..4dee23bcda 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -860,10 +860,34 @@ pub fn find(s: &Session, name: &str) -> Option { /// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names /// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without -/// `preset`. +/// `preset`. A `preset` or `presetCategory` that is not a string, a `presetCategory` that names no +/// category, and a `presetCategory` without a `preset` are errors, except in a replay, which reads +/// a saved step as earlier versions did: such a value is left out, and an unknown category finds no +/// preset. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { - let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; - let found = match str_param(p, "presetCategory") { + if s.replaying() { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + return found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))); + } + let name = text_param(p, "preset", cmd)?; + let wanted = text_param(p, "presetCategory", cmd)? + .map(|c| { + category_names() + .find(|n| n.eq_ignore_ascii_case(c)) + .ok_or_else(|| bad(cmd, format!("unknown category `{c}` ({})", category_names().collect::>().join(", ")))) + }) + .transpose()?; + let Some(name) = name else { + return match wanted { + Some(_) => Err(bad(cmd, "presetCategory needs a preset")), + None => Ok(s.default_settings()), + }; + }; + let found = match wanted { Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), None => find(s, name), }; diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 955520427c..8ed4656295 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -106,8 +106,8 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { } /// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a -/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The -/// selection stays as it is. +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom; refused +/// in an Image Trace object, whose source image stays at the bottom). The selection stays as it is. pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { const C: &str = "object.newGroup"; // Only an omitted key takes its default; `null` is refused like any other bad value. @@ -132,6 +132,10 @@ pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { if !d.is_editable(parent) { return Err(bad(C, "the layer or group is hidden or locked")); } + // An Image Trace object keeps its source image first; a group below it would end the tracing. + if index == 0 && crate::cmd::is_trace_group(n) { + return Err(bad(C, "index 0 of an Image Trace object is its source image; use index 1 or more")); + } let label = if compound { "Compound Path" } else { "Group" }; let gid = s.edit(label, |d, _| { let gid = d.alloc_id(); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 04c8b606f2..f20f4fc782 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -142,7 +142,7 @@ pub fn specs() -> Vec { "Group", [], None, - "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; 0 is refused in an Image Trace object, whose source image stays at the bottom; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", has_doc, new_group ), diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 05d8f78767..427eb4ada7 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -525,9 +525,22 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> check_effect_color(id, effect, params)?; check_effect_channel(id, effect, params)?; check_effect_center(id, effect, params)?; + check_effect_halftone_style(id, effect, params)?; check_effect_pathfinder(id, effect, params) } +/// The `style` in `params` of Vector Halftone (`effect`), as command `id` was given it: a parameter +/// error unless it names Custom or one of the named styles, in any letter case. `effect.apply` and +/// `effect.setParams` run this themselves before they edit, as they run [`check_effect_channel`]. +pub(crate) fn check_effect_halftone_style(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects::addons::halftone::{HALFTONE, style}; + let Some(v) = params.get("style") else { return Ok(()) }; + if effect != HALFTONE || v.as_str().and_then(style).is_some() { + return Ok(()); + } + Err(bad(id, "`style` must be one of custom, grid, gridAngle, gridDots, gridDotsAngle")) +} + /// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given /// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and /// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index ba2b523f62..949b470263 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -841,6 +841,15 @@ fn place(s: &mut Session, p: &Value) -> Result { Some(read) => read, None => prepare(s, p)?.read()?, }; + let image = match read.loaded.art { + Art::Image(..) => read.loaded.link.is_some(), + Art::Dcs(_) => true, + _ => false, + }; + if s.image_only.get().is_some() && !image { + s.image_only.set(Some(false)); + return Err(bad(PLACE, "the file is not an image")); + } apply(s, read) } diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index 16684a3284..6b447fca7c 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -15,6 +15,16 @@ const MAX_CELLS: usize = 10_000; /// The most objects the copies may hold in all, counting every object inside each copy. const MAX_COPIED_OBJECTS: usize = 250_000; const EPS: f64 = 1e-9; +/// How far past a whole point a place may be and still count as on it, in points. +const GRID_EPS: f64 = 1e-6; + +/// Whether `n` or an object in it, the art of linked opacity masks included, is pixel-aligned: the +/// objects that the snap after a transform moves. +fn holds_pixel_aligned(n: &Node) -> bool { + n.extras().pixel_aligned + || n.children().is_some_and(|cs| cs.iter().any(|c| holds_pixel_aligned(c))) + || n.extras().mask.as_ref().is_some_and(|m| m.linked && holds_pixel_aligned(&m.art)) +} pub fn specs() -> Vec { vec![cmd!( @@ -22,7 +32,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); when the selection holds a pixel-aligned object, every cell moves by whole points (the pitch is rounded up, with fill the first cell's place is rounded toward the sheet's inside and only cells that still fit are counted, and a turned cell turns about a center up to half a point right of and below its own, with extra pitch only between alternating columns or rows and fill reserving the turn offset on both axes only where turned cells fit), so the copies stay on the pixel grid and the objects in each copy keep their places against each other; otherwise gaps are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; a single cell that neither moves nor groups the artwork and leaves the selection unchanged adds no undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -166,8 +176,75 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { } else { None }; + // With a pixel-aligned object in the selection, every cell moves by whole points, so the snap + // leaves each copy as it moved it and the objects in a copy keep their places against each other. + // The pitch and the first cell's place are rounded up, so neighbors never come closer than asked + // and the first cell stays inside the sheet. + let aligned = roots.iter().filter_map(|r| d.node(*r)).any(holds_pixel_aligned); + let whole = |v: f64| if aligned { (v - GRID_EPS).ceil() } else { v }; + // A half turn about the center maps x to 2 × center − x. On the pixel grid, twice the center is + // rounded up to whole points, so a turned copy also moves its objects by whole points; it then + // sits up to a point right of and below its cell, and the pitch and the fill make room for that. + let c2 = b.center().to_vec2() * 2.0; + let turn = if aligned && alt != Alternate::None { + let mut rounded = Vec2::new(whole(c2.x), whole(c2.y)); + if rounded.x < c2.x - EPS { + rounded.x += 1.0; + } + if rounded.y < c2.y - EPS { + rounded.y += 1.0; + } + rounded - c2 + } else { + Vec2::ZERO + }; + let center = (c2 + turn) / 2.0; + let clearance = match alt { + Alternate::Columns => Vec2::new(turn.x, 0.0), + Alternate::Rows => Vec2::new(0.0, turn.y), + Alternate::None => Vec2::ZERO, + }; + let (gx, gy) = if aligned { + let pitch = |v: f64| { + let rounded = whole(v).max(1.0); + if rounded < v - EPS { rounded + 1.0 } else { rounded } + }; + (pitch(w + gx + clearance.x) - w, pitch(h + gy + clearance.y) - h) + } else { + (gx, gy) + }; + let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| { + let raw = Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0); + let mut origin = Vec2::new(whole(raw.x), whole(raw.y)); + if b.x0 + origin.x < sh.x0 + m - EPS { + origin.x += 1.0; + } + if b.y0 + origin.y < sh.y0 + m - EPS { + origin.y += 1.0; + } + origin + }); let (rows, cols) = match anchor { - Some((sh, m)) => fill_counts(sh.width(), sh.height(), m, w, h, gx, gy), + Some((sh, m)) => { + let lead = origin - Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0); + let (sw, sh) = (sh.width() - lead.x - 2.0 * m, sh.height() - lead.y - 2.0 * m); + let (rows, cols) = fill_counts(sw, sh, 0.0, w, h, gx, gy); + // Turned cells have odd indices; an unturned cell may follow the last one that fits. + let alternating_count = |room, size, gap, shift, count: usize| count.min((fit_count(room - shift, size, gap) / 2 * 2).saturating_add(1)); + match alt { + Alternate::Columns => { + let cols = alternating_count(sw, w, gx, turn.x, cols); + let turned_rows = fit_count(sh - turn.y, h, gy); + if cols > 1 && turned_rows > 0 { (rows.min(turned_rows), cols) } else { (rows, cols.min(1)) } + } + Alternate::Rows => { + let rows = alternating_count(sh, h, gy, turn.y, rows); + let turned_cols = fit_count(sw - turn.x, w, gx); + if rows > 1 && turned_cols > 0 { (rows, cols.min(turned_cols)) } else { (rows.min(1), cols) } + } + Alternate::None => (rows, cols), + } + } None => (rows, cols), }; if rows == 0 || cols == 0 { @@ -182,14 +259,20 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS { return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects"))); } - let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; + if rows == 1 && cols == 1 && origin == Vec2::ZERO && roots.len() == 1 { + let selection = &s.doc()?.selection; + let mut next_selection = selection.clone(); + next_selection.set([roots[0]]); + if next_selection == *selection { + return Ok(json!({ "ids": [roots[0].0], "rows": 1, "columns": 1, "count": 1 })); + } + } let cells = layout(w, h, gx, gy, rows, cols, alt); - let center = b.center().to_vec2(); let place = |c: &Cell| -> Affine { let t = Affine::translate(origin + Vec2::new(c.dx, c.dy)); if c.turned { t * Affine::translate(center) * rotate_deg(180.0) * Affine::translate(-center) } else { t } }; - let sc = Scaling { patterns: super::object::transform_patterns(s, p, &roots)?, ..Scaling::default() }; let ids = s.edit("Step and Repeat", |d, sel| { if roots.len() > 1 { roots = vec![group_nodes(d, &roots)?]; diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 133d79ff48..6114943a36 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -60,6 +60,158 @@ fn creates_the_grid_in_one_undo_step_and_undoes_cleanly() { assert!(ids[1..].iter().all(|i| d.node(NodeId(*i)).is_none())); } +#[test] +fn a_single_unchanged_cell_keeps_undo_and_redo() { + for fill in [false, true] { + let (mut s, id) = setup(); + let copies = s.execute(CMD, &json!({"columns": 2})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let steps = undo_steps(&s); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": {"x": 0, "y": 0, "width": 50, "height": 30}})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps); + assert_eq!(s.doc().unwrap().history.redo.len(), redo); + s.execute("edit.redo", &json!({})).unwrap(); + let copy = copies["ids"][1].as_u64().unwrap(); + assert_eq!(bounds(&s, copy), (50.0, 0.0, 100.0, 30.0)); + } +} + +#[test] +fn a_single_unchanged_cell_clears_the_layer_target_in_one_undo_step() { + for fill in [false, true] { + let (mut s, id) = setup(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert_eq!(before.objects, [NodeId(id)]); + assert_eq!(before.target, Some(layer)); + let steps = undo_steps(&s); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + let mut expected = before.clone(); + expected.set([NodeId(id)]); + assert_eq!(s.doc().unwrap().selection, expected); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, expected); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_unchanged_cell_records_the_resolved_patterns_setting() { + for fill in [false, true] { + for patterns in [false, true] { + let (mut s, id) = setup(); + s.execute("object.pattern.make", &json!({"name": "Dots", "width": 50, "height": 30})).unwrap(); + s.execute("object.pattern.done", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "swatch": "Dots"})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.prefs.transform_pattern_tiles = patterns; + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + for explicit in [false, true] { + let mut params = json!({"fill": fill, "sheet": sheet}); + let expected = if explicit { !patterns } else { patterns }; + if explicit { + params["patterns"] = json!(expected); + } + let start = s.journal.len(); + let steps = undo_steps(&s); + let r = s.execute(CMD, ¶ms).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + params["patterns"] = json!(expected); + assert_eq!(s.journal_for_action(start), [(CMD.to_string(), params)]); + assert_eq!(undo_steps(&s), steps); + } + } + } +} + +#[test] +fn a_single_unchanged_cell_selects_the_compound_in_one_undo_step() { + for fill in [false, true] { + let (mut s, member) = setup(); + let inner_params = json!({"x": 10, "y": 5, "width": 20, "height": 10}); + let inner = s.execute("shape.rectangle", &inner_params).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [member, inner]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let before = bounds(&s, compound); + s.execute(CMD, &json!({"columns": 2})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.select(|_, sel| sel.set([NodeId(member)])).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]); + let steps = undo_steps(&s); + let redo = s.doc().unwrap().history.redo.len(); + assert!(redo > 0); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [compound], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps + 1); + assert!(s.doc().unwrap().history.redo.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(member)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [NodeId(compound)]); + assert_eq!(bounds(&s, compound), before); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_unchanged_cell_selects_the_whole_path_in_one_undo_step() { + for fill in [false, true] { + let (mut s, id) = setup(); + let id = NodeId(id); + s.select(|_, sel| { + sel.set([id]); + sel.anchors.insert(id, [(0, 0), (0, 1)].into_iter().collect()); + }) + .unwrap(); + let before = s.doc().unwrap().selection.clone(); + let steps = undo_steps(&s); + let sheet = json!({"x": 0, "y": 0, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": fill, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id.0], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + assert!(s.doc().unwrap().selection.segments.is_empty()); + assert_eq!(bounds(&s, id.0), (0.0, 0.0, 50.0, 30.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection, before); + assert_eq!(undo_steps(&s), steps); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert!(s.doc().unwrap().selection.anchors.is_empty()); + assert_eq!(undo_steps(&s), steps + 1); + } +} + +#[test] +fn a_single_moved_cell_records_an_undo_step() { + let (mut s, id) = setup(); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "sheet": {"x": 5, "y": 5, "width": 50, "height": 30}})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + assert_eq!(bounds(&s, id), (5.0, 5.0, 55.0, 35.0)); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, id), (0.0, 0.0, 50.0, 30.0)); +} + #[test] fn fill_sheet_with_margin_moves_the_first_copy_to_the_corner() { let (mut s, _) = setup(); @@ -211,6 +363,285 @@ fn fractional_gaps_are_exact_except_for_pixel_aligned_objects_which_stay_on_the_ assert!((pitch - pitch.round()).abs() < 1e-9); } +#[test] +fn pixel_aligned_pitch_preserves_requested_gaps_near_whole_points() { + for gap in [0.0, 0.25, -0.25] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let params = json!({"x": 0, "y": 0, "width": 50.0000005 - gap, "height": 30.0000005 - gap}); + let cut = s.execute("shape.rectangle", ¶ms).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gap": gap, "cutId": cut})).unwrap(); + assert_eq!(r["count"], json!(4)); + let d = &s.doc().unwrap().doc; + let cut_bounds = |id: &Value| { + let group = d.node(NodeId(id.as_u64().unwrap())).unwrap(); + group.children().unwrap()[0].geometric_bounds().unwrap() + }; + let ids = r["ids"].as_array().unwrap(); + for row in 0..2 { + let left = cut_bounds(&ids[row * 2]); + let right = cut_bounds(&ids[row * 2 + 1]); + assert!(right.x0 - left.x1 >= gap - EPS, "the horizontal gap shrank: {left:?} {right:?}"); + let pitch = right.x0 - left.x0; + assert!((pitch - pitch.round()).abs() < EPS); + } + for col in 0..2 { + let top = cut_bounds(&ids[col]); + let bottom = cut_bounds(&ids[col + 2]); + assert!(bottom.y0 - top.y1 >= gap - EPS, "the vertical gap shrank: {top:?} {bottom:?}"); + let pitch = bottom.y0 - top.y0; + assert!((pitch - pitch.round()).abs() < EPS); + } + } +} + +#[test] +fn a_pixel_aligned_cut_keeps_its_place_against_its_artwork_in_every_copy() { + let (mut s, cut) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [cut], "on": true})).unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 48, "height": 28})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 3, "gapX": 0.6, "gapY": 1.3, "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let inset = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + (rects[1].x0 - rects[0].x0, rects[1].y0 - rects[0].y0) + }; + let ids = r["ids"].as_array().unwrap(); + let first = inset(&ids[0]); + for id in &ids[1..] { + let (x, y) = inset(id); + assert!((x - first.0).abs() < 1e-9 && (y - first.1).abs() < 1e-9, "the artwork moved against the cut: {:?} against {first:?}", (x, y)); + } +} + +#[test] +fn pixel_aligned_art_stays_registered_in_turned_cells_and_gaps_never_shrink() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"columns": 3, "gapX": 0.1, "rotate": "columns", "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let rects = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + (rects[0], rects[1]) + }; + let ids = r["ids"].as_array().unwrap(); + let (c0, a0) = rects(&ids[0]); + let (c1, a1) = rects(&ids[1]); + let (c2, a2) = rects(&ids[2]); + // The turned cell mirrors the art inside its cut; the next unturned cell repeats it. + assert!(((c1.x1 - a1.x1) - (a0.x0 - c0.x0)).abs() < 1e-9, "turned art moved against its cut: {c1:?} {a1:?}"); + assert!(((a2.x0 - c2.x0) - (a0.x0 - c0.x0)).abs() < 1e-9); + assert!(c2.x0 - c0.x0 > 2.0 * (50.25 + 0.1) - 1e-9, "the pitch was rounded down: {c2:?}"); + assert!(c1.x0 - c0.x1 >= 0.1 - 1e-9 && c2.x0 - c1.x1 >= 0.1 - 1e-9, "a gap next to the turned cell shrank: {c0:?} {c1:?} {c2:?}"); +} + +#[test] +fn turned_pixel_aligned_cells_stay_on_the_sheet() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 101, "height": 30.75}); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!(r["columns"], json!(1)); + assert_eq!(r["count"], json!(1)); + assert_eq!(undo_steps(&s), steps + 1); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(group).unwrap().kind, vectorcraft_doc::NodeKind::Group { .. })); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 102, "height": 31.75}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!(r["columns"], json!(2)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= 102.0 + 1e-9 && b.y1 <= 31.75 + 1e-9, "a cell runs past the sheet: {b:?}"); + } +} + +#[test] +fn fill_keeps_rounded_turn_offsets_inside_the_sheet_near_whole_points() { + for (height, columns) in [(30.0000005, 1), (31.0000005, 2)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.0000005})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": 100, "height": height}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": "columns", "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(columns), json!(columns))); + for id in r["ids"].as_array().unwrap() { + let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap()); + assert!(x0 >= -1e-9 && y0 >= -1e-9 && x1 <= 100.0 + 1e-9 && y1 <= height + 1e-9, "a cell runs past the sheet"); + } + } +} + +#[test] +fn fill_accepts_exact_fit_when_the_doubled_turn_center_has_roundoff() { + for (rotate, x, y, width, height, sw, sh, rows, columns) in + [("columns", 0.0, 0.1, 50.0, 29.8, 100.0, 29.8, 1, 2), ("rows", 0.1, 0.0, 29.8, 50.0, 29.8, 100.0, 2, 1)] + { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let params = json!({"x": x, "y": y, "width": width, "height": height}); + let cut = s.execute("shape.rectangle", ¶ms).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let b = s.doc().unwrap().doc.node(NodeId(cut)).unwrap().geometric_bounds().unwrap(); + let c2 = if rotate == "columns" { b.center().y * 2.0 } else { b.center().x * 2.0 }; + assert!(c2 > c2.round() && c2 - c2.round() < EPS); + let sheet = json!({"x": x, "y": y, "width": sw, "height": sh}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(rows), json!(columns), json!(2))); + for id in r["ids"].as_array().unwrap() { + let (x0, y0, x1, y1) = bounds(&s, id.as_u64().unwrap()); + assert!(x0 >= x - EPS && y0 >= y - EPS && x1 <= x + sw + EPS && y1 <= y + sh + EPS, "a cell runs past the sheet"); + } + } +} + +#[test] +fn fill_reserves_turn_clearance_only_for_turned_cells() { + for (rotate, width, height, rows, columns) in [ + ("columns", 101.25, 31.0, 1, 1), + ("columns", 102.0, 31.0, 1, 2), + ("columns", 152.25, 31.0, 1, 3), + ("columns", 152.25, 30.75, 1, 1), + ("rows", 51.0, 61.75, 1, 1), + ("rows", 51.0, 62.0, 2, 1), + ("rows", 51.0, 92.75, 3, 1), + ("rows", 50.25, 92.75, 1, 1), + ] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50.25, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": 0, "y": 0, "width": width, "height": height}); + let r = s.execute(CMD, &json!({"fill": true, "rotate": rotate, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone()), (json!(rows), json!(columns)), "{rotate} on {width} by {height}"); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x0 >= -1e-9 && b.y0 >= -1e-9 && b.x1 <= width + 1e-9 && b.y1 <= height + 1e-9, "a cell runs past the sheet: {b:?}"); + } + } +} + +#[test] +fn turned_columns_keep_the_vertical_pitch_without_turn_clearance() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 30.75})).unwrap()["id"].as_u64().unwrap(); + let art = s.execute("shape.rectangle", &json!({"x": 10, "y": 5, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let r = s.execute(CMD, &json!({"rows": 2, "columns": 2, "gapY": 0.2, "rotate": "columns", "cutId": cut})).unwrap(); + let d = &s.doc().unwrap().doc; + let cut_bounds = |id: &Value| { + let mut rects = vec![]; + d.node(NodeId(id.as_u64().unwrap())).unwrap().walk(&mut |c| { + if matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. }) { + rects.push(c.geometric_bounds().unwrap()); + } + }); + rects[0] + }; + let ids = r["ids"].as_array().unwrap(); + for col in 0..2 { + let first = cut_bounds(&ids[col]); + let second = cut_bounds(&ids[col + 2]); + assert!((second.y0 - first.y0 - 31.0).abs() < 1e-9, "the vertical pitch includes turn clearance: {first:?} {second:?}"); + assert!(second.y0 - first.y1 >= 0.2 - 1e-9, "the vertical gap shrank: {first:?} {second:?}"); + } +} + +#[test] +fn fill_counts_only_the_pixel_aligned_copies_that_stay_on_the_sheet() { + let (mut s, id) = setup(); + // The 1 pt stroke puts the snapped rectangle at (0.5, 0.5), 50 by 30. + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + assert_eq!(bounds(&s, id), (0.5, 0.5, 50.5, 30.5)); + let steps = undo_steps(&s); + let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 100.6, "height": 30}})).unwrap(); + assert_eq!(r["columns"], json!(1)); + assert_eq!(undo_steps(&s), steps); + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let r = s.execute(CMD, &json!({"fill": true, "gapX": 0.6, "sheet": {"x": 0.5, "y": 0.5, "width": 101, "height": 30}})).unwrap(); + assert_eq!(r["columns"], json!(2)); + let d = &s.doc().unwrap().doc; + for id in r["ids"].as_array().unwrap() { + let b = d.node(NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + assert!(b.x1 <= 101.5 + 1e-9, "a copy runs past the sheet: {b:?}"); + } +} + +#[test] +fn fill_rounds_pixel_aligned_origins_inside_the_sheet_near_whole_points() { + for (dx, dy) in [(0.0000005, 0.0), (0.0, 0.0000005), (-0.9999995, -0.9999995)] { + let (mut s, id) = setup(); + s.execute("object.setPixelAligned", &json!({"ids": [id], "on": true})).unwrap(); + let (x, y, _, _) = bounds(&s, id); + let (sx, sy) = (x + dx, y + dy); + let steps = undo_steps(&s); + let tight = json!({"x": sx, "y": sy, "width": 50, "height": 30}); + assert!(s.execute(CMD, &json!({"fill": true, "sheet": tight})).is_err()); + assert_eq!(undo_steps(&s), steps); + let sheet = json!({"x": sx, "y": sy, "width": 51, "height": 31}); + let r = s.execute(CMD, &json!({"fill": true, "sheet": sheet})).unwrap(); + assert_eq!(r, json!({"ids": [id], "rows": 1, "columns": 1, "count": 1})); + let (x0, y0, x1, y1) = bounds(&s, id); + assert!(x0 >= sx && y0 >= sy && x1 <= sx + 51.0 && y1 <= sy + 31.0); + } +} + +#[test] +fn fill_accepts_exact_fit_when_the_origin_subtraction_has_roundoff() { + for (x, y, sx, sy) in [(1.2, 0.0, 2.2, 0.0), (0.0, 1.2, 0.0, 2.2), (1.2, 1.2, 2.2, 2.2)] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 210, "height": 297})).unwrap(); + let cut_params = json!({"x": x, "y": y, "width": 50, "height": 30}); + let cut = s.execute("shape.rectangle", &cut_params).unwrap()["id"].as_u64().unwrap(); + let art_params = json!({"x": 10, "y": 5, "width": 20, "height": 20}); + let art = s.execute("shape.rectangle", &art_params).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [art], "on": true})).unwrap(); + s.execute("select.set", &json!({"ids": [cut, art]})).unwrap(); + let sheet = json!({"x": sx, "y": sy, "width": 50, "height": 30}); + let r = s.execute(CMD, &json!({"fill": true, "cutId": cut, "sheet": sheet})).unwrap(); + assert_eq!((r["rows"].clone(), r["columns"].clone(), r["count"].clone()), (json!(1), json!(1), json!(1))); + let (x0, y0, x1, y1) = bounds(&s, cut); + assert!((x0 - sx).abs() < EPS && (y0 - sy).abs() < EPS); + assert!((x1 - (sx + 50.0)).abs() < EPS && (y1 - (sy + 30.0)).abs() < EPS); + } +} + #[test] fn fill_picks_the_artboard_of_the_selection_not_of_the_cut_contour() { let first_x = |sheet: Option| { diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 1a79fbfbc9..1d15de3a3b 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -509,6 +509,17 @@ impl<'a> ThreadIndex<'a> { pub(crate) fn threaded(&self, id: NodeId) -> bool { self.first.get(&id).and_then(|i| self.live.get(*i)).is_some_and(|n| *n >= 2) && text_of(self.doc, id).is_some() } + + /// The index in the document's threads of the first thread that lists `id`. + pub(crate) fn first_thread_index(&self, id: NodeId) -> Option { + self.first.get(&id).copied() + } + + /// [`story_of`] for `id`, its thread found through the index. + pub(crate) fn story(&self, id: NodeId) -> Vec { + let Some(thread) = self.first.get(&id).and_then(|i| self.doc.text_threads.get(*i)) else { return vec![] }; + story_in(self.doc, thread, id) + } } /// `ids` followed by the other frames of the threads they are in, each once, in thread order. diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index afc8c52e73..7f817726cc 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -1606,4 +1606,31 @@ mod tests { assert_eq!(roots.check(&s(base.join("out/x.svg")), Access::Write), Ok(())); let _ = std::fs::remove_dir_all(base); } + + /// A checked write to a real path passes a script gate only inside the gate's write folder, and + /// only when every gate chained to it passes the path too. + #[cfg(unix)] + #[test] + fn a_checked_write_to_a_real_path_passes_every_chained_gate() { + let (base, _) = folders("check-real"); + let base = std::fs::canonicalize(&base).unwrap(); + let gate = |dir: &str| ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&base.join(dir)), + documents: vec![], + held: vec![], + linked: LinkedFiles::default(), + also: None, + }; + let (inside, outside) = (base.join("out/new.svg"), base.join("outside/new.svg")); + let denied = |p: &Path| Err(format!("Script file access denied: {}", p.display())); + assert_eq!(gate("out").check_real(&inside, Access::Write), Ok(())); + assert_eq!(gate("out").check_real(&outside, Access::Write), denied(&outside)); + assert_eq!(with_script_gate(gate("out"), || check_write_real(&inside)), Ok(()), "the running command's gate passes it"); + assert_eq!(with_script_gate(gate("out"), || check_write_real(&outside)), denied(&outside), "the running command's gate refuses it"); + let chained = gate("out").followed_by(Arc::new(gate("outside"))); + assert_eq!(chained.check_real(&inside, Access::Write), denied(&inside), "the chained gate refuses it"); + assert_eq!(chained.check_real(&outside, Access::Write), denied(&outside), "the first gate refuses it"); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6036a03276..16e1e7f5a5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -328,6 +328,10 @@ pub struct Session { /// While [`Session::place_read`] runs `file.place`: the file read for it, which the command /// places instead of reading the file; `None` otherwise. pub(crate) place_hand_off: Option, + /// While a script places or relinks a file as an image: `Some(true)`, and `file.place` or + /// `links.relink` refuses a file that holds no image before the document changes, setting it to + /// `Some(false)`; `None` otherwise. + pub(crate) image_only: std::cell::Cell>, /// While [`Session::place_queue_read`] runs `file.place.queue`: the files read for it, which /// the command loads the place cursor with instead of reading them; `None` otherwise. pub(crate) queue_hand_off: Option, diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 7a60028afc..4a85763667 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -86,8 +86,9 @@ struct Pending { to: Vec<(Recipient, Vec<&'static str>)>, /// When it was queued ([`PluginEvents::queued`] then). seq: u64, - /// The event this enqueue pushed out of the waiting queue. - displaced: Option, + /// The [`Pending::seq`] of the event that pushed this one out of the waiting queue, and whether + /// that event was a `document.opened`. + pushed_out_by: Option<(u64, bool)>, /// Queued by a command of the running script, whose run has not ended yet /// ([`Session::plugin_events_script_ended`]). by_script: bool, @@ -162,6 +163,8 @@ pub struct PluginEvents { /// The events dropped from `pending` since the last delivery, oldest first, which /// [`Session::forget_plugin_opens_since`] puts back when a rollback frees room. evicted: VecDeque, + /// The [`Pending::seq`] of each `document.opened` the running script's commands queued. + script_opens: HashSet, /// How many events have been queued as their own entry. queued: u64, dispatching: bool, @@ -223,11 +226,10 @@ impl PluginEvents { } return; } - let mut displaced = None; if self.pending.len() >= MAX_PENDING - && let Some(dropped) = self.pending.pop_front() + && let Some(mut dropped) = self.pending.pop_front() { - displaced = Some(dropped.seq); + dropped.pushed_out_by = Some((self.queued, event == Event::DocumentOpened)); log::warn!("plug-in events: dropped a waiting {} event, past {MAX_PENDING} waiting", dropped.event.name()); // Kept until the next delivery, in case a rollback frees room for it again. // When that store is full, an open goes first, since only opens are rolled back. @@ -238,8 +240,37 @@ impl PluginEvents { self.evicted.push_back(dropped); } let to = to.into_iter().map(|r| (r, reasons.clone())).collect(); - self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, displaced, by_script: false }); + self.pending.push_back(Pending { event, document: uid, to, seq: self.queued, pushed_out_by: None, by_script: false }); self.queued += 1; + self.prune_script_opens(); + } + + /// Drops the `document.opened` events, waiting or pushed out, whose [`Pending::seq`] `undone` + /// picks. The events those opens pushed out of the waiting queue return in their original + /// order, ahead of the events still waiting, while there is room. + fn drop_opens(&mut self, undone: impl Fn(u64) -> bool) { + let dropped = |p: &Pending| p.event == Event::DocumentOpened && undone(p.seq); + self.pending.retain(|p| !dropped(p)); + self.evicted.retain(|p| !dropped(p)); + let first = self.evicted.iter().filter(|p| p.pushed_out_by.is_some_and(|(seq, open)| open && undone(seq))).map(|p| p.seq).min(); + while self.pending.len() < MAX_PENDING + && let Some(at) = self.evicted.iter().rposition(|p| first.is_some_and(|seq| p.seq >= seq)) + && let Some(mut p) = self.evicted.remove(at) + { + p.pushed_out_by = None; + self.pending.push_front(p); + } + self.prune_script_opens(); + } + + /// Forgets the running script's opens that no waiting or pushed-out event refers to. + fn prune_script_opens(&mut self) { + if self.script_opens.is_empty() { + return; + } + let referenced: HashSet = + self.pending.iter().chain(self.evicted.iter()).flat_map(|p| std::iter::once(p.seq).chain(p.pushed_out_by.map(|(seq, _)| seq))).collect(); + self.script_opens.retain(|seq| referenced.contains(seq)); } fn notice(&mut self, n: Notice) { @@ -362,6 +393,9 @@ impl Session { && let Some(p) = self.plugin_events.pending.back_mut() { p.by_script = true; + if event == Event::DocumentOpened { + self.plugin_events.script_opens.insert(p.seq); + } } } @@ -370,12 +404,13 @@ impl Session { /// failed (`kept` false), drops the waiting `document.opened` events its commands queued, since /// the documents they opened were discarded with its working copy. Its saves stay, since the /// files they wrote stay written, and so do the events of documents a frontend opened while the - /// run was paused. The next delivery gives what is left in the order it was queued. + /// run was paused. Events those opens pushed out of the waiting queue come back, as after + /// [`Session::forget_plugin_opens_since`]. The next delivery gives what is left in the order it was queued. pub(crate) fn plugin_events_script_ended(&mut self, kept: bool) { let events = &mut self.plugin_events; + let opens = std::mem::take(&mut events.script_opens); if !kept { - events.pending.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); - events.evicted.retain(|p| !(p.by_script && p.event == Event::DocumentOpened)); + events.drop_opens(|seq| opens.contains(&seq)); } for p in events.pending.iter_mut().chain(events.evicted.iter_mut()) { p.by_script = false; @@ -389,21 +424,9 @@ impl Session { /// Drops the waiting `document.opened` events queued since `mark`, for opens that a rollback /// undid (a failed `command.batch`, or a failed command of a script or a plug-in call). The - /// saves stay, since the files they wrote stay written. - /// Events displaced by those opens return in their original order, ahead of the events still - /// waiting, while there is room. + /// saves stay, since the files they wrote stay written ([`PluginEvents::drop_opens`]). pub(crate) fn forget_plugin_opens_since(&mut self, mark: u64) { - let events = &mut self.plugin_events; - let undone = |p: &Pending| p.event == Event::DocumentOpened && p.seq >= mark; - let displaced: Vec<_> = events.pending.iter().chain(&events.evicted).filter(|p| undone(p)).filter_map(|p| p.displaced).collect(); - events.pending.retain(|p| !undone(p)); - events.evicted.retain(|p| !undone(p)); - while events.pending.len() < MAX_PENDING - && let Some(at) = events.evicted.iter().rposition(|p| displaced.contains(&p.seq)) - && let Some(p) = events.evicted.remove(at) - { - events.pending.push_front(p); - } + self.plugin_events.drop_opens(|seq| seq >= mark); } /// Compares each open document with how the last check saw it and queues the events its changes @@ -489,7 +512,19 @@ impl Session { } let subs: HashMap> = self.plugin_events.subscribers().into_iter().map(|p| (recipient(&p), p)).collect(); self.plugin_events.dispatching = true; - self.plugin_events.evicted.clear(); + // Events pushed out by the opens of a running script stay until its run ends, which puts + // them back if the run fails. + let events = &mut self.plugin_events; + let opens = &events.script_opens; + let restorable = |p: &Pending| p.pushed_out_by.is_some_and(|(seq, open)| open && opens.contains(&seq)); + let first = events.evicted.iter().filter(|p| restorable(p)).map(|p| p.seq).min(); + events.evicted.retain(|p| { + restorable(p) + || (first.is_some_and(|seq| p.seq >= seq) + && (!p.by_script || p.event != Event::DocumentOpened || p.to.iter().any(|(r, _)| subs.contains_key(r)))) + }); + let frontend_barrier = events.evicted.iter().filter(|p| !p.by_script).map(|p| p.seq).min(); + events.prune_script_opens(); // A handler's calls are checked as calls from outside, also when the command that ended // played saved steps ([`Session::replay`] puts its flag back only after this delivery). let replaying = self.set_replaying(false); @@ -512,6 +547,11 @@ impl Session { if !p.event.outlives_document() && !self.docs.iter().any(|d| d.uid == p.document) { continue; } + p.to.retain(|(r, _)| subs.get(r).is_some_and(|plugin| plugin.manifest().reacts_to(p.event))); + if !p.to.is_empty() && frontend_barrier.is_some_and(|seq| p.seq > seq) { + held.push_back(p); + continue; + } let mut served = 0; for (i, (r, reasons)) in p.to.iter().enumerate() { let Some(plugin) = subs.get(r).filter(|s| s.manifest().reacts_to(p.event)) else { @@ -547,8 +587,10 @@ impl Session { self.depth = depth; self.set_replaying(replaying); self.plugin_events.dispatching = false; + self.plugin_events.prune_script_opens(); self.plugin_events.pending.iter().any(|p| { !p.by_script + && frontend_barrier.is_none_or(|seq| p.seq < seq) && (p.event.outlives_document() || self.docs.iter().any(|d| d.uid == p.document)) && p.to.iter().any(|(r, _)| subs.get(r).is_some_and(|plugin| !self.plugin_event_status(plugin).0)) }) @@ -854,6 +896,121 @@ mod tests { ); } + #[test] + fn a_failed_script_run_brings_back_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + // Enough opens to fill the store of pushed-out events, which then drops opens first. + for uid in 0..(MAX_PENDING + MAX_EVICTED + 8) as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + assert_eq!(s.plugin_events.evicted.len(), MAX_EVICTED); + assert_eq!(s.plugin_events.pending.len(), MAX_PENDING); + assert!(s.plugin_events.pending.iter().all(|p| p.event == Event::DocumentOpened), "the saves were pushed out"); + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + #[test] + fn a_failed_script_keeps_the_newest_saves_when_its_open_displaced_a_save() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=MAX_PENDING as u64 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + queue_script_open(&mut s, 100, &r); + s.plugin_events.queue(Event::DocumentSaved, MAX_PENDING as u64 + 1, vec![], vec![r]); + s.plugin_events.pending.back_mut().unwrap().by_script = true; + s.plugin_events_script_ended(false); + let saves: Vec<_> = s.plugin_events.pending.iter().map(|p| (p.event, p.document)).collect(); + let expected: Vec<_> = (2..=MAX_PENDING as u64 + 1).map(|uid| (Event::DocumentSaved, uid)).collect(); + assert_eq!(saves, expected); + } + + #[test] + fn a_frontend_save_waits_for_its_restorable_open_between_script_slices() { + use vectorcraft_plugins::wat as tpl; + + let mut s = Session::new(); + let manifest = concat!( + r#"{"id":"test.events.frontend_order","name":"Test","kind":"filter","api":2,"permissions":["progress","events"],"#, + r#""events":["document.opened","document.saved"]}"# + ); + let wasm = wat::parse_str(tpl::reacting(manifest, tpl::HOST_IMPORTS, tpl::LOG_EVENT)).unwrap(); + let plugin = Arc::new(Plugin::load(&wasm, vectorcraft_plugins::Limits::default()).unwrap()); + let r = recipient(&plugin); + s.plugin_events.test_subscribers = Some(vec![plugin]); + s.plugin_events.queue(Event::DocumentOpened, 1, vec![], vec![r.clone()]); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + s.plugin_events.queue(Event::DocumentSaved, 1, vec![], vec![r]); + assert!(!s.deliver_plugin_events(), "the blocked save must not request another frame"); + assert!(s.take_plugin_event_notices().is_empty(), "the save must wait for the earlier frontend open"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + s.deliver_plugin_events(); + let given: Vec = s.take_plugin_event_notices().iter().map(|n| serde_json::from_str(&n.text).unwrap()).collect(); + let events: Vec<_> = given.iter().map(|event| (event["type"].as_str().unwrap(), event["document"].as_u64().unwrap())).collect(); + assert_eq!(events, [("document.opened", 1), ("document.saved", 1)]); + } + + #[test] + fn script_open_tracking_is_bounded_after_batch_rollbacks_and_queue_overflow() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 0..2 * MAX_PENDING as u64 { + let mark = s.plugin_events_mark(); + queue_script_open(&mut s, uid, &r); + s.forget_plugin_opens_since(mark); + assert!(s.plugin_events.script_opens.is_empty(), "a rolled-back open has no remaining references"); + } + for uid in 0..2 * (MAX_PENDING + MAX_EVICTED) as u64 { + queue_script_open(&mut s, uid, &r); + let events = &s.plugin_events; + assert!(events.script_opens.len() <= 2 * (events.pending.len() + events.evicted.len())); + } + s.plugin_events_script_ended(false); + assert!(s.plugin_events.pending.is_empty()); + assert!(s.plugin_events.evicted.is_empty()); + assert!(s.plugin_events.script_opens.is_empty()); + } + + #[test] + fn a_delivery_between_script_slices_keeps_the_events_its_opens_pushed_out() { + let mut s = Session::new(); + let r: Recipient = ("a".into(), "h".into(), 1); + for uid in 1..=3 { + s.plugin_events.queue(Event::DocumentSaved, uid, vec![], vec![r.clone()]); + } + let before = s.plugin_events.pending.clone(); + s.script_in_run = true; + for uid in 0..MAX_PENDING as u64 { + queue_script_open(&mut s, 100 + uid, &r); + } + // A save a frontend queued while the run is paused pushes out the first open. + s.plugin_events.queue(Event::DocumentSaved, 50, vec![], vec![r]); + s.deliver_plugin_events(); + assert_eq!(s.plugin_events.evicted.len(), 3, "kept while the run goes on"); + s.script_in_run = false; + s.plugin_events_script_ended(false); + assert_eq!(s.plugin_events.pending, before); + } + + /// Queues a `document.opened` as a command of a running script does. + fn queue_script_open(s: &mut Session, uid: u64, r: &Recipient) { + s.plugin_events.queue(Event::DocumentOpened, uid, vec![], vec![r.clone()]); + if let Some(p) = s.plugin_events.pending.back_mut() { + p.by_script = true; + s.plugin_events.script_opens.insert(p.seq); + } + } + #[test] fn a_rollback_of_an_open_that_displaced_nothing_does_not_restore_an_earlier_save() { let mut s = Session::new(); diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 8728bd76fb..0356db27d1 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -254,7 +254,7 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. // A document whose active artboard the script chose uses that choice, not the one the run - // started with. + // started with, nor the Artboard tool's selection from the start of the run. let chosen = h.session.borrow().active().and_then(|st| { h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; Some((st.uid, super::dom::active_artboard(st))) @@ -263,7 +263,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { Some(chosen) => std::slice::from_ref(chosen), None => h.active_artboards.as_slice(), }; - let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !chosen.as_ref().is_some_and(|(c, _)| c == uid)); + let start = Start { active, picks, batch: s.artboard }; let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 28b215315c..edd447afa3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -125,6 +125,7 @@ pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; /// What [`after_command`] compares with, taken before each command a script runs /// ([`variables::before_command`]). pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + tracing::before_command(h); variables::before_command(h, id) } @@ -427,7 +428,7 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { /// Notes the changes a command made to the points of the paths the run has read /// ([`paths::see_all_points`]). -pub(super) fn see_points(h: &Host) { +pub(super) fn see_points(h: &Host) -> std::result::Result<(), HostError> { paths::see_all_points(h) } @@ -1070,7 +1071,7 @@ fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Res /// is made active, so bounds it reads take in type that the switch measured again (in the /// document's own composite fonts, [`Session::set_active`]). fn edit_item_with(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { - paths::see_all_points(h); + paths::see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f)); h.dom.editing.set(kept); diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index ec2c7997cf..60f322e79f 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -302,8 +302,8 @@ fn may_read(h: &Host, path: &str) -> bool { /// The real path of the `File` `d` gives as an image to place or relink: one the script may read /// ([`super::super::files::Disk::open_target`], as `app.open` reads its file), a regular file of -/// at most [`MAX_PLACED_BYTES`] that holds an image. Its size is read before any of it is, and no -/// error names the path. +/// at most [`MAX_PLACED_BYTES`]. Its size is read before any of it is, and no error names the path. +/// What the file holds is checked by the command that places or relinks it, which reads it once. fn image_path(h: &Host, d: &Data, what: &str) -> Result { let path = file_ref_path(d).ok_or_else(|| HostError::Type(format!("{what} must be a File")))?; if path.len() > super::super::files::MAX_PATH_CHARS { @@ -321,13 +321,21 @@ fn image_path(h: &Host, d: &Data, what: &str) -> Result { if meta.len() > MAX_PLACED_BYTES { return Err(HostError::Range(format!("{what} is larger than {} MiB", MAX_PLACED_BYTES >> 20))); } - let path = crate::cmd::findfiles::plain(real).to_string_lossy().into_owned(); - // What the file holds, read the way `file.place` reads it, before the document changes. - let info = command(h, "file.place.info", &json!({"path": path, "link": true}))?; - if field(&info, "pixelWidth").is_none() { - return Err(HostError::Error(NOT_AN_IMAGE.into())); + Ok(crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()) +} + +/// Runs `f`, which places or relinks a file `image_path` gave, with `file.place` and `links.relink` +/// refusing a file that holds no image before the document changes: that refusal is +/// [`NOT_AN_IMAGE`], which does not name the path. The command reads the file once, for its check +/// and for the image it places. +fn image_only(h: &Host, f: impl FnOnce(&Host) -> Result) -> Result { + let kept = h.session.borrow().image_only.replace(Some(true)); + let r = f(h); + let refused = h.session.borrow().image_only.replace(kept) == Some(false); + match r { + Err(HostError::Error(_)) if refused => Err(HostError::Error(NOT_AN_IMAGE.into())), + r => r, } - Ok(path) } // ---- PlacedItem ---- @@ -397,7 +405,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { // The placement and its check run under one savepoint, so an error after the place leaves // no linked image behind. let id = super::atomically(h, |h| { - let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let (_, placed) = image_only(h, |h| on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true}))))?; let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); let linked = @@ -414,7 +422,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { fn placed_relink(h: &Host, a: &[Data]) -> Answer { let item = this_of(h, a, "PlacedItem")?; let path = image_path(h, arg(a, 1), "relink's file")?; - edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path}))?; + image_only(h, |h| edit_item(h, item, "links.relink", &json!({"ids": [item.id.0], "path": path})))?; Ok(Data::Undefined) } @@ -473,7 +481,8 @@ fn area_of(m: Affine) -> bool { /// `matrix = Matrix`: `object.transform` of the image by what takes its pixels to the new matrix. /// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted -/// image is refused before anything changes; the matrix the image has already changes nothing. +/// image is refused before anything changes, and so is a locked or hidden image or one on a locked +/// artboard, as the transform methods refuse them; the matrix the image has already changes nothing. fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { let item = this_of(h, a, cls)?; let m = matrix_value(arg(a, 1))?; @@ -484,6 +493,22 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer { if n.is_distorted_image() { return Err(HostError::Error(DISTORTED.into())); } + // The transform methods' refusals: a locked or hidden image, one inside a locked or hidden + // layer or group, and one on a locked artboard, whether or not the matrix changes. + let d = &st.doc; + let line = d.ancestry(item.id); + let any = |f: fn(&vectorcraft_doc::Node) -> bool| { + line.as_ref().is_none_or(|l| l.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(f))) + }; + if any(|n| n.locked) { + return Err(HostError::Error(format!("{}: {}", super::transform::LOCKED, item.id.0))); + } + if any(|n| !n.visible) { + return Err(HostError::Error(format!("{}: {}", super::transform::HIDDEN, item.id.0))); + } + if super::on_locked_artboard(h, st, item.id) { + return Err(HostError::Error(format!("{}: {}", super::transform::ON_LOCKED_ARTBOARD, item.id.0))); + } let f = frame(st)?; let target = Affine::new(match h.dom.coords.get() { Coords::Document => [m[0], -m[1], m[2], -m[3], m[4] + f.left0, f.bottom0 - m[5]], diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 694140656e..59c4ea8ccf 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -309,7 +309,14 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer { fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; - Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) + let selected = with_doc(h, doc, |_, st| { + // The scan is charged by every selected object it looks at. + let objects = &st.selection.objects; + let found = objects.iter().position(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))); + h.charge_call(found.map_or(objects.len(), |i| i + 1) as u64)?; + Ok::<_, HostError>(found.is_some()) + })?; + Ok(Data::Bool(selected)) } /// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every @@ -336,7 +343,7 @@ fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec) -> u64 { fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "hasSelectedArtwork")?; let (doc, id) = this_layer(h, a)?; - let (ids, over) = with_doc(h, doc, |_, st| { + let (ids, over) = with_doc(h, doc, |s, st| { let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); let selected = &st.selection.objects; h.charge_call(selected.len() as u64)?; @@ -349,10 +356,31 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { // The walk is charged by every node it looks at, hidden and locked ones included, whether // or not anything is added. h.charge_call(count)?; + // While an object is isolated, the art that holds it is replaced by the isolated object, + // or by what an isolated group or other container holds, as Select All takes it. + let isolated = st.isolation.and_then(|i| st.doc.node(i)); + let path = isolated.and_then(|c| st.doc.ancestry(c.id)).unwrap_or_default(); + let editable = path.iter().all(|i| st.doc.node(*i).is_some_and(|n| n.visible && !n.locked && !n.is_template())); + let mut candidates = Vec::with_capacity(art.len()); + for o in art { + match isolated { + Some(_) if path.contains(&o) && !editable => {} + Some(c) if path.contains(&o) && c.is_container() => { + // The same walk as the layer's, through any sublayer the container holds. + let visited = collect_editable_art(c, &mut candidates); + h.charge_call(visited)?; + } + Some(c) if path.contains(&o) => candidates.push(c.id), + _ => candidates.push(o), + } + } let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); - for o in art { - if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + for o in candidates { + if have.contains(&o) + || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) + || (s.guides_locked() && crate::is_guide_path(&st.doc, o)) + { continue; } // Only art that would be added counts toward the limit. diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 752b8ea5b1..abccf28096 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -862,7 +862,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { if clipping { return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0))); } - see_all_points(h); + see_all_points(h)?; let kept = h.dom.editing.replace(Some(item)); let r = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; @@ -1236,6 +1236,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c Ok(((new_width - width).abs() > 1e-9).then_some(new_width)) } +/// The largest stroke weight in the path `item`'s own appearance, in points. +pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |_, n, _| { + n.appearance + .items + .iter() + .filter_map(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .fold(0.0, f64::max) + }) +} + /// Whether `item` is a path, so [`resized_stroke_weight`] applies to it. pub(super) fn is_path(h: &super::Host, item: Item) -> bool { with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) @@ -1377,24 +1391,32 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// the object model is changing ([`super::State`]), or that object itself, take the change as the /// object model's own, and their points stay valid; the other Global Edit members, which take the /// object model's edit too, are looked at as well. A document that is the one the run last looked -/// at is skipped, as are its paths. -pub(super) fn see_all_points(h: &super::Host) { - let keys: Vec<(u64, u64)> = { +/// at is skipped, as are its paths. The look is charged by the objects it looks at. +pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> { + let (keys, looked_at): (Vec<(u64, u64)>, u64) = { let s = h.session.borrow(); let mut docs = h.dom.point_docs.borrow_mut(); let seen = h.dom.point_nodes.borrow(); let mut keys = Vec::new(); + let mut looked_at = 0u64; docs.retain(|uid, before| { let state = s.documents().iter().find(|d| d.uid == *uid); let after = state.map(|st| &st.doc); if after.is_some_and(|after| Arc::ptr_eq(before, after)) { return true; } + // A document none of whose paths the run still holds points of is not looked at; reading + // points again keeps it as it is then. + if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) { + return false; + } // Editing a path in an Objects on Path group can move the other paths in the group, so // the outermost such group is looked at in place of the path. While Global Edit is on, // an edit of the selected member (also one made by moving a group that holds it) is // given to the other members, so each of them, or the outermost Objects on Path group // holding it, is looked at too. Subtrees the command left as they were are skipped. + // Each node is paired with the node of the same id under the same parent now, so that no + // node is searched for through the whole document. let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { Some(item) => { let root = |id: NodeId| { @@ -1405,19 +1427,44 @@ pub(super) fn see_all_points(h: &super::Host) { }; let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten(); let mut roots = std::collections::HashSet::new(); - std::iter::once(item.id).chain(members).map(root).filter(|id| roots.insert(*id)).filter_map(|id| node_arc(before, id)).collect() + std::iter::once(item.id) + .chain(members) + .map(root) + .filter(|id| roots.insert(*id)) + .filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id))))) + .collect() } - None => before.layers.iter().collect(), + None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at), }; - while let Some(node) = todo.pop() { - if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) { + // A group that moved to another parent keeps its node, so a node with children that is + // not found under its old parent is looked for among all the nodes now, listed once. + let mut all: Option>> = None; + while let Some((node, mut now)) = todo.pop() { + looked_at += 1; + if now.is_none() + && node.children().is_some() + && let Some(d) = after + { + let all = all.get_or_insert_with(|| { + let mut m = std::collections::HashMap::new(); + let mut stack: Vec<&Arc> = d.layers.iter().collect(); + while let Some(n) = stack.pop() { + m.insert(n.id, n); + stack.extend(n.children().into_iter().flatten()); + } + looked_at += m.len() as u64; + m + }); + now = all.get(&node.id).copied(); + } + if now.is_some_and(|n| Arc::ptr_eq(node, n)) { continue; } if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) { keys.push((*uid, node.id.0)); } if let Some(children) = node.children() { - todo.extend(children); + todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at)); } } if let Some(after) = after { @@ -1429,8 +1476,11 @@ pub(super) fn see_all_points(h: &super::Host) { }); keys.sort_unstable(); keys.dedup(); - keys + (keys, looked_at) }; + if looked_at > 0 { + h.charge_call(looked_at)?; + } let editing = h.dom.editing.get(); for (uid, id) in keys { let own = || match editing { @@ -1443,6 +1493,20 @@ pub(super) fn see_all_points(h: &super::Host) { }; see_points(h, (uid, id), own); } + Ok(()) +} + +/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the +/// nodes of `after` it looks at. +fn paired<'a>( + before: &'a [Arc], + after: Option<&'a Vec>>, + looked_at: &mut u64, +) -> Vec<(&'a Arc, Option<&'a Arc>)> { + let after = after.map_or(&[][..], Vec::as_slice); + *looked_at += after.len() as u64; + let now: std::collections::HashMap> = after.iter().map(|n| (n.id, n)).collect(); + before.iter().map(|n| (n, now.get(&n.id).copied())).collect() } fn points_at(h: &super::Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 1ec57d7ba9..34f7755d1a 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -32,8 +32,8 @@ //! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not //! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page //! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to -//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one -//! `unit`, more than 0 and at most 1000. +//! true colors, PNG, millimeters and 100. `unitScaleRatio` is a percentage: at 100 one `unit` is +//! one drawing unit. It is at least 0.0001 and at most 1000. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is @@ -739,10 +739,12 @@ fn autocad_map(name: &str, d: &Data, p: &mut Map) -> std::result: Data::Number(n) if n.is_finite() => *n, _ => return Err(HostError::Type(format!("{what} must be a finite number"))), }; - if !(n > 0.0 && n <= 1000.0) { - return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000"))); + // A percentage: the DXF writer's `scale` is `n / 100`, and its smallest scale (1e-6) is + // 0.0001%. + if !(0.0001..=1000.0).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 0.0001 and at most 1000"))); } - p.insert("scale".into(), json!(n)); + p.insert("scale".into(), json!((n / 100.0).max(*vectorcraft_cad::SCALE_RANGE.start()))); } "version" => { let version = match pick("AutoCADCompatibility")? { @@ -1025,7 +1027,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); } // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. - // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`. + // A DXF's `scale` is its drawing units per unit, from `unitScaleRatio` divided by 100. if !matches!(kind.format, "svg" | "dxf") { p.insert("scale".into(), json!(hs / 100.0)); } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index a37a062849..22a1e36f1d 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -128,6 +128,10 @@ pub(super) struct State { prev: RefCell>, sources: RefCell>, descendants: RefCell>>, + /// For each document uid, stores the last noted revert count ([`crate::DocState::reverts`]) + /// and the lowest id the run could allocate after the first note or the latest revert + /// ([`note_document`]). + marks: RefCell>, retraces: Cell, } @@ -208,6 +212,37 @@ pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { }); } +/// Before each command a script runs: notes the active document ([`note_document`]). +pub(super) fn before_command(h: &Host) { + let s = h.session.borrow(); + if let Some(st) = s.active() { + note_document(h, st); + } +} + +/// Records the next object id when the run first notes the document `st`. A revert resets +/// the mark to the reloaded document's next object id and keeps the descendant snapshots. +/// Loaded objects have ids below the mark; objects the run makes afterward have ids at or above it. +fn note_document(h: &Host, st: &crate::DocState) { + let mut marks = h.dom.tracing.marks.borrow_mut(); + match marks.get_mut(&st.uid) { + Some((reverts, _)) if *reverts == st.reverts => {} + Some((reverts, mark)) => { + *reverts = st.reverts; + *mark = st.doc.peek_next_id(); + } + None => { + marks.insert(st.uid, (st.reverts, st.doc.peek_next_id())); + } + } +} + +/// Returns the lowest id the run could allocate in document `uid` after its first note or latest +/// revert ([`note_document`]). +fn mark(h: &Host, uid: u64) -> Option { + h.dom.tracing.marks.borrow().get(&uid).map(|(_, mark)| *mark) +} + pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) @@ -325,15 +360,22 @@ fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result< /// and "Cannot edit page item" when it holds a locked object other than its source image, which /// the replacement would discard. The objects looked at are charged to the run either way. fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { - let (visited, result) = read_group(h, item, |_, group| { + let (visited, result) = read_group(h, item, |st, group| { + note_document(h, st); remember_source(h, item.doc.uid, group); - // The objects the trace made, as the tracing records them; a tracing saved without that - // record is checked against the objects it held when this run first saw it. + // A tracing with a record is checked against the objects its trace made. A tracing without + // a record is checked against its first descendant snapshot, which survives reverts. + // If the group id is below the document's mark, members at or above the mark are also added. + // A revert resets the mark to the reloaded document's next object id. let made = group.trace_made(); let descendants = h.dom.tracing.descendants.borrow(); let ids = match made { Some(_) => None, - None => Some(descendants.get(&(item.doc.uid, item.id.0)).ok_or_else(stale)?), + None => descendants.get(&(item.doc.uid, item.id.0)), + }; + let newer = match made { + Some(_) => None, + None => mark(h, item.doc.uid).filter(|m| group.id.0 < *m), }; let source = group.children().and_then(|c| c.first()).map(|n| n.id); let mut visited = 0u64; @@ -345,7 +387,7 @@ fn refuse_added(h: &Host, item: Item, refusal: &str) -> Result<(), HostError> { (Some(m), _) => !m.contains(n.id), (None, Some(ids)) => !ids.contains(&n.id), (None, None) => false, - }; + } || newer.is_some_and(|m| n.id.0 >= m); // Added artwork is reported before a locked object, whichever comes first. if added { return Ok((visited, Err(HostError::Error(refusal.into())))); diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index b0c3a1de8b..3bf88a577c 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -20,9 +20,13 @@ //! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own //! scale in percent, the square root of the area it scales by (stroke weights and effects scale //! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to -//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any -//! other value, and a scale of strokes and effects with positions left as they are, throws an -//! error that says so. +//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points. +//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight +//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale +//! of strokes and effects with positions left as they are, throws an error that says so. +//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN` +//! still uses the first artboard's bottom-left corner; other named points use the origin. +//! Its linked opacity mask, strokes, effects and patterns transform with the same options. //! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a //! locked object, an object on a locked artboard and a guide while guides are locked are refused //! with nothing changed, and so are @@ -37,16 +41,16 @@ use super::matrix::{self, Matrix}; use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc}; /// The error for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; /// The error for a locked object. -const LOCKED: &str = "cannot transform locked objects"; +pub(super) const LOCKED: &str = "cannot transform locked objects"; /// The error for a guide while guides are locked. const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked"; /// The error for a hidden object. -const HIDDEN: &str = "cannot transform hidden objects"; +pub(super) const HIDDEN: &str = "cannot transform hidden objects"; /// The identity matrix. const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; @@ -136,8 +140,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { } /// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` -/// ([`anchor_name`]) names. -fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result { +/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`. +fn anchor(h: &Host, item: Item, r: Option, name: &str) -> std::result::Result { + if r.is_none() && !paths::is_path(h, item) { + return Err(HostError::Error("the object has no bounds".into())); + } + if name == "DOCUMENTORIGIN" { + return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0]))); + } + let Some(r) = r else { + return Ok(Point::ORIGIN); + }; let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); Ok(match name { "TOPLEFT" => Point::new(r.x0, r.y0), @@ -148,7 +161,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result Point::new(r.x0, r.y1), "BOTTOM" => Point::new(cx, r.y1), "BOTTOMRIGHT" => Point::new(r.x1, r.y1), - "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?, _ => Point::new(cx, cy), }) } @@ -222,12 +234,10 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) { return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0))); } - // The identity acts the same about every point, so an object without bounds (an empty path) - // takes it too. + // The identity acts the same about every point for any object. let o = match (about, bounds) { _ if m == IDENTITY => Point::ORIGIN, - (Some(name), Some(r)) => anchor(h, item, r, name)?, - (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (Some(name), r) => anchor(h, item, r, name)?, (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); @@ -249,6 +259,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, } let c = xf.as_coeffs(); let identity = xf == Affine::IDENTITY; + // Every stroke layer's weight is checked with the factor `object.transform` applies. + let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None }; + if let Some(k) = factor + && paths::is_path(h, item) + && (!k.is_finite() || { + let width = paths::largest_stroke_weight(h, item)? * k; + !width.is_finite() || width > paths::MAX_STROKE_WIDTH + }) + { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; // The transformation and the stroke weight change together or not at all. atomically(h, |h| { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index cd966a5605..a33e6c732b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1519,8 +1519,10 @@ fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std:: dom::after_command(host, before); // Style objects follow only a command that is kept. if crossed.is_ok() { - dom::see_points(host); + // The command stays kept when the look at its changes passes a limit, which ends the run. + let seen = dom::see_points(host); dom::after_kept_command(host); + seen?; } else { session.borrow_mut().script_style_trail = StyleTrail::default(); } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 69ae5958a2..1a3a285725 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -143,6 +143,7 @@ impl Session { composite_names_registered: HashSet::new(), reading: false, place_hand_off: None, + image_only: std::cell::Cell::new(None), queue_hand_off: None, place_queue_roots: None, place_queue_loads: 0, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 264d3dcf32..e880f436f6 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5189,6 +5189,39 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() { assert!(!s.doc().unwrap().selection.contains(b)); } +/// The selection commands and Curvature edits refuse a mode or op they do not know, and leave the +/// selection, the document and the undo history as they were. +#[test] +fn an_unknown_selection_mode_or_curvature_op_is_refused_without_changes() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 30.0, 20.0); + let b = rect(&mut s, 50.0, 10.0, 30.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let objects = s.doc().unwrap().selection.objects.clone(); + let anchors = s.doc().unwrap().selection.anchors.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let mut wrong = vec![]; + for (cmd, p, says) in [ + ("select.segments", json!({"id": a.0, "segments": [[0, 0]], "mode": "bogus"}), "unknown mode"), + ("select.anchorsMany", json!({"items": [{"id": a.0, "anchors": [[0, 0]]}], "mode": "bogus"}), "unknown mode"), + ("select.magicWand", json!({"id": a.0, "mode": "bogus"}), "unknown mode"), + ("path.curvatureEdit", json!({"id": a.0, "op": "bogus", "anchor": 0, "x": 0, "y": 0}), "unknown op"), + ] { + match s.execute(cmd, &p) { + Err(e) if e.to_string().contains(says) => {} + other => wrong.push(format!("{cmd}: {other:?}")), + } + let st = s.doc().unwrap(); + let changed = st.selection.objects != objects || st.selection.anchors != anchors || st.doc != doc || st.history.undo.len() != undo; + if changed { + wrong.push(format!("{cmd} changed the selection, the document or the undo history")); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + /// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With /// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that /// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 38bb94a6f3..c640c08e26 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -225,6 +225,7 @@ fn a_linked_handle_makes_the_anchor_smooth() { json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}), json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "symmetric": true}), json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}), json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}), diff --git a/crates/engine/src/tests/arrowheads.rs b/crates/engine/src/tests/arrowheads.rs index 0cdc3312ff..656f034be7 100644 --- a/crates/engine/src/tests/arrowheads.rs +++ b/crates/engine/src/tests/arrowheads.rs @@ -444,3 +444,20 @@ fn a_group_used_as_the_clipping_path_adds_none_of_its_own_fills() { let b = read.heads[0].path.bounds().unwrap(); assert!((b.width() - 4.0).abs() < 1e-3 && (b.height() - 4.0).abs() < 1e-3, "the square alone: {b:?}"); } + +/// An arrowheads file over the size limit is refused from its size: no heads are listed, and the +/// error says why. +#[test] +fn an_arrowheads_file_over_the_size_limit_lists_no_heads() { + let dir = folder("too-big"); + let file = dir.join(arrowheads::FILE_NAME); + // Sparse: no data blocks are written. + std::fs::File::create(&file).unwrap().set_len(arrowheads::MAX_FILE_BYTES + 1).unwrap(); + let (mut s, _) = session_with_line(); + s.attach_arrowheads_file(file.to_string_lossy().to_string()); + let list = s.execute("stroke.arrowheads.list", &json!({})).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(list["arrowheads"], json!([])); + let error = list["error"].as_str().unwrap_or_default(); + assert!(error.contains(&format!("larger than {} MB", arrowheads::MAX_FILE_BYTES >> 20)), "{list}"); +} diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index 7f7c7fffa4..88a5c7b4b1 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -456,6 +456,7 @@ fn a_linked_spine_handle_makes_the_point_smooth() { for bad in [ json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}), json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}), + json!({"anchor": 1, "handle": "out", "x": 60, "y": 40, "link": true, "symmetric": true}), json!({"anchor": 1, "x": 75, "y": 25, "link": true}), ] { assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}"); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 516e4fb3b0..3be402bb94 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -6802,6 +6802,80 @@ fn join_two_subpaths_of_same_path_node() { assert_eq!(pd.subpaths[0].anchors[3].p, Point::new(250.0, 0.0)); } +/// A path with one open two-anchor subpath per pair of points. +fn path_of_lines(s: &mut Session, lines: &[[Point; 2]]) -> NodeId { + let p = line(s, lines[0][0].x, lines[0][0].y, lines[0][1].x, lines[0][1].y); + let rest: Vec<_> = lines[1..].iter().map(|l| vectorcraft_geom::SubPath::polyline(l, false)).collect(); + s.edit("Add Subpaths", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(p).unwrap().kind { + path.subpaths.extend(rest); + } + Ok(()) + }) + .unwrap(); + p +} + +fn subpath_points(s: &Session, id: NodeId) -> Vec> { + path(s, id).subpaths.iter().map(|sp| sp.anchors.iter().map(|a| a.p).collect()).collect() +} + +/// `path.join` with the same id twice and `subpaths` joins two subpaths of one path. Here the later +/// subpath comes first, so the earlier one is removed and the joined subpath takes the later one's +/// place, the coincident junction anchors become one, and the subpath between them stays as it was. +/// One undo step brings back all three subpaths. +#[test] +fn join_of_one_path_by_ids_and_subpaths_merges_the_junction_and_keeps_the_other_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(100.0, 0.0), pt(110.0, 0.0)], [pt(500.0, 0.0), pt(510.0, 0.0)], [pt(0.0, 0.0), pt(100.0, 0.0)]]); + let before = subpath_points(&s, p); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("path.join", &json!({"ids": [p.0, p.0], "subpaths": [2, 0], "ends": ["last", "first"]})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(500.0, 0.0), pt(510.0, 0.0)], vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(110.0, 0.0)]]); + assert!(path(&s, p).subpaths.iter().all(|sp| !sp.closed)); + assert_eq!(s.doc().unwrap().selection.objects, vec![p]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(subpath_points(&s, p), before); +} + +/// With both ends of one open subpath direct-selected, Join closes that subpath and leaves the +/// other open subpath of the same path as it is, instead of joining the two. +#[test] +fn join_with_both_ends_of_one_subpath_selected_closes_that_subpath() { + let mut s = session(); + let pt = Point::new; + let p = path_of_lines(&mut s, &[[pt(0.0, 0.0), pt(100.0, 0.0)], [pt(0.0, 50.0), pt(100.0, 50.0)]]); + s.execute("select.anchors", &json!({"id": p.0, "anchors": [[1, 0], [1, 1]], "mode": "set"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + assert_eq!(subpath_points(&s, p), vec![vec![pt(0.0, 0.0), pt(100.0, 0.0)], vec![pt(0.0, 50.0), pt(100.0, 50.0)]]); + let pd = path(&s, p); + assert!(!pd.subpaths[0].closed, "the other subpath stays open"); + assert!(pd.subpaths[1].closed, "the subpath with both ends selected is closed"); +} + +/// With both ends of one line selected and only the first end of another, Join takes the nearest +/// pair of selected ends: the second line's unselected end is nearer but is not joined. +#[test] +fn join_with_both_ends_of_one_line_selected_takes_the_nearest_selected_pair() { + let mut s = session(); + let pt = Point::new; + let a = line(&mut s, 0.0, 0.0, 100.0, 0.0); + let b = line(&mut s, 300.0, 0.0, 105.0, 0.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + s.execute("path.join", &json!({})).unwrap(); + + let joined = paths(&s); + assert_eq!(joined.len(), 1, "{joined:?}"); + let pts: Vec = joined[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, vec![pt(0.0, 0.0), pt(100.0, 0.0), pt(300.0, 0.0), pt(105.0, 0.0)]); +} + /// Direct-selecting 2 open endpoints in a complex compound path with multiple open segments joins only those 2. #[test] fn join_complex_compound_path_direct_endpoints() { diff --git a/crates/engine/src/tests/halftone.rs b/crates/engine/src/tests/halftone.rs index d836502baa..c7ec58549c 100644 --- a/crates/engine/src/tests/halftone.rs +++ b/crates/engine/src/tests/halftone.rs @@ -66,6 +66,65 @@ fn halftone_options() { } } +/// The dot path Vector Halftone makes from a gray square with `params`. +fn dots_of(params: serde_json::Value) -> vectorcraft_geom::PathData { + let mut s = session(); + red_rect(&mut s); + s.execute("paint.setFill", &json!({"color": "#808080"})).unwrap(); + let r = s.execute("object.vectorHalftone", ¶ms).unwrap(); + let g = node(&s, NodeId(r["id"].as_u64().unwrap())); + g.children().unwrap()[0].path_data().unwrap().clone() +} + +#[test] +fn halftone_styles_set_the_shape_and_angle_unless_given() { + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots"})), dots_of(json!({"frequency": 18, "shape": "circle", "angle": 0}))); + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridAngle"})), dots_of(json!({"frequency": 18, "shape": "euclidean", "angle": 45}))); + assert_ne!(dots_of(json!({"frequency": 18, "style": "grid"})), dots_of(json!({"frequency": 18}))); + // A given shape or angle wins over the style's. + assert_eq!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "angle": 0}))); + assert_ne!(dots_of(json!({"frequency": 18, "style": "grid", "shape": "circle"})), dots_of(json!({"frequency": 18, "style": "grid"}))); + assert_eq!(dots_of(json!({"frequency": 18, "style": "gridDots", "angle": 45})), dots_of(json!({"frequency": 18, "style": "gridDotsAngle"}))); + // An unknown style is refused and leaves the document as it was. + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("object.vectorHalftone", &json!({"style": "checker"})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); +} + +#[test] +fn halftone_refuses_null_and_non_string_styles() { + for style in [json!(null), json!(42), json!(true), json!([]), json!({})] { + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let result = s.execute("object.vectorHalftone", &json!({"style": style})); + assert!(matches!(result, Err(EngineError::BadParams { .. })), "{style}: {result:?}"); + assert_eq!(s.doc().unwrap().doc, before, "{style}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{style}"); + } + assert_eq!(dots_of(json!({"style": "custom"})), dots_of(json!({}))); +} + +/// The live effect refuses an unknown style when applied or edited, and leaves the document as it +/// was; a known style in another letter case is taken. +#[test] +fn halftone_effect_refuses_an_unknown_style() { + const HALFTONE: &str = "addon.color.halftone"; + let mut s = session(); + red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "gridDot"}})).is_err()); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("effect.apply", &json!({"effect": HALFTONE, "params": {"style": "GRIDDOTS"}})).unwrap(); + let applied = s.doc().unwrap().doc.clone(); + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "gridDot"}})).is_err()); + assert_eq!(s.doc().unwrap().doc, applied); + s.execute("effect.setParams", &json!({"index": 0, "params": {"style": "custom"}})).unwrap(); +} + #[test] fn halftone_refuses_a_param_of_the_wrong_type() { for bad in [ diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index cf5fc3c269..1ee23ef47d 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -1299,3 +1299,26 @@ fn a_library_is_exported_to_a_file_and_imported_from_it() { v.libraries.set_dir(Some(folder)); assert_eq!(groups(&mut v), [("Logos".into(), refs(&[("graphic", &g)]))]); } + +/// A library file over 512 MB is refused from its size before it is opened: the file here cannot +/// be opened at all, so only the size check gives this error. +#[cfg(unix)] +#[test] +fn a_library_file_over_the_size_limit_is_refused_before_it_is_read() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("vc-library-too-big-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("big.vclibrary"); + // Sparse: no data blocks are written. + std::fs::File::create(&path).unwrap().set_len((512 << 20) + 1).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap(); + // A process that may read any file (root) opens it: nothing to check. + let opened = std::fs::File::open(&path).is_ok(); + let r = (!opened).then(|| session().execute("library.import", &json!({"path": path.to_string_lossy()}))); + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); + let _ = std::fs::remove_dir_all(&dir); + let Some(r) = r else { return }; // root opened the file: the size check is not what refuses it + let e = r.err().unwrap_or_else(|| panic!("the file was imported")).to_string(); + assert!(e.contains("the file is larger than 512 MB"), "{e}"); +} diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index a320b09b18..21cc4af602 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -137,6 +137,45 @@ fn a_preset_starts_the_document_and_params_change_it() { assert_eq!(s.doc().unwrap().doc.units, Unit::Pixels); } +#[test] +fn a_bad_preset_or_preset_category_is_an_error() { + let s = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + assert!((s.doc().unwrap().doc.artboards[0].rect.height() - 841.89).abs() < 0.01); + for p in [ + json!({"preset": "A4", "presetCategory": "Napkins"}), + json!({"preset": "A4", "presetCategory": 5}), + json!({"preset": "A4", "presetCategory": ""}), + json!({"preset": "A4", "presetCategory": " Print "}), + json!({"presetCategory": "Print"}), + json!({"presetCategory": "Napkins"}), + json!({"preset": 5}), + json!({"preset": true, "presetCategory": "Print"}), + ] { + assert!(Session::new().execute("file.new", &p).is_err(), "file.new {p}"); + let mut save = p.clone(); + save["name"] = json!("Mine"); + assert!(Session::new().execute("file.newPresets.save", &save).is_err(), "file.newPresets.save {save}"); + } + let e = Session::new().execute("file.new", &json!({"preset": "A4", "presetCategory": "Napkins"})).unwrap_err().to_string(); + assert!(e.contains("unknown category `Napkins`"), "{e}"); + // Null leaves a param out. + Session::new().execute("file.new", &json!({"preset": null, "presetCategory": null})).unwrap(); + // A step this version took replays, and one an earlier version took still plays as it did then. + let recorded = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + let mut recorded = new_doc(json!({})); + recorded.journal.last_mut().unwrap().1["presetCategory"] = json!("Print"); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); +} + #[test] fn ppi_overprint_preview_and_bad_params() { // Overprint Preview is process-wide. diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 802748e407..a5a082058e 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -123,6 +123,54 @@ fn intersect_disjoint_is_error_and_no_change() { assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); } +/// Pathfinder refuses a selection that holds no paths (an image alone) and paths with an anchor +/// that is not a finite number, and leaves the document and the undo history as they were. +#[test] +fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() { + let mut s = session(); + let image = s + .edit("Place", |d, sel| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![0; 8])); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 2, + height: 2, + xf: Default::default(), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select paths"), "{e}"); + assert!(s.doc().unwrap().doc == before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); + + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 0.0, 10.0, 10.0); + s.edit("Break", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(a).unwrap().kind { + path.subpaths[0].anchors[1].p.x = f64::NAN; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let undo_len = s.doc().unwrap().history.undo.len(); + let e = s.execute("object.pathfinder.unite", &json!({})).unwrap_err().to_string(); + assert!(e.contains("invalid coordinates"), "{e}"); + assert!(s.doc().unwrap().doc.node(a).is_some() && s.doc().unwrap().doc.node(b).is_some()); + assert!(s.doc().unwrap().doc.node(image).is_some()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); +} + #[test] fn exclude_makes_compound() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 54c599d5fd..42728c7fa6 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2739,6 +2739,78 @@ fn stored_files_whose_reads_fail_leave_the_store_budget_to_the_others() { assert!(vectorcraft_plugins::registry::remove(id)); } +/// Sets the bytes the stored plug-ins of this thread's stores may read together, and puts the +/// usual budget back when dropped, a failed assertion included. +struct StoreBudget; + +impl StoreBudget { + fn set(bytes: u64) -> Self { + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(bytes)); + StoreBudget + } +} + +impl Drop for StoreBudget { + fn drop(&mut self) { + crate::store::PLUGIN_STORE_BUDGET.with(|b| b.set(crate::store::MAX_PLUGIN_STORE)); + } +} + +/// The failure listed for each stored file of `folder`, as (file name, reason), sorted. +fn stored_failures_in(folder: &std::path::Path) -> Vec<(String, String)> { + let mut rows: Vec<(String, String)> = crate::store::failed_stored_plugins(folder) + .into_iter() + .map(|(p, why)| (p.file_name().unwrap().to_string_lossy().into_owned(), why)) + .collect(); + rows.sort(); + rows +} + +/// Once the stored plug-ins have used up the bytes a store may read, the stored files after them +/// are listed as failed and are not installed. +#[test] +fn stored_plugins_past_the_store_budget_are_listed_as_failed() { + let (folder, first) = store_with("plugin-budget-used-up", "test.engine.budgetused.a"); + for id in ["test.engine.budgetused.b", "test.engine.budgetused.c"] { + let module = wat::parse_str(tpl::returning(&tpl::manifest(id, "filter", "{}"), r#"{"objects":[]}"#)).unwrap(); + std::fs::write(folder.0.join(format!("{id}.wasm")), module).unwrap(); + } + let len = std::fs::metadata(&first).unwrap().len(); + let mut s = session(); + { + let _budget = StoreBudget::set(len); + s.attach_plugin_store(folder.0.clone()); + } + let installed: Vec = + ["a", "b", "c"].iter().map(|n| vectorcraft_plugins::registry::get(&format!("test.engine.budgetused.{n}")).is_some()).collect(); + let failed = stored_failures_in(&folder.0); + for n in ["a", "b", "c"] { + vectorcraft_plugins::registry::remove(&format!("test.engine.budgetused.{n}")); + } + assert_eq!(installed, [true, false, false], "only the first file fits the budget"); + let why = format!("the stored plug-ins hold more than {} bytes together", crate::store::MAX_PLUGIN_STORE); + let expected: Vec<(String, String)> = ["b", "c"].iter().map(|n| (format!("test.engine.budgetused.{n}.wasm"), why.clone())).collect(); + assert_eq!(failed, expected); +} + +/// A stored file longer than the bytes the store may still read is skipped and listed as failed. +#[test] +fn a_stored_plugin_larger_than_the_store_budget_is_skipped() { + let id = "test.engine.budgetsmall"; + let (folder, module) = store_with("plugin-budget-small", id); + let len = std::fs::metadata(&module).unwrap().len(); + let mut s = session(); + { + let _budget = StoreBudget::set(len - 1); + s.attach_plugin_store(folder.0.clone()); + } + let installed = vectorcraft_plugins::registry::remove(id); + assert!(!installed, "a file over the budget is not read"); + let failed = stored_failures_in(&folder.0); + assert_eq!(failed.len(), 1, "{failed:?}"); + assert!(failed[0].1.contains(&format!("larger than {} bytes", len - 1)), "{failed:?}"); +} + /// A stored file replaced after its module loaded, by one of the same length with the same modified /// time, is skipped: its content no longer holds the module. That holds for a file modified moments /// ago and for one modified an hour ago. diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index ea399d2fd2..cdb3275607 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -458,6 +458,18 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // Once the script makes an artboard active, the selection from the start of the run no longer holds. + let (mut s, was, _) = setup(); + let before = objects(&s); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 1, "one copy, on the artboard the script made active"); + let pasted = s.active().unwrap().selection.objects.clone(); + let copy = s.active().unwrap().doc.bounds_of(&pasted, false).unwrap(); + assert!(copy.x0 >= was[1].x0 && copy.x1 <= was[1].x1, "the copy is on artboard 1: {copy:?}"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(2); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [was[0], was[1], art[2]], "only the artboard the script made active fits its art"); // A kept artboard past the last one is left out; with fewer than two left, the active one applies. let (mut s, ..) = setup(); s.reset_tool(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index d484e10e81..8f71d64e62 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -4276,6 +4276,62 @@ fn has_selected_artwork_charges_the_walk_when_nothing_is_added() { assert!(error.contains("passed more data"), "{error}"); } +/// Reading `hasSelectedArtwork` is charged for every selected object it looks at. +#[test] +fn has_selected_artwork_charges_the_selection_it_reads() { + let repeated = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + r + }; + repeated(1).unwrap(); + let error = repeated(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +/// While a group is isolated, `hasSelectedArtwork = true` selects the art inside the group, as +/// Select All does. +#[test] +fn has_selected_artwork_selects_inside_an_isolated_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.isolate", &json!({"id": g})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true; vc.log(l.hasSelectedArtwork);"); + assert_eq!(out, [json!(true)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b), "{sel:?}"); +} + +/// While Lock Guides is on, a path made into a guide is not counted as art to add, so a selection +/// at the limit does not refuse a layer that holds only such a path. +#[test] +fn has_selected_artwork_skips_locked_guide_paths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.active_mut().unwrap().selection.objects = vec![other; 10_000]; + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_000); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index ac1e9ca782..8fc2876981 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -287,6 +287,45 @@ fn a_file_that_is_not_an_image_is_refused_before_placing() { let _ = std::fs::remove_dir_all(base); } +/// How many times the engine read the file at `path` on this thread since the last call. +#[cfg(not(target_arch = "wasm32"))] +fn reads_of(path: &Path) -> usize { + let path = path.to_string_lossy(); + crate::cmd::fileio::FILES_READ.with(|r| r.take().iter().filter(|p| plain_path(p) == path).count()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn placing_or_relinking_from_a_script_reads_the_file_once() { + let base = folder("read-once"); + let (a, b) = (base.join("main/a.png"), base.join("main/b.png")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(&b, gray_png(20, 10)).unwrap(); + let mut s = session(); + reads_of(&a); + log(&mut s, &base, &format!("app.activeDocument.placedItems.add().file = new File('{}');", js_path(&a))); + assert_eq!(reads_of(&a), 1, "placing reads the file once"); + log(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(&b))); + assert_eq!(reads_of(&b), 1, "relinking reads the file once"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn relinking_to_a_file_that_is_not_an_image_keeps_the_link() { + let base = folder("relink-text"); + let (a, notes) = (base.join("main/a.png"), base.join("main/notes.txt")); + std::fs::write(&a, gray_png(10, 10)).unwrap(); + std::fs::write(¬es, "hello").unwrap(); + let mut s = session(); + let id = place(&mut s, &a, true); + let before = undo_steps(&s); + let e = failure(&mut s, &base, &format!("app.activeDocument.placedItems[0].relink(new File('{}'));", js_path(¬es))); + assert!(e.contains("The file is not an image") && !e.contains("notes.txt"), "{e}"); + assert_eq!(images(&s), vec![(id, Some(a.to_string_lossy().into_owned()))]); + assert_eq!(undo_steps(&s), before); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn placed_items_add_is_bounded() { let base = folder("pending"); @@ -497,6 +536,41 @@ fn a_stale_placed_item_is_not_a_relative_object() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn image_matrix_refuses_locked_hidden_and_locked_artboard_images() { + let base = folder("matrix-locks"); + let g = base.join("main/g.png"); + std::fs::write(&g, gray_png(10, 20)).unwrap(); + let mut s = session(); + let id = place(&mut s, &g, true); + // A moved matrix and the matrix the image already has are refused alike. + let sets = [ + "var p = app.activeDocument.placedItems[0], m = p.matrix; m.mValueTX = m.mValueTX + 5; p.matrix = m;", + "var p = app.activeDocument.placedItems[0]; p.matrix = p.matrix;", + ]; + let refused = |s: &mut Session, message: &str| { + for set in sets { + let (was, before) = (s.active().unwrap().doc.clone(), undo_steps(s)); + let e = failure(s, &base, set); + assert!(e.contains(message), "{set}: {e}"); + assert_eq!(*s.active().unwrap().doc, *was, "{set}"); + assert_eq!(undo_steps(s), before, "{set}"); + } + }; + for (field, set_to, message) in [("locked", true, "cannot transform locked objects"), ("visible", false, "cannot transform hidden objects")] { + s.execute("object.setProps", &json!({"ids": [id.0], field: set_to})).unwrap(); + refused(&mut s, message); + s.execute("object.setProps", &json!({"ids": [id.0], field: !set_to})).unwrap(); + } + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + refused(&mut s, "cannot transform objects on a locked artboard"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn image_matrix_refuses_bad_values_without_changing_the_image() { let base = folder("matrix-bad"); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 3b44785b3a..1078f7078e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1089,6 +1089,42 @@ fn editing_one_point_on_each_of_many_paths_looks_at_each_path_a_few_times() { assert!(looks < 3000, "{looks} looks at paths for 300 one-point edits"); } +/// After a run reads a path's points, each command makes the run look through the document's +/// changed layers for paths whose points it read, and that look is charged by the objects it +/// looks at: a loop of commands on a large layer ends at the limit on data passed to commands. +#[test] +fn looking_for_changed_points_after_each_command_is_charged() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut last = NodeId(0); + for i in 0..2000 { + last = rect(&mut s, f64::from(i % 40) * 10.0, f64::from(i / 40) * 5.0, 4.0, 4.0); + } + s.execute("select.none", &json!({})).unwrap(); + let source = format!( + "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor.length);\ + for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", + last.0 + ); + let r = run(&mut s, &source).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["log"], json!([2])); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let e = run(&mut s, &source).map(|r| r.to_string()); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = e.map(|r| panic!("100 commands, each followed by a look at 2,000 objects, ran: {r}")).unwrap_err(); + assert!(e.to_string().ends_with("(limit)"), "{e}"); + // Once the path whose points the run read is gone, later commands look for nothing. + let source = format!( + "var p = app.activeDocument.pathItems[1]; vc.log(p.pathPoints[0].anchor.length); p.remove();\ + for (var i = 0; i < 100; i++) vc.run('object.move', {{ids: [{}], dx: 1, dy: 0}});", + last.0 + ); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let r = run(&mut s, &source); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap_or_else(|e| panic!("{e}"))["log"], json!([2])); +} + #[test] fn point_edits_are_written_before_the_next_other_member_reads() { let (mut s, a, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 403510d73c..ede881af0d 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -506,6 +506,57 @@ fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() { + let base = folder("retrace-legacy-paths"); + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + let held = members(&s, group); + // The script reaches the tracing's paths before the tracing itself. + let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);"; + let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0))); + assert_eq!(out, [json!(ADDED_ARTWORK)]); + assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() { + let base = folder("retrace-legacy-revert"); + let path = base.join("main/legacy.vectorcraft"); + for seen_first in [false, true] { + for added in [false, true] { + let (mut s, image) = session(&base, false); + let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap()); + let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc); + let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap(); + trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = members(&s, group); + s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap(); + let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" }; + let add = if added { + format!( + "var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\ + r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';", + json!(path.to_string_lossy()) + ) + } else { + String::new() + }; + let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0))); + // A revert keeps the snapshot taken before it. + let message = if added || seen_first { ADDED_ARTWORK } else { "" }; + assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}"); + } + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn engine_trace_can_be_retraced_by_a_script() { let base = folder("retrace-engine-artwork"); @@ -1367,6 +1418,22 @@ fn unimplemented_tracing_members_are_not_reported() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn new_group_at_the_bottom_of_a_tracing_is_refused() { + let base = folder("new-group-bottom"); + let (mut s, id) = session(&base, false); + let tid = NodeId(s.execute("imageTrace.make", &json!({"id": id.0})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let e = s.execute("object.newGroup", &json!({"parent": tid.0, "index": 0})).unwrap_err().to_string(); + assert!(e.contains("source image"), "{e}"); + assert_eq!(traces(&s), [tid]); + assert_eq!(undo_steps(&s), steps); + let g = NodeId(s.execute("object.newGroup", &json!({"parent": tid.0, "index": 1})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(traces(&s), [tid]); + assert_eq!(s.active().unwrap().doc.children(Some(tid)).unwrap()[1].id, g); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn retrace_keeps_the_tracing_opacity_and_blend_mode() { let base = folder("retrace-appearance"); diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index d57d4570d5..f3aa67c361 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -130,6 +130,69 @@ fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); } +#[test] +fn a_line_width_of_the_scale_itself_keeps_a_path_stroke_within_1000_points() { + let (mut s, _, _) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 600;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["resize(200, 200, true, true, true, true, 200)", "transform(app.getScaleMatrix(200), true, true, true, true, 200)"] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains("more than 1000 points"), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A scale that keeps the weight within the limit still scales it. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.resize(150, 150, true, true, true, true, 150); vc.log(i.strokeWidth);"); + assert!(close(&numbers(&out[0]), &[900.0]), "{out:?}"); + + // The lower stroke must stay within the limit too. + let (mut s, a, _) = doc(); + s.execute("stroke.set", &json!({"id": a.0, "weight": 600})).unwrap(); + s.execute("appearance.addStroke", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 1;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(200, 200, true, true, true, true, 200);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + + // A nonfinite scale must not turn a zero-width stroke into NaN. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.strokeWidth = 0;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(1e202, 1e202, true, true, true, true, 1e202);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); +} + +#[test] +fn an_empty_path_takes_any_transformation_about_any_point() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.add();"); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.rotate(30); n.rotate(30, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(50, 200); n.resize(50, 50, true, true, true, true, 100, Transformation.BOTTOM);\ + n.transform(app.getRotationMatrix(45)); n.rotate(30, true, true, true, true, Transformation.DOCUMENTORIGIN);\ + vc.log(n.pathPoints.length);", + ); + assert_eq!(out, vec![json!(0)]); + // Its stroke weight still scales with the transformation. + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.strokeWidth = 10; n.resize(200, 200, true, true, true, true, 200); vc.log(n.strokeWidth);", + ); + assert!(close(&numbers(&out[0]), &[20.0]), "{out:?}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].rotate(30, true, true, true, true, 'x');"); + assert!(e.contains("Transformation value"), "{e}"); +} + #[test] fn transform_applies_a_matrix_record_about_the_center() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 643e8f50ea..5a58964284 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -678,9 +678,9 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\ try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\ o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\ - o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ + o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 1000; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\ d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\ - o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\ o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\ var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\ d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});" @@ -694,7 +694,8 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it"); assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format"); assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each"); - assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); + // The DXF writes six decimals. + assert!((dxf_widest(&a) - dxf_widest(&b) * 10.0).abs() < 1e-4, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b)); for name in ["c.dxf", "u.dxf"] { let dxf = std::fs::read_to_string(dir.join(name)).unwrap(); assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24"); @@ -706,6 +707,34 @@ fn an_autocad_export_writes_a_dxf_with_its_options() { let _ = std::fs::remove_dir_all(base); } +/// `unitScaleRatio` is a percentage: 100 writes the drawing at the size an option left out gives, +/// and 200 writes it twice as wide. +#[test] +fn an_autocad_unit_scale_ratio_is_a_percentage() { + let base = folder("autocad-ratio"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF;\n\ + d.exportFile(new File(dir + '/n'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 100; d.exportFile(new File(dir + '/h'), ExportType.AutoCAD, o);\n\ + o.unitScaleRatio = 200; d.exportFile(new File(dir + '/t'), ExportType.AutoCAD, o);\n\ + vc.log(1);" + ), + ); + let width = |name: &str| dxf_widest(&std::fs::read_to_string(dir.join(name)).unwrap()); + let (n, h, t) = (width("n.dxf"), width("h.dxf"), width("t.dxf")); + assert!((h - n).abs() < 1e-6, "100 is full size: {h} and {n}"); + assert!((t - 2.0 * n).abs() < 1e-5, "200 is twice the size: {t} and {n}"); + let _ = std::fs::remove_dir_all(base); +} + /// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and /// an option the script changes applies over the preset. #[test] @@ -1171,6 +1200,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "at most 1000", ), + ( + format!( + "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 0.00001; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" + ), + "ExportOptionsAutoCAD.unitScaleRatio must be at least 0.0001", + ), ( format!( "var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);" diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index 72966faf81..c3249ed756 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -497,3 +497,60 @@ impl Writer<'_> { s.push_str("/End X!\n"); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A closed outline through `points`, each side a straight segment. + fn outline(points: &[(f64, f64)]) -> PathData { + let mut bp = kurbo::BezPath::new(); + for (i, &(x, y)) in points.iter().enumerate() { + if i == 0 { + bp.move_to((x, y)); + } else { + bp.line_to((x, y)); + } + } + bp.close_path(); + PathData::from_bezpath(&bp) + } + + fn assert_near(got: Option, want: (f64, f64)) { + let Some(got) = got else { panic!("no grid point") }; + assert!(got.distance(Point::new(want.0, want.1)) < 1e-9, "{got:?} is not {want:?}"); + } + + /// A top object with two segments on each side is written as a 2 × 2 grid whose middle point + /// blends the four sides' middles less the four corners. + #[test] + fn a_top_object_with_two_segments_a_side_gets_its_middle_point_from_the_sides() { + let path = outline(&[(30.0, 10.0), (100.0, 0.0), (170.0, 10.0), (180.0, 50.0), (170.0, 90.0), (100.0, 90.0), (30.0, 90.0), (30.0, 50.0)]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 2, 4, 6])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 2)); + // (100, 0) and (100, 90) halved, (30, 50) and (180, 50) halved, less the corners' mean. + assert_near(pts.get(4).map(|q| q.0), (105.0, 45.0)); + } + + /// Three segments across and two down: each middle point is weighted by its column across and + /// its row down, not the other way around. + #[test] + fn a_top_object_wider_than_it_is_tall_blends_by_column_across_and_row_down() { + let path = outline(&[ + (0.0, 0.0), + (40.0, -6.0), + (80.0, 4.0), + (120.0, 0.0), + (126.0, 40.0), + (120.0, 80.0), + (80.0, 86.0), + (40.0, 84.0), + (0.0, 80.0), + (-4.0, 40.0), + ]); + let Some((rows, cols, pts)) = top_object_grid(&path, Some([0, 3, 5, 8])) else { panic!("the outline is written as a grid") }; + assert_eq!((rows, cols), (2, 3)); + assert_near(pts.get(5).map(|q| q.0), (39.0 + 1.0 / 3.0, 39.0)); + assert_near(pts.get(6).map(|q| q.0), (82.0 + 2.0 / 3.0, 45.0)); + } +} diff --git a/crates/eps/src/import/ai/mesh.rs b/crates/eps/src/import/ai/mesh.rs index 8e2a46c852..1fcdc67266 100644 --- a/crates/eps/src/import/ai/mesh.rs +++ b/crates/eps/src/import/ai/mesh.rs @@ -785,6 +785,17 @@ mod tests { } } + /// A row of patches with as many columns as a mesh keeps is stitched into one mesh; one more + /// column is not. + #[test] + fn a_mesh_with_more_lines_than_are_kept_is_not_stitched() { + for (n, kept) in [(MAX_LINES, true), (MAX_LINES + 1, false)] { + let r = Grid::new(n, 1).read([n as f64, 1.0]); + let at: Vec<(usize, usize)> = (0..n).map(|i| (0, i)).collect(); + assert_eq!(stitch(&r.cells, &at, 1, n).is_some(), kept, "{n} columns"); + } + } + /// A 2 × 2 mesh comes in as one mesh of 9 shared points, each where the patches put it, with /// the colours the separate patches had at every place. #[test] diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index fe425346d2..57c7e21442 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -2799,6 +2799,43 @@ fn ai_variable_library_without_the_layers() { assert_eq!(variables(stream(&square).as_bytes()), read::VariableRead::default()); } +/// A library whose `variableSets` node writes its children and attributes before its name is +/// still found on its own when reading stops before it. +#[test] +fn a_variable_library_named_after_its_children_is_read_when_reading_stops_early() { + use vectorcraft_doc::DataValue; + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_text}; + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let value = xml_element("Team", &[], &[xml_element("p", &[], &[xml_text(XmlValue::Unicode("Home Team"))])]); + let set = xml_element( + "variableSet", + &[("locked", "none"), ("varSetName", "binding1")], + &[ + xml_element("variables", &[], &[xml_element("variable", &[("trait", "textcontent"), ("varName", "Team")], &[])]), + xml_element( + "v:sampleDataSets", + &[("xmlns", "&ns_custom;"), ("xmlns:v", "&ns_vars;")], + &[xml_element("v:sampleDataSet", &[("dataSetName", "Home")], &[value])], + ), + ], + ); + let named_first = xml_element("variableSets", &[("xmlns", "&ns_vars;")], &[set]); + // Move the name line from the top of the node to just before the line that closes it. + let name = "%_(variableSets) /String (xmlnode-nodename) ,\n"; + let body = named_first.strip_prefix(&format!("%_/XMLNode :\n{name}")).and_then(|b| b.strip_suffix("%_;\n")).unwrap_or_default(); + assert!(!body.is_empty(), "{named_first}"); + let named_last = format!("%_/XMLNode :\n{body}{name}%_;\n"); + let early = stream(&format!("LB\n{}{square}", variable_library_data(&named_last))); + assert!(read(early.as_bytes()).is_err()); + let found = variables(early.as_bytes(), &mut Names::default()); + assert!(found.present); + let names: Vec<&str> = found.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["Team"]); + assert_eq!(found.variables.datasets.len(), 1); + assert_eq!(found.variables.datasets[0].name, "Home"); + assert_eq!(found.variables.datasets[0].values.get("Team"), Some(&DataValue::Text("Home Team".into()))); +} + #[test] fn a_drawn_look_stands_for_its_object() { // The look (a group, with a part on `%_` lines for newer readers), then the object on `%_` diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 3fb4393b19..43cb3b35d2 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -2361,6 +2361,12 @@ mod tests { } let deep = format!("/0 {}", "[".repeat(200)); assert!(read(deep.as_bytes()).is_none()); + // Balanced nesting: 65 levels are read, and a 66th ends the parse. + let nest = |open: &str, close: &str, n: usize| format!("/0 {}1{}", open.repeat(n), close.repeat(n)); + for (open, close) in [("<< /0 ", " >>"), ("[ ", " ]")] { + assert!(read(nest(open, close, MAX_DEPTH + 1).as_bytes()).is_some(), "{open}nested {} levels", MAX_DEPTH + 1); + assert!(read(nest(open, close, MAX_DEPTH + 2).as_bytes()).is_none(), "{open}nested {} levels", MAX_DEPTH + 2); + } } /// A text document's frame on a path of `segments` (each `x0 y0 x1 y1 x2 y2 x3 y3`) with the diff --git a/crates/eps/src/import/tests.rs b/crates/eps/src/import/tests.rs index f920a1c364..63793ff690 100644 --- a/crates/eps/src/import/tests.rs +++ b/crates/eps/src/import/tests.rs @@ -1061,6 +1061,20 @@ fn clipsave_and_cliprestore_bring_the_clip_back() { assert!(matches!(o[0].kind, NodeKind::Path { .. }), "{:?}", o[0].kind); } +/// `clipsave` and `gsave` each keep up to 1,000 saved states. One more is a limit error: the +/// square drawn before it stays, and the one after it is left out. +#[test] +fn clipsave_and_gsave_stop_at_a_thousand_saved_states() { + for (op, why) in [("clipsave", "too many saved clips"), ("gsave", "too many saved graphics states")] { + let r = read(&format!("0 0 10 10 rectfill 1000 {{ {op} }} repeat 20 20 10 10 rectfill")); + assert_eq!(objects(&r.document).len(), 2, "{op}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains(why)), "{op}: {:?}", r.warnings); + let r = read(&format!("0 0 10 10 rectfill 1001 {{ {op} }} repeat 20 20 10 10 rectfill")); + assert_eq!(objects(&r.document).len(), 1, "{op}: {:?}", r.warnings); + assert!(r.warnings.first().is_some_and(|w| w.contains(why)), "{op}: {:?}", r.warnings); + } +} + #[test] fn languagelevel_is_an_integer_and_runs() { // #234. @@ -1099,6 +1113,25 @@ fn intervals_share_their_arrays_and_strings() { ); } +/// `cvs` writes the text of each kind of object (PLRM 3rd ed., `cvs`): a real keeps a decimal +/// point, booleans, names and operators their names, other objects `--nostringval--`. `cvrs` +/// writes a number in a radix from 2 to 36 with uppercase digits, a negative one as its 32-bit +/// two's complement, and refuses any other radix. +#[test] +fn cvs_and_cvrs_write_the_text_of_each_kind() { + check("/s 16 string def 3.0 s cvs (3.0) eq"); + check("/s 16 string def 2.5 s cvs (2.5) eq"); + check("/s 16 string def true s cvs (true) eq"); + check("/s 16 string def /abc s cvs (abc) eq"); + check("/s 16 string def /add load s cvs (add) eq"); + check("/s 16 string def [1] s cvs (--nostringval--) eq"); + check("/s 16 string def 255 16 s cvrs (FF) eq"); + check("/s 16 string def 10 2 s cvrs (1010) eq"); + check("/s 16 string def 0 2 s cvrs (0) eq"); + check("/s 16 string def -1 16 s cvrs (FFFFFFFF) eq"); + check("/s 16 string def { 10 1 s cvrs } stopped { 10 37 s cvrs } stopped and"); +} + #[test] fn resourceforall_enumerates_matching_names() { // #234. diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 63859b3e52..260a6c0fe6 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -861,6 +861,11 @@ fn probing_operators_answer() { "/n 0 def 0 0 moveto 10 0 lineto { pop pop /n n 1 add def } { pop pop /n n 2 add def } { 6 { pop } repeat } {} pathforall n 3 eq", ); super::tests::check("1 0 0 setrgbcolor currenthsbcolor 1 eq exch 1 eq and exch 0 eq and"); + // Green largest: hue (2 + (b - r) / d) / 6 = 5/12; blue largest: (4 + (r - g) / d) / 6 = 9/12; + // each with saturation 0.8 and brightness 1. Gray has no hue and no saturation. + super::tests::check("0.2 1 0.6 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 5 sub abs 1e-5 lt and"); + super::tests::check("0.6 0.2 1 setrgbcolor currenthsbcolor 1 eq exch 0.8 sub abs 1e-6 lt and exch 12 mul 9 sub abs 1e-5 lt and"); + super::tests::check("0.5 setgray currenthsbcolor 0.5 sub abs 1e-6 lt exch 0 eq and exch 0 eq and"); super::tests::check("currentcacheparams counttomark 2 eq exch pop exch pop exch pop"); super::tests::check("cachestatus 7 { pop } repeat true"); super::tests::check("currentcolorrendering /ColorRenderingType known"); @@ -997,6 +1002,17 @@ fn hostile_patterns_glyphs_and_shadings_end() { /Function << /FunctionType 0 /Domain [0 1] /Range [0 1] /Size [99999999] /BitsPerSample 8 /DataSource () >> >> shfill", ); assert!(r.warnings[0].contains("rangecheck in `shfill`: a sampled function"), "{:?}", r.warnings); + // A sampled function of two inputs may hold 2^24 samples (4096 × 4096), and no more. + let sized = |size: &str| { + read(&format!( + "0 0 1 1 rectfill << /ShadingType 1 /ColorSpace /DeviceGray \ + /Function << /FunctionType 0 /Domain [0 1 0 1] /Range [0 1] /Size [{size}] /BitsPerSample 8 /DataSource () >> >> shfill" + )) + }; + let r = sized("4096 4096"); + assert!(!r.warnings.iter().any(|w| w.contains("error")), "{:?}", r.warnings); + let r = sized("4096 4097"); + assert!(r.warnings[0].contains("limitcheck in `shfill`: Size"), "{:?}", r.warnings); // Procedures nesting through operators that run them end at the nesting limit. for body in ["/f { { f } exec } def f", "/f { true { f } if } def f", "/f { 1 { f } repeat } def f", "/f { { f } stopped } def f"] { assert!(import(&super::tests::eps(body)).is_err(), "{body}"); diff --git a/crates/eps/src/import/tests_images.rs b/crates/eps/src/import/tests_images.rs index 87a7560bfd..2324de4eb4 100644 --- a/crates/eps/src/import/tests_images.rs +++ b/crates/eps/src/import/tests_images.rs @@ -148,6 +148,35 @@ fn filters_read_the_file_they_were_made_over() { ); } +/// LZW data (`LZWDecode`, `EarlyChange` 1, PDF 32000 §7.4.4.2) decodes: the specification's +/// example, whose third code is the entry that code adds; data long enough that the table grows +/// past 511, 1023 and 2047 entries (9-, 10-, 11- and 12-bit codes) and is cleared and grown again; +/// and a code past the end of the table is an `ioerror`, the art after it left out. +#[test] +fn lzw_data_decodes_at_every_code_width() { + super::tests::check("<800B6050220C0C8501> /LZWDecode filter 20 string readstring pop (-----A---B) eq"); + let mut x = 0x2545_F491_u32; + let data: Vec = (0..12_000) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 24) as u8 + }) + .collect(); + let lzw = craft_stream_codecs::lzw::encode(&data, true); + super::tests::check(&format!( + "/f <{}> /LZWDecode filter def f {} string readstring exch <{}> eq and f read {{ pop false }} {{ true }} ifelse and", + hex(&lzw), + data.len(), + hex(&data) + )); + // A clear-table code, then code 300 while the table ends at 257. + let r = read("0 0 10 10 rectfill <804B00> /LZWDecode filter 4 string readstring 20 20 10 10 rectfill"); + assert_eq!(super::tests::objects(&r.document).len(), 1, "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("ioerror") && w.contains("LZWDecode")), "{:?}", r.warnings); +} + /// CMYK samples keep their ink amounts in a CMYK TIFF: in the operand and dictionary forms, from /// hex and binary data, from one source or one a component, at 4, 8 and 16 bits, read through /// the Decode array. Gray and RGB images stay PNGs. @@ -656,7 +685,8 @@ fn an_image_of_more_data_than_the_reader_holds_keeps_only_the_rows_it_reads() { /// An image too large to read even at a lower resolution (its samples are more data than the /// reader holds) is left out, and its data is skipped: when a procedure reads it, the procedure /// is called until the data ends; when its first filter decompresses to more than the reader -/// holds (and can't be read a row at a time), the compressed data is measured without keeping it. +/// holds (and can't be read a row at a time), the compressed data (Flate, LZW or run-length) is +/// measured without keeping it. #[test] fn the_data_of_an_image_too_large_to_hold_is_skipped() { let after = "0 0 1 setrgbcolor 10 10 80 80 rectfill"; @@ -666,6 +696,20 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec(); flate.extend(&zeros); flate.extend(format!("\n{after}").as_bytes()); + // The same through LZW, which counts the codes up to its end-of-data code. + let mut lzw = + b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /LZWDecode filter false 3 colorimage\n".to_vec(); + lzw.extend(craft_stream_codecs::lzw::encode(&vec![0u8; 300 << 20], true)); + lzw.extend(format!("\n{after}").as_bytes()); + // Run-length data isn't decoded a row at a time either: a literal run of three bytes, runs of + // 128 bytes, and the end-of-data byte (128) after which the art follows. The literal ends in + // 200 and every run repeats 200, so a count that lands on a wrong byte reads each 200 as a + // run's length and stays off by one. + let mut run_length = b"10000 10000 8 [1 0 0 1 0 0] currentfile /RunLengthDecode filter false 3 colorimage\n".to_vec(); + run_length.extend([2, 200, 200, 200]); + run_length.extend([129u8, 200].repeat((300 << 20) / 128)); + run_length.push(128); + run_length.extend(format!("\n{after}").as_bytes()); for program in [ format!( "/F currentfile 0 (%%EndData) /SubFileDecode filter def \ @@ -673,6 +717,8 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() { ) .into_bytes(), flate, + lzw, + run_length, ] { let text = String::from_utf8_lossy(program.get(..120).unwrap_or(&program)).into_owned(); let mut file = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n".to_vec(); diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index e43f2a1227..7a0685d80a 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -722,6 +722,21 @@ fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_place assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image"); } +/// A distorted image on a layer, which the format has no form for, is written as the pieces it is +/// drawn as, with a warning. +#[test] +fn a_distorted_image_on_a_layer_is_written_as_its_pieces() { + let mut doc = Document::new(200.0, 100.0); + let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0)); + art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap(); + doc.insert(doc.default_layer(), usize::MAX, art).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == LIVE), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes).unwrap(); + assert!(text.lines().filter(|l| l.ends_with(" XI")).count() > 1, "the pieces, not one image"); +} + /// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group /// holding an image and an image; a layer `Above` holding an orange square. Without `images`, /// `Below` is empty. diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index dc40025954..aa14fcde37 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -426,6 +426,61 @@ fn strokes_keep_their_caps_joins_and_dashes() { assert!(page.contains("0 0 0 rg\n20 20 m\n80 20 l\n80 80 l\n20 80 l\n20 20 l\nh\nS\n"), "{page}"); } +/// The page for a square stroked 4 pt with `paint`, aligned `align`. +fn aligned_stroke_page(align: vectorcraft_doc::StrokeAlign, paint: impl FnOnce(&mut Document) -> Paint) -> String { + let d = doc_with(|d| { + let paint = paint(d); + let mut n = path(d, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, paint, 4.0); + for i in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = i { + s.align = align; + } + } + vec![n] + }); + page_of(&d, &opts(&d)) +} + +/// Where the first line of `page` that `matches` is. +fn line_at(page: &str, matches: impl Fn(&str) -> bool) -> Option { + page.lines().position(matches) +} + +/// A stroke inside or outside a closed path is drawn at twice its width, clipped first: inside to +/// the path, outside to everything but the path (even-odd), so only its own half shows. +#[test] +fn inside_and_outside_strokes_are_clipped_to_their_side_and_drawn_twice_as_wide() { + use vectorcraft_doc::StrokeAlign; + let black = |_: &mut Document| Paint::solid(Color::BLACK); + for (align, clip) in [(StrokeAlign::Inside, "W"), (StrokeAlign::Outside, "W*")] { + let page = aligned_stroke_page(align, black); + let clip_at = line_at(&page, |l| l == clip); + let width_at = line_at(&page, |l| l.starts_with("8 w ")); + let stroke_at = line_at(&page, |l| l == "S"); + assert!(clip_at.is_some() && clip_at < width_at && width_at < stroke_at, "{align:?}: {page}"); + let other = if clip == "W" { "W*" } else { "W" }; + assert_eq!(line_at(&page, |l| l == other), None, "{align:?}: {page}"); + } + // Centered: the width as set, with no clip. + let page = aligned_stroke_page(StrokeAlign::Center, black); + assert!(line_at(&page, |l| l.starts_with("4 w ")).is_some(), "{page}"); + assert_eq!(line_at(&page, |l| l == "W" || l == "W*"), None, "{page}"); +} + +/// A stroke painted with a pattern is written as the area it covers, filled with the pattern's +/// tiles, not as a stroke. +#[test] +fn a_pattern_stroke_is_written_as_its_filled_outline() { + let pattern = |d: &mut Document| { + let square = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + d.patterns.push(vectorcraft_doc::PatternDef::new("tile", vec![Arc::new(square)])); + Paint::Pattern { pattern: "tile".into(), xf: Affine::IDENTITY } + }; + let page = aligned_stroke_page(vectorcraft_doc::StrokeAlign::Center, pattern); + assert!(page.contains("0 0 1 rg"), "the tile is painted: {page}"); + assert_eq!(line_at(&page, |l| l == "S" || l.contains("strokepath") || l.contains(" w ")), None, "{page}"); +} + #[test] fn transparency_is_written_opaque_with_a_warning() { let d = doc_with(|d| { diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 83901874fd..1e353f309f 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -1449,6 +1449,156 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A checked write whose fill fails puts nothing in place: the error is returned, the file + /// keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_keeps_the_original_when_its_fill_fails() { + let (d, root, _) = checked_folders("checked-fill-fails"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let r = write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + assert_eq!(r.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked write canceled while it fills puts nothing in place: the error is the + /// cancellation, the file keeps its old content, and the temporary file is removed. + #[cfg(unix)] + #[test] + fn a_checked_write_canceled_while_it_fills_keeps_the_original() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + let (d, root, _) = checked_folders("checked-cancel"); + let folder = root.join("inside"); + std::fs::write(folder.join("doc.txt"), b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_checked( + &folder.join("doc.txt"), + |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }, + under(&root), + ) + }); + assert!(r.as_ref().is_err_and(|e| e.get_ref().is_some_and(|e| e.is::())), "{r:?}"); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"original"); + assert!(leftovers(&folder, "doc.txt").is_empty(), "{:?}", leftovers(&folder, "doc.txt")); + let _ = std::fs::remove_dir_all(d); + } + + /// Makes `folder` refuse new files (mode 0o555). `false`, with the folder writable again, when + /// a new file can still be created there (root ignores the mode). + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn refuse_new_files(folder: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o555)).unwrap(); + let probe = folder.join("probe"); + if std::fs::write(&probe, b"").is_ok() { + let _ = std::fs::remove_file(&probe); + std::fs::set_permissions(folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + return false; + } + true + } + + /// Files in the system's temporary folder whose names start with the temporary names a write + /// to a file named `name` uses. + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + fn system_temp_files(name: &str) -> Vec { + let prefix = format!(".{name}.{}-", std::process::id()); + std::fs::read_dir(std::env::temp_dir()) + .unwrap() + .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().to_string())) + .filter(|n| n.starts_with(&prefix)) + .collect() + } + + /// A checked write over a file whose folder refuses the rename and then any new file: the copy + /// of the file as it was goes to the system's temporary folder, the new content is copied into + /// the file, and that copy is removed afterwards. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_keeps_the_old_copy_outside_a_folder_that_takes_no_new_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-old-elsewhere.txt"; + let (d, root, _) = checked_folders("checked-old-elsewhere"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + let refused = std::cell::Cell::new(true); + let r = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"new")?; + RENAME_REFUSED.with(|c| c.set(true)); + refused.set(refuse_new_files(&folder)); + Ok(()) + }, + under(&root), + ); + RENAME_REFUSED.with(|c| c.set(false)); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + if !refused.get() { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + r.unwrap(); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(!leftovers(&folder, name).iter().any(|n| n.ends_with(".old")), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that refuses the temporary file of a checked write but lets the file itself be + /// written: the content is written in the system's temporary folder and copied in, and nothing + /// is left behind. A failed fill there leaves the file as it was. (Skipped for root.) + #[cfg(any(target_os = "linux", target_vendor = "apple"))] + #[test] + fn a_checked_write_saves_through_the_system_folder_when_its_folder_takes_no_temporary_file() { + use std::os::unix::fs::PermissionsExt; + let name = "checked-no-temp.txt"; + let (d, root, _) = checked_folders("checked-no-temp"); + let folder = root.join("inside"); + std::fs::write(folder.join(name), b"original, and longer").unwrap(); + if !refuse_new_files(&folder) { + let _ = std::fs::remove_dir_all(d); + eprintln!("skipped: the folder takes new files whatever its mode (running as root)"); + return; + } + let saved = write_atomic_checked(&folder.join(name), |f| f.write_all(b"new"), under(&root)); + let saved_content = std::fs::read(folder.join(name)).unwrap(); + let saved_temp = system_temp_files(name); + let failed = write_atomic_checked( + &folder.join(name), + |f| { + f.write_all(b"half a fi")?; + Err(io::Error::other("disk full")) + }, + under(&root), + ); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + saved.unwrap(); + assert_eq!(saved_content, b"new"); + assert!(saved_temp.is_empty(), "{saved_temp:?}"); + assert_eq!(failed.map_err(|e| e.to_string()), Err("disk full".to_string())); + assert_eq!(std::fs::read(folder.join(name)).unwrap(), b"new"); + assert!(leftovers(&folder, name).is_empty(), "{:?}", leftovers(&folder, name)); + assert!(system_temp_files(name).is_empty(), "{:?}", system_temp_files(name)); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() diff --git a/crates/format/src/unpack.rs b/crates/format/src/unpack.rs index ec9623118c..e636aadf74 100644 --- a/crates/format/src/unpack.rs +++ b/crates/format/src/unpack.rs @@ -374,6 +374,36 @@ mod tests { assert!(matches!(Unpacked::within(&gz, json.len() as u64 - 1), Err(FormatError::TooBig))); } + /// A compressed file with data after its JSON is refused past its budget on both paths: the + /// JSON before the marker where the writer puts it, and the whole file when the marker is + /// elsewhere and the file is unpacked whole. + #[test] + fn a_compressed_file_with_data_is_capped_on_both_paths() { + let with_data = |json: &[u8]| { + let mut file = json.to_vec(); + file.extend(crate::BLOB_MAGIC); + file.extend([1u8; 64]); + file + }; + let mut json = br#"{"pad":""#.to_vec(); + json.extend(std::iter::repeat_n(b'x', 4096)); + json.extend(br#""}"#); + let streamed = gzip(&with_data(&json)); + let max_json = json.len() as u64; + let opened = Unpacked::within(&streamed, max_json).unwrap(); + assert!(matches!(opened.tail, Tail::Stream { .. }), "read as a stream"); + assert_eq!(opened.json(), json.as_slice()); + assert!(matches!(Unpacked::within(&streamed, max_json - 1), Err(FormatError::TooBig))); + // No `}` before the marker: unpacked whole, within the whole-file cap and not one byte past it. + let plain = with_data(b"1"); + let whole = gzip(&plain); + let max_whole = plain.len() as u64; + let opened = Unpacked::within_capped(&whole, 64, max_whole, MAX_BLOBS).unwrap(); + assert!(matches!(opened.tail, Tail::Whole(_)), "unpacked whole"); + assert_eq!(opened.json(), b"1"); + assert!(matches!(Unpacked::within_capped(&whole, 64, max_whole - 1, MAX_BLOBS), Err(FormatError::TooBig))); + } + #[test] fn entries_sharing_bytes_obey_the_limits_in_memory_too() { // Each entry within MAX_BLOB, together past MAX_BLOBS: many references to the same bytes. diff --git a/crates/geom/src/anchors.rs b/crates/geom/src/anchors.rs index 3b9f4aa9bd..186c4b53c0 100644 --- a/crates/geom/src/anchors.rs +++ b/crates/geom/src/anchors.rs @@ -892,4 +892,27 @@ mod tests { moved.remove(0); assert_eq!(before.pairs_not_shared(&moved).count(), 10_000); } + + /// The table bytes are what the chunk table and the running totals have reserved, which is at + /// least what they hold. A short list has no running totals; a list split unevenly by an insert + /// has both, and spare capacity in either table counts. + #[test] + fn table_bytes_count_the_chunk_table_and_the_running_totals() { + let (chunk, total) = (size_of::>>(), size_of::()); + let reserved = |a: &Anchors| { + let held = a.chunks.len() * chunk + a.ends.len() * total; + let reserved = a.chunks.capacity() * chunk + a.ends.capacity() * total; + assert!(held <= reserved); + a.table_bytes() == reserved + }; + let short = Anchors::from(line(5)); + assert!(short.ends.is_empty() && reserved(&short), "{}", short.table_bytes()); + let mut uneven = Anchors::from(line(CHUNK)); + uneven.insert(10, Anchor::corner(Point::ZERO)); + assert!(uneven.chunks.len() == 2 && uneven.ends.len() == 2, "{:?}", uneven.ends); + uneven.chunks.reserve(8); + uneven.ends.reserve(8); + assert!(uneven.chunks.capacity() > uneven.chunks.len() && uneven.ends.capacity() > uneven.ends.len()); + assert!(reserved(&uneven), "{}", uneven.table_bytes()); + } } diff --git a/crates/geom/src/bez.rs b/crates/geom/src/bez.rs index 8f6b3c4a0a..6565c7d68e 100644 --- a/crates/geom/src/bez.rs +++ b/crates/geom/src/bez.rs @@ -106,4 +106,15 @@ mod tests { assert_eq!(tangent(&c[0], 1.0), Vec2::new(0.0, 1.0)); assert_eq!(unit(Vec2::ZERO), Vec2::new(1.0, 0.0)); } + + /// A quadratic whose three points coincide has no length; one whose middle point lies off its + /// coinciding ends has length. + #[test] + fn a_quad_has_length_unless_its_points_coincide() { + use kurbo::{Point, QuadBez}; + let (p, q) = (Point::new(3.0, 4.0), Point::new(9.0, -2.0)); + assert!(!has_length(&PathSeg::Quad(QuadBez::new(p, p, p)))); + assert!(has_length(&PathSeg::Quad(QuadBez::new(p, q, p)))); + assert!(has_length(&PathSeg::Quad(QuadBez::new(p, p, q)))); + } } diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs index aea7afde1d..0a56d6101c 100644 --- a/crates/geom/src/curvature.rs +++ b/crates/geom/src/curvature.rs @@ -316,6 +316,33 @@ mod tests { assert!(curvature_circle(s, 0.25, false).is_ok()); } + /// A segment that bends by a billionth of a point over 300 points is straight: the limit grows + /// with the segment's speed, so a fast segment needs a larger bend to count as curved. A bend + /// a million times larger is curved. + #[test] + fn a_fast_segment_that_barely_bends_is_straight() { + let nearly = |dy: f64| CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, dy), Point::new(200.0, 0.0), Point::new(300.0, 0.0)); + assert_eq!(curvature_circle_with(nearly(1e-9), 0.5, false, false), Err(NoCircle::Straight)); + assert_eq!(osculating(nearly(1e-9), 0.5), Err(NoCircle::Straight)); + assert!(curvature_circle_with(nearly(1e-3), 0.5, false, false).is_ok()); + } + + /// The ends of a 60° cubic at radii 100 and 105 from where their normals cross are not the + /// cubic of a circular arc, even with handles of the right length for the mean radius; the + /// same cubic with both ends at radius 100 is one. + #[test] + fn ends_at_different_radii_are_not_a_circular_arc() { + let turn = 60f64.to_radians(); + let arc = |r3: f64, mean: f64| { + let handle = 4.0 / 3.0 * (turn / 4.0).tan() * mean; + let (p0, p3) = (Point::new(100.0, 0.0), Point::new(r3 * turn.cos(), r3 * turn.sin())); + CubicBez::new(p0, p0 + Vec2::new(0.0, handle), p3 - Vec2::new(-turn.sin(), turn.cos()) * handle, p3) + }; + assert_eq!(circular_arc(arc(105.0, 102.5)), None); + let (center, radius) = circular_arc(arc(100.0, 100.0)).unwrap(); + assert!(center.distance(Point::ORIGIN) < 1e-9 && (radius - 100.0).abs() < 1e-9, "{center:?} {radius}"); + } + /// A cusp, a handle drawn back onto its anchor at that end, a segment with no length, points /// that are not finite and a `t` outside 0 to 1 have no curvature circle. #[test] diff --git a/crates/js/src/async_tests.rs b/crates/js/src/async_tests.rs index 6438392335..909b191571 100644 --- a/crates/js/src/async_tests.rs +++ b/crates/js/src/async_tests.rs @@ -194,6 +194,23 @@ fn async_function_prototype_has_its_to_string_tag() { assert_eq!(log(src), "AsyncFunction false false true [object AsyncFunction]"); } +#[test] +fn a_class_extends_async_function_and_its_instances_inherit_from_the_class() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2017 section + // 19.2.1.1.1). + let src = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + class X extends AF { tag() { return 'x'; } }\n\ + var f = new X('a', 'return a + 1');\n\ + log.push(Object.getPrototypeOf(f) === X.prototype, f instanceof AF, f.tag(), Object.prototype.toString.call(f));\n\ + f(1).then(function (v) { log.push(v); });"; + assert_eq!(log(src), "true true x [object AsyncFunction] 2"); + // The source is parsed before `new.target.prototype` is read. + let order = "var AF = Object.getPrototypeOf(async function () {}).constructor;\n\ + var NT = new Proxy(function () {}, { get: function (t, k) { if (k === 'prototype') log.push('read'); return t[k]; } });\n\ + try { Reflect.construct(AF, ['(('], NT); } catch (e) { log.push(e instanceof SyntaxError); }"; + assert_eq!(log(order), "true"); +} + #[test] fn an_await_stays_within_the_heap_limit() { // The activation, its two reactions, the derived promise and the suspended frame's bytes all diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 4314aa60f8..87c1c744c8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -172,7 +172,15 @@ impl Interp { let i = &self.intrinsics; Ok([i.object_proto, i.function_proto, i.array_proto, i.string_proto, i.number_proto, i.boolean_proto, i.regexp_proto, i.date_proto] .contains(&p) - || i.error_protos.contains(&p)) + || i.error_protos.contains(&p) + || self.dynamic_function_proto(p)) + } + + /// Is `p` the prototype of the functions that `GeneratorFunction` or `AsyncFunction` makes? + /// Both constructors take a subclass's prototype from `new.target` (ECMA-262 2017 sections + /// 25.2.1.1 and 25.5.1.1, through CreateDynamicFunction in section 19.2.1.1.1). + fn dynamic_function_proto(&self, p: ObjId) -> bool { + self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) || self.promises.async_function_proto == Some(p) } /// `new.target`'s `prototype` when it is an object, otherwise `fallback` (section 9.1.14). @@ -367,13 +375,13 @@ impl Interp { return Err(self.type_error("the Promise executor is not a function")); } // `Number`, `String` and `Date` convert arguments before reading `prototype` - // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function` and `GeneratorFunction` - // convert and parse source first (sections 19.2.1.1.1 and 25.2.1.1). + // (sections 20.1.1.1, 21.1.1.1 and 20.4.2). `Function`, `GeneratorFunction` and + // `AsyncFunction` convert and parse source first (sections 19.2.1.1.1, 25.2.1.1 + // and 25.5.1.1). let converts_first = { let i = &self.intrinsics; intrinsic.is_some_and(|p| { - [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) - || self.symbols.objects.is_some_and(|o| p == o.generator_function_proto) + [i.number_proto, i.string_proto, i.date_proto, i.function_proto].contains(&p) || self.dynamic_function_proto(p) }) }; let fallback = intrinsic.unwrap_or(self.intrinsics.object_proto); diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 1a076c43c1..ec43bfe327 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,17 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn a_block_function_in_eval_in_a_default_parameter_leaves_a_parameter_of_its_name_alone() { + // A parameter between the eval code and its variable environment has the name, so the block + // function gets no variable (Annex B.3.2.3) and the parameter keeps its value. + truth("function f(a = eval('{ function a() {} }'), b = a) { return typeof b; } f() === 'undefined'"); + truth("function f(a = 1, b = eval('{ function a() {} }'), c = a) { return c + typeof a; } f() === '1number'"); + truth("function f(a = 2, b = eval('{ function a() {} }')) { return a; } f() === 2"); + // A name that no parameter has still gets the variable. + truth("function f(x = eval('{ function a() { return 3; } }'), b = a) { return b(); } f() === 3"); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); diff --git a/crates/js/src/generator_tests.rs b/crates/js/src/generator_tests.rs index 551fb4e5e6..19eb0c1edf 100644 --- a/crates/js/src/generator_tests.rs +++ b/crates/js/src/generator_tests.rs @@ -253,6 +253,23 @@ fn bad_generators_are_syntax_errors() { truth("function* g(a = function* () { yield 2; }, b = (c = function* () { yield 3; }) => c) { yield* b()(); } g().next().value === 3"); } +#[test] +fn a_class_extends_generator_function_and_function() { + // CreateDynamicFunction takes the prototype from `new.target` (ECMA-262 2015 section + // 19.2.1.1.1). + truth( + "var GF = Object.getPrototypeOf(function* () {}).constructor;\n\ + class G extends GF { tag() { return 'g'; } }\n\ + var g = new G('yield 7');\n\ + Object.getPrototypeOf(g) === G.prototype && g instanceof GF && g.tag() === 'g' && g().next().value === 7", + ); + truth( + "class F extends Function { tag() { return 'f'; } }\n\ + var f = new F('a', 'return a * 2');\n\ + Object.getPrototypeOf(f) === F.prototype && f.tag() === 'f' && f(3) === 6", + ); +} + #[test] fn realms_without_es2015_have_no_generators() { let es5 = Options::default(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 0639d52d25..3784b3a515 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4813,7 +4813,8 @@ impl Interp { /// A block function's variable in script or eval code can be declared (Annex B.3.3.2 and /// B.3.3.3, ): no /// `let`, `const` or block function from `env` out to `var_env` has the name, a `catch` - /// parameter does not count, and on the global object the name is its own property or the + /// parameter does not count, no parameter has the name when the code is in a default + /// parameter's value (B.3.2.3), and on the global object the name is its own property or the /// object is extensible. Each environment passed takes a unit of fuel. fn annex_var_declarable(&mut self, name: &Key, env: EnvId, var_env: EnvId) -> JsResult { let mut cur = Some(env).filter(|&e| e != var_env); @@ -4832,7 +4833,14 @@ impl Interp { .filter(|&o| o != var_env); } if var_env != self.global_env { - return Ok(true); + // Eval code in a default parameter's value declares into the parameters' environment, + // where the parameters are lexical bindings. + self.use_fuel()?; + return match self.heap.env(var_env) { + Some(Env::Decl { bindings, .. }) => Ok(!bindings.get(name).is_some_and(|b| b.lexical)), + Some(Env::Obj { .. }) => Ok(true), + None => internal("environment out of range"), + }; } let global = self.global; Ok(self.get_own_property(global, name)?.is_some() || self.object(global)?.extensible) diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index 850846abe1..0cfb20cce2 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -266,7 +266,10 @@ impl Parser<'_> { self.bump()?; return self.export_default(info, span).map(Some); } - let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some(); + let exportable = self.at_keyword(Keyword::Var) + || self.at_keyword(Keyword::Function) + || self.at_async_function() + || self.at_lexical_declaration().is_some(); if !exportable { return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok)))); } @@ -287,7 +290,7 @@ impl Parser<'_> { if self.at_keyword(Keyword::Class) { return Err(self.error_at_token(&self.tok, "classes are not supported")); } - if self.at_keyword(Keyword::Function) { + if self.at_keyword(Keyword::Function) || self.at_async_function() { self.enter()?; let result = self.default_function(); self.leave(); @@ -305,19 +308,22 @@ impl Parser<'_> { Ok(stmt) } - /// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of - /// `name`, or of [`DEFAULT_BINDING`] for a function without one. + /// `function name(…) {…}` or `function (…) {…}` after `export default`, either one optionally + /// `async`: a declaration of `name`, or of [`DEFAULT_BINDING`] for a function without one. fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> { + let is_async = self.at_async(); + let async_start = if is_async { Some(self.bump()?.span) } else { None }; let keyword = self.expect_keyword(Keyword::Function)?; - let start = keyword.span; - let generator = self.es2015 && self.eat(Punct::Star)?; + let start = async_start.unwrap_or(keyword.span); + // Async generators (ECMAScript 2018) stay syntax errors, as in a plain declaration. + let generator = !is_async && self.es2015 && self.eat(Punct::Star)?; let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { self.function_name()? } else { (Name { name: DEFAULT_BINDING.into(), span: start }, keyword) }; let local = name.0.name.clone(); - let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, false)?; + let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start, generator, is_async)?; let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start)); Ok((stmt, fid, local)) } @@ -410,6 +416,36 @@ mod tests { assert_eq!(realm.run("out.join('|')"), Ok(crate::JsValue::String("true".into()))); } + #[test] + fn async_function_declarations_are_exported() { + let options = Options { es2015: true, es2017: true, ..Options::default() }; + let cases = [ + ("export async function f() {}", "f", "f"), + ("export default async function f() {}", "default", "f"), + ("export default async function () {}", "default", crate::ast::DEFAULT_BINDING), + ]; + for (source, export, binding) in cases { + let (program, info) = match parse_module(source, &options) { + Ok(parsed) => parsed, + Err(error) => panic!("{source}: {error:?}"), + }; + assert!( + matches!(info.exports.as_slice(), [crate::ExportEntry::Local { export_name, local, .. }] if export_name == export && local == binding), + "{source}: {:?}", + info.exports + ); + let declared = program.body.iter().any(|&stmt| match program.ast.stmt(stmt) { + Some(crate::ast::Stmt::FunctionDecl(fid)) => program.ast.function(*fid).is_some_and(|f| f.is_async), + _ => false, + }); + assert!(declared, "{source}: an async function declaration"); + } + // A line break after `async` ends the declaration; the export is then an expression. + assert!(parse_module("export async\nfunction f() {}", &options).is_err()); + // Without ES2017, `async` is an identifier and cannot start an exported declaration. + assert!(parse_module("export async function f() {}", &Options { es2015: true, ..Options::default() }).is_err()); + } + #[test] fn module_specifiers_reject_legacy_octal_escapes() { for source in diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 0d82f5086d..345e1ff995 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1768,7 +1768,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.placementOptionsDialog", "Placement Options…", "", - "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)", ), ( "ui.relinkDialog", diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index ef282e5b4d..c0efa55a0b 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -99,12 +99,22 @@ impl crate::Renderer { // Trim View clips each draw when blending reaches the page and clips one composited // layer otherwise. Changing modes can change unchanged art at an artboard edge. if opts.trim && !old.artboards.is_empty() { + // `children_blend` caches the groups it reads in `blends`, which holds their nodes, + // so this counts as a measurement for `finish_measurement_only`. + self.measuring = true; let before = crate::proof::prepare(old, opts, &mut self.proof_art); let after = crate::proof::prepare(new, opts, &mut self.proof_art); if self.children_blend(&before.layers) != self.children_blend(&after.layers) { return Changed::Everything; } } + // A change outside the layers (symbol definitions among them) redraws everything without + // measuring anything here; the caches still age so that bounds kept for the old + // definitions expire. + if new.pattern_edit.is_some() || !old.same_outside_layers(new) { + self.measuring = true; + return Changed::Everything; + } let renderer = (!crate::proof::overprints(opts)).then_some(self); changed_with(old, new, renderer, opts) } @@ -249,7 +259,11 @@ impl Diff<'_, '_> { Side::New => new, }; match renderer { - Some(r) => r.bounds_of(symbols, n), + Some(r) => { + // Only a measurement ages the renderer's caches in `finish_measurement_only`. + r.measuring = true; + r.bounds_of(symbols, n) + } None => crate::brush_fx::cull_bounds(symbols, n), } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 544438d96f..4358cc180d 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -182,6 +182,9 @@ pub struct Renderer { /// ([`lru::MEASURED_BUDGET`]). measured_bytes: usize, measured_budget: usize, + /// [`Renderer::changed`] measured through this renderer since its last frame began or since + /// [`Renderer::finish_measurement_only`] last aged its caches. + measuring: bool, /// The export bounds of the objects measured without their hidden members /// (`encode::drawn_bounds`), by the object they were made from: kept for a pass over artboards, /// let go when a frame ends. diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 065055f96c..fdf7847412 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -76,6 +76,7 @@ impl Renderer { measured: PtrMap::default(), measured_bytes: 0, measured_budget: lru::MEASURED_BUDGET, + measuring: false, pass_bounds: PtrMap::default(), three_d_bounds: PtrMap::default(), three_d_kept: 0, @@ -244,6 +245,7 @@ impl Renderer { /// Start a frame: cache entries used from now on are marked with its stamp. fn begin_frame(&mut self) { self.stamp += 1; + self.measuring = false; self.inline_depth = 0; // Nothing is drawn offscreen yet (even if an earlier frame stopped part way). (self.offscreen_live, self.offscreen_budget) = (0, 0); @@ -267,7 +269,12 @@ impl Renderer { /// Finish measuring an edit whose frame is drawn elsewhere or needs no pixel update. /// Age the measurement caches and keep the previous draw's effect rasters available. + /// Without a [`Self::changed`] since the last frame or the last call, nothing changes: + /// the paths of the last frame stay for this renderer's next frame. pub fn finish_measurement_only(&mut self) { + if !std::mem::take(&mut self.measuring) { + return; + } self.stamp += 1; self.sweep_node_geometry(); let g = self.stamp; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 99ee9a5f0c..9ee678965c 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1730,6 +1730,33 @@ fn a_kept_decoded_image_is_drawn_without_decoding_it() { assert!(!image_cached(&cmyk)); } +/// Pixels [`keep_decoded_image`] refuses (here, pixels past the decode allowance) are not +/// kept anywhere: the first render that draws the image decodes it, as for any image. +#[test] +fn a_refused_decoded_image_is_decoded_when_first_drawn() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + // Pixels no other test uses, since every test shares the store. + let img = image::RgbaImage::from_fn(29, 17, |x, y| image::Rgba([(x * 5) as u8, (y * 13) as u8, 41, 255])); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let blob = ImageBlob::new("image/png", png.clone()); + paint::TEST_ALLOWANCE.with(|c| c.set(Some(64))); + let kept = keep_decoded_image(&blob, image::load_from_memory(&png).unwrap()); + paint::TEST_ALLOWANCE.with(|c| c.set(None)); + assert!(!kept, "past the allowance: the pixels are refused"); + assert!(!image_cached(&blob)); + let mut d = Document::new(29.0, 17.0); + d.images.insert("refused".into(), blob); + let id = d.alloc_id(); + let im = + ImageObject { key: "refused".into(), width: 29, height: 17, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + let decodes = image_decodes(); + let r = Renderer::new().render(&d, 29, 17, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(image_decodes(), decodes + 1, "the first draw decodes the image"); + assert!(r.pixel(14, 8)[3] > 0, "the image is drawn"); +} + /// A CMYK image's inks and the pixels shown from them are admitted against the decode allowance /// before either is made: past it, the image is read as other images are (reduced), not whole. #[test] diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 8579c314b8..023a62bad3 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -34,6 +34,54 @@ fn geometry_from_measurement_only_frames_releases_old_node_versions() { assert!(oldest.upgrade().is_none(), "obsolete measured nodes must be released without a full draw"); } +/// The canvas finishes a measurement in every frame that waits for another renderer's frame, also +/// when it measured nothing (a zoom or a pan). Those frames keep the paths this renderer drew, so +/// its next frame, the next step of a pan, does not build them all again. +#[test] +fn finishing_without_a_measurement_keeps_the_drawn_paths() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize; + let mut renderer = Renderer::new(); + renderer.render(&doc, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert!(renderer.geom.contains_key(&drawn), "the frame keeps the path it drew"); + for _ in 0..8 { + renderer.finish_measurement_only(); + } + assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); +} + +/// Comparing a document with itself measures nothing, so the frames that follow keep the paths +/// this renderer drew. +#[test] +fn an_unchanged_document_keeps_the_drawn_paths() { + let mut doc = Document::new(100.0, 100.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let path = Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(5.0, 10.0, 25.0, 30.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + doc.insert(Some(layer), 0, path).unwrap(); + let drawn = Arc::as_ptr(&doc.layers[0].children().unwrap()[0]) as usize; + let mut renderer = Renderer::new(); + let opts = RenderOptions::default(); + renderer.render(&doc, 100, 100, Affine::IDENTITY, &opts); + for _ in 0..4 { + assert!(matches!(renderer.changed(&doc, &doc, &opts), Changed::Nothing)); + renderer.finish_measurement_only(); + } + assert!(renderer.geom.contains_key(&drawn), "frames that measured nothing keep the drawn path"); +} + /// A `w`×`h` PNG whose pixels depend on `seed` (each test its own image: the store is shared by /// the tests running alongside). fn png(w: u32, h: u32, seed: u8) -> Vec { diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e8c84530d5..140b94e183 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -85,9 +85,8 @@ fn physical_num(v: f64) -> String { return "0".into(); } let leading_zeros = (-v.log10().floor() as i32).max(0); - let decimals = (leading_zeros + 3).clamp(3, 14) as u8; - let s = fmt_num(v, decimals); - if s == "0" && v > 0.0 { format!("{v:.16}").trim_end_matches('0').trim_end_matches('.').to_string() } else { s } + let decimals = (leading_zeros + 3).max(3); + if decimals > 14 { format!("{v:e}") } else { fmt_num(v, decimals as u8) } } /// `doc` as SVG with `opts`, the native file `native` embedded for Preserve Editing, its generated @@ -186,7 +185,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: .join(nl); svg.doctype_internal("svg", &entities, nl); } - let (ww, hh) = (w.num(rect.width()), w.num(rect.height())); + // A positive pixel size that the chosen decimals round to 0 is written with enough digits to stay positive. + let nonzero = |v: f64, s: String| if v > 0.0 && s == "0" { physical_num(v) } else { s }; + let (ww, hh) = (nonzero(rect.width(), w.num(rect.width())), nonzero(rect.height(), w.num(rect.height()))); let mut root = svg.root().attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); for (ns, prefix) in &w.foreign_ns { root = root.attr(&format!("xmlns:{prefix}"), ns); @@ -197,7 +198,9 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: if !opts.responsive { // Explicit SVG Options override the document unit; absence keeps its native save behavior. if let Some(unit) = opts.units { - let (width, height) = (unit.length(rect.width(), opts.decimals), unit.length(rect.height(), opts.decimals)); + // Pixels are written bare at one per point. + let (width, height) = + (nonzero(rect.width(), unit.length(rect.width(), opts.decimals)), nonzero(rect.height(), unit.length(rect.height(), opts.decimals))); root = root.attr("width", &width).attr("height", &height); } else if let Some((unit, suffix)) = doc.units.svg_unit().and_then(|u| Some((u, u.svg_suffix()?))) { let w_val = physical_num(unit.from_pt(rect.width())); @@ -207,9 +210,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: root = root.attr("width", &ww).attr("height", &hh); } } - let vb_w = if rect.width() > 0.0 && ww == "0" { physical_num(rect.width()) } else { ww.clone() }; - let vb_h = if rect.height() > 0.0 && hh == "0" { physical_num(rect.height()) } else { hh.clone() }; - root.attr("viewBox", format_args!("0 0 {vb_w} {vb_h}")).open(); + root.attr("viewBox", format_args!("0 0 {ww} {hh}")).open(); let mut out = svg.as_str().to_string(); out.push_str(nl); let css = opts.styling == Styling::InternalCss && !w.classes.is_empty(); diff --git a/crates/svg/tests/it/import_units.rs b/crates/svg/tests/it/import_units.rs index 91138d8a93..1c17c156fe 100644 --- a/crates/svg/tests/it/import_units.rs +++ b/crates/svg/tests/it/import_units.rs @@ -3,7 +3,7 @@ use vectorcraft_doc::{Document, Node, NodeKind, Unit}; use vectorcraft_geom::Rect; -use vectorcraft_svg::{ExportOptions, export, import}; +use vectorcraft_svg::{ExportOptions, SizeUnit, export, import}; fn art(d: &Document) -> Vec<&Node> { let mut v = Vec::new(); @@ -191,6 +191,28 @@ fn export_physical_units_writes_unit_suffixes() { // Re-importing preserved physical units let back = import(&s).unwrap(); assert_eq!(back.units, Unit::Millimeters); + + // A small positive size in pixels keeps a nonzero width and height, with the document unit + // and with Pixels chosen in the SVG options + for (w, h) in [(0.0004, 0.0002), (1e-17, 2e-17), (5.1e-17, 1e-17), (5.1e-15, 4.9e-15)] { + let mut d = Document::new(w, h); + d.units = Unit::Pixels; + for opts in [ExportOptions::default(), ExportOptions { units: Some(SizeUnit::Px), ..Default::default() }] { + let s = export(&d, &opts); + let num = |name: &str| -> f64 { root_attr(&s, name).and_then(|v| v.parse().ok()).unwrap_or_else(|| panic!("{name}: {s}")) }; + let view: Vec = root_attr(&s, "viewBox").unwrap_or_default().split(' ').filter_map(|v| v.parse().ok()).collect(); + for (got, want) in [(num("width"), w), (num("height"), h), (view[2], w), (view[3], h)] { + assert!((got - want).abs() <= want * 1e-3, "{got} for {want}: {s}"); + } + } + } +} + +/// The value of attribute `name` on `svg`'s root element. +fn root_attr<'a>(svg: &'a str, name: &str) -> Option<&'a str> { + let start = svg.find("').next()?; + tag.split(&format!(" {name}=\"")).nth(1)?.split('"').next() } /// The `width` of `svg`'s root as a length in points, read by the SVG and CSS absolute units diff --git a/crates/ui-egui/src/addons/cleanup.rs b/crates/ui-egui/src/addons/cleanup.rs index 8ce1aa6812..1b012b66f7 100644 --- a/crates/ui-egui/src/addons/cleanup.rs +++ b/crates/ui-egui/src/addons/cleanup.rs @@ -8,10 +8,11 @@ use craft::behavior::{DisplayOrder, ItemSource, Selection}; use craft::keymap::Mods; use craft::menu::Node; use craft::ui::buttons::Button; -use craft::ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; use craft::ui::layout_components::Row; use craft::ui::list::{List, ListRow}; +use craft::ui::menu::{Menu, MenuItem}; use craft::ui::sections::Section; use egui::Ui; use serde_json::{Value, json}; @@ -136,6 +137,8 @@ pub(crate) struct Results { rows: Vec<(String, String, u64)>, /// The rows picked in the list, by position in `rows`. picked: Selection, + /// The clicked finding and the kinds to fix, captured when its menu opens. + menu: Option<(String, Vec)>, /// What the last fix did. status: String, } @@ -320,14 +323,41 @@ fn text_tools(ui: &mut Ui, selected: bool, editing: bool, action: &mut Option) { let source = Positional { rows: &r.rows, label: |row| row.1.as_str() }; - List::::new(tl!("Issues").to_string()).empty(tl!("No issues found.").to_string()).selection(Bind::bound(&mut r.picked)).show_items( - ui, - &source, - &mut |key, _| match r.rows.get(*key) { - Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()), + let mut selection = r.picked.clone(); + let out = List::::new(tl!("Issues")) + .id(ui.scope_id().with(("cleanup-issues", r.doc))) + .select(SelectMode::Multi) + .row_menu() + .empty(tl!("No issues found.").to_string()) + .selection(Bind::bound(&mut selection)) + .show_items(ui, &source, &mut |key, item| match r.rows.get(*key) { + Some((_, label, count)) => ListRow::new(tl!(label).to_string()).trailing(count.to_string()).state(item.row.clone()), None => ListRow::spacer(), - }, - ); + }); + if let Some(key) = out.events.iter().find_map(|event| match event { + CollectionEvent::ContextMenu(request) => Some(request.key), + _ => None, + }) { + if !r.picked.items.contains(&key) { + r.picked = Selection::single(key); + } + r.menu = r.rows.get(key).map(|row| (row.0.clone(), r.picked_kinds())); + } else { + r.picked = selection; + } + if let Some((kind, kinds)) = &r.menu { + let menu = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Show Affected Artwork")).show(ui).ran { + *action = Some(Action::Show(kind.clone())); + } + if MenuItem::new(tl!("Fix Selected")).show(ui).ran { + *action = Some(Action::Fix(kinds.clone())); + } + }); + if menu.output.closed.is_some() || action.is_some() { + r.menu = None; + } + } if !r.status.is_empty() { Text::new(r.status.clone()).show(ui); } diff --git a/crates/ui-egui/src/addons/cleanup/tests.rs b/crates/ui-egui/src/addons/cleanup/tests.rs index 1b414177fb..072eb5e8fc 100644 --- a/crates/ui-egui/src/addons/cleanup/tests.rs +++ b/crates/ui-egui/src/addons/cleanup/tests.rs @@ -3,6 +3,7 @@ use vectorcraft_engine::Session; use super::{check, current, fix}; use crate::VectorcraftApp; +use crate::tests::panel_harness::Panel; /// An app with a rectangle and a stray point (a path of one anchor), nothing selected. fn app() -> VectorcraftApp { @@ -46,3 +47,52 @@ fn a_fix_with_no_results_does_nothing() { assert!(app.addon_panels.cleanup.is_none()); assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "nothing was fixed without a check"); } + +#[test] +fn a_selected_rows_menu_shows_its_own_artwork_and_fixes_the_whole_selection() { + let mut app = app(); + let outside = app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + check(&mut app, None); + let mut panel = Panel::new(app, super::show); + panel.click("Off-Artboard Art"); + panel.click_with("Stray Points", egui::Modifiers::SHIFT); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Show Affected Artwork"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(outside)]); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Fix Selected"); + assert!(current(&panel.app()).unwrap().rows.is_empty(), "both findings were fixed"); +} + +#[test] +fn opening_the_menu_on_an_unselected_row_fixes_only_that_finding() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 500, "y": 500, "width": 20, "height": 20})).unwrap(); + check(&mut app, Some("document")); + let mut panel = Panel::new(app, super::show); + panel.click("Stray Points"); + panel.secondary_click("Off-Artboard Art"); + panel.click_menu_item("Fix Selected"); + let app = panel.app(); + let remaining = ¤t(&app).unwrap().rows; + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].0, "strayPoints"); +} + +#[test] +fn dismissing_the_keyboard_menu_returns_focus_to_the_finding() { + let mut app = app(); + check(&mut app, None); + let mut panel = Panel::new(app, super::show); + panel.focus("Stray Points"); + panel.key(egui::Key::F10, egui::Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Show Affected Artwork")); + panel.key(egui::Key::Escape, egui::Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(panel.focused("Stray Points")); + assert!(!panel.shows("Show Affected Artwork")); +} diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index a6aa04dfc7..7a0de94cb4 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -23,7 +23,7 @@ use craft::ui::display::{Divider, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row as Line; use craft::ui::list::{Finding, Findings, FindingsList, FindingsWords, List, ListRow, Severity, ThumbSize}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::UnitKind; use craft::ui::text::NumberField; @@ -149,6 +149,8 @@ fn doc_key(app: &VectorcraftApp) -> Option { pub(crate) struct FoldLines { /// The last check of each document. checks: Checks, + /// The immutable check and row on which the context menu opened. + menu: Option<(Weak, usize)>, /// The role rows for the document state they were read for. rows: Rows, } @@ -210,22 +212,45 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } - let Some(checked) = last_check(app) else { return }; + let Some(checked) = last_check(app) else { + app.addon_panels.fold.menu = None; + return; + }; Text::new(crate::i18n::msg(&checked.summary())).show(ui); let findings: Vec = (0u64..) .zip(&checked.issues) .map(|(id, issue)| Finding::new(id, if issue.error { Severity::Error } else { Severity::Warning }, crate::i18n::msg(&issue.message))) .collect(); - let out = - FindingsList::new(tl!("Issues").to_string()).show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) { - Some(finding) => finding.row(&icx.words::()), - None => ListRow::spacer(), - }); - for event in &out.events { - if let CollectionEvent::Activate(n) = event { - select_issue(app, &checked, *n as usize); + let list = FindingsList::new(tl!("Issues").to_string()).id(ui.scope_id().with(("fold-issues", Arc::as_ptr(&checked)))); + let out = list.show_items(ui, &Findings::new(&findings), &mut |key, icx| match findings.get(*key as usize) { + Some(finding) => finding.row(&icx.words::()).row_menu(), + None => ListRow::spacer(), + }); + for event in out.events { + match event { + CollectionEvent::Activate(n) => select_issue(app, &checked, n as usize), + CollectionEvent::ContextMenu(request) => app.addon_panels.fold.menu = Some((Arc::downgrade(&checked), request.key as usize)), + _ => {} } } + let Some((owner, n)) = &app.addon_panels.fold.menu else { return }; + let n = *n; + let Some(issue) = checked.issues.get(n).filter(|_| owner.as_ptr() == Arc::as_ptr(&checked)) else { + app.addon_panels.fold.menu = None; + return; + }; + let shown = Menu::context(tl!("Issues"), &out.response).show(ui, |ui, _| { + if MenuItem::new(tl!("Select Affected Objects")).enabled(!issue.ids.is_empty()).show(ui).ran { + select_issue(app, &checked, n); + } + if MenuItem::new(tl!("Copy Finding")).show(ui).ran { + app.clipboard_out = Some(crate::i18n::msg(&issue.message)); + app.status(tl!("Copied finding")); + } + }); + if shown.output.closed.is_some() { + app.addon_panels.fold.menu = None; + } } /// One role row: (role id, swatch name, the swatch's paint if the document has it, count). @@ -346,6 +371,7 @@ fn role_label(role: &str) -> &str { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(selected) = app.session.active().map(|st| !st.selection.is_empty()) else { + app.addon_panels.fold.menu = None; empty_state(ui, "scissors", tl!("No document"), tl!("Open a document to mark its fold lines.")); return; }; diff --git a/crates/ui-egui/src/addons/packaging/tests.rs b/crates/ui-egui/src/addons/packaging/tests.rs index 26d9ac729b..ea89dcd928 100644 --- a/crates/ui-egui/src/addons/packaging/tests.rs +++ b/crates/ui-egui/src/addons/packaging/tests.rs @@ -116,6 +116,58 @@ fn each_document_keeps_its_own_check() { assert!(last_check(&app).is_some_and(|kept| Arc::ptr_eq(&kept, &second))); } +#[test] +fn a_finding_menu_selects_its_objects_and_restores_keyboard_focus_on_escape() { + let (mut app, slit) = blank(); + let checked = run_check(&mut app, json!({})).unwrap(); + let row = format!("{}, Error", checked.issues[0].message); + let mut panel = Panel::new(app, super::show_check); + panel.focus(&row); + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Select Affected Objects")); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(panel.focused(&row)); + panel.secondary_click(&row); + panel.frame(); + panel.click_menu_item("Select Affected Objects"); + assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(slit)]); +} + +#[test] +fn a_recheck_and_a_document_switch_dismiss_the_menu_and_an_objectless_finding_can_be_copied() { + let (mut app, a, _) = app(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let checked = run_check(&mut app, json!({})).unwrap(); + let row = format!("{}, Error", checked.issues[0].message); + let mut panel = Panel::new(app, super::show_check); + panel.secondary_click(&row); + panel.frame(); + assert!(!panel.menu_item_enabled("Select Affected Objects")); + panel.click_menu_item("Copy Finding"); + assert_eq!(panel.app().clipboard_out.as_deref(), Some(checked.issues[0].message.as_str())); + assert_eq!(panel.app().session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(a)]); + + panel.secondary_click(&row); + panel.frame(); + assert!(panel.shows("Copy Finding")); + let replacement = run_check(&mut panel.app(), json!({"ids": [a]})).unwrap(); + panel.frame(); + assert!(!panel.shows("Copy Finding")); + assert!(!panel.shows("Select Affected Objects")); + panel.secondary_click(&format!("{}, Error", replacement.issues[0].message)); + panel.frame(); + assert!(panel.shows("Copy Finding")); + panel.app().run("file.new", json!({"width": 100, "height": 100})).unwrap(); + run_check(&mut panel.app(), json!({})).unwrap(); + panel.frame(); + assert!(!panel.shows("Copy Finding")); + assert!(!panel.shows("Select Affected Objects")); +} + /// The messages `addon.packaging.check` gives its issues, one for each code (three for `noCut`). const ISSUE_MESSAGES: [&str; 17] = [ "No cut lines are in the selection.", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 628d39faac..442ddaffbf 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -168,6 +168,8 @@ impl VectorcraftApp { carry_target: None, last_drag: None, escaped_press: false, + pressed_at: None, + keys_at: None, host_caps_lock: None, committed_preview: false, panes: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 58b2e6c803..6dcec22bff 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -129,6 +129,12 @@ pub struct CanvasCache { /// Escape cancelled the tool's press while the button is still down: its release still sends the tool its Up, /// which gives back a selection tool Cmd lent. pub escaped_press: bool, + /// The input time of the last pass whose pointer button events all landed on a canvas, with no other layer over it: + /// the menus' state key leaves such a press out (`menus::model::last_press`). + pub pressed_at: Option, + /// The input time of the last pass in which the canvas or nothing had the focus, so that the canvas or the app's + /// shortcuts took its keys: the menus' state key leaves those keys out (`menus::model::last_press`). + pub keys_at: Option, /// The host's Caps Lock state at the last canvas pass, which `VectorcraftApp::follow_caps_lock` compares with the /// next reading; `None` before the first pass. pub host_caps_lock: Option, diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index bfef665bb8..a52c6d64c1 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -1,3 +1,5 @@ +use craft::behavior::IconId; +use craft::menu::Item; use craft::ui::canvas::CanvasSpace; use craft::ui::contract::overlay::Anchor; use craft::ui::contract::{Bind, ShowContainer as _, Trigger}; @@ -47,7 +49,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp .opened_by(opener, Trigger::Manual) .anchor(Anchor::Point(at)) .open(Bind::bound(&mut open)) - .show(ui, |ui, _| craft::menu::context::rows(ui, &nodes)); + .show(ui, |ui, _| craft::menu::context::rows_with_icons(ui, &nodes, canvas_icon)); if shown.output.closed.is_some() || !open { app.ui.context_menu_at = None; app.ui.context_locked = None; @@ -57,6 +59,54 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp } } +/// The icon each canvas menu command shows in this menu, so a row can be found by its shape (#4602). A command +/// left out has no glyph that says what it does here, and shows its catalog icon, if any, or none. +const ICONS: &[(&str, &str)] = &[ + ("edit.undo", "undo-2"), + ("edit.redo", "redo-2"), + ("edit.cut", "scissors"), + ("edit.copy", "copy"), + ("edit.paste", "clipboard-paste"), + ("edit.clear", "trash-2"), + ("object.group", "group"), + ("object.ungroup", "ungroup"), + ("object.path.smooth", "dc-smooth"), + ("object.objectsOnPath.attach", "dc-objects-on-path"), + ("path.join", "dc-join"), + ("type.applyBullets", "dc-para-bullets"), + ("type.applyNumbers", "dc-para-numbers"), + ("view.grid", "grid-3x3"), + ("view.rulers", "ruler"), + ("view.guides.lock", "lock"), + ("view.fitArtboard", "maximize-2"), + ("artboard.new", "file-plus"), + ("artboard.duplicate", "copy"), + ("artboard.copy", "copy"), + ("artboard.cut", "scissors"), + ("artboard.delete", "trash-2"), + ("artboard.rearrange", "dc-rearrange"), + ("file.exportSelection", "share-2"), + ("file.exportForScreens", "share-2"), +]; + +/// The icons of rows whose command alone doesn't say what they do: Artboard Options (`tool.options` for the +/// Artboard tool) and the Lock Artboards and Unlock Artboards rows (`artboard.setProps` with `locked`). +const ARTBOARD_OPTIONS_ICON: &str = "dc-artboard-options"; +const LOCK_ICON: &str = "lock"; +const UNLOCK_ICON: &str = "lock-open"; + +/// The canvas menu's icon for `item`: Artboard Options' and the artboard lock rows' by their parameters, otherwise +/// its command's entry in [`ICONS`]. +fn canvas_icon(item: &Item) -> Option { + let params = &item.command.params; + let icon = match item.command.id.as_str() { + "tool.options" => (params["tool"] == "artboard").then_some(ARTBOARD_OPTIONS_ICON), + "artboard.setProps" => params["artboards"][0]["locked"].as_bool().map(|locked| if locked { LOCK_ICON } else { UNLOCK_ICON }), + id => ICONS.iter().find(|(command, _)| *command == id).map(|(_, icon)| *icon), + }; + icon.map(IconId::new) +} + /// The one-shot work of a request at screen point `at`: the facts the menu's rows read, and the selection. fn prepare(app: &mut VectorcraftApp, space: &CanvasSpace, at: Pos2) { let p = space.view.to_doc(at); @@ -114,3 +164,47 @@ fn prepare_key(app: &mut VectorcraftApp, space: &CanvasSpace) -> Pos2 { } at } + +#[cfg(test)] +mod tests { + use craft::behavior::IconId; + use craft::ui::primitives::has_icon; + + use craft::menu::Node; + use serde_json::json; + + use super::{ARTBOARD_OPTIONS_ICON, ICONS, LOCK_ICON, UNLOCK_ICON, canvas_icon}; + use crate::menus::cp; + + /// Each canvas menu icon names a drawn icon and a command: a misspelt icon would leave its row's icon slot + /// empty, and a renamed command would quietly lose its icon. + #[test] + fn every_canvas_menu_icon_is_an_icon_of_a_command() { + crate::icons::register(); + for (id, icon) in ICONS { + assert!(has_icon(&IconId::new(icon)), "{id}'s icon {icon} isn't an icon"); + let ui_command = crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id); + assert!(vectorcraft_engine::find_command(id).is_some() || ui_command, "{id} isn't a command"); + } + for icon in [ARTBOARD_OPTIONS_ICON, LOCK_ICON, UNLOCK_ICON] { + assert!(has_icon(&IconId::new(icon)), "{icon} isn't an icon"); + } + } + + /// Rows that share a command take their icon from their parameters: the Artboard Options glyph goes on + /// Artboard Options (`tool.options` for the Artboard tool), not on another tool's options, and the Lock + /// Artboards and Unlock Artboards rows (`artboard.setProps`) show a closed and an open lock. + #[test] + fn rows_that_share_a_command_take_their_icon_from_its_parameters() { + let icon = |node: Node| match node { + Node::Item(item) => canvas_icon(&item), + _ => None, + }; + let lock = |locked| cp("Lock All", "artboard.setProps", json!({ "artboards": [{ "index": 0, "locked": locked }] })); + assert_eq!(icon(cp("Artboard Options", "tool.options", json!({ "tool": "artboard" }))), Some(IconId::new(ARTBOARD_OPTIONS_ICON))); + assert_eq!(icon(cp("Options", "tool.options", json!({ "tool": "pen" }))), None); + assert_eq!(icon(lock(true)), Some(IconId::new(LOCK_ICON))); + assert_eq!(icon(lock(false)), Some(IconId::new(UNLOCK_ICON))); + assert_ne!(icon(lock(true)), icon(lock(false))); + } +} diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs index 9b2846847e..ec268beb61 100644 --- a/crates/ui-egui/src/canvas/quick_pen_bar.rs +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -19,7 +19,7 @@ use craft::ui::canvas_controls::TaskBar; use craft::ui::choice::Segmented; use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; use craft::ui::primitives::IconSpec; -use craft::ui::runtime::env::{Direction, Env}; +use craft::ui::runtime::env::{Direction, Env, WordsOverride, with_env}; use vectorcraft_tools::quickpen::{self, Stroke as Action}; use super::{Ui, VectorcraftApp, json}; @@ -31,6 +31,13 @@ pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &Canva if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { return None; } + let lang = app.ui_language(); + let words = super::task_bar::bar_words(lang, "Move Toolbar", "Hide Toolbar", "window.quickPenToolbar.pin", "window.quickPenToolbar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_quick_pen_bar(app, ui, space)) +} + +/// The Quick Pen toolbar of [`quick_pen_bar`], in a scope with the toolbar's words. +fn shown_quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { // PLAN: assumed `super::tool_adapter::in_gesture(app: &VectorcraftApp, ctx: &egui::Context) -> bool` (cv.S3) if super::tool_adapter::in_gesture(app, ui.ctx()) { return None; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index 56657ef670..d2bbdf1f5c 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -1,17 +1,18 @@ use craft::behavior::CanvasView; use craft::behavior::{IconId, Mixed}; use craft::color_ui::ui::{PaintChip, PaintChipSize}; +use craft::i18n::WordSet as _; use craft::theme::{Srgba, Variant}; use craft::ui::buttons::{Button, IconButton}; use craft::ui::canvas::CanvasSpace; -use craft::ui::canvas_controls::{TaskBar, TaskBarGrip, TaskBarHang}; +use craft::ui::canvas_controls::{CanvasControlWords, TaskBar, TaskBarGrip, TaskBarHang}; use craft::ui::contract::{Bind, Gap, Props as _, Show as _, ShowContainer as _, Trigger}; use craft::ui::display::Text; use craft::ui::menu::PanelRow; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates}; -use craft::ui::runtime::env::Label; +use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env}; use vectorcraft_doc::NodeKind; use vectorcraft_doc::text::TextKind; use vectorcraft_geom::{Point, Rect}; @@ -442,12 +443,43 @@ fn more_rows(offer: &Offer) -> Vec { ] } +/// VectorCraft's words for a canvas bar's More Options button, its grip (`grip`) and the rows the framework puts in +/// More Options (`hide`, and the commands `pin` and `reset`, named by their titles), over the framework's words. Outside +/// English, a word the language's catalog does not translate keeps the framework's translation. +pub(crate) fn bar_words(lang: crate::i18n::Lang, grip: &'static str, hide: &'static str, pin: &str, reset: &str) -> WordRows { + fn plain(lang: crate::i18n::Lang, english: &'static str) -> (&'static str, &'static str) { + (english, crate::i18n::tr(lang, english)) + } + fn command(lang: crate::i18n::Lang, id: &str) -> (&'static str, &'static str) { + let english = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map_or("", |c| c.1); + (english, crate::i18n::tr_id(lang, id, english)) + } + let words = [ + ("taskBar.more", plain(lang, "More Options")), + ("taskBar.move", plain(lang, grip)), + ("taskBar.hide", plain(lang, hide)), + ("taskBar.pin", command(lang, pin)), + ("taskBar.reset", command(lang, reset)), + ]; + words + .into_iter() + .filter(|(_, (english, shown))| !english.is_empty() && (lang == crate::i18n::Lang::EN || shown != english)) + .filter_map(|(id, (_, shown))| Some((CanvasControlWords::word(id)?, shown))) + .fold(WordRows::new(), |rows, (word, shown)| rows.row(word, shown)) +} + /// The Contextual Task Bar: a floating pill under the selection with the most likely next actions /// ([`offered`]). Its grip drags it anywhere on the canvas; unpinned it keeps that offset as it follows the /// selection, pinned it stays put ([`super::bar_place::KeyedPlace`]). More Options › Bar Actions turns each action /// and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); with every one of them off, the /// bar still shows its grip and More Options, where they turn back on. Returns the bar's rect on screen. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { + let words = bar_words(app.ui_language(), "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset"); + with_env(ui, |env| env.words = Some(WordsOverride::Overlay(words)), |ui| shown_task_bar(app, ui, space)) +} + +/// The Contextual Task Bar of [`task_bar`], in a scope with the bar's words. +fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Option { let offer = offered(app)?; let key = (app.session.active()?.uid, false); let mut local = app.ui.task_bar_place.for_key(key); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 41d0e93837..df0d8fc387 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -897,13 +897,12 @@ fn the_move_of_a_releasing_frame_counts_for_the_tool_drag() { assert_eq!(draw(true), Rect::new(130.0, 115.0, 160.0, 130.0), "with Space held through the release the last move moves it"); } -/// A Selection tool move builds the menus' states again twice, in the frame of its press and in the frame of its -/// release, which commits the move. The frame the move begins in and the frames of its previews, which change the -/// document's revision, keep them. The menus are also built again when a process-wide catalog changes, so the fonts -/// and plug-ins are held steady against tests running alongside for the whole run, and the move runs again on a new -/// app, at most 20 times, until the other catalogs held still through it. -#[test] -fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { +/// How many times each frame of `steps` builds the menus' states again, with the Selection tool and a 60 × 30 +/// rectangle at (100, 100) selected and the pointer resting over its middle (`steps` gets that point). The menus are +/// also built again when a process-wide catalog changes, so the fonts and plug-ins are held steady against tests +/// running alongside for the whole run, and the steps run again on a new app, at most 20 times, until the other +/// catalogs held still through them. +fn selection_tool_rebuilds(steps: impl Fn(Pos2, &craft::behavior::CanvasView) -> Vec>) -> (VectorcraftApp, Vec) { let fonts = vectorcraft_text::FontDb::global(); let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); let catalogs = || { @@ -920,33 +919,59 @@ fn a_selection_move_rebuilds_the_menus_for_its_press_and_release_only() { let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 60, "height": 30})).unwrap()["id"].as_u64().unwrap(); app.select_tool("selection"); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); - let (from, to) = (xf.to_screen(Point::new(130.0, 115.0)), xf.to_screen(Point::new(170.0, 135.0))); + let from = xf.to_screen(Point::new(130.0, 115.0)); app_step(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); for _ in 0..2 { app_step(&mut app, &ctx, vec![]); } - let none = egui::Modifiers::NONE; - let mut steps = vec![vec![primary(from, true, none)]]; - steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); - steps.push(vec![primary(to, false, none)]); - steps.extend([vec![], vec![], vec![]]); let mut rebuilt = vec![]; - for events in steps { + for events in steps(from, &xf) { let before = app.menus.rebuilds; app_step(&mut app, &ctx, events); rebuilt.push(app.menus.rebuilds - before); } (app, rebuilt) }; - let (app, rebuilt) = (0..20) + (0..20) .find_map(|_| { let before = catalogs(); let out = run(); (catalogs() == before).then_some(out) }) - .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")) +} + +/// A Selection tool move builds the menus' states again once, for the release that commits it. Its press lands on the +/// canvas, and the frame the move begins in and the frames of its previews, which change the document's revision, keep +/// them. +#[test] +fn a_selection_move_rebuilds_the_menus_for_its_release_only() { + let none = egui::Modifiers::NONE; + let (app, rebuilt) = selection_tool_rebuilds(|from, xf| { + let to = xf.to_screen(Point::new(170.0, 135.0)); + let mut steps = vec![vec![primary(from, true, none)]]; + steps.extend((1..=8).map(|i| vec![egui::Event::PointerMoved(from.lerp(to, i as f32 / 8.0))])); + steps.push(vec![primary(to, false, none)]); + steps.extend([vec![], vec![], vec![]]); + steps + }); assert_eq!(drawn_paths(&app), vec![Rect::new(140.0, 120.0, 200.0, 150.0)], "the drag moves the rectangle"); - assert_eq!(rebuilt, [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], "rebuilds in each frame: press, 8 moves, release, 3 idle"); + assert_eq!(rebuilt[..9].iter().sum::(), 0, "the press and the 8 moves keep the menus: {rebuilt:?}"); + assert_eq!(rebuilt.iter().sum::(), 1, "the release that commits the move rebuilds them once: {rebuilt:?}"); +} + +/// A click on the selected rectangle that leaves it where it was, and F20 pressed and released with no field or dialog +/// taking it and no command on it, change nothing the menus show: no frame builds the menus' states again. +#[test] +fn a_canvas_click_that_changes_nothing_keeps_the_menus() { + let none = egui::Modifiers::NONE; + let f20 = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: none }; + let (app, rebuilt) = selection_tool_rebuilds(|from, _| { + vec![vec![primary(from, true, none)], vec![primary(from, false, none)], vec![f20(true)], vec![f20(false)], vec![], vec![]] + }); + assert_eq!(drawn_paths(&app), vec![Rect::new(100.0, 100.0, 160.0, 130.0)], "the click leaves the rectangle where it was"); + assert_eq!(app.session.active().map(|d| d.selection.objects.len()), Some(1), "the rectangle stays selected"); + assert_eq!(rebuilt, [0; 6], "rebuilds in each frame: press, release, a key press and release, 2 idle"); } /// #6369: only the selection box remains over the temporary halftone, and the original @@ -4489,6 +4514,38 @@ fn plain(app: &VectorcraftApp, id: u64) -> String { } } +/// While the Type tool edits text, a click in the text and an arrow key, which move the caret without an edit, build +/// the menus' states again: the type rows read the caret's range. +#[test] +fn a_click_or_a_key_in_edited_text_rebuilds_the_menus() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.placeholder_text = false; + let ctx = crate::testing::ui_context(); + let id = start_typing(&mut app, &ctx); + typing_frame(&mut app, &ctx, vec![Event::Text("abc".into())]); + typing_frame(&mut app, &ctx, vec![]); + let at = app.canvas_view().unwrap().to_screen(Point::new(101.0, 100.0)); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + let left = |pressed| Event::Key { key: egui::Key::ArrowLeft, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let rebuilds = |app: &mut VectorcraftApp, steps: Vec>| { + let before = app.menus.rebuilds; + for events in steps { + typing_frame(app, &ctx, events); + } + app.menus.rebuilds - before + }; + let click = || vec![vec![Event::PointerMoved(at), button(true)], vec![button(false)]]; + // The first click puts the caret there; the second leaves the document's revision as it is. + rebuilds(&mut app, click()); + let revision = app.session.active().map(|d| d.revision); + assert!(rebuilds(&mut app, click()) > 0, "a click in the text"); + assert_eq!(app.session.active().map(|d| d.revision), revision, "the click changes no revision"); + assert!(rebuilds(&mut app, vec![vec![left(true)], vec![left(false)]]) > 0, "an arrow key in the text"); + assert_eq!(plain(&app, id), "abc", "neither edits the text"); + assert!(app.session.tool_wants_text(), "editing goes on"); +} + /// Starts editing new point type with the Type tool; returns its id. fn start_typing(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 { app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 8b2b35db16..70f1080db5 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -656,6 +656,17 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too if ui.ctx().current_pass_index() == 0 && view_press { app.session.tool_press_elsewhere(); } + // A press on the canvas, and a key while the canvas or nothing has the focus, change what the menus show only through + // the document, the tool or a command, which the menus' state key reads, so the key leaves them out + // (`menus::model::last_press`). + let presses: Vec = + ui.input(|i| i.events.iter().filter_map(|e| if let egui::Event::PointerButton { pos, .. } = e { Some(*pos) } else { None }).collect()); + if !presses.is_empty() && presses.iter().all(|&at| over(Some(at)) && ui.ctx().layer_id_at(at) == Some(ui.layer_id())) { + app.canvas.pressed_at = Some(ui.input(|i| i.time)); + } + if ui.ctx().memory(|m| m.focused()).is_none_or(|id| id == pass.id) { + app.canvas.keys_at = Some(ui.input(|i| i.time)); + } let view_info = app.view_info(); let mut picked = ToolHostResponse::default(); let mut response = if crate::dialogs::recolor::edit_tab::with_theme_pick(app, |app, tool| picked = host_run(app, ui, pass, tool)) { diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index ec06404f2c..0020757e44 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -286,6 +286,8 @@ fn normalized(app: &VectorcraftApp, id: &str, values: Map, fresh: super::effect_rows::clamp_blur_center(&mut values); } else if id == vectorcraft_effects::RASTERIZE { super::raster_effects::preset_of(&mut values); + } else if id == vectorcraft_effects::addons::halftone::HALFTONE { + super::halftone::canonical_style(&mut values); } values } @@ -705,6 +707,19 @@ mod tests { app.session.doc().unwrap().history.undo.len() } + #[test] + fn halftone_dialog_normalizes_stored_style_case() { + let mut app = app(); + let node = rect(&mut app, 10); + let effect = vectorcraft_effects::addons::halftone::HALFTONE; + app.run("effect.apply", json!({"ids": [node], "effect": effect, "item": null, "params": {"style": "GRIDDOTS"}})).unwrap(); + app.run("select.set", json!({"ids": [node]})).unwrap(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + let open = app.effect_dialogs.effect.as_ref().unwrap(); + assert_eq!(open.opened["style"], json!("gridDots")); + assert_eq!(fields(&app, id(&app)).text("style"), Some("gridDots")); + } + #[test] fn edit_and_add_new_still_open_after_an_idle_effect_prompt() { for (choice, editing) in [("proceed", true), ("alternate", false)] { diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index ebc54223f6..654aebad35 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -2,7 +2,7 @@ //! or CMYK screens, Invert, Clip to Art and Keep Original, previewed live on the canvas; OK keeps //! the preview as one undo step (`object.vectorHalftone`). //! -//! Fields: `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal` (the +//! Fields: `style`, `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal` (the //! command's parameters). The live effect's dialog shows the same rows but Keep Original //! ([`screen_params`]). @@ -33,7 +33,20 @@ pub(crate) struct Open { /// The dialog's fields as it opens: the command's defaults. pub fn fields() -> Value { - json!({"shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false}) + json!({"style": "custom", "shape": "circle", "frequency": 20, "angle": 45, "mode": "mono", "color": "#000000", "invert": false, "clip": true, "keepOriginal": false}) +} + +/// The Style picker's choices: their ids and labels. +const STYLES: [(&str, &str); 5] = + [("custom", "Custom"), ("grid", "Grid"), ("gridAngle", "Grid Angle"), ("gridDots", "Grid Dots"), ("gridDotsAngle", "Grid Dots Angle")]; + +/// Spells a stored `style` as the picker's id, matched in any letter case as the effect reads it, +/// so the picker shows it selected and the choice ids stay the ones the dialog accepts. +pub(crate) fn canonical_style(values: &mut serde_json::Map) { + let Some(stored) = values.get("style").and_then(Value::as_str) else { return }; + if let Some((id, _)) = STYLES.iter().find(|(id, _)| id.eq_ignore_ascii_case(stored)) { + values.insert("style".into(), json!(id)); + } } /// A choice's options from `(id, label)` pairs, the labels translated. @@ -56,12 +69,17 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { ("euclidean", "Euclidean"), ("elliptical", "Elliptical"), ]; - let mut rows = vec![ - Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), - Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), - Param::new("angle", tl!("Angle"), ParamKind::range(-90.0, 90.0, 45.0, SliderScale::Linear)).unit(UnitKind::Degrees), - Param::new("mode", tl!("Screens"), ParamKind::choice(options(&[("mono", "Mono"), ("cmyk", "CMYK")]), Some("mono".into()))), - ]; + let styles = STYLES; + let custom = !named_style(fields); + let mut rows = vec![Param::new("style", tl!("Style"), ParamKind::choice(options(&styles), Some("custom".into())))]; + if custom { + rows.push(Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into())))); + } + rows.push(Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch)); + if custom { + rows.push(Param::new("angle", tl!("Angle"), ParamKind::range(-90.0, 90.0, 45.0, SliderScale::Linear)).unit(UnitKind::Degrees)); + } + rows.push(Param::new("mode", tl!("Screens"), ParamKind::choice(options(&[("mono", "Mono"), ("cmyk", "CMYK")]), Some("mono".into())))); if live { rows.push(Param::new("fromArt", tl!("Dot Color from Art"), ParamKind::bool(false)).visible_when("mode", "mono")); } @@ -98,7 +116,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { }; return Err(why.into()); } - let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields)); + let params = Value::Object(command_params(&result.fields)); let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?; let done = std::mem::take(&mut open.preview).commit(app, CMD, params); if done.is_err() { @@ -119,6 +137,23 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result { Ok(Value::Null) } +/// The command's parameters from the dialog's fields. With a named style, the stored Shape and +/// Angle are left out so that the style's own shape and angle apply. +pub(crate) fn command_params(fields: &DialogFields) -> serde_json::Map { + let mut params = json_of(&screen_params(false, fields), fields); + if named_style(fields) { + params.remove("shape"); + params.remove("angle"); + } + params +} + +/// Whether the stored style is a named one, which sets the shape and the angle; Custom, no style +/// and a style this build does not know keep the stored Shape and Angle, so their rows show. +fn named_style(fields: &DialogFields) -> bool { + matches!(fields.text("style").and_then(vectorcraft_effects::addons::halftone::style), Some(Some(_))) +} + /// Runs or ends the open dialog's preview for this frame. pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let Some(mut open) = app.effect_dialogs.halftone.take() else { return }; @@ -130,7 +165,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { let shown = app.dialogs().and_then(|host| { host.with(|h| { h.get_by_id::(open.id).map(|d| { - let params = json_of(&screen_params(false, d.fields()), d.fields()); + let params = command_params(d.fields()); (d.is_previewing(), Value::Object(params)) }) }) @@ -278,6 +313,77 @@ mod tests { assert_eq!(undo_steps(&panel), undo + 1, "the reopened dialog's OK is one undo step"); } + /// A named style sends no Shape or Angle, so the style's own apply; Custom sends both. + #[test] + fn a_named_style_hides_shape_and_angle() { + for (style, shown) in [("custom", true), ("gridDots", false)] { + let mut values = fields(); + values["style"] = json!(style); + let rows = screen_params(false, &DialogFields::new()); + let f = fields_of(&rows, values.as_object().unwrap()); + let sent = command_params(&f); + assert_eq!(sent.get("style"), Some(&json!(style))); + assert_eq!((sent.contains_key("shape"), sent.contains_key("angle")), (shown, shown), "{style}: {sent:?}"); + } + } + + #[test] + fn style_picker_selects_stored_styles_in_any_case() { + for (style, label) in [("GRIDDOTS", "Grid Dots"), ("CUSTOM", "Custom")] { + let mut values = fields(); + values["style"] = json!(style); + let mut values = values.as_object().unwrap().clone(); + canonical_style(&mut values); + let f = fields_of(&screen_params(false, &DialogFields::new()), &values); + let rows = screen_params(false, &f); + let row = rows.iter().find(|p| p.key == "style").unwrap(); + let ParamKind::Choice { options, .. } = &row.kind else { panic!("Style is not a choice") }; + let ids: Vec<&str> = options.iter().map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, STYLES.map(|(id, _)| id), "{style}: the choice ids stay as the dialog accepts them"); + let selected = options.iter().find(|(id, _)| Some(id.as_str()) == f.text("style")); + assert_eq!(selected.map(|(_, label)| label.as_str()), Some(label), "{style}"); + } + } + + /// A stored style matches Custom in any letter case, as the effect reads it, so Shape and + /// Angle stay on screen and OK sends both. + #[test] + fn custom_style_in_any_case_keeps_shape_and_angle() { + let mut values = fields(); + values["style"] = json!("CUSTOM"); + let f = fields_of(&screen_params(false, &DialogFields::new()), values.as_object().unwrap()); + let rows = screen_params(false, &f); + let shown = |k: &str| rows.iter().any(|p| p.key == k); + assert!(shown("shape") && shown("angle"), "Shape and Angle rows are hidden"); + let sent = command_params(&f); + assert!(sent.contains_key("shape") && sent.contains_key("angle"), "{sent:?}"); + } + + #[test] + fn only_recognized_presets_hide_shape_and_angle() { + for style in [None, Some("custom"), Some("CUSTOM"), Some(""), Some("unknown"), Some("GRIDDOTS")] { + let mut values = fields().as_object().unwrap().clone(); + values.remove("style"); + if let Some(style) = style { + values.insert("style".into(), json!(style)); + } + values.insert("shape".into(), json!("diamond")); + values.insert("angle".into(), json!(23)); + let f = fields_of(&screen_params(false, &DialogFields::new()), &values); + let shown = style != Some("GRIDDOTS"); + for live in [false, true] { + let rows = screen_params(live, &f); + for key in ["shape", "angle"] { + assert_eq!(rows.iter().any(|p| p.key == key), shown, "{style:?}, live={live}, {key}"); + } + } + let sent = command_params(&f); + for key in ["shape", "angle"] { + assert_eq!(sent.get(key), if shown { values.get(key) } else { None }, "{style:?}, {key}"); + } + } + } + /// With Preview off, OK after File > Revert is refused and leaves the restored drawing as it is. #[test] fn vector_halftone_without_preview_refuses_ok_after_file_revert() { diff --git a/crates/ui-egui/src/dialogs/placement_options.rs b/crates/ui-egui/src/dialogs/placement_options.rs index 03b4cc19bd..3dc00a9bfb 100644 --- a/crates/ui-egui/src/dialogs/placement_options.rs +++ b/crates/ui-egui/src/dialogs/placement_options.rs @@ -45,7 +45,7 @@ fn params() -> Vec { /// Open the dialog on the placement options of images `ids` (default: the selected ones). pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let active = app.session.active().ok_or("no document open")?; - let source = (active.uid, active.reverts); + let source = (active.uid, active.reverts, active.history_restores); let ids = p.get("ids").cloned().unwrap_or(Value::Null); let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?; // The images read: OK applies to these, whatever is selected by then. @@ -57,7 +57,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { ("align", FieldValue::Int(align as i64)), ("clip", FieldValue::Bool(placement["clip"].as_bool().unwrap_or(false))), ]); - fields.set(OPENING, FieldValue::Json(json!({"uid": source.0, "reverts": source.1, "ids": ids}))); + fields.set(OPENING, FieldValue::Json(json!({"uid": source.0, "reverts": source.1, "historyRestores": source.2, "ids": ids}))); let ctx = app.ui_ctx.clone().ok_or("no window")?; let dialog = HostedParamDialog::new(&ctx, KEY, fields, |fields| { ParamDialog::new(KEY, tl!("Placement Options"), params()) @@ -74,6 +74,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { if Some(active.reverts) != opening["reverts"].as_u64() { return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned()); } + if Some(active.history_restores) != opening["historyRestores"].as_u64() { + return Err(tl!("Reopen Placement Options after Undo or Redo.").to_owned()); + } let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]); let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) }); app.run(CMD, params).map(|_| ()) @@ -170,4 +173,35 @@ mod tests { crate::tests::picks::answer_dialog(&mut app, dialog, &[("preserve", json!("fit"))], true); assert_eq!(placement(&mut app)["preserve"], "fit"); } + + #[test] + fn held_placement_options_do_not_edit_an_image_placed_after_undo() { + let dir = vectorcraft_testkit::TempDir::new("placement-options-undo"); + let path = dir.join("linked.png"); + let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap(); + std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap(); + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let place = |app: &mut VectorcraftApp| { + app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap() + }; + let link = place(&mut app); + let placement = |app: &mut VectorcraftApp| app.run(CMD, json!({"ids": [link]})).unwrap()["placement"].clone(); + open(&mut app, &json!({"ids": [link]})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let dialog = dialog_id(KEY); + let host = app.dialogs().unwrap(); + host.with(|h| { + h.set_json_field(&ctx, dialog, "preserve", json!("fit")).unwrap(); + assert!(!h.confirm_by_id(&ctx, dialog)); + }); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(place(&mut app), link, "the replacement image takes the undone image's id"); + let original = placement(&mut app); + let undo = app.session.active().unwrap().history.undo.len(); + crate::dialogs::host::pump(&mut app, &ctx); + assert_eq!(placement(&mut app), original, "the replacement image keeps its Placement Options"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_)))); + } } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6597377645..4863a67cb3 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -235,6 +235,13 @@ fn same_size(a: &Paper, b: &Paper) -> bool { (a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5 } +/// The paper of `papers` with the name and size of `old`. A Windows paper's key is its name, or its name and size when +/// the printer lists that name at more than one size, so one printer's key can differ from another's for the same paper. +fn same_paper<'a>(old: &Paper, papers: &'a [Paper]) -> Option<&'a Paper> { + let name = |p: &Paper| p.key.split('\t').next().unwrap_or_default().to_string(); + papers.iter().find(|p| name(p) == name(old) && same_size(old, p)) +} + /// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { let mut out = settings(fields); @@ -609,7 +616,8 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ctx.request_repaint(); } // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of - // the same Width and Height. One the new printer lists at the size of one of the dialog's own papers becomes that + // the same Width and Height. One the new printer lists by the same name and size under another key keeps that + // paper. One the new printer lists at the size of one of the dialog's own papers becomes that // paper, the choice the new list offers for it. if papers_changed && media.starts_with(PRINTER_PAPER) @@ -622,6 +630,19 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, fields.set("media", own.id()); return Some((own.id().to_string(), settings(fields))); } + // The new printer lists the same paper under another key: it stays chosen. + // A built-in paper takes its place only the same way up, since the built-in paper prints at its own size. + if let Some(new) = chosen.as_ref().and_then(|old| same_paper(old, &open.papers.1)) + && let Some(id) = match own_media_choice(new, &open.papers.1) { + None => Some(format!("{PRINTER_PAPER}{}", new.key)), + Some(own) => { + own.size().filter(|&(w, h)| (w - new.width).abs() <= 0.5 && (h - new.height).abs() <= 0.5).map(|_| own.id().to_string()) + } + } + { + fields.set("media", id.as_str()); + return Some((id, settings(fields))); + } if let Some(paper) = &chosen { fields.set("width", paper.width); fields.set("height", paper.height); @@ -850,8 +871,11 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st app.run("print.setup", json!({ "settings": settings }))?; match answer.finish { PrintFinish::Print => { - let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None }; - let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper }); + let mut job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf }); + // `paper` is left out when there is none: `file.print` refuses a null one. + if applies_paper && let Some(paper) = driver_paper_key(&answer.fields, &open.papers.1) { + job["paper"] = json!(paper); + } crate::print::run(app, &job).map(|_| ()) } // Done only keeps the settings. diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f311a93abd..9340f14350 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -814,7 +814,7 @@ fn the_job_asks_the_queue_for_the_driver_paper_chosen() { // Without the dialog, the keyword is given as `paper`, and anything else is refused before printing. app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap(); assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm")); - for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] { + for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4), json!(null)] { assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}"); } assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err()); @@ -943,6 +943,70 @@ fn windows_forms_stay_selected_when_queue_enumeration_order_changes() { } } +/// Single lists one paper named Custom; Double lists Custom at that size and at another. +struct SharedNameForms; + +impl PrintService for SharedNameForms { + fn printers(&mut self) -> Vec { + vec![Printer::new("Single").is_default(true), Printer::new("Double"), Printer::new("Sideways")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let out = if printer == "Double" { + "256\tCustom\t400\t600\n256\tCustom\t500\t700\n1\tLetter\t850\t1100\n1\tLetter\t1100\t850\n" + } else if printer == "Sideways" { + "1\tLetter\t1100\t850\n" + } else { + "256\tCustom\t400\t600\n1\tLetter\t850\t1100\n" + }; + Papers::Ready(crate::print::windows_papers(out)) + } +} + +#[test] +fn a_windows_paper_stays_chosen_when_another_printer_lists_its_name_at_more_sizes() { + let services = Services { print: Some(Box::new(SharedNameForms)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:Custom")); + pump(&mut app); + set(&mut app, "printer", json!("Double")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:Custom\t400x600", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(288.0), Some(432.0)), "{f}"); + set(&mut app, "printer", json!("Single")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:Custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(288.0), Some(432.0)), "{f}"); + // Double's upright Letter is Single's only Letter, which the Size list offers as the built-in Letter. + set(&mut app, "printer", json!("Double")); + pump(&mut app); + set(&mut app, "media", json!("printer:Letter\t850x1100")); + pump(&mut app); + set(&mut app, "printer", json!("Single")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "letter", "{f}"); + // Sideways lists the same sideways Letter under a different key. It becomes custom at 792 x 612 points. + set(&mut app, "printer", json!("Double")); + pump(&mut app); + set(&mut app, "media", json!("printer:Letter\t1100x850")); + pump(&mut app); + set(&mut app, "printer", json!("Sideways")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(792.0), Some(612.0)), "{f}"); +} + #[test] fn long_windows_paper_labels_keep_dimensions_and_collision_numbers() { let name = "é".repeat(128); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d5f31df6c3..ea6dcb4c69 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,19 +1,23 @@ //! Panel bodies: what the dock area ([`crate::panel_docking`]) draws inside a docked, floating or //! flyout panel. -use craft::ui::contract::{Props as _, Scroll, ShowContainer as _}; +use craft::ui::contract::{MemoProps, MemoView, Props as _, Scroll, ShowContainer as _}; use craft::ui::layout_components::Stack; use egui::Ui; use crate::state::DockTab; use crate::{VectorcraftApp, panels}; +/// The panels whose bodies show in a `MemoView` ([`memoized`]): a frame that changes none of what [`BodyInputs`] holds +/// replays the body instead of running it again. +const MEMOIZED: [&str; 8] = ["appearance", "character", "color", "gradient", "layers", "paragraph", "stroke", "swatches"]; + /// Panel `id`'s contents in the room its group gives it; content taller than the group scrolls in /// the group's body. pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { match DockTab::from_id(id) { Some(DockTab::Properties) => panels::properties::show(app, ui), - Some(DockTab::Layers) => panels::layers::show(app, ui), + Some(DockTab::Layers) => memoized(app, ui, id, layers_body), Some(DockTab::Libraries) => panels::libraries(app, ui), None if matches!( id, @@ -36,8 +40,340 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { { // These panels lay out forms. Collection panels own their scrolling viewport // and reserve their own footer outside it. - Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| panels::show_icon_panel(app, ui, id)); + Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body)); + } + None => memoized(app, ui, id, icon_panel_body), + } +} + +/// The Layers panel's body. +fn layers_body(p: &mut BodyProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + panels::layers::show(p.app, ui); +} + +/// An icon panel's body. +fn icon_panel_body(p: &mut BodyProps<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::count_run(); + panels::show_icon_panel(p.app, ui, p.id); +} + +/// Shows panel `id`'s `body`: in a `MemoView` keyed on [`BodyInputs`] for a panel in [`MEMOIZED`], directly for any +/// other. What the body picks it carries out on the app in the run that picks it: a view runs in every pass the pointer +/// or the focus engages it. +fn memoized(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, body: fn(&mut BodyProps<'_>, &mut Ui)) { + #[cfg(test)] + let memoized = MEMOIZED.contains(&id) && !tests::shown_directly(); + #[cfg(not(test))] + let memoized = MEMOIZED.contains(&id); + let inputs = memoized.then(|| BodyInputs::of(app, ui.ctx(), id)); + let mut props = BodyProps { app, id, inputs }; + if !memoized { + body(&mut props, ui); + return; + } + let _ = MemoView::new(("panel-body", id), props, body).shown_out_of_view().show(ui); +} + +/// What a panel body shows: the app, read through [`BodyInputs`]. +#[derive(MemoProps)] +struct BodyProps<'a> { + #[memo_props(covered_by = "inputs", reason = "the bodies read the app only where BodyInputs follows it")] + app: &'a mut VectorcraftApp, + /// The panel's id. + id: &'a str, + /// `None` for a body shown directly. + inputs: Option, +} + +/// What can change a panel body from outside it: the active document's edits, selection and view (its revision), the +/// documents open, every command run (panel menus, shortcuts, other panels and dialogs, and the commands a tool runs on +/// the session), a gesture's previews, the active tool and its +/// options (the Type tool's text selection), the fill or stroke in front, a font preview, the fonts and plug-ins +/// installed, the interface language, and panel settings shared with dialogs and popovers. +#[derive(MemoProps)] +struct BodyInputs { + /// The active document's uid and revision. + document: Option<(u64, u64)>, + /// How many documents are open. + documents: usize, + /// How many commands the app has run. + commands: u64, + /// How many commands the session journaled, and how many times it rewrote its journal: a tool runs its commands + /// on the session without the app (the Gradient tool's click on a stop). + journal: (usize, u64), + /// The active tool. + tool: &'static str, + /// The active tool's options, as JSON. + tool_options: String, + /// Whether the fill is in front of the stroke. + fill_active: bool, + /// The options replaced by the Layers Panel Options dialog's OK callback. + #[memo_props(hash = "the Layers panel's saved display options")] + layers_options: panels::layers::PanelOptions, + /// The Color panel's settings, also edited by the paint chip's Color Mixer popover. + color_options: craft::color_ui::ui::ColorPanelState, + /// Options shared with the Stroke popover, including the last disabled dash pattern. + stroke_options: (bool, bool, Option<(Vec, bool)>), + /// The browser state shared with a paint chip's Swatches popover. `None` for every panel but Swatches: no other + /// body reads it. + swatches: Option, + /// Whether the Swatches footer's library button is pressed. `None` for every panel but Swatches. + swatch_libraries_open: Option, + /// Whether a font preview shows in the document. + font_preview: bool, + /// While a gesture previews its edit (a scrubbed field, a drag on the canvas) or a tool computes its edit, the + /// pass: a preview can change what new art takes without a command, so the bodies run in every pass until it ends. + live: Option, + /// The fonts and hyphenation exceptions ([`vectorcraft_text::layout_inputs`]). + fonts: u64, + /// The plug-ins installed. + plugins: u64, + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, +} + +impl BodyInputs { + /// The inputs of panel `id`'s body. + fn of(app: &VectorcraftApp, ctx: &egui::Context, id: &str) -> Self { + let swatches = id == "swatches"; + let live = app.session.active().is_some_and(|d| d.interaction.is_some()) || app.session.tool_waiting(); + BodyInputs { + live: live.then(|| ctx.cumulative_pass_nr()), + document: app.session.active().map(|d| (d.uid, d.revision)), + documents: app.session.documents().len(), + commands: app.run_count, + journal: (app.session.journal.len(), app.session.journal.rewrites()), + tool: app.session.tool_id(), + tool_options: app.session.tool_options().to_string(), + fill_active: app.session.fill_active, + layers_options: app.ui.layers_panel.clone(), + color_options: app.ui.color_panel, + stroke_options: (app.ui.stroke_panel.hide_options, app.ui.stroke_panel.scale_linked, app.ui.stroke_panel.dash_last.clone()), + swatches: swatches.then(|| panels::swatches::BodyInputs::of(app)), + swatch_libraries_open: swatches.then(|| panels::library_panel::any_open::(&app.ui)), + font_preview: app.font_preview_owner.is_some(), + fonts: vectorcraft_text::layout_inputs(), + plugins: vectorcraft_plugins::registry::revision(), + lang: crate::i18n::current(), + } + } +} + +#[cfg(test)] +mod tests { + use std::cell::{Cell, RefCell}; + + use egui::Ui; + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::VectorcraftApp; + use crate::tests::panel_harness::Panel; + + thread_local! { + /// How many times this thread ran a panel body. + static BODY_RUNS: Cell = const { Cell::new(0) }; + /// This thread shows the memoized bodies directly, outside their `MemoView`s. + static DIRECT: Cell = const { Cell::new(false) }; + /// The panel [`draw`] shows. + static SHOWN: RefCell<&'static str> = const { RefCell::new("") }; + } + + pub(super) fn count_run() { + BODY_RUNS.with(|n| n.set(n.get() + 1)); + } + + fn runs() -> u64 { + BODY_RUNS.with(Cell::get) + } + + pub(super) fn shown_directly() -> bool { + DIRECT.with(Cell::get) + } + + fn draw(app: &mut VectorcraftApp, ui: &mut Ui) { + super::panel_body(app, ui, SHOWN.with(|s| *s.borrow())); + } + + /// Panel `id` over a document with a rectangle selected, after its first frames. + fn panel(id: &'static str) -> Panel { + SHOWN.with(|s| *s.borrow_mut() = id); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let mut panel = Panel::new(app, draw); + panel.frame(); + panel.frame(); + panel + } + + /// How many times `frames` frames run the body. + fn runs_in(panel: &mut Panel, frames: usize) -> u64 { + let before = runs(); + for _ in 0..frames { + panel.frame(); + } + runs() - before + } + + /// Frames that change nothing replay the Color panel's body. A fill set by a command run elsewhere runs it again, + /// and its Hex field shows the new color; so does the fill or stroke brought to the front without a command, as + /// the Contextual Task Bar does. + #[test] + fn idle_frames_replay_the_color_panel() { + let mut panel = panel("color"); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Color panel"); + panel.app().run("paint.setFill", json!({"color": "#336699"})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a new fill runs the Color panel again"); + assert!(panel.shows_value_with(|v| v.eq_ignore_ascii_case("336699")), "and it shows the fill: {:?}", panel.values()); + assert_eq!(runs_in(&mut panel, 10), 0, "the frames after replay it again"); + let active = panel.app().session.fill_active; + panel.app().session.fill_active = !active; + assert!(runs_in(&mut panel, 2) > 0, "the other well brought to the front runs the Color panel again"); + } + + /// Frames that change nothing replay the Layers panel's body, and a new object, drawn by a command run elsewhere, + /// runs it again and adds a row. + #[test] + fn idle_frames_replay_the_layers_panel() { + let mut panel = panel("layers"); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Layers panel"); + let rows = panel.texts().len(); + panel.app().run("shape.ellipse", json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a new object runs the Layers panel again"); + assert!(panel.texts().len() > rows, "and it shows a row for it"); + // The panel runs while it reveals the new row. + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "once the row is revealed, the frames after replay it again"); + } + + /// Replacing the options outside app.run, as the dialog's OK callback does, refreshes an idle body. + #[test] + fn layers_options_changed_by_a_dialog_refresh_the_body() { + let mut panel = panel("layers"); + panel.app().run("ui.layersExpand", json!({"open": true})).unwrap(); + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "the Layers panel has settled"); + let texts = panel.texts(); + assert!(texts.iter().any(|(text, _)| text.contains("Rectangle")), "the object row shows: {texts:?}"); + let before = super::BodyInputs::of(&panel.app(), panel.ctx(), "layers"); + let options = panel.app().ui.layers_panel.clone(); + panel.app().ui.layers_panel = crate::panels::layers::PanelOptions { layers_only: true, ..options }; + let after = super::BodyInputs::of(&panel.app(), panel.ctx(), "layers"); + assert_eq!((after.document, after.commands, after.journal), (before.document, before.commands, before.journal)); + assert!(runs_in(&mut panel, 2) > 0, "the options run the body again without a command"); + assert!(!panel.texts().iter().any(|(text, _)| text.contains("Rectangle")), "Show Layers Only hides the object row"); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// The Color Mixer can change display units without changing a paint or running a command. + #[test] + fn color_options_changed_in_a_popover_refresh_the_body() { + let mut panel = panel("color"); + assert_eq!(runs_in(&mut panel, 10), 0, "the Color panel has settled"); + let values = panel.values(); + let percent = panel.app().ui.color_panel.rgb_percent; + panel.app().ui.color_panel.rgb_percent = !percent; + assert!(runs_in(&mut panel, 2) > 0, "shared Color Mixer settings run the body again"); + assert_ne!(panel.values(), values, "the RGB fields show the new units"); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// A Swatches popover's find field filters the docked browser too, without a command. + #[test] + fn swatches_filter_changed_in_a_popover_refreshes_the_body() { + let mut panel = panel("swatches"); + panel.app().run("swatch.new", json!({"name": "Memo swatch", "color": "#336699"})).unwrap(); + panel.app().ui.swatches_panel.show_find = true; + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "the Swatches panel has settled"); + panel.app().ui.swatches_panel.state.browser.filter = "No matching swatch".into(); + assert!(runs_in(&mut panel, 2) > 0, "the shared filter runs the body again"); + assert!(panel.shows_value_with(|v| v == "No matching swatch"), "the find field shows the new filter"); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// Only the Swatches body reads the swatch browser, so a filter changed in a popover replays the Color panel. + #[test] + fn swatches_filter_does_not_run_the_color_panel() { + let mut panel = panel("color"); + assert_eq!(runs_in(&mut panel, 10), 0, "the Color panel has settled"); + let inputs = super::BodyInputs::of(&panel.app(), panel.ctx(), "color"); + assert!(inputs.swatches.is_none() && inputs.swatch_libraries_open.is_none(), "the Color body's inputs hold no swatch state"); + panel.app().ui.swatches_panel.state.browser.filter = "No matching swatch".into(); + assert_eq!(runs_in(&mut panel, 10), 0, "the swatch filter replays the Color panel"); + } + + /// The Stroke popover changes linked arrowhead scales without a command. + #[test] + fn stroke_options_changed_in_a_popover_refresh_the_body() { + let mut panel = panel("stroke"); + assert_eq!(runs_in(&mut panel, 10), 0, "the Stroke panel has settled"); + let linked = panel.app().ui.stroke_panel.scale_linked; + panel.app().ui.stroke_panel.scale_linked = !linked; + assert!(runs_in(&mut panel, 2) > 0, "shared Stroke popover settings run the body again"); + assert_eq!(panel.toggled("Make all settings the same"), Some(craft::behavior::Mixed::Same(!linked))); + // The link toggle runs the panel while its animation finishes. + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "the updated body replays again"); + } + + /// A stop selected by a command the session runs without the app, as the Gradient tool's click on a stop does, + /// runs the Gradient panel again. + #[test] + fn a_stop_selected_on_the_canvas_runs_the_gradient_panel() { + let mut panel = panel("gradient"); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#000000"}]); + panel.app().run("paint.setFill", json!({"gradient": {"stops": stops}})).unwrap(); + panel.app().run("gradient.selectStop", json!({"index": 0})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a new fill runs the Gradient panel"); + // The panel runs while the controls the gradient brought in finish their animations. + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Gradient panel"); + panel.app().session.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + assert!(runs_in(&mut panel, 2) > 0, "a stop selected through the session runs the Gradient panel again"); + } + + /// A stroke weight scrubbed outside the Stroke panel with nothing selected previews what new art takes, without a + /// command or a new document revision: the panel runs in every frame of the gesture and shows the weight. + #[test] + fn a_weight_scrubbed_elsewhere_runs_the_stroke_panel() { + let mut panel = panel("stroke"); + panel.app().run("select.none", json!({})).unwrap(); + runs_in(&mut panel, 10); + assert_eq!(runs_in(&mut panel, 10), 0, "idle frames replay the Stroke panel"); + let scrub = |panel: &mut Panel, weight: f64| { + let mut app = panel.app(); + crate::panels::live_run(&mut app, "Stroke Weight", "stroke.set", json!({"weight": weight}), crate::panels::Live::Dragging); + }; + for weight in [6.0, 7.0] { + scrub(&mut panel, weight); + assert!(runs_in(&mut panel, 1) > 0, "a frame of the gesture at {weight} pt runs the Stroke panel"); + } + assert!(panel.shows_value_with(|v| v.starts_with('7')), "the panel shows the 7 pt weight: {:?}", panel.values()); + } + + /// The texts `id`'s body paints after idle frames, shown in its `MemoView` or, with `direct`, directly. + fn texts(id: &'static str, direct: bool) -> Vec<(String, egui::Rect)> { + DIRECT.with(|d| d.set(direct)); + let mut panel = panel(id); + panel.frame(); + let texts = panel.texts(); + DIRECT.with(|d| d.set(false)); + texts + } + + /// A body shown in its `MemoView` lands where the same body shown directly does: a form panel in its scrolling + /// stack, a collection panel that fills its room, and the Layers tab. + #[test] + fn memoized_bodies_land_where_direct_ones_do() { + for id in ["stroke", "gradient", "layers"] { + let direct = texts(id, true); + assert!(!direct.is_empty(), "{id} paints text"); + assert_eq!(texts(id, false), direct, "the memoized {id} body lands where the direct one does"); } - None => panels::show_icon_panel(app, ui, id), } } diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 7aa701c83b..cd4d481cc5 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -92,9 +92,11 @@ pub(crate) fn translate_label(english: &'static str) -> String { /// What the menus' rows depend on, cheaply (no allocation): commands run, the active document, /// its revision (edits, selection and view changes), history and clipboard, the filter plug-in that ran last, the language, /// shortcuts, plug-ins, the Scripts folder's listing, an open file dialog and the fonts (Type › Font lists the loaded fonts -/// until the installed ones are scanned, then all of them, #5483). `input`, the pass of the last frame with a pointer -/// button pressed or released or a key pressed ([`last_press`]), changes once for each, which covers what the hash -/// doesn't list (panels shown, a tool picked). While an +/// until the installed ones are scanned, then all of them, #5483), the tool, whether the panels show, the open panel +/// flyout, the dock workspace's identity and revision, the current window and whether a dialog is open or a shortcut +/// is being recorded. `input`, the pass of the last frame with a click away from the canvas or a key a field or a dialog +/// took ([`last_press`]), changes once for each, which covers what the hash +/// doesn't list (a panel's own state, a dialog's fields). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the hash takes the revision the interaction began from in place of the current one, /// which each of its previews changes, and changes as it ends. The hash stays the same as a tool's drag begins. An @@ -126,6 +128,14 @@ fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { // Apply Last Filter and Last Filter… are named after the filter that ran last. app.last_filters.last_id().hash(&mut h); app.file_dialog_open().hash(&mut h); + // What a click on the canvas or a key no field takes changes without a command: the tool (a tool's key, a held + // Space), the panels shown (Tab), the open panel flyout and the dock workspace's identity and revision (panels + // shown, hidden or moved), the current window, the view's rotation (Rotate View's checks) and active artboard + // (a selection tool's press on one), and a dialog opened or closed (Escape, Enter). + (s.tool_id(), crate::panel_docking::panels_shown(app), crate::doc_windows::current(app)).hash(&mut h); + (&app.ui.open_panel, std::sync::Arc::as_ptr(&app.ui.dock_workspace).addr(), app.ui.dock_workspace.revision()).hash(&mut h); + app.view().map(|v| (v.rotation.to_bits(), v.artboard)).hash(&mut h); + (app.any_dialog_open(), recording_shortcut(app)).hash(&mut h); (crate::i18n::current().code(), plugin_revision(), crate::scripts_menu::revision(), crate::dialogs::proof_setup::saved_revision()).hash(&mut h); hash_listed_names(&app.ui, &mut h); let fonts = vectorcraft_text::FontDb::global(); @@ -216,20 +226,33 @@ fn lay_out(app: &mut VectorcraftApp, target: Target) { } } -/// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read -/// last included: the `input` of [`state_key`]. It stays the same over the frames after that one, so each of them -/// changes the key once. +/// The pass number of the last frame with a press that [`pressed_pass`] counts, the frame `ctx` read last included: the +/// `input` of [`state_key`]. It stays the same over the frames after that one, so each of them changes the key once. pub(crate) fn last_press(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option { - if let Some(pass) = pressed_pass(ctx) { + if let Some(pass) = pressed_pass(app, ctx) { app.menus.pressed = Some(pass); } app.menus.pressed } -/// The frame's pass number when it has a pointer button pressed or released (a click ends at the release) or a key -/// pressed. -fn pressed_pass(ctx: &egui::Context) -> Option { - let pressed = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { .. } | egui::Event::Key { pressed: true, .. }))); +/// The frame's pass number when it has a pointer button pressed or released (a click ends at the release) away from +/// the canvas, or a key pressed while a text field, a dialog or a panel's control has the keys. A click on the canvas +/// changes the rows only through the document, the tool or a command, and a key the canvas or the app's shortcuts take +/// only through those, the panels shown (Tab) or a dialog it opens or closes, which [`rows_key`] reads. While the tool +/// edits text, a click or a key on the canvas counts too: it moves the caret or the selected range, which the type rows +/// read. +fn pressed_pass(app: &VectorcraftApp, ctx: &egui::Context) -> Option { + let editing = app.session.tool_wants_text(); + let typing = editing || WindowHost::of(ctx).typing() || app.any_dialog_open(); + let pressed = ctx.input(|i| { + let on_canvas = !editing && app.canvas.pressed_at == Some(i.time); + let canvas_keys = !typing && app.canvas.keys_at == Some(i.time); + i.events.iter().any(|e| match e { + egui::Event::PointerButton { .. } => !on_canvas, + egui::Event::Key { pressed: true, .. } => !canvas_keys, + _ => false, + }) + }); pressed.then(|| ctx.cumulative_pass_nr()) } diff --git a/crates/ui-egui/src/menus/native.rs b/crates/ui-egui/src/menus/native.rs index 2450a9b201..fae289c8d5 100644 --- a/crates/ui-egui/src/menus/native.rs +++ b/crates/ui-egui/src/menus/native.rs @@ -39,8 +39,9 @@ pub(crate) fn run(app: &mut VectorcraftApp, ctx: &egui::Context) { } } -/// Once per frame, after the UI: bring the native menu up to date. A frame with a click or a key -/// press reads the menus again, as input may change state the key doesn't list. +/// Once per frame, after the UI: bring the native menu up to date. A frame with a click away from +/// the canvas or a key a field or a dialog took reads the menus again, as that input may change +/// state the key doesn't list ([`last_press`]). pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { if app.services.native_menu.is_none() { return; diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 20daf678db..a59fe7f769 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -209,13 +209,10 @@ fn window_menu_labels_start_in_one_column() { } /// An app with a new document whose installed fonts are cataloged, after the frames that build its first menus and the -/// window's keymap. It runs in a process of its own ([`crate::testing::in_own_process`]): the menus' key holds the -/// installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in that another test -/// installs, or a font it adds, rebuilds this app's menus. `None` in the parent process. -fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { - if !crate::testing::in_own_process(test) { - return None; - } +/// window's keymap. Each test that uses it runs in a process of its own ([`crate::testing::in_own_process`]): the menus' +/// key holds the installed plug-ins' revision and the fonts' generation, which are the whole process's, so a plug-in +/// that another test installs, or a font it adds, rebuilds this app's menus. +fn settled_app() -> (VectorcraftApp, egui::Context) { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); // The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends: wait for it. vectorcraft_text::FontDb::global().family_list(); @@ -224,25 +221,128 @@ fn settled_app(test: &str) -> Option<(VectorcraftApp, egui::Context)> { for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); } - Some((app, ctx)) + (app, ctx) } -/// A key press builds the menus' states again once: the frames after it, with no press, keep them. +/// A key press that a dialog takes builds the menus' states again once: the frames after it, with no press, keep them. +/// The same key with no dialog or field to take it keeps them. #[test] -fn a_key_press_rebuilds_the_menus_once() { - let Some((mut app, ctx)) = settled_app("menus::tests::a_key_press_rebuilds_the_menus_once") else { return }; - let before = app.menus.rebuilds; +fn a_key_press_a_dialog_takes_rebuilds_the_menus_once() { + if !crate::testing::in_own_process("menus::tests::a_key_press_a_dialog_takes_rebuilds_the_menus_once") { + return; + } + let (mut app, ctx) = settled_app(); + // F20 runs no command and changes nothing the menus show. + let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + let rebuilds = |app: &mut VectorcraftApp, events: Vec| { + let before = app.menus.rebuilds; + app_frame(app, &ctx, events); + for _ in 0..4 { + app_frame(app, &ctx, vec![]); + } + app.menus.rebuilds - before + }; + assert_eq!(rebuilds(&mut app, vec![]), 0, "idle frames keep the menus"); + assert_eq!(rebuilds(&mut app, vec![press(true), press(false)]), 0, "a key nothing takes keeps the menus"); + app.run("file.documentSetup", json!({})).unwrap(); + rebuilds(&mut app, vec![]); + // No field of the dialog has the keys: the dialog itself takes them. + ctx.memory_mut(|m| { + if let Some(field) = m.focused() { + m.surrender_focus(field); + } + }); + rebuilds(&mut app, vec![]); + assert!(app.any_dialog_open(), "Document Setup is open"); + assert!(!craft::ui::runtime::windows::WindowHost::of(&ctx).typing(), "no text field has the keys"); + assert_eq!(rebuilds(&mut app, vec![press(true), press(false)]), 1, "a key the dialog takes rebuilds the menus once"); +} + +/// Show or Hide Panels, which the framework runs itself (Tab) with no app command, takes the check marks off the Window +/// menu's panel rows. +#[test] +fn hiding_the_panels_unchecks_the_window_rows() { + use craft::ui::runtime::commands::{ChromeCommand, CommandSet as _, CommandState, FireSource}; + if !crate::testing::in_own_process("menus::tests::hiding_the_panels_unchecks_the_window_rows") { + return; + } + let (mut app, ctx) = settled_app(); + let checked_panels = |app: &VectorcraftApp| { + app.menus + .bar + .items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && app.menus.states.get(&it.command).and_then(CommandState::is_checked) == Some(true)) + .count() + }; + assert!(checked_panels(&app) > 0, "a panel shows, and its Window row is checked"); + let raw = || egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 850.0))), ..Default::default() }; + crate::testing::part_frame(&mut app, &ctx, raw(), |app, ui| { + craft::ui::runtime::commands::fire(ui.ctx(), CommandRef::new(ChromeCommand::TogglePanels.id()), FireSource::Menu); + app.tick(ui.ctx()); + app.ui(ui); + }); for _ in 0..3 { app_frame(&mut app, &ctx, vec![]); } - assert_eq!(app.menus.rebuilds, before, "idle frames keep the menus"); - // F20 runs no command and changes nothing the menus show. - let press = |pressed| egui::Event::Key { key: egui::Key::F20, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; - app_frame(&mut app, &ctx, vec![press(true), press(false)]); - for _ in 0..4 { + assert!(!crate::panel_docking::panels_shown(&app), "the panels are hidden"); + assert_eq!(checked_panels(&app), 0, "no Window row is checked while the panels are hidden"); +} + +/// A panel flyout opened or closed without a command or input updates its Window row's check mark. +#[test] +fn closing_a_panel_flyout_unchecks_its_window_row() { + use craft::ui::runtime::commands::CommandState; + if !crate::testing::in_own_process("menus::tests::closing_a_panel_flyout_unchecks_its_window_row") { + return; + } + let (mut app, ctx) = settled_app(); + let row = app + .menus + .bar + .items() + .into_iter() + .find(|it| { + it.command.id == "window.panel" + && it.command.params["panel"] + .as_str() + .is_some_and(|panel| crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&panel.to_owned())) + }) + .expect("the default layout has an iconic panel's Window row") + .command + .clone(); + let checked = |app: &VectorcraftApp| app.menus.states.get(&row).and_then(CommandState::is_checked) == Some(true); + app.ui.open_panel = Some(row.params["panel"].as_str().unwrap().to_owned()); + for _ in 0..2 { app_frame(&mut app, &ctx, vec![]); } - assert_eq!(app.menus.rebuilds, before + 1); + assert!(checked(&app), "the Window row is checked while its panel shows in a flyout"); + app.ui.open_panel = None; + for _ in 0..2 { + app_frame(&mut app, &ctx, vec![]); + } + assert!(!checked(&app), "the Window row is unchecked after its panel's flyout closes"); +} + +/// A view turned by the canvas's navigation (a Shift+drag on the canvas), with no command and no document change, moves +/// View › Rotate View's check to the angle it was turned to. +#[test] +fn a_view_turned_on_the_canvas_moves_the_rotate_view_check() { + use craft::ui::runtime::commands::CommandState; + if !crate::testing::in_own_process("menus::tests::a_view_turned_on_the_canvas_moves_the_rotate_view_check") { + return; + } + let (mut app, ctx) = settled_app(); + let rows: Vec = app.menus.bar.items().into_iter().filter(|it| it.command.id == "view.rotate").map(|it| it.command.clone()).collect(); + let angle = |row: &CommandRef| row.params["angle"].as_f64().unwrap_or(0.0); + let turned = rows.iter().find(|row| angle(row) != 0.0).expect("Rotate View lists an angle other than 0").clone(); + let checked = |app: &VectorcraftApp, row: &CommandRef| app.menus.states.get(row).and_then(CommandState::is_checked) == Some(true); + assert!(!checked(&app, &turned), "the view starts unturned"); + app.view_mut().expect("a view").rotation = angle(&turned); + for _ in 0..2 { + app_frame(&mut app, &ctx, vec![]); + } + assert!(checked(&app, &turned), "the angle the view is turned to is checked"); } /// A font added to the fonts the whole process shares builds the menus again with no input, Type › Font then lists it, @@ -250,7 +350,10 @@ fn a_key_press_rebuilds_the_menus_once() { #[test] fn a_new_font_rebuilds_the_menus() { const FAMILY: &str = "Menurebuild Sans"; - let Some((mut app, ctx)) = settled_app("menus::tests::a_new_font_rebuilds_the_menus") else { return }; + if !crate::testing::in_own_process("menus::tests::a_new_font_rebuilds_the_menus") { + return; + } + let (mut app, ctx) = settled_app(); let lists = |app: &VectorcraftApp| app.menus.bar.items().into_iter().any(|it| it.command.id == "text.setStyle" && it.command.params["font"] == FAMILY); assert!(!lists(&app)); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 4dd9694c3b..61edc5a5c4 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1769,7 +1769,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.placementOptionsDialog", "Placement Options…", "", - "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions", + "{ids?} open Placement Options for images `ids` (default: the selected ones; dialog `placementOptions`: ids, preserve, align, clip, see links.placementOptions); OK runs links.placementOptions in the document it opened in, and refuses after that document is reverted or after an Undo or Redo there (reopen the dialog)", ), ( "ui.relinkDialog", diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 271d605d7f..45babc785c 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1257,6 +1257,20 @@ fn the_overflow_menu_of_a_docked_group_is_reached_and_used_from_the_keyboard() { assert!(h.strip_has_focus(), "the focus stays on the strip after the pick"); } +/// A key that a panel's control takes builds the menus' states again: the control can change what a panel menu row +/// reads without running a command. +#[test] +fn a_key_a_panel_control_takes_rebuilds_the_menus() { + let mut h = Harness::new(); + let strip = h.named("Panels", egui::accesskit::Role::TabList).expect("a group's tab strip"); + h.click(pos2(strip.center().x, strip.bottom() + 25.0)); + assert!(h.strip_has_focus(), "a press in the group focuses its strip"); + let before = h.app.menus.rebuilds; + h.press(egui::Key::F20, egui::Modifiers::NONE); + h.frames(2); + assert!(h.app.menus.rebuilds > before, "the key the strip took rebuilds the menus"); +} + /// A tab group dragged out of the icon column by its grip floats as an expanded panel: its tabs show /// in the window, and a click on each tab shows that panel. #[test] diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 0591631dff..8f28023e0a 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -1414,10 +1414,14 @@ fn has_options(id: &str) -> bool { /// The values the inline editor lists: the effect's own values over its defaults, with earlier keys /// in their current form (Scribble's one `variation` as its Path Overlap and Spacing variations). fn editor_params(e: &Effect) -> serde_json::Map { - match vectorcraft_effects::merged_params(&e.id, &e.params) { + let mut values = match vectorcraft_effects::merged_params(&e.id, &e.params) { Value::Object(m) => m, _ => serde_json::Map::new(), + }; + if e.id == vectorcraft_effects::addons::halftone::HALFTONE { + crate::dialogs::halftone::canonical_style(&mut values); } + values } /// The paint a fill/stroke row's swatch sets: of the selection's fill/stroke row `index`, or, with diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 0ca5b4caf2..5c601967d3 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -2,6 +2,15 @@ use super::*; use crate::i18n::LangExt as _; use crate::tests::panel_harness::Panel; +#[test] +fn halftone_inline_editor_normalizes_stored_style_case() { + let mut app = app_with_a_selected_rectangle(); + let effect = vectorcraft_effects::addons::halftone::HALFTONE; + app.run("effect.apply", json!({"effect": effect, "item": null, "params": {"style": "GRIDDOTS"}})).unwrap(); + let n = node(&app); + assert_eq!(editor_params(&n.appearance.effects[0])["style"], json!("gridDots")); +} + /// A selected rectangle, for the panel's rows and footer. fn app_with_a_selected_rectangle() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 845552dd76..a62d126f24 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -20,7 +20,7 @@ use craft::ui::contract::{ use craft::ui::display::Text; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, ThumbSize, ToggleCell}; -use craft::ui::menu::PanelRow; +use craft::ui::menu::{Menu, MenuItem, PanelRow}; use craft::ui::notices::Notice; use craft::ui::pickers::Select; use craft::ui::runtime::commands::{CommandState, CommandStates}; @@ -132,7 +132,7 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(want) = check(ui, tl!("Overprint Preview (separations)"), on, app.session.active().is_some()) { act(app, "view.separationsPreview", json!({"on": want})); } - let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { + let Some((document, doc)) = app.session.active().map(|d| (d.uid, d.doc.clone())) else { Notice::new(Tone::Neutral, tl!("No document open.")).show(ui); return; }; @@ -151,7 +151,7 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { ]; // Disabled while the preview is off: the eyes then take no press and the rows read dim. let out = List::new(tl!("Plates")) - .id_salt("plates") + .id(ui.scope_id().with(("plates", document))) .select(SelectMode::None) .sizing(Sizing::Content) .natural_height(true) @@ -163,13 +163,23 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { if *key == 0 { tl!("Show all plates") } else { tl!("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)") }; let mut list_row = ListRow::new(row.shown.clone()).toggle(ToggleCell::eye(EYE, row.visible).tooltip(tooltip)); if let Some(ink) = row.chip { - list_row = list_row.thumb(ThumbSize::Small, move |painter, rect| { + list_row = list_row.row_menu().thumb(ThumbSize::Small, move |painter, rect| { painter.painter.rect_filled(rect, 2.0, ink); }); } list_row.cells(item.cells()).state(item.row.clone()) }); + let target_id = out.response.id.with("ink-menu-target"); for event in out.events { + if let CollectionEvent::ContextMenu(request) = &event { + let ink = request.key.checked_sub(1).and_then(|i| plates.get(i)); + ui.ctx().data_mut(|data| { + data.remove::(target_id); + if let Some(ink) = ink { + data.insert_temp(target_id, ink.name.clone()); + } + }); + } // A flip lands once: a click's set, or a sweep's commit at the release. It carries the Alt held at the press. let CollectionEvent::Toggle(EditEvent::Set { after: edit, .. } | EditEvent::Commit { after: edit, .. }) = event else { continue }; let p = match edit.key.checked_sub(1).and_then(|n| plates.get(n)) { @@ -178,6 +188,26 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { }; act(app, "view.separationsPreview", p); } + let name = ui.ctx().data(|data| data.get_temp::(target_id)); + if on && let Some(plate) = name.as_ref().and_then(|name| plates.iter().find(|p| &p.name == name)) { + let menu = Menu::context(tl!("Plates"), &out.response).show(ui, |ui, _| { + let toggle = if visible(&plate.name) { tl!("Hide Plate") } else { tl!("Show Plate") }; + if MenuItem::new(toggle).show(ui).ran { + act(app, "view.separationsPreview", eye_click(&plate.name, false)); + } + if MenuItem::new(tl!("Show Only This Plate")).show(ui).ran { + act(app, "view.separationsPreview", json!({"only": plate.name})); + } + if MenuItem::new(tl!("Show All Plates")).show(ui).ran { + act(app, SHOW_ALL_PLATES, json!({})); + } + }); + if menu.output.closed.is_some() { + ui.ctx().data_mut(|data| data.remove::(target_id)); + } + } else { + ui.ctx().data_mut(|data| data.remove::(target_id)); + } } /// The `view.separationsPreview` params for a click on plate `name`'s eye: with Alt, that plate @@ -464,6 +494,69 @@ mod tests { use crate::tests::panel_harness::Panel; use vectorcraft_engine::Session; + #[test] + fn plate_menu_keyboard_focus_and_actions() { + use egui::{Key, Modifiers}; + + if !crate::testing::in_own_process("panels::separations::tests::plate_menu_keyboard_focus_and_actions") { + return; + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + app.run("view.separationsPreview", json!({"on": true})).unwrap(); + let mut panel = Panel::new(app, plates_section); + panel.focus("Black"); + assert!(panel.focused("Black")); + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + assert!(panel.focused("Hide Plate")); + for item in ["Hide Plate", "Show Only This Plate", "Show All Plates"] { + assert!(panel.menu_item_enabled(item)); + } + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + panel.frame(); + assert!(!panel.shows("Hide Plate")); + assert!(panel.focused("Black")); + panel.key(Key::F10, Modifiers::SHIFT); + panel.frame(); + panel.frame(); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert!(panel.focused("Show Only This Plate")); + panel.key(Key::Enter, Modifiers::NONE); + assert_eq!(proof::view().separations.unwrap(), ["Black"]); + } + + #[test] + fn plate_menu_targets_the_clicked_process_or_spot_ink() { + // Plate visibility belongs to the process-wide proof view. + if !crate::testing::in_own_process("panels::separations::tests::plate_menu_targets_the_clicked_process_or_spot_ink") { + return; + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + app.run("swatch.new", json!({"name": "Menu Test Ink", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "spot": true})).unwrap(); + app.run("view.separationsPreview", json!({"on": true})).unwrap(); + let visible = || proof::view().separations.unwrap(); + let all = visible(); + let mut panel = Panel::new(app, plates_section); + panel.secondary_click("Magenta"); + panel.click_menu_item("Hide Plate"); + assert_eq!(visible(), all.iter().filter(|n| n.as_str() != "Magenta").cloned().collect::>()); + panel.secondary_click("Magenta"); + panel.click_menu_item("Show Plate"); + assert!(visible().iter().any(|n| n == "Magenta")); + for _ in 0..2 { + panel.secondary_click("Menu Test Ink (spot)"); + panel.click_menu_item("Show Only This Plate"); + assert_eq!(visible(), ["Menu Test Ink"]); + } + panel.secondary_click("Menu Test Ink (spot)"); + panel.click_menu_item("Show All Plates"); + assert_eq!(visible(), all); + } + #[test] fn load_profile_only_offers_a_picker_that_returns_a_path() { use craft::host::ScriptedFiles; diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index dbaba5c761..8ea894b54a 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -502,6 +502,7 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) { let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone())) .sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN) .closed(mixed.can_align) + .caps_on_closed(true) .mixed(&mixed_of(&mixed)) .host_labels(true); let output = editor.show(ui); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index ca2b52c605..bea36866bb 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -81,7 +81,7 @@ impl View { } /// Swatch-kind filter (Show Swatch Kinds menu). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Kind { #[default] All, @@ -213,6 +213,44 @@ impl Model { } } +/// The browser settings and selection shared with the paint chip popover, without its document caches. +#[derive(MemoProps)] +pub(crate) struct BodyInputs { + view: PresetView, + zoom: f64, + toggled: Vec<(bool, String)>, + filter: String, + selected: Vec, + lead: Option, + anchor: Option, + rename: Option, + #[memo_props(hash = "the Show Swatch Kinds filter")] + kind: Kind, + show_find: bool, +} + +impl BodyInputs { + pub(crate) fn of(app: &VectorcraftApp) -> Self { + let model = &app.ui.swatches_panel; + let state = &model.state; + let browser = &state.browser; + let mut toggled: Vec<_> = browser.toggled.iter().map(|key| (matches!(key, SwatchKey::Group(_)), name_of(key).to_owned())).collect(); + toggled.sort_unstable(); + Self { + view: browser.view, + zoom: browser.zoom, + toggled, + filter: browser.filter.clone(), + selected: state.selection.items.clone(), + lead: state.selection.lead.clone(), + anchor: state.selection.anchor.clone(), + rename: state.rename.clone(), + kind: model.kind, + show_find: model.show_find, + } + } +} + fn name_of(key: &SwatchKey) -> &str { match key { SwatchKey::Group(n) | SwatchKey::Swatch(n) => n, diff --git a/crates/ui-egui/src/panels/tests_strokeux.rs b/crates/ui-egui/src/panels/tests_strokeux.rs index 12839f283c..11dd24ebd5 100644 --- a/crates/ui-egui/src/panels/tests_strokeux.rs +++ b/crates/ui-egui/src/panels/tests_strokeux.rs @@ -157,6 +157,28 @@ fn inside_and_outside_are_off_for_open_paths_and_on_for_type() { assert_eq!(align(&panel), vectorcraft_doc::StrokeAlign::Inside, "type's characters do, around their glyphs"); } +/// A closed path without dashes still shows its cap and takes a new one, ready for when dashes are turned on. +#[test] +fn caps_stay_on_for_a_solid_closed_path() { + use craft::behavior::Mixed; + use vectorcraft_doc::LineCap; + + let mut app = app_with_rect(); + run(&mut app, "paint.setStroke", json!({"color": "#222222"})); + run(&mut app, "stroke.set", json!({"cap": "square"})); + let mut panel = Panel::new(app, stroke::show); + panel.frame(); + let stroke = |p: &Panel| current_stroke(&p.app()).unwrap(); + assert!(stroke(&panel).dash.is_none(), "the rectangle's stroke is solid"); + assert!(panel.enabled("Butt / Flat")); + assert!(panel.enabled("Square")); + assert_eq!(panel.toggled("Square"), Some(Mixed::Same(true)), "the current cap is lit"); + let baseline = panel.app().session.active().unwrap().history.undo.len(); + panel.click("Butt / Flat"); + assert_eq!(stroke(&panel).cap, LineCap::Butt); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), baseline + 1); +} + /// While the Type tool edits text, Align Stroke styles the selected characters' stroke. #[test] fn align_stroke_styles_the_characters_the_type_tool_selects() { diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 9d1cc5be02..9d972c06a5 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -16,7 +16,7 @@ use std::sync::mpsc::{Receiver, TryRecvError, channel}; use craft::ui::dialog::{DialogId, dialog_id}; use serde_json::{Value, json}; use vectorcraft_engine::cancel::{self, CancelToken}; -use vectorcraft_engine::cmd::clipboard::{Clipboard, Flavour, ImageRead, read_image}; +use vectorcraft_engine::cmd::clipboard::{Clipboard, Flavour, ImageRead}; use vectorcraft_engine::cmd::place::{PlaceRead, QueueRead}; use vectorcraft_engine::file_access::ScopeHandle; @@ -312,7 +312,7 @@ pub fn start_queue(app: &mut VectorcraftApp, p: &Value, asks: bool) -> Result Result, String> { @@ -353,7 +353,8 @@ pub fn adopt_for_paste(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result< let started = spawn_labeled(app, "clipboard".into(), "Pasting".into(), false, Some(chain), move || { let pasted = make.and_then(|m| m()).map(|f| { if crate::sysclip::imports_as_image(f.mime) { - Pasted::Image(f.mime, read_image(&f.data).map_err(|e| e.to_string())) + let (mime, read) = crate::sysclip::read_bitmap(f); + Pasted::Image(mime, read) } else { Pasted::Flavour(f) } diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index c318aa4aa7..5276329c86 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -411,11 +411,11 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result, jo Ok(notes) } -/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable -/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error. +/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent: none). Anything but printable +/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, null included, is an error. fn paper_param(p: &Value) -> Result, String> { match p.get("paper") { - None | Some(Value::Null) => Ok(None), + None => Ok(None), Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())), Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")), } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 74ceaab6b6..eedac25ef3 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -74,9 +74,11 @@ pub fn poll(app: &mut VectorcraftApp) { let limit = limited.then(|| app.ui.status.clone()); app.publish_clipboard(false); // The limit's message is set again, so the notes of the Copy's formats do not - // replace it. A write failure reported at once stays on the status bar. + // replace it, whether they are written later or at once (while the worker has a + // save, an export, a print or a recovery copy to finish). A write failure reported + // at once stays on the status bar. if let Some(limit) = limit - && app.ui.status == limit + && (app.ui.status == limit || app.clipboard_publishing.shows_notes(&app.ui)) { app.status(limit); app.ui.status_notes = None; diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 8c54822d2f..9c8b7662c1 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -15,7 +15,7 @@ use std::sync::mpsc::channel; use craft::platform::clipboard::{Clipboard, Flavor, RGBA8, Written}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::clipboard::{ - AI, BITMAP, EMF, EPS, Flavour, ImageRead, PASTE_ORDER, PDF, PNG, SVG, TEXT, looks_like_svg, names_a_picture, + AI, BITMAP, EMF, EPS, Flavour, ImageRead, PASTE_ORDER, PDF, PNG, SVG, TEXT, looks_like_svg, names_a_picture, read_image, read_pixels, }; use crate::VectorcraftApp; @@ -53,12 +53,61 @@ pub(crate) fn engine_flavour(f: Flavor) -> Option { Some(Flavour { mime, data: f.data }) } -/// A raw bitmap (width and height as little-endian `u32`s, then straight RGBA8 pixels) as a PNG flavour. -fn rgba8_png(data: &[u8]) -> Option { - let (header, pixels) = data.split_first_chunk::<8>()?; +/// [`engine_flavour`] for a paste whose bitmap is read off the UI thread: a raw bitmap ([`RGBA8`]) +/// stays raw, and [`read_bitmap`] reads its pixels as they are instead of encoding and decoding them. +fn deferred_flavour(f: Flavor) -> Option { + if f.mime == RGBA8 { + return Some(Flavour { mime: RGBA8, data: f.data }); + } + engine_flavour(f) +} + +/// Do the pixels of a raw bitmap ([`RGBA8`]) fill the size its header gives, as [`rgba8_image`] +/// requires? The pixels are not copied. +fn rgba8_fits(data: &[u8]) -> bool { + let Some(([w0, w1, w2, w3, h0, h1, h2, h3], pixels)) = data.split_first_chunk::<8>() else { return false }; + let (width, height) = (u32::from_le_bytes([*w0, *w1, *w2, *w3]), u32::from_le_bytes([*h0, *h1, *h2, *h3])); + rgba8_len(width, height).is_some_and(|n| n <= pixels.len()) +} + +/// The byte count of `width` × `height` RGBA8 pixels; `None` for an empty size or one that +/// overflows. +fn rgba8_len(width: u32, height: u32) -> Option { + if width == 0 || height == 0 { + return None; + } + let n = u64::from(width).checked_mul(u64::from(height))?.checked_mul(4)?; + usize::try_from(n).ok() +} + +/// The bitmap of `f`, a flavour that imports as an image ([`imports_as_image`]), read as +/// `clipboard.importImage` reads it, and the type `clipboard.importImage` is given for it. A raw +/// bitmap ([`RGBA8`]) is read from its pixels ([`read_pixels`]); other types are decoded from their +/// bytes ([`read_image`]). +pub(crate) fn read_bitmap(f: Flavour) -> (&'static str, Result) { + if f.mime != RGBA8 { + return (f.mime, read_image(&f.data).map_err(|e| e.to_string())); + } + let read = rgba8_image(f.data).ok_or_else(|| "the copied bitmap is cut short".to_string()); + (PNG, read.and_then(|img| read_pixels(img).map_err(|e| e.to_string()))) +} + +/// A raw bitmap (width and height as little-endian `u32`s, then straight RGBA8 pixels) as an +/// image; `None` when the size is empty or the pixels don't fill it. Bytes past the pixels are +/// dropped. +fn rgba8_image(mut data: Vec) -> Option { + let (header, _) = data.split_first_chunk::<8>()?; let [w0, w1, w2, w3, h0, h1, h2, h3] = *header; let (width, height) = (u32::from_le_bytes([w0, w1, w2, w3]), u32::from_le_bytes([h0, h1, h2, h3])); - let img = image::RgbaImage::from_raw(width, height, pixels.to_vec())?; + let len = rgba8_len(width, height)?; + data.drain(..8); + data.truncate(len); + image::RgbaImage::from_raw(width, height, data) +} + +/// A raw bitmap (width and height as little-endian `u32`s, then straight RGBA8 pixels) as a PNG flavour. +fn rgba8_png(data: &[u8]) -> Option { + let img = rgba8_image(data.to_vec())?; let mut png = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?; Some(Flavour { mime: PNG, data: png }) @@ -130,6 +179,12 @@ impl Publishing { self.kept = Some((ui.status.clone(), ui.status_sets)); } + /// Does `ui`'s status bar show the notes of a Copy's or Cut's formats ([`show_copy_notes`]), + /// with nothing setting the status since? + pub(crate) fn shows_notes(&self, ui: &crate::state::UiState) -> bool { + self.notes_status.as_ref().is_some_and(|(status, sets)| *status == ui.status && *sets == ui.status_sets) + } + /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? Different text read from `cb` shows /// a later copy: the record of the failed write is then dropped, so the clipboard holding the @@ -577,9 +632,12 @@ impl VectorcraftApp { .filter(|t| stands_in_for_a_picture(t)) .and_then(|_| self.clipboard.read_later(&[BITMAP]).ok().flatten()); Some(Box::new(move || { - let f = engine_flavour(first()?)?; + let f = deferred_flavour(first()?)?; match picture { - Some(picture) if is_picture_stand_in(&f) => picture().and_then(engine_flavour).or(Some(f)), + // A raw bitmap cut short gives way to the text, as a picture that can't be read does. + Some(picture) if is_picture_stand_in(&f) => { + picture().and_then(deferred_flavour).filter(|p| p.mime != RGBA8 || rgba8_fits(&p.data)).or(Some(f)) + } _ => Some(f), } })) diff --git a/crates/ui-egui/src/tests/quickpenbar.rs b/crates/ui-egui/src/tests/quickpenbar.rs index 709e2b4822..841cc76d18 100644 --- a/crates/ui-egui/src/tests/quickpenbar.rs +++ b/crates/ui-egui/src/tests/quickpenbar.rs @@ -1,6 +1,6 @@ //! The Quick Pen toolbar: it shows while the Quick Pen tool is active, its buttons set the tool's //! action and flip the last sharp-corner arc, it follows the drawing beside the path's last point, -//! and its More options menu's commands hide it, pin it and reset its place. +//! and its More Options menu's commands hide it, pin it and reset its place. use egui::{Event, PointerButton, Pos2, Rect, Vec2, vec2}; use serde_json::json; @@ -15,7 +15,7 @@ use crate::VectorcraftApp; const BAR: &str = "Quick Pen"; /// The names of its members. -const MEMBERS: [&str; 5] = ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More options"]; +const MEMBERS: [&str; 5] = ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More Options"]; fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); @@ -251,8 +251,8 @@ fn the_toolbar_goes_to_the_other_side_where_it_runs_off_the_canvas() { fn the_toolbar_stays_while_its_handle_drags_far() { let mut app = app(); on_canvas(&mut app, |rig| { - assert!(bar(rig).is_some()); - let grip = rig.target("Move bar").expect("the toolbar's handle"); + let before = bar(rig).expect("the toolbar is shown"); + let grip = rig.target("Move Toolbar").expect("the toolbar's handle"); rig.fx.press(&grip); let from = grip.center(); for k in 1..=6 { @@ -260,12 +260,14 @@ fn the_toolbar_stays_while_its_handle_drags_far() { assert!(rig.fx.by_label(BAR).is_some(), "shown at step {k}"); } rig.fx.release_at(from + vec2(-120.0, -180.0)); - assert!(bar(rig).is_some()); + let after = bar(rig).expect("the toolbar stays after the release"); + assert_eq!(after.size(), before.size(), "the drag keeps the toolbar's size"); + assert_ne!(after.min, before.min, "the drag moved the toolbar"); }); } /// The handle drags the toolbar, which keeps that offset as it follows the drawing, but not in its -/// resting place with no path being drawn; pinned, it stays put; Reset bar position puts it back beside +/// resting place with no path being drawn; pinned, it stays put; Reset Toolbar Position puts it back beside /// the drawing, unpinned. #[test] fn the_toolbar_drags_pins_and_resets() { @@ -277,7 +279,7 @@ fn the_toolbar_drags_pins_and_resets() { click_doc(rig, 150.0, 100.0); let beside = from_end(rig, 150.0, 100.0); assert!(beside.x > 0.0 && beside.y > 0.0, "beside the end, below it: {beside:?}"); - let grip = rig.target("Move bar").expect("the toolbar's handle"); + let grip = rig.target("Move Toolbar").expect("the toolbar's handle"); let by = vec2(30.0, 40.0); rig.fx.drag(&grip, by); rig.fx.settle(); @@ -313,3 +315,19 @@ fn the_toolbar_drags_pins_and_resets() { assert!((reset - beside).length() < 1.5, "back beside the drawing: {beside:?} then {reset:?}"); }); } + +/// The toolbar's More Options rows read as the commands they run, Hide Toolbar as Window › Quick Pen +/// Toolbar's description names it, and Pin Toolbar Position pins the toolbar. +#[test] +fn more_options_rows_read_as_their_commands() { + let mut app = app(); + on_canvas(&mut app, |rig| { + rig.click("More Options"); + let pin = super::taskbar::command_title("window.quickPenToolbar.pin"); + for row in ["Hide Toolbar", pin, super::taskbar::command_title("window.quickPenToolbar.reset")] { + assert!(rig.target(row).is_some(), "More Options lists {row}"); + } + rig.click(pin); + assert!(rig.app().ui.quick_pen_bar_place.place.pinned, "Pin Toolbar Position pins the toolbar"); + }); +} diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 87ac38b1d1..2d30d27f28 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -655,6 +655,52 @@ fn a_copy_note_does_not_replace_a_scripts_recording_limit() { assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit"); } +/// Runs a script whose Copy is followed by commands that take a recording past its limit, to its end. +fn run_copy_script_past_recording_limit(app: &mut VectorcraftApp) { + run(app, crate::panels::actions::START_RECORDING, json!({})); + for _ in 0..vectorcraft_engine::script::actions::MAX_ACTION_STEPS - 1 { + app.session.journal.push(("object.group".to_string(), json!({}))); + } + app.session.script_frames = true; + let source = "vc.run('edit.copy', {}); vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});"; + run(app, "script.run", json!({"source": source, "name": "t.js"})); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + crate::script_runs::poll(app); + } + assert!(!app.session.script_running(), "the script ends"); +} + +/// While the worker has a save to finish, a script's Copy writes its formats at once: their note +/// does not replace the recording limit's message either. +#[test] +fn a_copy_note_written_at_once_does_not_replace_a_scripts_recording_limit() { + let (mut app, board, hold) = app_with_busy_worker("Saving a.vectorcraft"); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + run_copy_script_past_recording_limit(&mut app); + assert_eq!(written(&board), [TEXT, SVG, PNG], "the formats are written before the save ends"); + let limit = "the action already has 10,000 steps"; + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit"); + drop(hold); + background::wait_all(&mut app); + assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the save's end leaves the limit"); +} + +/// While the worker has a save to finish, a script's Copy whose formats cannot be written says so +/// in place of the recording limit's message. +#[test] +fn a_copy_written_at_once_that_fails_is_reported_over_a_scripts_recording_limit() { + let (mut app, board, hold) = app_with_busy_worker("Saving a.vectorcraft"); + vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({})); + refuse_writes(&board, true); + run_copy_script_past_recording_limit(&mut app); + assert!(app.ui.status.starts_with("Couldn't copy to the system clipboard: "), "the failure is shown: {}", app.ui.status); + drop(hold); + background::wait_all(&mut app); +} + /// A message shown while a Copy's formats are made on the worker stays: the formats are written /// once they are ready, and their note does not replace the newer message. #[test] @@ -998,6 +1044,86 @@ fn an_image_copied_in_a_browser_pastes_as_the_picture_not_its_address() { assert_eq!(t.plain_text(), "https://example.com/images/cat.png"); } +/// A paste whose bitmap is read off the UI thread takes the pixels the clipboard gives as they are: +/// it encodes them once for the document and decodes nothing, before or after the paste. +#[test] +fn a_bitmap_read_off_the_ui_thread_is_not_decoded_again() { + let (mut app, board) = app(); + let img = image::RgbaImage::from_fn(3, 2, |x, y| image::Rgba([(x * 80) as u8, (y * 120) as u8, 200, 255 - x as u8])); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + copy_elsewhere(&board, vec![(TEXT, b"https://example.com/images/cat.png".to_vec()), (PNG, png)]); + let make = app.adopt_system_clipboard_or_defer(true).unwrap().expect("the picture is read later"); + let before = vectorcraft_doc::decode::decodes(); + let (mime, read) = crate::sysclip::read_bitmap(make().expect("a picture")); + app.adopt_image_read(mime, Some([250.0, 180.0]), read).unwrap(); + // The paste the read was for, of the internal clipboard the read loaded. + app.session.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(vectorcraft_doc::decode::decodes() - before, 0, "the pixels were decoded again"); + let NodeKind::Image(im) = &pasted(&app)[0].kind else { panic!("not an image: {:?}", pasted(&app)[0].kind) }; + assert_eq!((im.width, im.height), (3, 2)); + let blob = &app.session.active().unwrap().doc.images[&im.key]; + assert_eq!(image::load_from_memory(&blob.bytes).unwrap().to_rgba8(), img, "the document keeps the copied pixels"); + // The first draw paints the image from the pixels the read kept. + let center = im.xf * Point::new(1.5, 1.0); + let decodes = vectorcraft_render::image_decodes(); + let doc = &app.session.active().unwrap().doc; + let opts = vectorcraft_render::RenderOptions::default(); + let r = vectorcraft_render::Renderer::new().render(doc, 800, 800, vectorcraft_geom::Affine::IDENTITY, &opts); + assert_eq!(vectorcraft_render::image_decodes(), decodes, "the first draw decoded the pasted image"); + assert!(r.pixel(center.x as u32, center.y as u32)[3] > 0, "the pasted image is drawn at {center:?}"); +} + +/// A raw bitmap read off the UI thread whose pixels don't fill its size is not taken: the text +/// beside it is pasted instead. +#[test] +fn a_cut_short_bitmap_read_off_the_ui_thread_gives_way_to_its_text() { + let (mut app, board) = app(); + assert!(RGBA8.starts_with("image/"), "the fake clipboard finds a raw bitmap as any bitmap"); + // 3 by 2 pixels need 24 bytes after the header; 20 are there. + let mut raw = [3u32.to_le_bytes(), 2u32.to_le_bytes()].concat(); + raw.extend_from_slice(&[255; 20]); + copy_elsewhere(&board, vec![(TEXT, b"https://example.com/images/cat.png".to_vec()), (RGBA8, raw.clone())]); + let make = app.adopt_system_clipboard_or_defer(true).unwrap().expect("the picture is read later"); + let f = make().expect("the text"); + assert_eq!((f.mime, f.data.as_slice()), (TEXT, &b"https://example.com/images/cat.png"[..])); + // With no text beside it, the bitmap is read and its error reported, not dropped. + copy_elsewhere(&board, vec![(RGBA8, raw)]); + let make = app.adopt_system_clipboard_or_defer(true).unwrap().expect("the picture is read later"); + let (_, read) = crate::sysclip::read_bitmap(make().expect("the bitmap")); + assert_eq!(read.err().as_deref(), Some("the copied bitmap is cut short")); +} + +/// A raw bitmap read off the UI thread with no width or no height is not taken: the text beside +/// it is pasted instead. +#[test] +fn an_empty_bitmap_read_off_the_ui_thread_gives_way_to_its_text() { + let (mut app, board) = app(); + for (w, h) in [(0u32, 2u32), (3, 0)] { + let raw = [w.to_le_bytes(), h.to_le_bytes()].concat(); + copy_elsewhere(&board, vec![(TEXT, b"https://example.com/images/cat.png".to_vec()), (RGBA8, raw)]); + let make = app.adopt_system_clipboard_or_defer(true).unwrap().expect("the picture is read later"); + let f = make().expect("the text"); + assert_eq!((f.mime, f.data.as_slice()), (TEXT, &b"https://example.com/images/cat.png"[..]), "{w} by {h}"); + } +} + +/// A raw bitmap read off the UI thread with bytes past its pixels pastes its pixels. +#[test] +fn a_padded_bitmap_read_off_the_ui_thread_pastes_its_pixels() { + let (mut app, board) = app(); + // 3 by 2 pixels need 24 bytes after the header; 28 are there. + let mut raw = [3u32.to_le_bytes(), 2u32.to_le_bytes()].concat(); + raw.extend_from_slice(&[255; 28]); + copy_elsewhere(&board, vec![(TEXT, b"https://example.com/images/cat.png".to_vec()), (RGBA8, raw)]); + let make = app.adopt_system_clipboard_or_defer(true).unwrap().expect("the picture is read later"); + let (mime, read) = crate::sysclip::read_bitmap(make().expect("the bitmap")); + app.adopt_image_read(mime, Some([250.0, 180.0]), read).unwrap(); + app.session.execute("edit.paste", &json!({})).unwrap(); + let NodeKind::Image(im) = &pasted(&app)[0].kind else { panic!("not an image: {:?}", pasted(&app)[0].kind) }; + assert_eq!((im.width, im.height), (3, 2)); +} + #[test] fn a_pdf_from_another_app_pastes_as_vectors_ahead_of_its_bitmap() { let (mut app, board) = app(); diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 1995432740..42b27f59ac 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1501,7 +1501,7 @@ fn shape_tools_show_edit_path_paint_and_properties_after_drawing() { assert!(!offers(&o, what), "{tool}: {what} is left out of {:?}", names_of(&o)); } on_canvas(&mut app, |rig| { - assert!(rig.target("More options").is_some(), "{tool}: More options"); + assert!(rig.target("More Options").is_some(), "{tool}: More Options"); if let Some(heading) = heading { rig.click("Shape Properties"); assert!(rig.has_text(heading), "{tool}: {heading}"); @@ -1570,7 +1570,7 @@ fn the_smooth_tool_shows_fidelity_and_tool_options_for_a_path() { select(&mut app, &[path]); app.run("tool.select", json!({"tool": "smooth"})).unwrap(); on_canvas(&mut app, |rig| { - assert!(rig.target("Tool Options…").is_some() && rig.target("More options").is_some()); + assert!(rig.target("Tool Options…").is_some() && rig.target("More Options").is_some()); let field = rig.field_after("Fidelity:"); rig.enter_value(field, "7"); }); @@ -1967,7 +1967,7 @@ fn more_options_bar_actions_turns_an_action_off_and_on() { show_action(&mut app, "offsetPath", false); assert!(!shows(&offer(&mut app).unwrap(), "Offset Path")); on_canvas(&mut app, |rig| { - rig.click("More options"); + rig.click("More Options"); assert!(rig.target("Bar Actions").is_some(), "More lists Bar Actions"); rig.click("Reset Bar Actions"); }); @@ -1975,6 +1975,52 @@ fn more_options_bar_actions_turns_an_action_off_and_on() { assert!(shows(&offer(&mut app).unwrap(), "Offset Path")); } +/// The title of the command `id`. +pub(crate) fn command_title(id: &str) -> &'static str { + crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).map(|c| c.1).unwrap_or_else(|| panic!("no command {id}")) +} + +/// The bar's More Options button, its grip and its menu's rows read in title case, as the rows of the +/// bar's own Bar Actions and the commands Pin and Reset run do, and Pin Bar Position pins the bar. +#[test] +fn more_options_rows_read_as_their_commands() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + on_canvas(&mut app, |rig| { + assert!(rig.target("Move Bar").is_some(), "the grip"); + rig.click("More Options"); + let (pin, reset) = (command_title("window.taskBar.pin"), command_title("window.taskBar.reset")); + for row in ["Hide Bar", pin, reset] { + assert!(rig.target(row).is_some(), "More Options lists {row}"); + } + rig.click(pin); + }); + assert!(app.ui.task_bar_place.place.pinned, "Pin Bar Position pins the bar"); +} + +/// Outside English, a bar's word takes VectorCraft's translation where its catalog has one and the framework's +/// otherwise; a command that does not exist leaves its row to the framework. +#[test] +fn bar_words_keep_the_framework_translation_without_a_catalog_row() { + use crate::i18n::LangExt as _; + use craft::i18n::WordSet as _; + use craft::ui::canvas_controls::CanvasControlWords; + let word = |id: &str| CanvasControlWords::word(id).unwrap_or_else(|| panic!("no word {id}")); + let de = crate::i18n::Lang::from_code("de").unwrap(); + let rows = canvas::task_bar::bar_words(de, "Move Bar", "Hide Bar", "window.taskBar.pin", "no.such.command"); + let german = crate::i18n::tr(de, "More Options"); + assert_ne!(german, "More Options", "the German catalog translates More Options"); + assert_eq!(rows.text(word("taskBar.more")), Some(german)); + assert_eq!(rows.text(word("taskBar.pin")), Some(crate::i18n::tr_id(de, "window.taskBar.pin", command_title("window.taskBar.pin")))); + assert_eq!(rows.text(word("taskBar.move")), None, "no German row for Move Bar"); + assert_eq!(rows.text(word("taskBar.reset")), None, "no such command"); + let english = canvas::task_bar::bar_words(crate::i18n::Lang::EN, "Move Bar", "Hide Bar", "window.taskBar.pin", "window.taskBar.reset"); + assert_eq!(english.text(word("taskBar.move")), Some("Move Bar")); + assert_eq!(english.text(word("taskBar.reset")), Some(command_title("window.taskBar.reset"))); +} + /// Every action and chip the bar offers, for every kind of selection and tool, has an id in Bar /// Actions, and with all of them turned off the bar shows none of them but still shows, with More /// options. That covers Connect and Join (both `join`), the actions matched by the tool they switch to @@ -2154,8 +2200,8 @@ fn every_action_the_bar_offers_can_be_turned_off() { let off = offer(&mut app).unwrap_or_else(|| panic!("{case}: the bar still shows")); assert!(off.actions.is_empty() && off.chips.is_empty(), "{case}: every action is off: {:?}", names_of(&off)); assert_eq!(off.listed.len(), o.listed.len(), "{case}: Bar Actions still lists them"); - // The bar still shows, with More options, where Bar Actions turns them back on. - let more = on_canvas(&mut app, |rig| rig.target(BAR).is_some() && rig.target("More options").is_some()); - assert!(more, "{case}: the bar still shows its More options"); + // The bar still shows, with More Options, where Bar Actions turns them back on. + let more = on_canvas(&mut app, |rig| rig.target(BAR).is_some() && rig.target("More Options").is_some()); + assert!(more, "{case}: the bar still shows its More Options"); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 21c81bda1e..71e3d0fae9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -884,7 +884,8 @@ art too large at that scale) keeps the dialog open. Placement Options: the Links panel's flyout (or `ui.placementOptionsDialog {ids?}` for agents) opens the `placementOptions` dialog for the selected images (fields `ids`, `preserve`: `transforms`/`bounds`/`fileDimensions`/ `fit`/`fill`, `align`: `topLeft` … `bottomRight`, `clip`). `ui.dialog.confirm` runs `links.placementOptions` with them as -one undo step, on the images the dialog opened on even when the selection has changed since. +one undo step, on the images the dialog opened on even when the selection has changed since. After that document is +reverted, or after an Undo or Redo in it, the confirm is refused and the dialog stays open; reopen it to continue. Relink: the Links panel's Relink… button and flyout item (or `ui.relinkDialog {ids?}` for agents) open the `relink` dialog for the selected images and placed documents (fields `ids`, `links`: `[{name, ids}]`, one row per linked file, @@ -1077,8 +1078,10 @@ Colour adjustment effects (Effect → Color Adjustments) open the `effect` dialo `channel` for Curves and Levels, `points` for Curves, `color` for Shift to Color) and they preview live; set them with `ui.dialog.set` and `ui.dialog.confirm` to apply (Curves also has a graph: drag its points). Object → Vector Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "object.vectorHalftone"}}`) opens the -`object.vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`, -`preview`): it previews live and `ui.dialog.confirm` keeps the halftone as one undo step. +`object.vectorHalftone` dialog (fields `style`, `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, +`keepOriginal`, `preview`): it previews live and `ui.dialog.confirm` keeps the halftone as one undo step. +The `style` field accepts `custom`, `grid`, `gridAngle`, `gridDots`, and `gridDotsAngle`. A named style hides +Shape and Angle, which apply only with Custom. Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay diff --git a/docs/development.md b/docs/development.md index e2aed29e62..52efff471b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,8 +178,8 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- that face lacks and that doesn't fit a Latin row, such as Georgian), then the other scripts' faces, then the installed fonts it finds for other scripts on the desktop. On the web the `startup` and `demand` faces of `crates/text/web-fonts.txt` are served under `fonts/ui/` - instead: the stack fetches the UI language's at once and the others the first time text needs - them. + instead (`cargo xtask web-fonts`, the Trunk hook, publishes them there): the stack fetches the UI + language's at once and the others the first time text needs them. - Document tab titles: desktop builds also embed the Noto Sans Condensed SemiBold row of the checkout's opt-in `fonts/latin-manifest.txt` (`Embed::tab_face` in `crates/text/build.rs`). The interface font stack draws document tab titles in it, scaled to the x-height of the @@ -583,6 +583,7 @@ Scores and hour estimates are unchanged. | Date | Change | Summary | |---|---|---| +| 2026-12-02 | patch | Fonts (#10567): the Trunk hook `cargo xtask web-fonts` also publishes the interface's `startup` and `demand` faces under `fonts/ui/`, where `SERVED_FONTS` points; before, the site lacked them and the web interface drew those scripts as missing-glyph boxes. | | 2026-11-24 | minor | Fonts: the interface font stack is the framework's, set up by `ui_fonts()` and installed by `embed::install` (craft-fonts faces, the web's served faces, embedders); `theme::install_fonts` is gone and `interface-fonts` changes nothing. | | 2026-11-12 | minor | Tests (#6860): compare preset refusal roots after canonicalization and Windows display normalization; canonicalize the script fixture base before constructing `MAIN`. This keeps macOS `/var` → `/private/var` aliases from masking the case-sensitivity checks; no production-code change. | | 2026-11-12 | minor | Compile the clipboard failure helper only for Linux/BSD worker callers and unit tests; keep production macOS free of the unused helper without suppressing workspace dead-code warnings. | diff --git a/docs/gaps.md b/docs/gaps.md index 6054399bc1..79fdb40586 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -474,7 +474,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Done (2026-11-03):** SVG Options › Units (`units`) explicitly overrides `width` and `height` with `px` (bare numbers; CSS pixels are 96 per inch), `pt`, `mm`, `cm` or `in`, with the `viewBox` in points (#4462). Responsive omits both dimensions; unknown units and explicit null are errors. Without an override, export - retains the document's physical units as below. Estimate unchanged. + retains the document's physical units as below; positive root `width`/`height` and `viewBox` dimensions that would round to 0 at the chosen decimals use enough digits to stay positive. Estimate unchanged. - **Done (#864):** SVG export writes physical unit suffixes on the root `` for documents with physical units (`mm`, `cm`, `in`, `pc`; documents in feet and yards are written in `in`, in meters in `cm`, and in Q or Ha in `mm`, since SVG has no unit for them: `every_physical_document_unit_exports_its_printed_size`), so external vector tools (Inkscape, LightBurn) and browsers render drawings at their intended physical scale rather than scaling to 75% under point-based user-unit assumptions; unitless user coordinates in `viewBox` and path geometry remain in 1:1 internal points per SVG 1.1 coords §7.10. A round trip keeps `mm`, `cm`, `in` and `pc` documents in their unit (`export_physical_units_writes_unit_suffixes`, `svg_round_trip_preserves_document_units`); documents in feet, yards, meters, Q or Ha keep their printed size and open again in the SVG unit they were written in. General document unit preferences across restarts remain tracked under #864. - **Missing:** general document unit preference on restart (#864; SVG export physical units done). Shape Builder regions (#937, closed), PDF text placement (#722, above), the bezier drag preview (#834, #3065, #3729) and deleting an interior anchor of an open path (above) diff --git a/docs/mcp.md b/docs/mcp.md index a9ab3debc4..fcc0ad062b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1357,7 +1357,7 @@ SVG Options: `export` to SVG takes them in `options`, flat or as `{"svg": {…}} SVG, or returned as `linked`), `objectIds` (`layerNames`, `minimal`, `unique`), `decimals` (1–7), `minify`, `responsive`, `units` (`px`, `pt`, `mm`, `cm` or `in`: overrides the document unit for `width` and `height`; omit to retain the document unit, explicit null is rejected; `px` means bare numbers, the `viewBox` stays in points; ignored with `responsive`), `useArtboards`, `range: "all"` (one SVG per artboard, listed in `files`, each holding only the art over its artboard), `preserveEditing` (the SVG reopens as the full document), `metadata` and `fewerTspans` (one `` per line of type). Unknown keys inside `svg` are rejected; `run_command document.formats` -lists every option with its default. `encoding` is `utf8`, `utf16` (big-endian after a byte order mark) or `latin1` +lists every option with its default. If `decimals` would round a positive dimension to zero, root `width`/`height` values in unitless or px form and `viewBox` sizes use enough digits to stay positive, with scientific notation when more than 14 decimal places are needed. `encoding` is `utf8`, `utf16` (big-endian after a byte order mark) or `latin1` (ISO 8859-1, other characters as `&#x…;` references); `document.serialize` still answers `text`, plus `dataBase64` (the file) when it isn't UTF-8, and such files open again. `profile: "tiny12"` writes a simplified SVG Tiny 1.2 (presentation attributes only; filters, masks, blend modes and embedded fonts left out, symbols as art, each with @@ -2838,7 +2838,7 @@ inside a method, accessor or class constructor, and `super(…)` inside a derive arrow function within one; elsewhere, through an indirect `eval` and in a `Function` body they are a `SyntaxError` (https://262.ecma-international.org/6.0/#sec-performeval). A class can extend a class, a function, `null` or the built-in constructors `Object`, `Function`, `Array`, `String`, -`Number`, `Boolean`, `RegExp`, `Date` and the error types. A class can name another built-in constructor in +`Number`, `Boolean`, `RegExp`, `Date`, the error types, `GeneratorFunction` and `AsyncFunction`. A class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Spread, `for`-`of` and array patterns use the iterator protocol. A loop or pattern left early, by `break`, `return`, a @@ -2898,7 +2898,7 @@ its symbol property is nonwritable, nonenumerable and configurable. A failure during conversion or validation throws before the prototype getter runs. `Reflect.construct(Promise, args, newTarget)` rejects a missing or noncallable executor with `TypeError` before reading `newTarget.prototype`. For a callable executor, it reads that prototype before calling the executor; a throwing prototype getter prevents the call. -`Function` and `GeneratorFunction` convert and parse their source arguments before reading `newTarget.prototype`. +`Function`, `GeneratorFunction` and `AsyncFunction` convert and parse their source arguments before reading `newTarget.prototype`. A conversion or syntax error throws before that prototype getter runs. `Reflect.has` and an empty-handler proxy's membership checks use host collection indexers, including numeric indices and named items. @@ -3184,13 +3184,17 @@ through `$`: object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is, so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and `transform` act about the center of the geometric bounds unless a `Transformation` value names another point of - them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients - default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different + them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. A path without points takes + any of them about any point named. `Transformation.DOCUMENTORIGIN` still uses the first artboard's bottom-left + corner; other named points use the origin. Its linked opacity mask, strokes, effects and patterns transform with + the same options. Positions and gradients default to `true` and patterns to the Transform Pattern Tiles + preference. Fill and stroke patterns with different values, and gradients different from positions, counting the defaults of arguments left out, throw an error that says they are not available yet. `changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the - square root of the area it scales by (stroke weights and effects scale with it). `resize` on a path also takes any - other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, + square root of the area it scales by (stroke weights and effects scale with it; the scale and every stroke layer's + resulting weight on a path must stay finite, and a weight that would pass 1000 points throws). `resize` on a path + also takes any other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, at most 1000 points). On a member of a compound path or compound shape, the compound's stroke weight follows the percent through `stroke.set`; when the percent is the resize's own scale, the member's own strokes and effects also scale with it. `transform` with `changeLineWidths` at the matrix's own scale sets the compound's stroke weight the @@ -3322,6 +3326,9 @@ through `$`: deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer with nothing to add or deselect runs no command. Each assignment counts the current selection toward the script's operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included. + While an object in the layer is isolated, `true` adds what Select All takes in isolation: the art inside an + isolated group, or the isolated object itself. Reading `hasSelectedArtwork` counts each selected object it checks + toward the same budget. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is hidden or locked, or its artboard is locked, and `true` is also refused when the topmost object is hidden or @@ -3354,7 +3361,9 @@ through `$`: collection whose document, layer or group was deleted throws `Stale page item` or `Stale document` first. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, - index 0 puts it directly above the clipping path), as one undo step named Group, and + index 0 puts it directly above the clipping path; in an Image Trace object, index 0 is refused and changes nothing, + since the source image stays at the bottom, and index 1 puts it directly above the source image), as one undo step + named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. An omitted key takes its default (`parent`: the current layer; `index`: on top; `compound`: false). Explicit `null` is refused for `parent`, `index` and `compound`. @@ -3436,10 +3445,10 @@ through `$`: `ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/) and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version` (`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`, - `unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`, + `unitScaleRatio` (a percentage: at 100 one `unit` is one drawing unit; at least 0.0001 and at most 1000), `colors`, `rasterFormat`, `exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`. An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and - `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values. + `unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 100, VectorCraft's own values. `AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and `AutoCADColors.TrueColors` throws an error. `AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an @@ -3532,7 +3541,9 @@ through `$`: that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning `matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a - nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point + nearly singular image cannot reach exactly throw an error with nothing changed. Assigning `matrix` to a locked or + hidden image, one inside a locked or hidden layer or group, or one on a locked artboard throws the transform methods' + error with nothing changed, even when the matrix is unchanged. `boundingBox` is the pixel rectangle at one point a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()` @@ -3710,6 +3721,9 @@ through `$`: Path group moves a path inside that group, and when Global Edit changes another member's path points. Their existing `PathPoint` handles throw `Stale path point`. An appearance-only change, such as a fill change, leaves the handles valid. + After each command, the script checks each document that holds a path whose points it still holds: it goes down + through every layer and group the command changed and counts each object directly inside them, changed or not, toward + the script's operation budget. Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point, and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment @@ -3930,7 +3944,8 @@ through `$`: If the script has not chosen an artboard on that document since its last revert, the step uses the index of its active artboard as the run started: after the script deletes artboards, the artboard now at that index, or the last one past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to - Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + Artwork Bounds step act on those instead, as in the panel's playback, until the script calls + `setActiveArtboardIndex` on that document; after a revert discards that choice, the selection applies again. A step of a recorded `command.batch` step that names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's own rules: the action and its set are matched by their exact names, and a name that matches no action or more than one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have @@ -4057,7 +4072,8 @@ and does not read `Symbol.toStringTag`. A `.js` script, and a `.jsx` file or a `source` string run with `module: true`, also read async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): `async function` declarations and expressions, -async arrow functions and async methods in object literals. A call returns a `Promise` that the function's `return` +async arrow functions and async methods in object literals. A module also exports async function declarations +(`export async function f() {}`, and `export default async function` with or without a name). A call returns a `Promise` that the function's `return` resolves and an uncaught exception rejects. `await` suspends the function until its operand settles, and the function goes on in a promise job with the value, or with the rejection thrown at the `await`, so `try`, `catch` and `finally` work around it. Async functions cannot be called with `new` and have no `prototype` property. `AsyncFunction` is @@ -9939,6 +9955,31 @@ Absolute target, so it leaves objects that already have that size as they are; r {"name":"run_command","arguments":{"command":"object.transformEach","params":{"relative":false,"scaleH":50,"scaleV":50}}} ``` +## Step and Repeat + +`object.stepAndRepeat` (Object › Transform › Step and Repeat…) copies the selection into a grid of `rows` by +`columns` cells, left to right and top to bottom, the selection itself being the first cell. With `fill: true` the grid +holds as many cells as fit `sheet` (default: the artboard that holds the selection's center, else the first artboard) +inside `margin`, and the first cell moves to the sheet's top-left corner plus `margin`. `gap`, `gapX` and `gapY` are +measured between the geometric bounds of `cutId` (a selected object, such as a cut contour), else of the selection, +and `fill` places and counts cells by the same bounds, so art outside a cut contour may cross the sheet's edge. A negative gap overlaps neighbors and must +be smaller than the width or height it is between; a negative `margin` is refused. `rotate: "columns"` or `"rows"` +turns every other column or row by 180° about its cell's center. Several selected objects are grouped first, so a cut +contour stays with its artwork. When the selection holds a pixel-aligned object, every cell moves by whole points: the +pitch is rounded up, with `fill` the first cell's place is rounded toward the inside of the sheet and only the cells +that still fit are counted, and a turned cell turns about a center up to half a point right of and below its own. +Turn clearance increases only the horizontal pitch for `rotate: "columns"` or the vertical pitch for `rotate: "rows"`. +With `fill`, turned cells must fit on both axes including their turn offset. If no turned column or row fits, the grid +has one unturned column or row. The copies then stay on the pixel grid and the objects in each copy keep +their places against each other. The grid is one undo step, at most 10,000 cells, and the copies are selected. A grid +whose new copies (every cell but the first) would hold more than 250,000 objects in all is refused; the count includes +the art of opacity masks and the group made for a selection of several objects. +A single cell that neither moves nor groups the artwork and leaves the selection unchanged adds no undo step. + +```json +{"name":"run_command","arguments":{"command":"object.stepAndRepeat","params":{"fill":true,"gap":3,"margin":9,"rotate":"columns"}}} +``` + ## Align to Pixel Grid `object.setPixelAligned {ids?|id?, on?}` turns the pixel-aligned property of the objects given (default: the selected @@ -11233,7 +11274,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`, a saved preset before a built-in one of the same name; with `presetCategory`, a category of `file.newPresets`, the preset of that name in -that category), `name`, `width`/`height` +that category; an unknown category, or `presetCategory` without `preset`, is an error), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are @@ -12448,7 +12489,10 @@ panel menu's Unembed… with several embedded images selected asks for one folde downloads each image instead and links none). `links.placementOptions {ids?, preserve?: transforms|bounds|fileDimensions|fit|fill, align?: topLeft…bottomRight, clip?}` decides how a relinked or updated file takes an image's place (default `bounds`: stretched into the old -bounds; `clip` puts it in a clip group of the old bounds when it is larger). The UI commands `links.editOriginal` and +bounds; `clip` puts it in a clip group of the old bounds when it is larger). +MCP clients must reopen the Placement Options dialog (`ui.placementOptionsDialog`) before confirming again after +Undo, Redo, or a revert in the document where it opened. +The UI commands `links.editOriginal` and `links.reveal` open the linked file in its app or show it in its folder (desktop). Edit Original runs only from the app's window, except for a placed document, which opens in a tab. With the preference `editOriginalSystemDefaults` (Preferences › File Handling › Use System Defaults for Edit Original, on by default) off, Edit Original opens a raster image in the app @@ -13676,15 +13720,22 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or -remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, +remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than CUPS's own domain socket, a socket a `Listen` line of `/etc/cups/cupsd.conf` names (or a link to either), `localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is -asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the -server is asked as `localhost` on port 631; another socket path is not asked. +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. When CUPS's own domain socket +or a link to one is named as the server, the lookup asks `localhost` on port 631. Other socket paths, including those added only by +`cupsd.conf` `Listen` lines, are not asked. In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available. +After a `printer` change, read `media` again once the new printer's sizes have loaded. Until then, the dialog keeps +the previous printer's paper list. A printer paper the new printer lists by the same name and size stays chosen under +the new printer's `printer:` id or as the built-in paper when the new list offers it. With the same key, the built-in +paper can replace it either way up. With a different key, the built-in paper replaces it only when its orientation +matches; otherwise, it becomes `custom` at its Width and Height. Any other printer paper also becomes `custom` at +its Width and Height. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} @@ -16265,7 +16316,7 @@ effects keep their colours. ## Vector halftone `object.vectorHalftone` turns the selection into vector dots, lines or shapes sized by its -tone (the `shape` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the +tone (the `shape` and `style` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. Here a `shape` or `angle` given with a `style` wins over the style's, and an unknown style is refused. An image in the art that can't be decoded is sampled as blank (no dots, or full dots with `invert`), and the result carries the `warning` that Flatten Transparency gives: @@ -18242,7 +18293,8 @@ so with the ids in another order the same seed can give each object a different An id naming a nested member targets the outermost compound. Paths, compound paths and live compound shapes with no fill, clipping paths (a compound path that clips included), hidden and locked objects and the objects in hidden or locked groups and layers or on a locked artboard (also when `ids` names them; new art made there while it is still selected takes a color), generated graph design art, paths a user groups inside a graph series, type, images, symbol instances, blends and envelopes keep their fills; a gradient or pattern fill is replaced by -the color. On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them +the color. A user compound path or live compound shape directly inside a graph series group takes a color unless that series is set to draw a compound design: a marker design while it draws markers, or a column design while it draws columns. +On paths directly in a graph series whose fill changes, the graph stores the fill of the frontmost of them for its next redraw, so after the redraw every mark of the series has that one color. It returns the `count` of objects whose fill changed. An unknown scheme, `min` or `max` with `color`, `swatch` without `tint`, a percent outside 0 to 100, `min` above `max`, a missing or process swatch, a tint swatch whose base cannot produce tints and a seed that is not a whole number are @@ -18336,7 +18388,8 @@ Object › Vector Halftone without Keep Original, and the Appearance panel reope | Parameter | Values (default) | Does | |---|---|---| -| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes | +| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; at partial tones `circle`, `ellipse` and `diamond` dots stay inside their cell, sized to preserve the tone's coverage; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes; at full tone every shape but `line` is the cell's own square | +| `style` | `custom`, `grid`, `gridAngle`, `gridDots`, `gridDotsAngle` (`custom`) | A named style sets the shape and angle in place of the stored ones: `grid` is `euclidean` at 0°, `gridAngle` `euclidean` at 45°, `gridDots` `circle` at 0°, `gridDotsAngle` `circle` at 45°; the dialog hides Shape and Angle while one is chosen. Names match in any letter case, and `effect.apply` and `effect.setParams` refuse an unknown style | | `frequency` | lines per inch 1…300 (20) | Cells per inch of the screen | | `angle` | degrees (45) | The screen angle; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it | | `mode` | `mono`, `cmyk` (`mono`) | One screen following lightness, or four ink screens following the art's ink amounts, multiplied over each other | @@ -18459,7 +18512,7 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | -| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | +| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group, clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or clipping pieces group) that holds it, so a blend key or compound shape operand gets its marks outside the live object. In isolation mode, an object whose marks would go outside the isolated art is an error that makes no step. Selected parts of compound paths, envelopes, meshes, repeats, Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, @@ -18670,7 +18723,7 @@ Result: `{ok, blanks, panels, hinges, holes, issues: [{severity, code, message, no issue is an error. `message` is in English, and the Fold Lines panel shows it in the interface language. `ids` names the objects each issue is about. With `select: true`, those objects become the selection; when no issue names an object, the selection stays as it is. The Fold Lines panel's Check button runs the same check, shows a summary line -(panels, hinges, errors and warnings) and lists the issues; clicking an issue or its Select button selects its objects. +(panels, hinges, errors and warnings) and lists the issues; clicking an issue or choosing Select Affected Objects from its row menu selects its objects. Copy Finding copies the displayed message, including for issues that name no objects. The list is shown until the document changes. ```json @@ -18955,7 +19008,8 @@ script. - Values are rounded to the most decimal places among `start`, `step` and `end` (at most 6), so 0.1 by 0.1 gives 0.1, 0.2, 0.3. - Objects that already read so are left as they are; when nothing changes no undo step is made. -- A frame of threaded type among the objects is an error, and nothing changes. +- A frame of threaded type among the objects is an error, and nothing changes. With `replace` set to numbers or + placeholder, a frame whose story holds none is skipped instead. | Parameter | Values (default) | |---|---| diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57cc0de8f3..9253366bec 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1129,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). @@ -1137,7 +1137,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document, untargeted paste and Fit to Artwork Bounds use that artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. @@ -1201,7 +1201,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,676 of 4,682 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1 when run as scripts. With `module: true`, they run as modules and accept these ECMAScript 2015 forms. `import` and `export` outside a module are syntax errors (the modules entry below). `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. The collector retains tagged-template cache entries only while the site's code is reachable. - - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date`, the error types, `GeneratorFunction` and `AsyncFunction` (neither is a global: a script reaches each through the prototype of a generator or async function, and writing an async function needs `Options::es2017`); a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string and Symbol property keys. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate key or a value that is neither a string nor a Symbol), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. @@ -1215,7 +1215,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - A realm made with `Options::es2015` also has `Object.setPrototypeOf(o, proto)` (ECMA-262 2015 section 19.1.2.18, https://262.ecma-international.org/6.0/#sec-object.setprototypeof), which returns `o` with `proto` as its prototype. `undefined` or `null` for `o`, a `proto` that is neither an object nor `null`, a non-extensible object given a different prototype, and a prototype whose chain leads back to the object are `TypeError`s; any other primitive `o` is returned unchanged. `Object.prototype` keeps its `null` prototype, as later editions give it (https://262.ecma-international.org/11.0/#sec-immutable-prototype-exotic-objects). For a proxy it calls the handler's `setPrototypeOf` trap, or sets the target's prototype when the handler has none, and a `false` result, a revoked proxy and a trap that breaks the invariant of section 9.5.2 are `TypeError`s. When the trap returns `true`, the call returns the proxy, and the proxy's prototype is whatever the trap left, which may be unchanged for an extensible target. It uses the same [[SetPrototypeOf]] as `Reflect.setPrototypeOf`, so the cycle check stops at a proxy in the chain and each prototype it passes takes fuel. A realm made without the option has no `Object.setPrototypeOf`. Tests: `crates/js/src/es2015_object_tests.rs`. - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). + - Scripts: with `Options::es2017` (which turns on `Options::es2015` too), `vectorcraft-js` reads and runs async functions and `await` as ECMA-262 2017 section 25.5 defines them (https://262.ecma-international.org/8.0/#sec-async-function-objects): declarations, expressions, async arrow functions and async object methods. A module exports async function declarations with `export async function`, which requires a name, and `export default async function`, which allows a name to be omitted. A call returns a `Promise`, `return` resolves it and an uncaught exception rejects it, and `await` suspends the frame until the value settles and goes on in a promise job, with a rejection thrown at the `await`. The suspended frame is an object the collector traces, so a function waiting on a promise that nothing can settle is freed. Async functions are not constructors and have no `prototype`; `AsyncFunction` and its prototype exist without a global. In script code `await` is an identifier outside async functions, and module code rejects it as one; `async` and `await` stay identifiers without the option. `script.run` sets it for a `.js` file and for any run with `module: true`; `.jsx` scripts and `source` strings run as scripts do not read the syntax. Each resume takes 1 unit of fuel and counts as a job (VectorCraft's own rule). `cargo xtask test262` reads the suite's `expressions/async-function`, `statements/async-function`, `expressions/await` and `expressions/async-arrow-function` tests that need only the features present: with the option, 178 of 178 negative parse runs and 183 of 208 other runs pass (178 and 10 with `Options::es2015` alone); 21 of the failing runs read `globalThis` and 4 expect a `name` property on the function. Tests: `crates/js/src/async_tests.rs`, `crates/js/src/parser/module.rs` (`async_function_declarations_are_exported`), `crates/js/tests/test262.rs` (`async_functions_run`), `crates/engine/src/tests/script_run.rs` (`a_js_script_runs_async_functions_and_a_jsx_script_does_not_read_them`). - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. @@ -1478,6 +1478,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). - Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone. + - Vector Halftone styles are Custom (Shape and Angle as set), Grid (Euclidean dots at 0°), Grid Angle (Euclidean at 45°), Grid Dots (round dots at 0°) and Grid Dots Angle (round at 45°). Explicit `shape` and `angle` values override the style in `object.vectorHalftone`; named styles override stored values in the live effect. The dialog hides Shape and Angle for named styles. `object.vectorHalftone`, `effect.apply` and `effect.setParams` reject an unknown style, and a stored effect with an unknown style draws as Custom (`styles_set_the_shape_and_angle`, `halftone_styles_set_the_shape_and_angle_unless_given`, `halftone_effect_refuses_an_unknown_style`, `a_named_style_hides_shape_and_angle`). At partial tones circle, ellipse and diamond dots stay inside their cell, sized to preserve the tone's coverage. At full tone every dot shape except Line is the cell's exact square (`full_tone_dots_have_exactly_the_cell_corners`). - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. @@ -2573,6 +2574,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Text Import Options' Character Set offers Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, the plain-text encodings [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-and-export-text.html) lists for placed text. `file.place {text: {characterSet}}` decodes each with its WHATWG Encoding Standard decoder. The mapping is VectorCraft's own: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with `platform: "mac"`), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD, and the last set confirmed is remembered (`crates/engine/src/tests/textimport.rs`, `crates/ui-egui/src/dialogs/text_import.rs`). - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. + - In Separations Preview, each process or spot ink row has a menu to show or hide that plate, show only that plate, or show all plates. - In the Separations Preview panel, an Alt-click (Option-click on macOS) on the eye of the plate shown alone shows every plate again, spot plates included, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for a second modified click on the eye (`view.separationsPreview {soloToggle: plate}`); an Alt-click on a plate shown among others shows only that plate, as the help page describes for the first one. VectorCraft's own rules: an Alt-click on a hidden plate, on another plate while one shows alone or while no plate is shown shows only that plate, and `only` still shows just the named plate when repeated (`crates/engine/src/tests/colormgmt.rs`, `crates/ui-egui/src/panels/separations.rs`). - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. @@ -2992,7 +2994,9 @@ panel run `addon.cleanup.*`: Simplify Anchors (Keep Shape) on the shared kernel Show, Fix Selected and Fix All (each one undo step), Deep Ungroup and Rejoin Path Pieces. Tests: `addons::` in `vectorcraft-pathops`, `cmd::addons::cleanup::tests` in `vectorcraft-engine` (each kind found, fixed and clean art left alone; Fix All as one step; scopes; rejoin within the gap only) and `addons::cleanup::tests` in `vectorcraft-ui-egui` -(the submenu opens the panel; Check lists what it finds). Commands: `docs/mcp.md` › Artwork Cleanup add-on. +(the submenu opens the panel; Check lists what it finds). A result row's context menu shows the artwork for that +finding or fixes the selected findings. Opening the menu on a selected row keeps the other selected rows. +Commands: `docs/mcp.md` › Artwork Cleanup add-on. The add-on's text tools (2026-10-31) work on the shared text layout: Break Text into lines, paragraphs, words or glyphs and Split Text at Cursor make point type pieces placed by the glyph of their first character, Combine Point Text merges @@ -3148,7 +3152,7 @@ add-on. ## Color Effects add-on: Randomize Fill Colors (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path, compound path and live compound shape, and each one inside the selected groups and clipping groups, its own top fill color, picked at random and evenly: any color in the document's color mode, a linked tint of a global or spot swatch, or a gray, the tints and grays between a minimum and a maximum percent. Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. A seed repeats a result exactly, and the dialog starts with a new one whenever the document has changed. Objects without a fill, clipping paths, hidden and locked objects, objects inside hidden or locked groups and layers or on a locked artboard, generated graph design art, type, images, symbol instances, blends and envelopes keep their fills. New art made on a locked artboard takes a color while it is still selected. The command records one undo step when a fill changes and rejects bad params without a change. Tests: `cmd::addons::color::random_fill::tests` in `vectorcraft-engine` (each scheme and its range, the seed, groups, compound paths, live compound shapes and clipping groups entered, unfilled, hidden and locked objects left alone, CMYK documents, one undo step or none, bad params refused), `addons::color::random_fill::tests` and the add-on dialog family test in `vectorcraft-ui-egui` (typed values preview, OK and Cancel, the Swatch choice), and `command_sweep`. Commands: `docs/mcp.md` › Color Effects add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Color Effects › Randomize Fill Colors… gives each selected filled path, compound path and live compound shape, and each one inside the selected groups and clipping groups, its own top fill color, picked at random and evenly: any color in the document's color mode, a linked tint of a global or spot swatch, or a gray, the tints and grays between a minimum and a maximum percent. Compound paths and live compound shapes take one color and keep their members' fills. An id naming a nested member targets the outermost compound. A seed repeats a result exactly, and the dialog starts with a new one whenever the document has changed. Objects without a fill, clipping paths, hidden and locked objects, objects inside hidden or locked groups and layers or on a locked artboard, generated graph design art, type, images, symbol instances, blends and envelopes keep their fills. A user compound path or live compound shape directly inside a graph series group takes a color unless that series is set to draw a compound design: a marker design while it draws markers, or a column design while it draws columns. New art made on a locked artboard takes a color while it is still selected. The command records one undo step when a fill changes and rejects bad params without a change. Tests: `a_user_compound_in_a_column_series_naming_an_undrawn_compound_marker_takes_a_color`, `cmd::addons::color::random_fill::tests` in `vectorcraft-engine` (each scheme and its range, the seed, groups, compound paths, live compound shapes and clipping groups entered, unfilled, hidden and locked objects left alone, CMYK documents, one undo step or none, bad params refused), `addons::color::random_fill::tests` and the add-on dialog family test in `vectorcraft-ui-egui` (typed values preview, OK and Cancel, the Swatch choice), and `command_sweep`. Commands: `docs/mcp.md` › Color Effects add-on. ## Arrange Tools add-on (2026-10-31) @@ -3190,7 +3194,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange ## Arrange Tools add-on: Mark Bounds of Each (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side; an object whose sides are too short for any leg gets no corner marks. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none`, `an_object_too_small_for_corner_legs_gets_no_empty_group` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group, clipping sublayer or live object (a blend, compound path, compound shape, Shaper group, Objects on Path group, Live Paint group, dimension, graph, flare, envelope, mesh, repeat, intertwine, Image Trace group, generated art group, graph series, graph design copy or clipping pieces group) that holds it; a clipping top-level layer keeps the marks inside it. In isolation mode, marks that would go outside the isolated art are an error with no undo step. Selected parts of compound paths, envelopes, meshes, repeats, Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side; an object whose sides are too short for any leg gets no corner marks. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `marks_on_envelope_sources_follow_the_drawn_bounds_once_per_live_object`, `marks_on_a_blend_key_or_compound_shape_operand_go_above_the_live_object`, `marks_on_a_dimension_part_go_above_the_live_object`, `marks_on_an_image_trace_part_go_above_the_live_object`, `marks_on_an_outlined_glyph_stay_directly_above_it_inside_the_outlines_group`, `flat_objects_get_lines_and_guides_and_empty_groups_none`, `an_object_too_small_for_corner_legs_gets_no_empty_group` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group by Row (2026-11-29) @@ -3206,7 +3210,7 @@ A VectorCraft addition, not a feature of the reference app (it has no command fo ## Type Tools add-on: Make Numbers Sequence (2026-12-01) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, objects that hold none are skipped before the ordering, so they take no number and are never deleted. Locked and hidden type is left alone, a clipping mask is not deleted, and threaded type and bad parameters are refused. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Type Tools › Make Numbers Sequence… numbers the selected type objects from a start value by a step, optionally stopping at an end value, and each number replaces the whole text, every number in it, or every `{%n}` placeholder (#10448). The objects are taken in stacking order, by rows or by columns, or in a seeded random order, with optional leading and trailing zeros, and the objects past the end can be deleted. When numbers or placeholders are replaced, an unthreaded object that holds none, and a threaded frame whose whole story holds none, are skipped before the ordering, so they take no number and are never deleted. A threaded frame is checked once per thread, against its whole story. Locked and hidden type is left alone, a clipping mask is not deleted, and bad parameters are refused. Any other threaded type is refused. A run that changes the document is one undo step, and a run that changes nothing makes none. The dialog has Preview. It is based on Sergey Osokin's MIT-licensed MakeNumbersSequence script. Tests: `cmd::addons::typetools::numbers::tests` in `vectorcraft-engine`, `addons::typetools::numbers::tests` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. ## Unit Converter add-on (2026-11-14) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 611ae42c25..a2b7812ee9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -81,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-12-02 | minor | Canvas context menu: rows for edit, group, path, type, view and artboard commands show a leading icon from the app's icon set, so a row can be found by its shape; rows without a fitting glyph stay text only (#4602); scores and estimates unchanged | | 2026-12-02 | minor | Headless (RFC-0052) column on the Summary table and every behaviour table: 365 unknown, with marking rules | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | @@ -193,7 +194,7 @@ tools, never checked side by side) isn't captured row by row. ## Headless (RFC-0052) -**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 365 unknown.** +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 0 yes, 0 no (window 0, os 0, engine-gap 0), 0 partial, 366 unknown.** Every parity table on this page has a Headless column: the Summary table (12 area rows, including the overall row) and the behaviour tables (353 rows). Every row is `unknown` until it is checked. A checked row may be marked `no ()` or `partial ()` by hand, where the reach is `window` (needs the desktop window, a dialog or the pointer), `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be a command, isn't one yet). A `partial` row's notes say which part a headless client can do. `yes` only when the row cites a command id from the engine registry that `vectorcraft-cli` and the MCP server load (LightCraft's `cmd:` check is the model). Some rows already cite command ids such as `toolbar.show`, `tool.select` and `guide.add`; those are not enough for `yes` until they are registry ids, and desktop-only ids (including the generated list in `crates/mcp/src/ui_catalog.rs`) do not count. Update the counts in this line when you mark rows. @@ -585,7 +586,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | -| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws inward Corner Marks or a Rectangle on each selected object's Geometric Bounds or Visual Bounds, with Length, Weight, Color and Preview; marks go above the object or its outermost clip group or clipping sublayer and become selected; one undo step | done | `addon.arrange.markBounds`, `crates/engine/src/cmd/addons/arrange/marks.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws inward Corner Marks or a Rectangle on each selected object's Geometric Bounds or Visual Bounds, with Length, Weight, Color and Preview. Marks go above the object or its outermost clip group, clipping sublayer or live object and become selected in one undo step. Marks that would go outside isolated art cause an error without an undo step. Selected parts of compound paths, envelopes, meshes, repeats, Shaper groups and blends with a stored spine or Align to Path, and hidden Image Trace sources, are measured as the outermost such live object, with one set of marks per object. Other blend keys and compound shape operands keep their own bounds. | done | `addon.arrange.markBounds`, `crates/engine/src/cmd/addons/arrange/marks.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group by Row… groups the selected objects whose visual bounds overlap from top to bottom into one group for each row, or with Group By Columns from left to right (within one layer or group and one artboard), each group at its frontmost member's stacking place; Preview; one undo step | done | `addon.arrange.groupRows`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | unknown | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | unknown | @@ -596,6 +597,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Anchor Inspector fields restore canceled edits | done | Canceling an X, Y, handle Length or Angle edit restores the anchor, with no undo step, and canceling a Points per segment edit restores its count. An accepted anchor edit is one undo step. | unknown | | Corner and Shared Edge Merge options restore canceled edits | done | Canceling a control gesture restores its opening draft values. Confirmed changes remain available to the tool. | unknown | | Parametric Shape panel restores canceled edits | done | Canceling a field edit or Shape menu choice restores the selected shape, with no undo step, or the tool's next shape. An accepted edit of a selected shape is one undo step. With no shape selected, a highlighted Shape entry applies only once chosen. | unknown | +| Fold Lines check-result row menu | done | Select Affected Objects selects the lines named by the finding. Copy Finding copies its displayed message, including for findings without objects. | unknown | | Fold Lines panel restores a canceled Fold Angle edit | done | Canceling a Fold Angle edit restores the selected lines' angles, with no undo step. An accepted edit is one undo step. | unknown | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Divide into Dashes… (Dash and Gap in any unit, Fit to Corners and Ends, Remove Gaps; Preview) cuts the selected paths, or only their direct-selected segments, into open pieces along the curve, keeping their appearance, one undo step | done | #4950; `addon.pathtools.divideDashes`, `crates/pathops/src/addons/pathtools/dashes.rs`, `crates/ui-egui/src/addons/pathtools/dashes.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | unknown | diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 7a5c83e8b5..d72887dfde 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -10,6 +10,11 @@ workspace = true [dependencies] serde_json = { workspace = true } +# The interface faces the web site serves under fonts/ui/, written as crates/text/build.rs serves them. +craft-fonts-build = { workspace = true } +# The private scratch folder web-fonts writes the served-faces table to. Already in Cargo.lock +# (the apps use it), so this adds no new crate. +tempfile = "3" # The files of other crates that this crate compiles, for CI's test selection. [package.metadata.craft] diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 40f38d85f2..2152369254 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -73,8 +73,9 @@ commands: and built-in tests its interpreter supports and the String, Number, RegExp and Date built-ins tests, printing the counts; then fetch json2.js into corpus/json2 (sha256 verified) and run it - web-fonts copy the craft-fonts faces in crates/text/web-fonts.txt into the web site (the Trunk - post_build hook; a no-op without CRAFT_FONTS_DIR) + web-fonts copy the craft-fonts faces in crates/text/web-fonts.txt into the web site, the + interface's startup and demand faces also under fonts/ui/ (the Trunk post_build + hook; a no-op without CRAFT_FONTS_DIR) "; fn main() -> ExitCode { diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e517292e73..0e17e13a13 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1082,6 +1082,14 @@ fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec { out } +/// Whether the `=` at `i` assigns (`=`, `+=`, `let x = …`), rather than being part of `==`, `!=`, +/// `<=`, `>=`, `=>` or `..=`. +fn is_assignment(b: &[u8], i: usize) -> bool { + b.get(i) == Some(&b'=') + && !i.checked_sub(1).and_then(|j| b.get(j)).is_some_and(|c| matches!(c, b'=' | b'!' | b'<' | b'>' | b'.')) + && !b.get(i + 1).is_some_and(|c| matches!(c, b'=' | b'>')) +} + /// The index of the bracket closing the one at `open`. fn matching(m: &[u8], open: usize) -> Option { let (o, c) = match m.get(open)? { @@ -2442,17 +2450,46 @@ fn numeric_literal(s: &str) -> bool { matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64") } -/// The value of a decimal integer literal such as `3`, `-4`, `1_000` or `2u8`. +/// The value of an integer literal such as `3`, `-4`, `1_000`, `2u8` or `0x1F`. fn integer_literal(s: &str) -> Option { let (sign, digits) = s.strip_prefix('-').map_or((1, s), |rest| (-1, rest)); + let (radix, unprefixed) = [("0x", 16), ("0o", 8), ("0b", 2)] + .iter() + .find_map(|&(prefix, radix)| digits.strip_prefix(prefix).map(|rest| (radix, rest))) + .unwrap_or((10, digits)); let body = ["u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"] .iter() - .find_map(|suffix| digits.strip_suffix(suffix)) - .unwrap_or(digits); - if !numeric_literal(digits) || !body.bytes().all(|c| c.is_ascii_digit() || c == b'_') { + .find_map(|suffix| unprefixed.strip_suffix(suffix)) + .unwrap_or(unprefixed); + if !numeric_literal(digits) || body.is_empty() || !body.chars().all(|c| c.is_digit(radix) || c == '_') { return None; } - body.replace('_', "").parse::().ok().map(|n| sign * n) + i128::from_str_radix(&body.replace('_', ""), radix).ok().map(|n| sign * n) +} + +/// The text after the last `let` keyword in `head` that a binding follows (`let x`, `let(x)`, +/// `let[x]`, `let&x`, not the `let` inside a name such as `inlet_fn`). +fn after_let(head: &str) -> Option<&str> { + let b = head.as_bytes(); + head.match_indices("let") + .map(|(at, _)| at) + .filter(|&at| (at == 0 || !is_ident(b[at - 1])) && opens_let_pattern(&head[at + 3..])) + .last() + .map(|at| &head[at + 3..]) +} + +/// Whether `rest`, the text right after a `let` keyword, starts its pattern: whitespace, or a +/// tuple, slice or reference pattern written without a space (`let(x)`, `let[x]`, `let&x`). +fn opens_let_pattern(rest: &str) -> bool { + rest.starts_with(|c: char| c.is_whitespace() || matches!(c, '(' | '[' | '&')) +} + +/// Whether `head`, the text before a call's opening parenthesis, ends with the name `block_on` +/// itself, not a longer name that ends with it (`discard_block_on`, `déblock_on`). +fn ends_with_block_on(head: &[u8]) -> bool { + head.trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| { + !String::from_utf8_lossy(h).chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_' || !(c.is_ascii() || c.is_whitespace())) + }) } /// Whether the source of the `for … in ` head `head` yields at least one item, for an @@ -2461,8 +2498,15 @@ fn integer_literal(s: &str) -> Option { fn literal_source_yields(head: &[u8]) -> Option { let &kw = words(head, b"in", 3, head.len()).first()?; let mut source: String = String::from_utf8_lossy(&head[kw + 2..]).chars().filter(|c| !c.is_whitespace()).collect(); - while source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { - source = source[1..source.len() - 1].to_owned(); + // A borrowed array literal (`&[a, b]`, `&mut [x; 0]`) yields as many items as the array. + loop { + if let Some(rest) = source.strip_prefix('&') { + source = rest.strip_prefix("mut").filter(|r| r.starts_with(['[', '('])).unwrap_or(rest).to_owned(); + } else if source.starts_with('(') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { + source = source[1..source.len() - 1].to_owned(); + } else { + break; + } } if source.starts_with('[') && matching(source.as_bytes(), 0) == Some(source.len() - 1) { let items = &source[1..source.len() - 1]; @@ -2556,13 +2600,26 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } } let prefix = b[head..open].trim_ascii(); + // A loop label (`'outer: for …`, `'été: for …`) comes before the keyword. + let labeled = prefix + .strip_prefix(b"'") + .map(|rest| rest.split_at(rest.iter().take_while(|&&c| is_ident(c) || !c.is_ascii()).count())) + .and_then(|(label, rest)| { + rest.trim_ascii_start() + .strip_prefix(b":") + .filter(|r| !label.is_empty() && r.first() != Some(&b':')) + .map(|r| (label, r.trim_ascii_start())) + }); + let label = labeled.map(|(label, _)| label); + let prefix = labeled.map_or(prefix, |(_, rest)| rest); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active) { return false; } - } else if nested_for && literal_source_yields(prefix) != Some(true) { - // A nested `for` body runs only when its source yields an item. + } else if nested_for && (literal_source_yields(prefix) != Some(true) || skips_rest_of_iteration(b, open, start, label)) { + // A nested `for` body runs only when its source yields an item, and its later statements + // only when no earlier `continue` skips them. return false; } else if !prefix.ends_with(b"|") && !nested_for @@ -2627,7 +2684,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); let head = strip_closure_keywords(&head).0.as_bytes(); - if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { + if !head.ends_with(b"=") || !head.starts_with(b"let") || !std::str::from_utf8(&head[3..]).is_ok_and(opens_let_pattern) { return None; } (pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end)) @@ -2697,9 +2754,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) })(); let binding_head = unwrapped.unwrap_or(bare); - let Some(binding) = - binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) - else { + let Some(binding) = binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| opens_let_pattern(h)) else { // `(|| app.run(c))()` calls the closure where it is written. let open = stmt + bare.len(); let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return false }; @@ -2709,15 +2764,24 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that - // never runs. - let outer = (stmt..open.saturating_sub(1)).rev().find(|&i| !b[i].is_ascii_whitespace()); - let blocked = matching(b, call).is_some_and(|call_close| { - outer.is_some_and(|o| { - b[o] == b'(' - && !b[stmt..o].contains(&b'|') - && b[..o].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) - && matching(b, o).is_some_and(|c| matches!(b[call_close + 1..c].trim_ascii(), b"" | b",")) - }) + // never runs. Grouping parentheses around the call (`block_on(((async || …)()))`) are skipped. + let before = |end: usize| (stmt..end).rev().find(|&i| !b[i].is_ascii_whitespace()); + let blocked = matching(b, call).is_some_and(|mut inner| { + let mut outer = before(open.saturating_sub(1)); + loop { + let Some((o, c)) = outer.filter(|&o| b[o] == b'(' && !b[stmt..o].contains(&b'|')).and_then(|o| matching(b, o).map(|c| (o, c))) else { + break false; + }; + let rest = b[inner + 1..c].trim_ascii(); + if ends_with_block_on(&b[..o]) { + break matches!(rest, b"" | b","); + } + if !rest.is_empty() { + break false; + } + inner = c; + outer = before(o); + } }); if !asynchronous || blocked { return true; @@ -2729,6 +2793,115 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, &active)) } +/// Whether a `continue` in the loop body that opens at `open` comes before `start` and skips the +/// rest of that loop's iteration: one with the loop's `label`, or one without a label that is not +/// inside a nested `for`, `while` or `loop` body. A labeled `continue` inside a nested loop with the +/// same label targets that nested loop. Only a `continue` that starts an expression counts, not one +/// inside the tokens of a macro that does not run them (`stringify!(continue)`) or a raw identifier +/// (`r#continue`). A `continue` inside a nested `for` over a literal source that yields nothing +/// (`for _ in 0..0`) never runs and does not count. A `continue` at the start of the body counts. A `break` in +/// the body already rules out a census hit, so only `continue` is read here. +fn skips_rest_of_iteration(b: &[u8], open: usize, start: usize, label: Option<&[u8]>) -> bool { + let label_at = |at: usize| { + let name = &b[at..]; + &name[..name.iter().take_while(|&&c| is_ident(c) || !c.is_ascii()).count()] + }; + // The labels of the nested loops whose bodies hold `at` (`None` for a loop without a label), each + // with whether the loop is a `for` over a literal source that yields nothing (`0..0`), so that + // its body never runs. + let nested_loops = |at: usize| -> Vec<(Option<&[u8]>, bool)> { + (open + 1..at) + .filter(|&k| b[k] == b'{' && matching(b, k).is_some_and(|close| at < close)) + .filter_map(|k| { + // Groups in the head (`for _ in (0..2).filter(|_| { true })`) are skipped whole. + let mut head_start = k; + while head_start > open + 1 { + head_start -= 1; + match b[head_start] { + b')' | b']' => head_start = (open + 1..head_start).rev().find(|&i| matching(b, i) == Some(head_start))?, + b';' | b'{' | b'}' => { + head_start += 1; + break; + } + _ => {} + } + } + let mut lead = k - b[head_start..k].trim_ascii_start().len(); + let loop_kw = + |head: &[u8]| [b"for".as_slice(), b"while", b"loop"].into_iter().find(|kw| words(head, kw, 0, head.len()).first() == Some(&0)); + // A loop used as an expression comes after an initializer or an operand (`let _ = for …`, + // `x = 'inner: loop …`, `return while …`). + if !b[lead..k].starts_with(b"'") && loop_kw(&b[lead..k]).is_none() { + let mut depth = 0i32; + let eq = (lead..k).find(|&i| { + match b[i] { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + depth == 0 && is_assignment(b, i) + }); + if let Some(eq) = eq { + lead = skip_ws(b, eq + 1); + } + // Grouping parentheses (`let _ = (for … { … });`) also open before the keyword. + for w in [b"(".as_slice(), b"return", b"break", b"("] { + while lead < k && b[lead..].starts_with(w) && (w == b"(" || words(b, w, lead, k).first() == Some(&lead)) { + lead = skip_ws(b, lead + w.len()); + } + } + } + let head = b[lead..k].trim_ascii_end(); + // A loop label (`'inner: for …`) comes before the keyword. + let (inner, head) = match head.strip_prefix(b"'") { + Some(rest) => { + let name = label_at(lead + 1); + let after = rest[name.len()..].trim_ascii_start().strip_prefix(b":")?; + (Some(name), after.trim_ascii_start()) + } + None => (None, head), + }; + let kw = loop_kw(head)?; + Some((inner, kw == b"for" && literal_source_yields(head) == Some(false))) + }) + .collect() + }; + // Whether `at` sits inside the tokens of a macro that does not run them (`stringify!({ continue; })`). + // Other macros (`vec![{ continue; }]`) may run their arguments, so their `continue` still counts. + let in_macro = |at: usize| { + (open + 1..at).any(|k| { + matches!(b[k], b'(' | b'[' | b'{') + && matching(b, k).is_some_and(|close| at < close) + && b[open + 1..k].trim_ascii_end().strip_suffix(b"!").is_some_and(|h| { + let name = &h[h.iter().rposition(|&c| !is_ident(c)).map_or(0, |i| i + 1)..]; + matches!(name, b"stringify" | b"concat_idents" | b"macro_rules") + }) + }) + }; + words(b, b"continue", open + 1, start).into_iter().any(|at| { + // The start of the loop body also starts an expression, and so do an assignment, an opening + // parenthesis, a comma, and a `return` or `break` operand (`let _: () = continue;`). + let before = b[open + 1..at].trim_ascii_end(); + let starts_expr = before.last().is_none_or(|&c| matches!(c, b'{' | b'}' | b';' | b'>' | b'(' | b',')) + || before.len().checked_sub(1).is_some_and(|i| is_assignment(before, i)) + || [b"return".as_slice(), b"break"] + .iter() + .any(|w| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|i| is_ident(before[i]))); + if !starts_expr || in_macro(at) { + return false; + } + let nested = nested_loops(at); + let quote = skip_ws(b, at + b"continue".len()); + if b.get(quote) == Some(&b'\'') { + let name = label_at(quote + 1); + // A `continue` inside a nested loop whose body never runs never executes. + label == Some(name) && !nested.iter().any(|&(inner, never_runs)| never_runs || inner == Some(name)) + } else { + nested.is_empty() + } + }) +} + /// The head before a closure's parameters with a trailing `move` and `async` removed, and whether /// the closure is async. fn strip_closure_keywords(head: &str) -> (&str, bool) { @@ -2759,7 +2932,9 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as .into_iter() .filter(|&at| { let open = skip_ws(b, at + name.len()); - if b[..at].trim_ascii_end().last() == Some(&b'.') || b.get(open) != Some(&b'(') { + // A method (`other.run()`) or a path (`other::run()`) names something else. + let before = b[..at].trim_ascii_end(); + if before.last() == Some(&b'.') || before.ends_with(b"::") || b.get(open) != Some(&b'(') { return false; } if words(b, b"let", bound + 3, at).into_iter().any(|l| rebinds(l, at)) { @@ -2771,7 +2946,25 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as let Some(close) = matching(b, open) else { return false }; let next = skip_ws(b, close + 1); let awaited = b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); - awaited || b[..at].trim_ascii_end().ends_with(b"block_on(") + // The future is the whole argument of `block_on` itself, not of a name that ends with it + // (`discard_block_on`), and not part of a longer expression that may never poll it. + // Grouping parentheses around the future (`block_on((run()))`) are skipped. + let opening = |end: usize| b[..end].trim_ascii_end().len().checked_sub(1).filter(|&p| b[p] == b'('); + let mut paren = opening(at); + let mut inner = close; + let blocked = loop { + let Some((p, c)) = paren.and_then(|p| matching(b, p).map(|c| (p, c))) else { break false }; + let rest = b[inner + 1..c].trim_ascii(); + if ends_with_block_on(&b[..p]) { + break matches!(rest, b"" | b","); + } + if !rest.is_empty() { + break false; + } + paren = opening(p); + inner = c; + }; + awaited || blocked }) .collect() } @@ -2869,7 +3062,7 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); let close = matching(b, i).unwrap_or(to); - let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); + let binding = head.strip_suffix('=').and_then(after_let); let stored = binding.is_none() && stored_closure(b, head, close, to); let Some(name) = binding.and_then(|binding| pattern_names(binding).last()).or_else(|| stored.then(String::new)) else { continue }; let bound = words(b, b"let", from, from + pipe).last().copied().unwrap_or(from); @@ -2899,11 +3092,13 @@ fn stored_closure(b: &[u8], head: &str, close: usize, to: usize) -> bool { let last = segments.next().unwrap_or_default(); let owner = segments.next().unwrap_or_default(); let constructor = matches!(last, "Some" | "Ok" | "Err") || (last == "new" && matches!(owner, "Box" | "Rc" | "Arc")); - let Some(binding) = rest.trim_end().strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { return false }; - let paren = skip_ws(b, close + 1); + let Some(binding) = rest.trim_end().strip_suffix('=').and_then(after_let) else { return false }; + // A trailing comma may follow the closure (`Some(|| { … },)`). + let after = skip_ws(b, close + 1); + let paren = if b.get(after) == Some(&b',') { skip_ws(b, after + 1) } else { after }; let semi = skip_ws(b, paren + 1); constructor - && binding.starts_with(char::is_whitespace) + && opens_let_pattern(binding) && b.get(paren) == Some(&b')') && b.get(semi) == Some(&b';') && pattern_names(binding).all(|n| words(b, n.as_bytes(), semi, to).is_empty()) @@ -10311,6 +10506,189 @@ mod tests { ); } + #[test] + fn census_reads_labels_radixes_paths_and_let_names() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!(census("for _ in 0x0..0x1 { app.run(c); } assert!(menu(c).is_some());"), [], "a hex range with one item runs its body"); + assert_eq!( + census("'inner: for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled empty loop does not run its body" + ); + assert_eq!( + census("'inner : for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a label with a space before its colon" + ); + assert_eq!(census("'été: for _ in 0..0 { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a label with non-ASCII letters"); + assert_eq!( + census("let(_run) = || { app.run(c); }; _run(); assert!(menu(c).is_some());"), + [], + "a let with no space before its pattern binds a closure that is called" + ); + assert_eq!( + census("let run = async || app.run(c); block_on((run())); assert!(menu(c).is_some());"), + [], + "a future in grouping parentheses passed to block_on runs" + ); + assert_eq!( + census("let run = async || app.run(c); déblock_on((run())); discard‿block_on((run())); assert!(menu(c).is_some());"), + [(2, "census")], + "a callee whose non-ASCII name ends in block_on does not run the future" + ); + assert_eq!( + census("let\u{85}run = || app.run(c); run(); assert!(menu(c).is_some());"), + [], + "Unicode whitespace after let separates the pattern" + ); + assert_eq!( + census("let run = async || app.run(c);\u{85}block_on(run()); assert!(menu(c).is_some());"), + [], + "Unicode whitespace before block_on" + ); + assert_eq!( + census("let run = || app.run(c); other::run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a path call does not call the local closure" + ); + assert_eq!( + census("let run = async || app.run(c); discard_block_on(run()); assert!(menu(c).is_some());"), + [(2, "census")], + "a callee that only ends in block_on does not run the future" + ); + assert_eq!( + census("let run = async || app.run(c); block_on (run()); assert!(menu(c).is_some());"), + [], + "block_on with a space before its parenthesis runs the future" + ); + assert_eq!(census("for _ in &[1] { app.run(c); } assert!(menu(c).is_some());"), [], "a borrowed array literal with one item runs its body"); + assert_eq!(census("'inner: for _ in (&[1]) { app.run(c); } assert!(menu(c).is_some());"), [], "a parenthesized borrowed array runs its body"); + assert_eq!( + census("for _ in &[1] { if skip { continue; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "an earlier continue may skip the call" + ); + assert_eq!( + census("'outer: for _ in 0..3 { for _ in 0..1 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled continue in a nested loop may skip the call" + ); + assert_eq!( + census("for _ in &[1] { for _ in 0..2 { if skip { continue; } } app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue that targets a nested loop does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { for _ in (0..2).filter(|_| { true }) { continue; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a nested loop with a block in its head holds its continue" + ); + assert_eq!( + census("'outer: for _ in 0..3 { 'outer: for _ in 0..1 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a labeled continue targets the nearest loop with that label" + ); + assert_eq!( + census("for _ in &[1] { let _k = stringify!(continue); let r#continue = 1; app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue token in a macro or a raw identifier does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { let _k = stringify!({ continue; }); app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue statement inside a macro's tokens does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { let _k = vec![{ if skip { continue; } 0 }]; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue in a macro argument that runs may skip the call" + ); + assert_eq!( + census("for _ in &[1] { continue; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue at the start of the loop body skips the call" + ); + assert_eq!( + census("block_on(((async || app.run(c))())); assert!(menu(c).is_some());"), + [], + "an inline async closure call in grouping parentheses passed to block_on runs" + ); + assert_eq!( + census("discard_block_on(((async || app.run(c))())); assert!(menu(c).is_some());"), + [(2, "census")], + "an inline async closure call passed to a callee that only ends in block_on does not run" + ); + assert_eq!( + census("let run = async || app.run(c); block_on(run().into_stream().take(0).count()); assert!(menu(c).is_some());"), + [(2, "census")], + "a future that is only part of block_on's argument may never be polled" + ); + assert_eq!(census("let inlet_fn =|| { app.run(c); }; inlet_fn(); assert!(menu(c).is_some());"), [], "a closure name that contains let"); + assert_eq!( + census("let mut input = c; let _saved = Some(|| { input = fallback(); },); app.run(input); assert!(menu(c).is_some());"), + [], + "a stored closure with a trailing comma never runs" + ); + } + + #[test] + fn census_ignores_a_continue_in_a_nested_loop_that_never_runs() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("'outer: for _ in &[1] { for _ in 0..0 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a labeled continue in a nested loop that never runs does not skip the call" + ); + assert_eq!( + census("'outer: for _ in &[1] { for _ in 0..1 { continue 'outer; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled continue in a nested loop that runs skips the call" + ); + assert_eq!( + census("'outer: for _ in &[1] { let _ = for _ in 0..0 { continue 'outer; }; app.run(c); } assert!(menu(c).is_some());"), + [], + "a labeled continue in an initializer loop that never runs does not skip the call" + ); + assert_eq!( + census("'outer: for _ in &[1] { let _ = for _ in 0..1 { continue 'outer; }; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a labeled continue in an initializer loop that runs skips the call" + ); + } + + #[test] + fn census_counts_a_continue_used_as_an_expression() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("for _ in &[1] { let _: () = continue; app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue as an initializer skips the call" + ); + assert_eq!( + census("for _ in &[1] { let _ = (continue); app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue in parentheses skips the call" + ); + assert_eq!( + census("for _ in &[1] { let _k = stringify!(continue); let _v = r#continue == 1; app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue token in a macro or a raw identifier still does not skip the call" + ); + assert_eq!( + census("for _ in &[1] { let _ = (for _ in 0..1 { let _: () = continue; }); app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue in a grouped nested loop targets that loop" + ); + assert_eq!( + census("for _ in &[1] { macro_rules! m { (continue) => {}; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue token in a named macro definition's matcher does not skip the call" + ); + } + #[test] fn census_needs_evidence_that_the_call_runs_on_the_entry() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); diff --git a/xtask/src/web_fonts.rs b/xtask/src/web_fonts.rs index b5f3e42d2e..d30ef58c8e 100644 --- a/xtask/src/web_fonts.rs +++ b/xtask/src/web_fonts.rs @@ -1,7 +1,9 @@ //! `cargo xtask web-fonts`: the Trunk `post_build` hook (`apps/*-web/Trunk.toml`). Copies the //! craft-fonts faces listed in `crates/text/web-fonts.txt` from `$CRAFT_FONTS_DIR` into the site, //! each at `fonts//` with its licence beside it: the URLs -//! `crates/text/build.rs` puts in `WEB_FONTS` (both use `crates/text/build/web_fonts.rs`). +//! `crates/text/build.rs` puts in `WEB_FONTS` (both use `crates/text/build/web_fonts.rs`). The +//! `startup` and `demand` faces are also published under `fonts/ui/`, where the interface font stack +//! fetches them (`SERVED_FONTS`), with the craft-fonts-build `Embed::serve` that build.rs uses. //! //! A no-op without `CRAFT_FONTS_DIR`. A listed face the checkout lacks (an older craft-fonts) is //! skipped with a warning, as `build.rs` does; a file whose SHA-256 doesn't match the manifest is an @@ -31,9 +33,40 @@ fn run_with(root: &Path, craft_fonts: Option, staging: Option) eprintln!("warning: web build won't fetch {} (not in CRAFT_FONTS_DIR={}; an older craft-fonts?)", skipped.join(", "), dir.display()); } println!("web-fonts: copied {copied} font(s) into {}", staging.join("fonts").display()); + let served = serve(&root.join("crates/text/web-fonts.txt"), &dir, &staging, None)?; + println!("web-fonts: published {served} interface font(s) into {}", staging.join(SERVED_URL).display()); Ok(()) } +/// Where the site serves the interface font stack's faces: the URL prefix `crates/text/build.rs` +/// gives them in `SERVED_FONTS`. +const SERVED_URL: &str = "fonts/ui/"; + +/// Publish the faces the web interface's font stack fetches (the list's `startup` and `demand` +/// lines) into `site` at their `fonts/ui/…` URLs. `crates/text/build.rs` serves the same faces with +/// the same craft-fonts-build `Embed::serve` into its `OUT_DIR`, for the URLs, sizes and integrity +/// values of `SERVED_FONTS`; this puts the files where those URLs point. `required` overrides +/// `CRAFT_FONTS_REQUIRED`, which decides it otherwise, as in build.rs. Returns how many faces. +fn serve(list_path: &Path, dir: &Path, site: &Path, required: Option) -> Result { + let list = std::fs::read_to_string(list_path).map_err(|e| format!("{}: {e}", list_path.display()))?; + let faces: Vec<(String, String)> = + list::parse_list(&list)?.into_iter().filter(|e| e.startup || e.demand).map(|e| (e.family.to_owned(), e.style.to_owned())).collect(); + // build.rs's table is the one the app uses; this copy, and Embed's hash cache beside it, go. + // A private folder this call creates (random name, created exclusively, owner-only on Unix) + // and removes when `scratch` drops, so nothing another process made is reused or removed. + let scratch = tempfile::Builder::new().prefix("vectorcraft-web-fonts-").tempdir().map_err(|e| format!("scratch folder: {e}"))?; + let embed = craft_fonts_build::Embed::new().dir(dir); + let embed = match required { + Some(required) => embed.required(required), + None => embed, + }; + let served = embed + .filter(move |f| faces.iter().any(|(family, style)| f.family == *family && f.style == *style)) + .serve(site.join(SERVED_URL), SERVED_URL) + .write(scratch.path().join("served.rs")); + served.map(|faces| faces.len()).map_err(|e| e.to_string()) +} + /// Copy the faces `list_path` names from the craft-fonts checkout `dir` into `site` (at their /// `fonts/…` URLs). Returns how many were copied and the listed faces the checkout lacks. fn copy(list_path: &Path, dir: &Path, site: &Path) -> Result<(usize, Vec), String> { @@ -120,6 +153,28 @@ mod tests { assert_eq!(skipped, ["Missing Sans Bold"], "a face the checkout lacks is skipped, not an error"); } + /// The interface font stack fetches `startup` and `demand` faces from `fonts/ui/` (build.rs's + /// `SERVED_FONTS`), so the site holds them there, licence beside; `background` faces are only + /// fetched from `fonts//`. + #[test] + fn publishes_the_interface_faces_at_their_served_urls() { + let (list, dir, site, _) = fixture("serve", None); + assert_eq!(serve(&list, &dir, &site, Some(false)).unwrap(), 1); + let at = site.join("fonts/ui/a"); + assert_eq!(std::fs::read(at.join("A-Regular.ttf")).unwrap(), b"font bytes"); + assert_eq!(std::fs::read(at.join("OFL.txt")).unwrap(), b"licence"); + + let (list, dir, site, _) = fixture("serve-demand", None); + std::fs::write(&list, "demand | A Sans | Regular\n").unwrap(); + assert_eq!(serve(&list, &dir, &site, Some(false)).unwrap(), 1); + assert!(site.join("fonts/ui/a/A-Regular.ttf").exists(), "a face fetched on demand is an interface face"); + + let (list, dir, site, _) = fixture("serve-background", None); + std::fs::write(&list, "background | A Sans | Regular\n").unwrap(); + assert_eq!(serve(&list, &dir, &site, Some(false)).unwrap(), 0); + assert!(!site.join("fonts/ui/a/A-Regular.ttf").exists(), "a background face is not an interface face"); + } + #[test] fn a_file_that_does_not_match_its_manifest_hash_is_an_error() { let (list, dir, site, _) = fixture("mismatch", Some(&"0".repeat(64)));